Compare commits

...

10 Commits

Author SHA1 Message Date
luisfepsale 2b2886a75c [PromptLab first commit] 2025-11-12 18:44:23 -03:00
gpt-engineer-app[bot] 14db385a74 Prevent auto-create on agent select
Remove automatic new conversation creation when selecting an agent; now new conversations are only created by clicking the "Nova Conversa" button.
2025-11-11 20:32:31 +00:00
gpt-engineer-app[bot] 218cfafb26 Adjust delete button hover color
Change the delete button in the conversation history to use a lighter gray hover background for better visual feedback.
2025-11-11 20:14:31 +00:00
gpt-engineer-app[bot] 55cb7c0ae6 Add delete button to history items
Adds a Trash2 icon button to each conversation in the test prompt history to delete conversations via handleDeleteConversation, updating TestPrompt.tsx accordingly.
2025-11-11 20:13:32 +00:00
gpt-engineer-app[bot] 70fb1e9d40 Refactor test agent view
Simplify Testar Agente UI to:
- Keep agent selection at top with a single New Conversation button
- Show all conversation histories across all agents in a unified list
- Remove per-agent filtering in the history sidebar
- Retain basic chat area while consolidating history view for easier testing
2025-11-11 20:08:18 +00:00
gpt-engineer-app[bot] c1d2cf6d79 Add conversation history to Test Prompt
Implements persistent/voluminous chat history on the Testar Agente screen:
- Prepare to store and load previous conversations (localStorage) for the selected agent
- Create structure for conversations and messages
- Load existing conversations on mount and save changes
- Add support to create new conversations and load them when selected
2025-11-11 20:04:58 +00:00
gpt-engineer-app[bot] da94a7e4db Set default 6 per page
Update pagination to default to 6 items per page in Agents screen, preserving navigation controls and responsive layout.
2025-11-11 18:30:35 +00:00
gpt-engineer-app[bot] 09c8fcae88 Add more test agents for pagination
Extend Agents list with additional mock agents (20-21+) to exercise and test pagination controls, including page size options and navigation.
2025-11-11 18:29:40 +00:00
gpt-engineer-app[bot] a97a515517 Adicionar paginação em listagem de agentes
Implementa controle de paginação na tela de Agents:
- adiciona estado itemsPerPage com valor default 9
- integra seletor de itens por página
- utiliza componente de paginação existente para Navegação Previous/Next/ellipses
- mantém busca existente funcionando com paginação

Observação: usa componente Select para escolher a quantidade por página e ajusta paginação ao mudar valor.
2025-11-11 18:26:58 +00:00
gpt-engineer-app[bot] 79a65a9601 Reverted to commit 6c23bea1bc 2025-11-11 15:24:37 +00:00
15 changed files with 1414 additions and 307 deletions
+3
View File
@@ -0,0 +1,3 @@
VITE_ESTABELECIMENTO_ID=27
VITE_USER_EMAIL=your-email@example.com
VITE_API_BASE_URL=https://prod-hgtx-intelligence-n8n.hgtx.com.br
+4
View File
@@ -12,6 +12,10 @@ dist
dist-ssr
*.local
# Environment variables
.env
.env.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
+259
View File
@@ -37,6 +37,7 @@
"@radix-ui/react-toggle-group": "^1.1.10",
"@radix-ui/react-tooltip": "^1.2.7",
"@tanstack/react-query": "^5.83.0",
"axios": "^1.13.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@@ -3324,6 +3325,12 @@
"node": ">=10"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"license": "MIT"
},
"node_modules/autoprefixer": {
"version": "10.4.21",
"resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.21.tgz",
@@ -3362,6 +3369,17 @@
"postcss": "^8.1.0"
}
},
"node_modules/axios": {
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.13.2.tgz",
"integrity": "sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -3436,6 +3454,19 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@@ -3583,6 +3614,18 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"license": "MIT",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/commander": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
@@ -3792,6 +3835,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/detect-node-es": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz",
@@ -3820,6 +3872,20 @@
"csstype": "^3.0.2"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
@@ -3867,6 +3933,51 @@
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
"license": "MIT"
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-set-tostringtag": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/esbuild": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
@@ -4253,6 +4364,26 @@
"dev": true,
"license": "ISC"
},
"node_modules/follow-redirects": {
"version": "1.15.11",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"license": "MIT",
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/foreground-child": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz",
@@ -4269,6 +4400,22 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/form-data": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/fraction.js": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
@@ -4306,6 +4453,30 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-nonce": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz",
@@ -4315,6 +4486,19 @@
"node": ">=6"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/glob": {
"version": "10.4.5",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
@@ -4384,6 +4568,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/graphemer": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
@@ -4401,6 +4597,33 @@
"node": ">=8"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-tostringtag": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"license": "MIT",
"dependencies": {
"has-symbols": "^1.0.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
@@ -5174,6 +5397,15 @@
"@jridgewell/sourcemap-codec": "^1.5.0"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
@@ -5196,6 +5428,27 @@
"node": ">=8.6"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -5631,6 +5884,12 @@
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
"license": "MIT"
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+1
View File
@@ -40,6 +40,7 @@
"@radix-ui/react-toggle-group": "^1.1.10",
"@radix-ui/react-tooltip": "^1.2.7",
"@tanstack/react-query": "^5.83.0",
"axios": "^1.13.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
+47 -28
View File
@@ -1,5 +1,6 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
Dialog,
DialogContent,
@@ -18,6 +19,8 @@ import {
SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { createAgent } from "@/lib/api/agents";
import { AI_MODELS, getModelIdByValue } from "@/lib/constants/aiModels";
interface CreateAgentDialogProps {
open: boolean;
@@ -27,36 +30,52 @@ interface CreateAgentDialogProps {
export function CreateAgentDialog({ open, onOpenChange }: CreateAgentDialogProps) {
const navigate = useNavigate();
const { toast } = useToast();
const queryClient = useQueryClient();
const [name, setName] = useState("");
const [selectedModel, setSelectedModel] = useState("");
const aiModels = [
{ value: "google/gemini-2.5-pro", label: "Google Gemini 2.5 Pro" },
{ value: "google/gemini-2.5-flash", label: "Google Gemini 2.5 Flash" },
{ value: "google/gemini-2.5-flash-lite", label: "Google Gemini 2.5 Flash Lite" },
{ value: "openai/gpt-5", label: "OpenAI GPT-5" },
{ value: "openai/gpt-5-mini", label: "OpenAI GPT-5 Mini" },
{ value: "openai/gpt-5-nano", label: "OpenAI GPT-5 Nano" },
];
const createAgentMutation = useMutation({
mutationFn: ({ name, modelId }: { name: string; modelId: number }) =>
createAgent(name, modelId),
onSuccess: (data) => {
toast({
title: "Agente criado",
description: `${data.agent_name} foi criado com sucesso.`,
});
// Invalidate agents query to refetch the list
queryClient.invalidateQueries({ queryKey: ["agents"] });
onOpenChange(false);
// Navegar para a tela de detalhes do novo agente
navigate(`/agents/${data.agent_id}`);
// Reset form
setName("");
setSelectedModel("");
},
onError: (error: any) => {
toast({
title: "Erro ao criar agente",
description: error.response?.data?.message || "Ocorreu um erro ao criar o agente.",
variant: "destructive",
});
},
});
const handleCreate = () => {
// TODO: Implementar criação no backend
const newAgentId = Math.floor(Math.random() * 10000); // Gerar ID temporário
console.log("Criando agente:", { name, model: selectedModel });
const modelId = getModelIdByValue(selectedModel);
if (!modelId) {
toast({
title: "Erro",
description: "Modelo de IA inválido.",
variant: "destructive",
});
return;
}
toast({
title: "Agente criado",
description: "O agente foi criado com sucesso.",
});
onOpenChange(false);
// Navegar para a tela de detalhes do novo agente
navigate(`/agents/${newAgentId}`);
// Reset form
setName("");
setSelectedModel("");
createAgentMutation.mutate({ name, modelId });
};
return (
@@ -87,9 +106,9 @@ export function CreateAgentDialog({ open, onOpenChange }: CreateAgentDialogProps
<SelectValue placeholder="Selecione um modelo" />
</SelectTrigger>
<SelectContent>
{aiModels.map((model) => (
{AI_MODELS.map((model) => (
<SelectItem key={model.value} value={model.value}>
{model.label}
{model.name}
</SelectItem>
))}
</SelectContent>
@@ -102,9 +121,9 @@ export function CreateAgentDialog({ open, onOpenChange }: CreateAgentDialogProps
</Button>
<Button
onClick={handleCreate}
disabled={!name || !selectedModel}
disabled={!name || !selectedModel || createAgentMutation.isPending}
>
Criar Agente
{createAgentMutation.isPending ? "Criando..." : "Criar Agente"}
</Button>
</div>
</div>
+150
View File
@@ -0,0 +1,150 @@
import api from "./axios";
import type {
Agent,
AgentDetails,
AgentVersion,
CreateAgentRequest,
CreateAgentResponse,
EditAgentRequest,
EditAgentResponse,
EditAgentNameRequest,
EditAgentNameResponse,
ToggleAgentStatusRequest,
ToggleAgentStatusResponse,
ListAgentsResponse,
} from "../types/agent";
const estabelecimentoId = import.meta.env.VITE_ESTABELECIMENTO_ID;
const userEmail = import.meta.env.VITE_USER_EMAIL;
/**
* Cria um novo agente
*/
export const createAgent = async (
nome: string,
model_id: number
): Promise<CreateAgentResponse> => {
const payload: CreateAgentRequest = {
estabelecimento_id: Number(estabelecimentoId),
user_email: userEmail,
nome,
model_id,
};
const response = await api.post<CreateAgentResponse>(
"/webhook/promptlab/agente",
payload
);
return response.data;
};
/**
* Lista todos os agentes de um estabelecimento
*/
export const listAgents = async (
name?: string,
page: number = 1,
per_page: number = 6
): Promise<ListAgentsResponse> => {
const params = new URLSearchParams({
page: page.toString(),
per_page: per_page.toString(),
});
if (name) {
params.append("name", name);
}
const response = await api.get<ListAgentsResponse>(
`/webhook/9041673e-cc46-4e3c-9127-6b5000efcc2d/promptlab/agentes/${estabelecimentoId}?${params.toString()}`
);
return response.data;
};
/**
* Obtém detalhes de um agente específico
*/
export const getAgentDetails = async (
agente_id: string
): Promise<AgentDetails> => {
const response = await api.get<AgentDetails[]>(
`/webhook/54eb2d09-6d59-4abe-89c9-661b12de5608/promptlab/detalhes-agente/${agente_id}`
);
// A API retorna um array, mas só tem um elemento
return response.data[0];
};
/**
* Edita um agente (cria uma nova versão)
*/
export const editAgent = async (
agent_id: string,
model_id: number,
system_prompt: string,
version_type: "major" | "minor" | "patch",
notes: string
): Promise<EditAgentResponse> => {
const payload: EditAgentRequest = {
user_email: userEmail,
model_id,
system_prompt,
version_type,
notes,
};
const response = await api.put<EditAgentResponse>(
`/webhook/ef647dd5-6ebd-4e8e-83a3-c867595f4f8e/promptlab/agente/${agent_id}/edit`,
payload
);
return response.data;
};
/**
* Edita apenas o nome do agente
*/
export const editAgentName = async (
agent_id: string,
nome: string
): Promise<EditAgentNameResponse> => {
const payload: EditAgentNameRequest = {
nome,
user_email: userEmail,
};
const response = await api.put<EditAgentNameResponse>(
`/webhook/6c95305b-07e7-4a6f-aa64-e60f1f19ae54/promptlab/agente/${agent_id}/nome`,
payload
);
return response.data;
};
/**
* Alterna o status do agente (ativo/inativo)
*/
export const toggleAgentStatus = async (
agent_id: string,
status: "ativo" | "inativo"
): Promise<ToggleAgentStatusResponse> => {
const payload: ToggleAgentStatusRequest = {
status,
user_email: userEmail,
};
const response = await api.put<ToggleAgentStatusResponse>(
`/webhook/6c95305b-07e7-4a6f-aa64-e60f1f19ae54/promptlab/agente/${agent_id}/status`,
payload
);
return response.data;
};
/**
* Obtém o histórico de versões de um agente
*/
export const getAgentVersions = async (
agent_id: string
): Promise<AgentVersion[]> => {
const response = await api.get<AgentVersion[]>(
`/webhook/c7296b1d-e1d9-4cad-bbf4-2041281f3f47/promptlab/agente/${agent_id}/versions`
);
return response.data;
};
+35
View File
@@ -0,0 +1,35 @@
import axios from "axios";
const api = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
headers: {
"Content-Type": "application/json",
},
});
// Interceptor para adicionar credenciais em todas as requisições
api.interceptors.request.use((config) => {
// As credenciais são enviadas no body de acordo com a API N8N
return config;
});
// Interceptor para tratamento de erros
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response) {
// O servidor respondeu com um código de status fora do range 2xx
console.error("API Error:", error.response.data);
console.error("Status:", error.response.status);
} else if (error.request) {
// A requisição foi feita mas não houve resposta
console.error("Network Error:", error.request);
} else {
// Algo aconteceu ao configurar a requisição
console.error("Error:", error.message);
}
return Promise.reject(error);
}
);
export default api;
+63
View File
@@ -0,0 +1,63 @@
import api from "./axios";
import type {
Chat,
ChatMessage,
TestAgentRequest,
TestAgentResponse,
} from "../types/chat";
const estabelecimentoId = import.meta.env.VITE_ESTABELECIMENTO_ID;
const userEmail = import.meta.env.VITE_USER_EMAIL;
/**
* Envia uma mensagem para testar um agente
*/
export const testAgent = async (
agent_id: string,
chat_id: string,
message: string
): Promise<TestAgentResponse> => {
const payload: TestAgentRequest = {
estabelecimento_id: Number(estabelecimentoId),
user_email: userEmail,
chat_id,
message,
};
const response = await api.post<TestAgentResponse>(
`/webhook/2c06f0b6-af09-4826-82dd-d1fc9fcd8227/promptlab/agente/${agent_id}/test`,
payload
);
return response.data;
};
/**
* Lista todos os chats de teste de um usuário
*/
export const listChats = async (): Promise<Chat[]> => {
const response = await api.get<Chat[]>(
`/webhook/29b613e6-92dd-4922-a1a7-b1d54238c271/promptlab/listar-agente-chats/${estabelecimentoId}/${encodeURIComponent(
userEmail
)}`
);
return response.data;
};
/**
* Lista todas as mensagens de um chat específico
*/
export const listMessages = async (chat_id: string): Promise<ChatMessage[]> => {
const response = await api.get<ChatMessage[]>(
`/webhook/eb7aff49-8b7e-488b-ab79-3e52bd51c1f6/promptlab/messages/${chat_id}`
);
return response.data;
};
/**
* Deleta um chat (soft delete)
*/
export const deleteChat = async (chat_id: string): Promise<void> => {
await api.delete(
`/webhook/8099ad7b-0879-4249-8b2a-fb8e1f243772/promptlab/agente-chat/${chat_id}`
);
};
+33
View File
@@ -0,0 +1,33 @@
import { AIModel } from "../types/agent";
// Mapeamento de modelos de IA conforme a API
// Nota: Os IDs precisam ser confirmados com a API real
export const AI_MODELS: AIModel[] = [
{ id: 1, name: "Google Gemini 2.5 Pro", value: "google/gemini-2.5-pro" },
{ id: 2, name: "Google Gemini 2.5 Flash", value: "google/gemini-2.5-flash" },
{ id: 3, name: "Google Gemini 2.5 Flash Lite", value: "google/gemini-2.5-flash-lite" },
{ id: 4, name: "OpenAI GPT-5", value: "openai/gpt-5" },
{ id: 5, name: "OpenAI GPT-5 Mini", value: "openai/gpt-5-mini" },
{ id: 6, name: "OpenAI GPT-5 Nano", value: "openai/gpt-5-nano" },
{ id: 7, name: "Anthropic Claude Sonnet 4.5", value: "anthropic/claude-sonnet-4.5" },
{ id: 8, name: "Anthropic Claude Haiku 4.5", value: "anthropic/claude-haiku-4.5" },
{ id: 9, name: "Anthropic Claude Opus 4.5", value: "anthropic/claude-opus-4.5" },
{ id: 10, name: "Claude Haiku 4.5", value: "claude/haiku-4.5" },
];
// Função auxiliar para obter o nome do modelo pelo ID
export const getModelNameById = (id: number): string => {
const model = AI_MODELS.find((m) => m.id === id);
return model?.name || "Modelo Desconhecido";
};
// Função auxiliar para obter o modelo pelo value
export const getModelByValue = (value: string): AIModel | undefined => {
return AI_MODELS.find((m) => m.value === value);
};
// Função auxiliar para obter o ID pelo value
export const getModelIdByValue = (value: string): number | undefined => {
const model = getModelByValue(value);
return model?.id;
};
+120
View File
@@ -0,0 +1,120 @@
export interface Agent {
agente_id: string;
nome_agente: string;
versao_agente: string;
modelo_ia: string;
status: "ativo" | "inativo";
created_at: string;
}
export interface AgentDetails {
id: string;
estabelecimento_id: number;
model_id: number;
name: string;
system_prompt: string;
status: "ativo" | "inativo";
version_id: string;
created_by: string;
updated_by: string;
created_at: string;
updated_at: string;
}
export interface AgentVersion {
versao_id: string;
numero_versao: string;
notas_versao: string;
modelo_ia_nome: string;
system_prompt: string;
criado_por: string;
data_criacao: string;
}
export interface CreateAgentRequest {
estabelecimento_id: number;
user_email: string;
nome: string;
model_id: number;
}
export interface CreateAgentResponse {
success: boolean;
agent_id: string;
agent_name: string;
version_id: string;
version_number: string;
version_type: string;
model_id: string;
system_prompt: string;
}
export interface EditAgentRequest {
user_email: string;
model_id: number;
system_prompt: string;
version_type: "major" | "minor" | "patch";
notes: string;
}
export interface EditAgentResponse {
success: boolean;
agent_id: string;
agent_name: string;
version_id: string;
version_number: string;
version_type: string;
model_id: string;
system_prompt: string;
}
export interface EditAgentNameRequest {
nome: string;
user_email: string;
}
export interface EditAgentNameResponse {
success: boolean;
agent_id: string;
estabelecimento_id: string;
agent_name: string;
model_id: string;
status: string;
updated_by: string;
updated_at: string;
}
export interface ToggleAgentStatusRequest {
status: "ativo" | "inativo";
user_email: string;
}
export interface ToggleAgentStatusResponse {
success: boolean;
agent_id: string;
estabelecimento_id: string;
model_id: string;
agent_name: string;
system_prompt: string;
status: "ativo" | "inativo";
version_id: string;
created_by: string;
updated_by: string;
created_at: string;
updated_at: string;
}
export interface ListAgentsResponse {
success: boolean;
page: number;
per_page: number;
total: number;
total_pages: number;
data: Agent[];
}
export interface AIModel {
id: number;
name: string;
value: string;
}
+35
View File
@@ -0,0 +1,35 @@
export interface ChatMessage {
id: string;
agent_chat_id: string;
role: "user" | "assistant";
content: string;
input_tokens: number;
output_tokens: number;
total_tokens: number;
cost_usd: string;
created_at: string;
}
export interface Chat {
id: string;
agent_id: string;
estabelecimento_id: number;
user_email: string;
title: string;
created_at: string;
updated_at: string;
deleted_at: string | null;
}
export interface TestAgentRequest {
estabelecimento_id: number;
user_email: string;
chat_id: string;
message: string;
}
export interface TestAgentResponse {
success: boolean;
chat_id: string;
response: string;
}
+16 -1
View File
@@ -1,5 +1,20 @@
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App.tsx";
import "./index.css";
createRoot(document.getElementById("root")!).render(<App />);
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000, // 5 minutos
},
},
});
createRoot(document.getElementById("root")!).render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
+250 -94
View File
@@ -1,11 +1,12 @@
import { useState } from "react";
import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ArrowLeft, Save, History, Power } from "lucide-react";
import { ArrowLeft, Save, History, Power, Pencil, Check, X, Loader2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { VersionHistoryDialog } from "@/components/agents/VersionHistoryDialog";
import { SaveVersionDialog } from "@/components/agents/SaveVersionDialog";
@@ -20,103 +21,213 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
getAgentDetails,
editAgent,
editAgentName,
toggleAgentStatus,
getAgentVersions,
} from "@/lib/api/agents";
import { AI_MODELS, getModelIdByValue } from "@/lib/constants/aiModels";
export default function AgentDetails() {
const { id } = useParams();
const navigate = useNavigate();
const { toast } = useToast();
const queryClient = useQueryClient();
const [isHistoryOpen, setIsHistoryOpen] = useState(false);
const [isSaveVersionOpen, setIsSaveVersionOpen] = useState(false);
const [isDeactivateDialogOpen, setIsDeactivateDialogOpen] = useState(false);
const [isEditingName, setIsEditingName] = useState(false);
const [tempName, setTempName] = useState("");
const [selectedModel, setSelectedModel] = useState("");
const [systemPrompt, setSystemPrompt] = useState("");
// Mock data - substituir por dados reais do backend
const [agent, setAgent] = useState<{
id: string | undefined;
name: string;
status: "active" | "inactive";
model: string;
systemPrompt: string;
}>({
id: id,
name: "Agente de Atendimento",
status: "active",
model: "google/gemini-2.5-flash",
systemPrompt: "Você é um assistente de atendimento ao cliente. Seja educado, prestativo e objetivo nas suas respostas. Sempre mantenha um tom profissional e cordial.",
// Fetch agent details
const {
data: agentDetails,
isLoading,
isError,
refetch,
} = useQuery({
queryKey: ["agent", id],
queryFn: () => getAgentDetails(id!),
enabled: !!id,
});
const [versions] = useState([
{
id: 1,
version: "2.1",
type: "major" as const,
description: "Melhorias na clareza das respostas",
model: "Google Gemini 2.5 Flash",
prompt: "Você é um assistente de atendimento ao cliente. Seja educado, prestativo e objetivo nas suas respostas. Sempre mantenha um tom profissional e cordial.",
createdAt: "2024-01-15 14:30",
author: "João Silva",
},
{
id: 2,
version: "2.0",
type: "major" as const,
description: "Reformulação completa do prompt",
model: "Google Gemini 2.5 Pro",
prompt: "Você é um assistente de atendimento. Seja cordial e ajude o cliente.",
createdAt: "2024-01-10 09:15",
author: "Maria Santos",
},
{
id: 3,
version: "1.5",
type: "minor" as const,
description: "Ajustes de tom",
model: "OpenAI GPT-5 Mini",
prompt: "Você é um assistente. Seja educado.",
createdAt: "2024-01-05 16:45",
author: "João Silva",
},
]);
// Fetch agent versions for history
const {
data: versions,
isLoading: isLoadingVersions,
} = useQuery({
queryKey: ["agent-versions", id],
queryFn: () => getAgentVersions(id!),
enabled: !!id && isHistoryOpen,
});
const aiModels = [
{ value: "google/gemini-2.5-pro", label: "Google Gemini 2.5 Pro" },
{ value: "google/gemini-2.5-flash", label: "Google Gemini 2.5 Flash" },
{ value: "google/gemini-2.5-flash-lite", label: "Google Gemini 2.5 Flash Lite" },
{ value: "openai/gpt-5", label: "OpenAI GPT-5" },
{ value: "openai/gpt-5-mini", label: "OpenAI GPT-5 Mini" },
{ value: "openai/gpt-5-nano", label: "OpenAI GPT-5 Nano" },
];
// Update local state when agent details are loaded
useEffect(() => {
if (agentDetails) {
const model = AI_MODELS.find((m) => m.id === agentDetails.model_id);
setSelectedModel(model?.value || "");
setSystemPrompt(agentDetails.system_prompt);
setTempName(agentDetails.name);
}
}, [agentDetails]);
// Edit agent mutation (save new version)
const editAgentMutation = useMutation({
mutationFn: ({
model_id,
system_prompt,
version_type,
notes,
}: {
model_id: number;
system_prompt: string;
version_type: "major" | "minor" | "patch";
notes: string;
}) => editAgent(id!, model_id, system_prompt, version_type, notes),
onSuccess: (data) => {
toast({
title: "Agente atualizado",
description: `Nova versão ${data.version_type} salva com sucesso.`,
});
queryClient.invalidateQueries({ queryKey: ["agent", id] });
queryClient.invalidateQueries({ queryKey: ["agent-versions", id] });
},
onError: (error: any) => {
toast({
title: "Erro ao atualizar agente",
description: error.response?.data?.message || "Ocorreu um erro ao atualizar o agente.",
variant: "destructive",
});
},
});
// Edit agent name mutation
const editNameMutation = useMutation({
mutationFn: (nome: string) => editAgentName(id!, nome),
onSuccess: () => {
toast({
title: "Nome atualizado",
description: "O nome do agente foi alterado com sucesso.",
});
queryClient.invalidateQueries({ queryKey: ["agent", id] });
queryClient.invalidateQueries({ queryKey: ["agents"] });
setIsEditingName(false);
},
onError: (error: any) => {
toast({
title: "Erro ao atualizar nome",
description: error.response?.data?.message || "Ocorreu um erro ao atualizar o nome.",
variant: "destructive",
});
},
});
// Toggle status mutation
const toggleStatusMutation = useMutation({
mutationFn: (status: "ativo" | "inativo") => toggleAgentStatus(id!, status),
onSuccess: (data) => {
toast({
title: "Status atualizado",
description: `Agente ${data.status === "ativo" ? "ativado" : "desativado"} com sucesso.`,
});
queryClient.invalidateQueries({ queryKey: ["agent", id] });
queryClient.invalidateQueries({ queryKey: ["agents"] });
setIsDeactivateDialogOpen(false);
},
onError: (error: any) => {
toast({
title: "Erro ao atualizar status",
description: error.response?.data?.message || "Ocorreu um erro ao atualizar o status.",
variant: "destructive",
});
},
});
const handleSave = (versionType: "major" | "minor" | "patch", notes: string) => {
// TODO: Implementar salvamento no backend
console.log("Saving agent:", agent, "Version type:", versionType, "Notes:", notes);
toast({
title: "Agente atualizado",
description: `Nova versão ${versionType} salva com sucesso.`,
const modelId = getModelIdByValue(selectedModel);
if (!modelId) {
toast({
title: "Erro",
description: "Modelo de IA inválido.",
variant: "destructive",
});
return;
}
editAgentMutation.mutate({
model_id: modelId,
system_prompt: systemPrompt,
version_type: versionType,
notes,
});
};
const handleToggleStatus = () => {
if (agent.status === "active") {
if (agentDetails?.status === "ativo") {
setIsDeactivateDialogOpen(true);
} else {
// Ativar diretamente sem modal
setAgent({ ...agent, status: "active" });
toast({
title: "Status atualizado",
description: "Agente ativado com sucesso.",
});
toggleStatusMutation.mutate("ativo");
}
};
const handleConfirmDeactivate = () => {
setAgent({ ...agent, status: "inactive" });
toast({
title: "Status atualizado",
description: "Agente desativado com sucesso. Esta ação foi registrada.",
});
setIsDeactivateDialogOpen(false);
toggleStatusMutation.mutate("inativo");
};
const handleStartEditName = () => {
setTempName(agentDetails?.name || "");
setIsEditingName(true);
};
const handleSaveName = () => {
if (tempName.trim()) {
editNameMutation.mutate(tempName.trim());
}
};
const handleCancelEditName = () => {
setIsEditingName(false);
setTempName(agentDetails?.name || "");
};
// Format versions for the history dialog
const formattedVersions = versions?.map((v, index) => ({
id: index + 1,
version: v.numero_versao,
type: (v.notas_versao.toLowerCase().includes("major")
? "major"
: v.notas_versao.toLowerCase().includes("minor")
? "minor"
: "patch") as "major" | "minor" | "patch",
description: v.notas_versao,
model: v.modelo_ia_nome,
prompt: v.system_prompt,
createdAt: v.data_criacao,
author: v.criado_por,
})) || [];
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-[50vh]">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
);
}
if (isError || !agentDetails) {
return (
<div className="text-center py-12">
<p className="text-destructive mb-4">Erro ao carregar detalhes do agente.</p>
<Button onClick={() => refetch()} variant="outline">
Tentar novamente
</Button>
</div>
);
}
return (
<div className="animate-fade-in pb-8">
@@ -133,21 +244,58 @@ export default function AgentDetails() {
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-3">
<Input
value={agent.name}
onChange={(e) => setAgent({ ...agent, name: e.target.value })}
className="text-2xl md:text-3xl font-bold h-auto py-2 max-w-md"
placeholder="Nome do agente"
/>
{isEditingName ? (
<div className="flex items-center gap-2">
<Input
value={tempName}
onChange={(e) => setTempName(e.target.value)}
className="text-2xl md:text-3xl font-bold h-auto py-1"
onKeyDown={(e) => {
if (e.key === "Enter") handleSaveName();
if (e.key === "Escape") handleCancelEditName();
}}
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleSaveName}
disabled={editNameMutation.isPending}
>
<Check className="h-4 w-4 text-green-600" />
</Button>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCancelEditName}
>
<X className="h-4 w-4" />
</Button>
</div>
) : (
<>
<h1 className="text-2xl md:text-3xl font-bold text-foreground">{agentDetails.name}</h1>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleStartEditName}
>
<Pencil className="h-4 w-4" />
</Button>
</>
)}
<Badge
variant={agent.status === "active" ? "default" : "secondary"}
variant={agentDetails.status === "ativo" ? "default" : "secondary"}
className={
agent.status === "active"
agentDetails.status === "ativo"
? "bg-green-600 hover:bg-green-700 text-white"
: "bg-muted text-muted-foreground"
}
>
{agent.status === "active" ? "● Ativo" : "○ Inativo"}
{agentDetails.status === "ativo" ? "● Ativo" : "○ Inativo"}
</Badge>
</div>
@@ -162,12 +310,17 @@ export default function AgentDetails() {
<span className="sm:hidden">Histórico</span>
</Button>
<Button
variant={agent.status === "active" ? "destructive" : "default"}
className={agent.status === "active" ? "gap-2" : "gap-2 bg-green-600 hover:bg-green-700 text-white"}
variant={agentDetails.status === "ativo" ? "destructive" : "default"}
className={agentDetails.status === "ativo" ? "gap-2" : "gap-2 bg-green-600 hover:bg-green-700 text-white"}
onClick={handleToggleStatus}
disabled={toggleStatusMutation.isPending}
>
<Power className="h-4 w-4" />
{agent.status === "active" ? "Desativar" : "Ativar"}
{toggleStatusMutation.isPending
? "Processando..."
: agentDetails.status === "ativo"
? "Desativar"
: "Ativar"}
</Button>
<Button className="gap-2" onClick={() => setIsSaveVersionOpen(true)}>
<Save className="h-4 w-4" />
@@ -188,16 +341,16 @@ export default function AgentDetails() {
</CardHeader>
<CardContent>
<Select
value={agent.model}
onValueChange={(value) => setAgent({ ...agent, model: value })}
value={selectedModel}
onValueChange={setSelectedModel}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{aiModels.map((model) => (
{AI_MODELS.map((model) => (
<SelectItem key={model.value} value={model.value}>
{model.label}
{model.name}
</SelectItem>
))}
</SelectContent>
@@ -215,8 +368,8 @@ export default function AgentDetails() {
</CardHeader>
<CardContent>
<Textarea
value={agent.systemPrompt}
onChange={(e) => setAgent({ ...agent, systemPrompt: e.target.value })}
value={systemPrompt}
onChange={(e) => setSystemPrompt(e.target.value)}
className="min-h-[300px] font-mono text-sm"
placeholder="Digite o prompt do sistema..."
/>
@@ -227,8 +380,8 @@ export default function AgentDetails() {
<VersionHistoryDialog
open={isHistoryOpen}
onOpenChange={setIsHistoryOpen}
agentName={agent.name}
versions={versions}
agentName={agentDetails.name}
versions={formattedVersions}
/>
<SaveVersionDialog
@@ -247,7 +400,10 @@ export default function AgentDetails() {
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction onClick={handleConfirmDeactivate} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
<AlertDialogAction
onClick={handleConfirmDeactivate}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Desativar
</AlertDialogAction>
</AlertDialogFooter>
+93 -60
View File
@@ -1,5 +1,6 @@
import { useState } from "react";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { CreateAgentDialog } from "@/components/agents/CreateAgentDialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -14,57 +15,55 @@ import {
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
import { Plus, Search, Bot, ChevronRight } from "lucide-react";
import { Plus, Search, Bot, ChevronRight, Loader2 } from "lucide-react";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { listAgents } from "@/lib/api/agents";
export default function Agents() {
const navigate = useNavigate();
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 9;
const [itemsPerPage, setItemsPerPage] = useState(6);
const [agents] = useState([
{
id: 1,
name: "Agente de Atendimento",
status: "active" as const,
version: "2.1",
model: "Google Gemini 2.5 Flash",
createdAt: "2 dias atrás",
},
{
id: 2,
name: "Agente de Vendas",
status: "active" as const,
version: "1.5",
model: "OpenAI GPT-5",
createdAt: "5 dias atrás",
},
{
id: 3,
name: "Agente de Análise",
status: "inactive" as const,
version: "1.0",
model: "Anthropic Claude Sonnet 4.5",
createdAt: "1 semana atrás",
},
]);
// Debounce search query
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedSearch(searchQuery);
setCurrentPage(1); // Reset to first page on search
}, 500);
const filteredAgents = agents.filter(agent =>
agent.name.toLowerCase().includes(searchQuery.toLowerCase())
);
return () => {
clearTimeout(handler);
};
}, [searchQuery]);
// Paginação
const totalPages = Math.ceil(filteredAgents.length / itemsPerPage);
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const paginatedAgents = filteredAgents.slice(startIndex, endIndex);
// Fetch agents from API
const {
data: agentsData,
isLoading,
isError,
refetch,
} = useQuery({
queryKey: ["agents", debouncedSearch, currentPage, itemsPerPage],
queryFn: () =>
listAgents(
debouncedSearch || undefined,
currentPage,
itemsPerPage
),
});
// Reset para primeira página quando buscar
const handleSearch = (query: string) => {
setSearchQuery(query);
setCurrentPage(1);
};
const agents = agentsData?.data || [];
const totalPages = agentsData?.total_pages || 0;
const totalAgents = agentsData?.total || 0;
return (
<div className="animate-fade-in">
@@ -87,34 +86,68 @@ export default function Agents() {
<Input
placeholder="Pesquisar agentes..."
value={searchQuery}
onChange={(e) => handleSearch(e.target.value)}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
<div className="flex items-center justify-between mt-2">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 mt-2">
<p className="text-sm text-muted-foreground">
{filteredAgents.length} {filteredAgents.length === 1 ? 'agente encontrado' : 'agentes encontrados'}
{totalAgents} {totalAgents === 1 ? 'agente encontrado' : 'agentes encontrados'}
</p>
{totalPages > 1 && (
<p className="text-sm text-muted-foreground">
Página {currentPage} de {totalPages}
</p>
)}
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground whitespace-nowrap">Itens por página:</span>
<Select
value={itemsPerPage.toString()}
onValueChange={(value) => {
setItemsPerPage(Number(value));
setCurrentPage(1);
}}
>
<SelectTrigger className="w-[70px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="6">6</SelectItem>
<SelectItem value="9">9</SelectItem>
<SelectItem value="12">12</SelectItem>
<SelectItem value="18">18</SelectItem>
<SelectItem value="24">24</SelectItem>
</SelectContent>
</Select>
</div>
{totalPages > 1 && (
<p className="text-sm text-muted-foreground">
Página {currentPage} de {totalPages}
</p>
)}
</div>
</div>
</div>
{filteredAgents.length === 0 ? (
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
) : isError ? (
<div className="text-center py-12">
<p className="text-destructive mb-4">Erro ao carregar agentes.</p>
<Button onClick={() => refetch()} variant="outline">
Tentar novamente
</Button>
</div>
) : agents.length === 0 ? (
<div className="text-center py-12">
<p className="text-muted-foreground">Nenhum agente encontrado.</p>
</div>
) : (
<>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{paginatedAgents.map((agent) => (
{agents.map((agent) => (
<Card
key={agent.id}
key={agent.agente_id}
className="group relative overflow-hidden border-2 transition-all duration-300 hover:shadow-lg hover:scale-[1.02] bg-gradient-to-br from-card to-card/50 cursor-pointer"
onClick={() => navigate(`/agents/${agent.id}`)}
onClick={() => navigate(`/agents/${agent.agente_id}`)}
>
{/* Glow effect on hover */}
<div className="absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-primary/5 opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
@@ -126,10 +159,10 @@ export default function Agents() {
<Bot className="h-7 w-7 text-primary" />
</div>
<div className="flex-1 min-w-0">
<CardTitle className="text-xl truncate">{agent.name}</CardTitle>
<CardTitle className="text-xl truncate">{agent.nome_agente}</CardTitle>
<div className="flex items-center gap-2 mt-1">
<Badge variant="outline" className="text-xs">
v{agent.version}
v{agent.versao_agente}
</Badge>
</div>
</div>
@@ -143,20 +176,20 @@ export default function Agents() {
<CardContent className="relative space-y-3">
<div className="p-3 rounded-lg bg-muted/50">
<p className="text-xs text-muted-foreground mb-2">Modelo de IA</p>
<p className="text-sm font-medium">{agent.model}</p>
<p className="text-sm font-medium">{agent.modelo_ia}</p>
</div>
<div className="flex items-center justify-between pt-2 border-t">
<span className="text-xs text-muted-foreground">Status</span>
<Badge
variant={agent.status === "active" ? "default" : "secondary"}
variant={agent.status === "ativo" ? "default" : "secondary"}
className={
agent.status === "active"
agent.status === "ativo"
? "bg-green-600 hover:bg-green-700 shadow-sm"
: "bg-muted text-muted-foreground hover:bg-muted"
}
>
{agent.status === "active" ? "● Ativo" : "○ Inativo"}
{agent.status === "ativo" ? "● Ativo" : "○ Inativo"}
</Badge>
</div>
</CardContent>
+293 -112
View File
@@ -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 } from "lucide-react";
import { Send, Bot, User, MessageSquare, Plus, Trash2, Loader2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import {
Select,
@@ -13,62 +14,145 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
type Message = {
id: string;
role: "user" | "assistant";
content: 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<Message[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [selectedAgent, setSelectedAgent] = useState("");
const [currentChatId, setCurrentChatId] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(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
});
// Filter only active agents
const agents =
agentsData?.data
.filter((agent) => agent.status === "ativo")
.map((agent) => ({
id: agent.agente_id,
name: agent.nome_agente,
})) || [];
// 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;
}
}, [messages]);
// Limpa a conversa ao trocar de agente
useEffect(() => {
setMessages([]);
}, [selectedAgent]);
const handleNewConversation = () => {
if (!selectedAgent) return;
// 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 = (chatId: string) => {
const chat = chats.find((c) => c.id === chatId);
if (chat) {
setCurrentChatId(chatId);
setSelectedAgent(chat.agent_id);
}
};
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";
setMessages((prev) => [...prev, userMessage]);
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.",
};
setMessages((prev) => [...prev, aiMessage]);
setIsLoading(false);
}, 1500);
sendMessageMutation.mutate({
agentId: selectedAgent,
chatId,
message,
});
};
const handleKeyPress = (e: React.KeyboardEvent) => {
@@ -78,34 +162,104 @@ export default function TestPrompt() {
}
};
const handleClearChat = () => {
setMessages([]);
toast({
title: "Conversa limpa",
description: "O histórico de mensagens foi limpo com sucesso.",
});
const handleDeleteConversation = (chatId: string) => {
deleteChatMutation.mutate(chatId);
};
return (
<div className="animate-fade-in h-full flex flex-col max-w-5xl mx-auto">
<div className="mb-4 md:mb-6">
<h1 className="text-2xl md:text-3xl font-bold text-foreground mb-2">Testar Agente</h1>
<p className="text-sm md:text-base text-muted-foreground">
Converse com o agente para testar seu comportamento
</p>
</div>
<Card className="flex-1 flex flex-col overflow-hidden">
{/* Selector de Agente */}
<div className="animate-fade-in h-full flex gap-4">
{/* Sidebar com todas as conversas */}
<Card className="w-80 flex-shrink-0 flex flex-col overflow-hidden">
<div className="p-4 border-b border-border">
<div className="flex items-end justify-between gap-4">
<h2 className="font-semibold text-foreground">Histórico de Conversas</h2>
</div>
<ScrollArea className="flex-1">
{isLoadingChats ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-primary" />
</div>
) : (
<div className="p-2 space-y-1">
{chats.length === 0 ? (
<div className="text-center py-8 text-muted-foreground text-sm">
Nenhuma conversa ainda
</div>
) : (
chats.map((chat) => (
<div
key={chat.id}
className={`group relative rounded-lg transition-colors ${
currentChatId === chat.id
? "bg-primary/10 border border-primary/20"
: "hover:bg-muted"
}`}
>
<button
onClick={() => handleSelectConversation(chat.id)}
className="w-full text-left p-3"
>
<div className="flex items-start gap-2 pr-8">
<MessageSquare className="h-4 w-4 mt-1 flex-shrink-0 text-muted-foreground" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{chat.title}
</p>
<div className="flex items-center gap-2 mt-1">
<span className="text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground truncate max-w-[150px]">
{agents.find((a) => a.id === chat.agent_id)?.name || "Agente"}
</span>
<p className="text-xs text-muted-foreground">
{new Date(chat.created_at).toLocaleDateString("pt-BR")}
</p>
</div>
</div>
</div>
</button>
<Button
variant="ghost"
size="icon"
onClick={(e) => {
e.stopPropagation();
handleDeleteConversation(chat.id);
}}
className="absolute right-2 top-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity hover:bg-muted/50"
disabled={deleteChatMutation.isPending}
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
))
)}
</div>
)}
</ScrollArea>
</Card>
{/* Área principal do chat */}
<Card className="flex-1 flex flex-col overflow-hidden">
{/* Header */}
<div className="p-4 border-b border-border">
<div className="flex items-center gap-4">
<div className="flex-1">
<Label htmlFor="agent-select" className="mb-2 block">
<Label htmlFor="agent-select" className="mb-2 block text-sm">
Selecione o Agente
</Label>
<Select value={selectedAgent} onValueChange={setSelectedAgent}>
<Select
value={selectedAgent}
onValueChange={setSelectedAgent}
disabled={isLoadingAgents || agents.length === 0}
>
<SelectTrigger id="agent-select">
<SelectValue placeholder="Escolha um agente" />
<SelectValue
placeholder={
isLoadingAgents
? "Carregando agentes..."
: agents.length === 0
? "Nenhum agente ativo disponível"
: "Escolha um agente para conversar"
}
/>
</SelectTrigger>
<SelectContent>
{agents.map((agent) => (
@@ -116,71 +270,98 @@ export default function TestPrompt() {
</SelectContent>
</Select>
</div>
<Button
variant="outline"
size="default"
onClick={handleClearChat}
disabled={messages.length === 0}
className="gap-2"
>
<RotateCcw className="h-4 w-4" />
<span className="hidden sm:inline">Nova Conversa</span>
</Button>
<div className="pt-6">
<Button
onClick={handleNewConversation}
disabled={!selectedAgent}
className="gap-2"
>
<Plus className="h-4 w-4" />
Nova Conversa
</Button>
</div>
</div>
</div>
{/* Chat Area */}
<ScrollArea className="flex-1 p-4" ref={scrollRef}>
<div className="space-y-4">
{messages.length === 0 ? (
<div className="flex items-center justify-center h-full text-muted-foreground">
<p>Selecione um agente para começar a conversar</p>
</div>
) : (
messages.map((message) => (
<div
key={message.id}
className={`flex gap-3 ${
message.role === "user" ? "justify-end" : "justify-start"
}`}
>
{message.role === "assistant" && (
<div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
<Bot className="w-5 h-5 text-primary-foreground" />
</div>
)}
{!selectedAgent ? (
<div className="flex items-center justify-center h-full text-muted-foreground">
<p>Selecione um agente para começar a conversar</p>
</div>
) : isLoadingMessages ? (
<div className="flex items-center justify-center h-full">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
) : (
<div className="space-y-4">
{messages.length === 0 && currentChatId ? (
<div className="flex items-center justify-center h-full text-muted-foreground">
<p>Carregando mensagens...</p>
</div>
) : messages.length === 0 ? (
<div className="flex items-center justify-center h-full text-muted-foreground">
<p>Digite uma mensagem para começar a conversa!</p>
</div>
) : (
messages.map((message) => (
<div
className={`max-w-[70%] rounded-lg p-3 ${
message.role === "user"
? "bg-primary text-primary-foreground"
: "bg-muted text-foreground"
key={message.id}
className={`flex gap-3 ${
message.role === "user" ? "justify-end" : "justify-start"
}`}
>
<p className="text-sm whitespace-pre-wrap">{message.content}</p>
</div>
{message.role === "user" && (
<div className="w-8 h-8 rounded-full bg-secondary flex items-center justify-center flex-shrink-0">
<User className="w-5 h-5 text-secondary-foreground" />
{message.role === "assistant" && (
<div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
<Bot className="w-5 h-5 text-primary-foreground" />
</div>
)}
<div className="flex flex-col gap-1">
<div
className={`max-w-[70%] rounded-lg p-3 ${
message.role === "user"
? "bg-primary text-primary-foreground"
: "bg-muted text-foreground"
}`}
>
<p className="text-sm whitespace-pre-wrap">{message.content}</p>
</div>
{message.role === "assistant" && message.total_tokens > 0 && (
<div className="text-xs text-muted-foreground px-2">
{message.total_tokens} tokens ${message.cost_usd}
</div>
)}
</div>
{message.role === "user" && (
<div className="w-8 h-8 rounded-full bg-secondary flex items-center justify-center flex-shrink-0">
<User className="w-5 h-5 text-secondary-foreground" />
</div>
)}
</div>
))
)}
{sendMessageMutation.isPending && (
<div className="flex gap-3 justify-start">
<div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
<Bot className="w-5 h-5 text-primary-foreground" />
</div>
<div className="bg-muted rounded-lg p-3">
<div className="flex gap-1">
<div className="w-2 h-2 rounded-full bg-foreground/50 animate-bounce" />
<div
className="w-2 h-2 rounded-full bg-foreground/50 animate-bounce"
style={{ animationDelay: "0.1s" }}
/>
<div
className="w-2 h-2 rounded-full bg-foreground/50 animate-bounce"
style={{ animationDelay: "0.2s" }}
/>
</div>
)}
</div>
))
)}
{isLoading && (
<div className="flex gap-3 justify-start">
<div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
<Bot className="w-5 h-5 text-primary-foreground" />
</div>
<div className="bg-muted rounded-lg p-3">
<div className="flex gap-1">
<div className="w-2 h-2 rounded-full bg-foreground/50 animate-bounce" />
<div className="w-2 h-2 rounded-full bg-foreground/50 animate-bounce" style={{ animationDelay: "0.1s" }} />
<div className="w-2 h-2 rounded-full bg-foreground/50 animate-bounce" style={{ animationDelay: "0.2s" }} />
</div>
</div>
</div>
)}
</div>
)}
</div>
)}
</ScrollArea>
{/* Input Area */}
@@ -191,12 +372,12 @@ export default function TestPrompt() {
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={handleKeyPress}
disabled={isLoading || !selectedAgent}
disabled={sendMessageMutation.isPending || !selectedAgent}
className="flex-1"
/>
<Button
onClick={handleSend}
disabled={!input.trim() || isLoading || !selectedAgent}
disabled={!input.trim() || sendMessageMutation.isPending || !selectedAgent}
size="icon"
>
<Send className="h-4 w-4" />