Compare commits

..

13 Commits

Author SHA1 Message Date
developer1054 5099311373 Add favicon support and update Open Graph/Twitter meta tags 2026-01-15 10:09:21 -03:00
luisfepsale 8cc5954563 fix/modelos de IA 2025-11-19 13:21:02 -03:00
developer1054 f0b86641b6 integracao-core 2025-11-14 17:17:30 -03:00
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
29 changed files with 1956 additions and 326 deletions
+19
View File
@@ -0,0 +1,19 @@
# API Configuration
# Base URL da API do HGTX
VITE_API_BASE_URL=https://prod-hgtx-intelligence-n8n.hgtx.com.br
VITE_BASE_URL_HGTX_CORE_API=https://core-api.hgtx.com.br/api/
VITE_BASE_URL_HGTX_CORE=https://core.hgtx.com.br/
# API Key para autenticação
# IMPORTANTE: Mantenha esta chave segura e não compartilhe publicamente
VITE_API_KEY=zp01m-pmn5q-0l2eg-aj5vy
# User Configuration
# Configure com os dados do usuário/estabelecimento
VITE_USER_EMAIL=suporte@hightechx.com
VITE_ESTABELECIMENTO_ID=27
# Instruções:
# 1. Copie este arquivo para .env
# 2. Substitua os valores acima com as configurações reais
# 3. NUNCA commite o arquivo .env no git
+19
View File
@@ -0,0 +1,19 @@
# API Configuration
# Base URL da API do HGTX
VITE_API_BASE_URL=https://prod-hgtx-intelligence-n8n.hgtx.com.br
VITE_BASE_URL_HGTX_CORE_API=https://core-api.hgtx.com.br/api/
VITE_BASE_URL_HGTX_CORE=https://core.hgtx.com.br/
# API Key para autenticação
# IMPORTANTE: Mantenha esta chave segura e não compartilhe publicamente
VITE_API_KEY=zp01m-pmn5q-0l2eg-aj5vy
# User Configuration
# Configure com os dados do usuário/estabelecimento
VITE_USER_EMAIL=suporte@hightechx.com
VITE_ESTABELECIMENTO_ID=1
# Instruções:
# 1. Copie este arquivo para .env
# 2. Substitua os valores acima com as configurações reais
# 3. NUNCA commite o arquivo .env no git
+4
View File
@@ -12,6 +12,10 @@ dist
dist-ssr dist-ssr
*.local *.local
# Environment variables
.env
.env.local
# Editor directories and files # Editor directories and files
.vscode/* .vscode/*
!.vscode/extensions.json !.vscode/extensions.json
+3 -2
View File
@@ -2,6 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/x-icon" href="/ficon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HGTX PromptLab - Laboratório de Prompts de IA</title> <title>HGTX PromptLab - Laboratório de Prompts de IA</title>
<meta name="description" content="Crie, edite, teste e versione prompts para agentes de IA de forma profissional e eficiente" /> <meta name="description" content="Crie, edite, teste e versione prompts para agentes de IA de forma profissional e eficiente" />
@@ -13,11 +14,11 @@
<meta property="og:title" content="HGTX PromptLab - Laboratório de Prompts de IA" /> <meta property="og:title" content="HGTX PromptLab - Laboratório de Prompts de IA" />
<meta property="og:description" content="Crie, edite, teste e versione prompts para agentes de IA de forma profissional e eficiente" /> <meta property="og:description" content="Crie, edite, teste e versione prompts para agentes de IA de forma profissional e eficiente" />
<meta property="og:type" content="website" /> <meta property="og:type" content="website" />
<meta property="og:image" content="https://lovable.dev/opengraph-image-p98pqg.png" /> <meta property="og:image" content="/favicon.png" />
<meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@lovable_dev" /> <meta name="twitter:site" content="@lovable_dev" />
<meta name="twitter:image" content="https://lovable.dev/opengraph-image-p98pqg.png" /> <meta name="twitter:image" content="/favicon.png" />
</head> </head>
<body> <body>
+268
View File
@@ -37,12 +37,14 @@
"@radix-ui/react-toggle-group": "^1.1.10", "@radix-ui/react-toggle-group": "^1.1.10",
"@radix-ui/react-tooltip": "^1.2.7", "@radix-ui/react-tooltip": "^1.2.7",
"@tanstack/react-query": "^5.83.0", "@tanstack/react-query": "^5.83.0",
"axios": "^1.13.2",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"date-fns": "^3.6.0", "date-fns": "^3.6.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"input-otp": "^1.4.2", "input-otp": "^1.4.2",
"jwt-decode": "^4.0.0",
"lucide-react": "^0.462.0", "lucide-react": "^0.462.0",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"react": "^18.3.1", "react": "^18.3.1",
@@ -3324,6 +3326,12 @@
"node": ">=10" "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": { "node_modules/autoprefixer": {
"version": "10.4.21", "version": "10.4.21",
"resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.21.tgz", "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.21.tgz",
@@ -3362,6 +3370,17 @@
"postcss": "^8.1.0" "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": { "node_modules/balanced-match": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -3436,6 +3455,19 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" "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": { "node_modules/callsites": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@@ -3583,6 +3615,18 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT" "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": { "node_modules/commander": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
@@ -3792,6 +3836,15 @@
"dev": true, "dev": true,
"license": "MIT" "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": { "node_modules/detect-node-es": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz",
@@ -3820,6 +3873,20 @@
"csstype": "^3.0.2" "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": { "node_modules/eastasianwidth": {
"version": "0.2.0", "version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
@@ -3867,6 +3934,51 @@
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
"license": "MIT" "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": { "node_modules/esbuild": {
"version": "0.21.5", "version": "0.21.5",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
@@ -4253,6 +4365,26 @@
"dev": true, "dev": true,
"license": "ISC" "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": { "node_modules/foreground-child": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz",
@@ -4269,6 +4401,22 @@
"url": "https://github.com/sponsors/isaacs" "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": { "node_modules/fraction.js": {
"version": "4.3.7", "version": "4.3.7",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
@@ -4306,6 +4454,30 @@
"url": "https://github.com/sponsors/ljharb" "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": { "node_modules/get-nonce": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz",
@@ -4315,6 +4487,19 @@
"node": ">=6" "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": { "node_modules/glob": {
"version": "10.4.5", "version": "10.4.5",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
@@ -4384,6 +4569,18 @@
"url": "https://github.com/sponsors/sindresorhus" "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": { "node_modules/graphemer": {
"version": "1.4.0", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
@@ -4401,6 +4598,33 @@
"node": ">=8" "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": { "node_modules/hasown": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
@@ -4605,6 +4829,14 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": { "node_modules/keyv": {
"version": "4.5.4", "version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -5174,6 +5406,15 @@
"@jridgewell/sourcemap-codec": "^1.5.0" "@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": { "node_modules/merge2": {
"version": "1.4.1", "version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
@@ -5196,6 +5437,27 @@
"node": ">=8.6" "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": { "node_modules/minimatch": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@@ -5631,6 +5893,12 @@
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT" "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": { "node_modules/punycode": {
"version": "2.3.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+2
View File
@@ -40,12 +40,14 @@
"@radix-ui/react-toggle-group": "^1.1.10", "@radix-ui/react-toggle-group": "^1.1.10",
"@radix-ui/react-tooltip": "^1.2.7", "@radix-ui/react-tooltip": "^1.2.7",
"@tanstack/react-query": "^5.83.0", "@tanstack/react-query": "^5.83.0",
"axios": "^1.13.2",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"date-fns": "^3.6.0", "date-fns": "^3.6.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"input-otp": "^1.4.2", "input-otp": "^1.4.2",
"jwt-decode": "^4.0.0",
"lucide-react": "^0.462.0", "lucide-react": "^0.462.0",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"react": "^18.3.1", "react": "^18.3.1",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

+19 -5
View File
@@ -10,6 +10,8 @@ import AgentDetails from "./pages/AgentDetails";
import TestPrompt from "./pages/TestPrompt"; import TestPrompt from "./pages/TestPrompt";
import History from "./pages/History"; import History from "./pages/History";
import NotFound from "./pages/NotFound"; import NotFound from "./pages/NotFound";
import Redirect from "./pages/Redirect";
import React from "react";
const queryClient = new QueryClient(); const queryClient = new QueryClient();
@@ -21,14 +23,26 @@ const App = () => (
<Sonner /> <Sonner />
<BrowserRouter> <BrowserRouter>
<Routes> <Routes>
<Route element={<AppLayout />}> <Route
<Route path="/" element={<Agents />} /> path="/redir/:gsikey"
<Route path="/agents/:id" element={<AgentDetails />} /> element={<Redirect />}
<Route path="/test" element={<TestPrompt />} /> />
<Route path="/history" element={<History />} /> {/* Layout principal para /prompt-labs */}
<Route path="/prompt-labs" element={<AppLayout />}>
{/* Página inicial: /prompt-labs */}
<Route index element={<Agents />} />
{/* Rotas internas */}
<Route path="agents/:id" element={<AgentDetails />} />
<Route path="test" element={<TestPrompt />} />
<Route path="history" element={<History />} />
{/* Catch-all exclusivo para o contexto de /prompt-labs */}
<Route path="*" element={<NotFound />} />
</Route> </Route>
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} /> <Route path="*" element={<NotFound />} />
<Route path="/404" element={<NotFound />} />
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>
</TooltipProvider> </TooltipProvider>
+286
View File
@@ -0,0 +1,286 @@
import { jwtDecode } from 'jwt-decode';
import { RedirectService } from './pages/RedirectService';
export class GlobalFunctions {
public static getTranferAreaObj(): TransferAreaResponse {
let objRetorno: TransferAreaResponse = {
aplicativoID: 0,
aplicativoNome: "",
areaTransferenciaID: 0,
dataRegistro: "",
estabelecimentoID: 0,
usuarioID: 0,
usuarioEmail: "",
usuarioNome: "",
aplicativoShareCode: "",
nivelAcesso: 0
};
try {
const objTransferStr = sessionStorage.getItem("TRANSFER_AREA");
if (
objTransferStr != null &&
objTransferStr != undefined &&
objTransferStr.trim() != ""
) {
const objTransfer = <TransferAreaResponse>JSON.parse(objTransferStr);
objRetorno = objTransfer;
}
} catch (error) {}
return objRetorno;
}
public static getRedirectComponent(): string {
let objRetorno = "";
try {
const objTransfer = GlobalFunctions.getTranferAreaObj();
if (objTransfer != null) {
// let objRedir = objTransfer.find(x => x.name == 'REDIRECT');
// objRetorno = objRedir?.value ?? '';
objRetorno = objTransfer.urlDestino ?? "";
if (objRetorno.startsWith("/")) objRetorno = objRetorno.substring(1);
} else {
objRetorno = "";
}
} catch (error) {
//console.log(error);
objRetorno = "";
}
return objRetorno;
}
public static getTransferProperty(propertyName: TransferAreaProperties): any {
let objRetorno: any = "";
try {
const objTransfer = this.getTranferAreaObj();
if (objTransfer != null) {
//let obj: any = objTransfer[propertyName];
const element = objTransfer[propertyName];
objRetorno = element;
} else {
objRetorno = null;
}
} catch (error) {
objRetorno = null;
}
return objRetorno;
}
public static isUsuarioLogado(): boolean {
let jsonUsuario = sessionStorage.getItem('usuarioLogado');
if (jsonUsuario) {
let tokenDecode: any = GlobalFunctions.getUsuarioLogado();
let d: Date = new Date();
let dateAtual: number = Date.UTC(d.getFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes() + 5, d.getUTCSeconds()) / 1000;
if (dateAtual > tokenDecode.exp) return false;
return true;
}
return false;
}
public static tokenExpired(tokenDecode: any): boolean {
let d: Date = new Date();
let dateAtual: number = Date.UTC(d.getFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes() + 5, d.getUTCSeconds()) / 1000;
if (dateAtual > tokenDecode.exp) return true;
return false;
}
public static handleNavigateBack(): void {
try {
// Verifica se existe histórico de navegação
if (window.history && window.history.length > 1) {
window.history.back();
return;
}
// Tenta fechar a janela
if (!window.closed) {
try {
const windowRef = window.open('', '_self');
if (windowRef) {
windowRef.close();
// Pequeno timeout para verificar se a janela foi fechada
setTimeout(() => {
// Se ainda estiver aberta, redireciona
if (!windowRef.closed) {
window.location.href = "https://core.hgtx.com.br/aplicativos/";
}
}, 100);
return;
}
} catch (closeError) {
console.warn("Não foi possível fechar a janela:", closeError);
}
}
// Se não conseguiu fechar, redireciona
window.location.href = "https://core.hgtx.com.br/aplicativos/";
} catch (error) {
// Em caso de qualquer erro, garante o redirecionamento
console.error("Erro ao tentar navegar:", error);
window.location.href = "https://core.hgtx.com.br/aplicativos/";
}
}
public static getUsuarioLogado(): UsuarioLogadoData {
const jsonUsuario = sessionStorage.getItem("usuarioLogado") ?? "";
try {
const objJwt = JSON.parse(jsonUsuario);
//return jwt_decode(objJwt.token);
return jwtDecode(objJwt.token);
} catch (error) {}
return {
EID: "0",
email: "",
exp: 0,
iat: 0,
jti: "",
name: "",
nbf: 0,
UID: "0",
};
}
public static getUsuarioLogadoToken(): string {
let retorno = "";
const jsonUsuario = sessionStorage.getItem("usuarioLogado") ?? "";
try {
const objJwt = JSON.parse(jsonUsuario);
retorno = objJwt.token;
} catch (error) {}
return retorno;
}
public static getUsuarioLogadoRefreshToken(): string {
let retorno = "";
const jsonUsuario = sessionStorage.getItem("usuarioLogado") ?? "";
try {
const objJwt = JSON.parse(jsonUsuario);
retorno = objJwt.refreshToken;
} catch (error) {}
return retorno;
}
public static getPerfilUsuario(): PerfilUsuario | null {
let retorno: PerfilUsuario | null = null;
const jsonUsuario = sessionStorage.getItem("perfilUsuario") ?? "";
try {
const objJwt = <PerfilUsuario>JSON.parse(jsonUsuario);
retorno = objJwt;
} catch (error) {
retorno = null;
}
return retorno;
}
public static getHighUserProfile(): number {
let retorno = 6;
const objPerfil = GlobalFunctions.getPerfilUsuario();
if (objPerfil) {
const tiposPerfil: number[] = objPerfil.results.map((v) => v.tipoPerfil);
retorno = Math.min(...tiposPerfil);
}
return retorno;
}
public static async getToken(): Promise<string> {
let token: string = GlobalFunctions.getUsuarioLogadoToken();
const tokenDecode: any = GlobalFunctions.getUsuarioLogado();
let currentDate = new Date();
// JWT exp is in seconds
if ((tokenDecode.exp * 1000) < currentDate.getTime()) {
//console.log("Token expired.");
let gsikey: number = parseInt(sessionStorage.getItem('gsikey') ?? '0');
RedirectService.loadTransferArea(gsikey).then((response) => {
if(response.data.errorCode == 0){
sessionStorage.setItem('TRANSFER_AREA',JSON.stringify(response.data.areTrs));
sessionStorage.setItem('usuarioLogado',JSON.stringify({
token: response.data.jwt.token,
refreshToken: response.data.jwt.refreshToken
}));
token = response.data.jwt.token;
}
// else if(error !== 1401){
// navigate('/',{replace: true});
// }
});
}
// else {
// //console.log("Valid token");
// result = true;
// }
return token;
}
}
export interface UsuarioLogadoData {
UID: string;
EID: string;
name: string;
email: string;
jti: string;
nbf: number;
exp: number;
iat: number;
}
export interface TransferAreaResponse {
estabelecimentoID: number;
nivelAcesso: number;
aplicativoID: number;
usuarioID: number;
areaTransferenciaID: number;
dataRegistro: string;
urlBase?: string;
urlDestino?: string;
aplicativoNome: string;
usuarioNome: string;
usuarioEmail: string;
aplicativoShareCode: string;
}
export enum TransferAreaProperties {
EstabelecimentoCodigo = "estabelecimentoID",
UsuarioCodigo = "usuarioID",
UsuarioNome = "usuarioNome",
UsuarioEmail = "usuarioEmail",
APP_COD = "aplicativoID",
APP_TITULO = "aplicativoNome",
areaTransferenciaID = "areaTransferenciaID",
urlBase = "urlBase",
urlDestino = "urlDestino",
aplicativoShareCode = "aplicativoShareCode",
nivelAcesso = "nivelAcesso",
}
type PerfilUsuario = {
errorCode: number;
errorMessage: string;
results: PerfilUsuarioResult[];
};
export type PerfilUsuarioResult = {
tipoPerfil: number;
itens: PerfilUsuarioItem[];
};
type PerfilUsuarioItem = {
id: number;
descricao: string;
identificador: string;
};
+35
View File
@@ -0,0 +1,35 @@
import { Loader2 } from "lucide-react";
import { useEffect, useState } from "react";
interface FullScreenLoaderProps {
show: boolean;
text?: string;
}
export default function FullScreenLoader({ show, text = "Carregando..." }: FullScreenLoaderProps) {
const [visible, setVisible] = useState(show);
useEffect(() => {
if (show) setVisible(true);
else {
// adiciona um pequeno atraso para suavizar o fade-out
const timeout = setTimeout(() => setVisible(false), 200);
return () => clearTimeout(timeout);
}
}, [show]);
if (!visible && !show) return null;
return (
<div
className={`fixed inset-0 z-[9999] flex items-center justify-center bg-background/80 backdrop-blur-sm transition-opacity duration-200 ${
show ? "opacity-100" : "opacity-0 pointer-events-none"
}`}
>
<div className="flex flex-col items-center gap-3 p-6 rounded-2xl bg-card shadow-lg border border-border transition-all duration-200">
<Loader2 className="h-10 w-10 animate-spin text-primary" />
<p className="text-card-foreground text-sm font-medium">{text}</p>
</div>
</div>
);
}
+55 -32
View File
@@ -1,5 +1,6 @@
import { useState } from "react"; import { useState } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@@ -18,6 +19,7 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { createAgent, getAIModels } from "@/lib/api/agents";
interface CreateAgentDialogProps { interface CreateAgentDialogProps {
open: boolean; open: boolean;
@@ -27,36 +29,57 @@ interface CreateAgentDialogProps {
export function CreateAgentDialog({ open, onOpenChange }: CreateAgentDialogProps) { export function CreateAgentDialog({ open, onOpenChange }: CreateAgentDialogProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
const queryClient = useQueryClient();
const [name, setName] = useState(""); const [name, setName] = useState("");
const [selectedModel, setSelectedModel] = useState(""); const [selectedModelId, setSelectedModelId] = useState("");
const aiModels = [ // Buscar modelos da API
{ value: "google/gemini-2.5-pro", label: "Google Gemini 2.5 Pro" }, const { data: aiModels = [], isLoading: isLoadingModels } = useQuery({
{ value: "google/gemini-2.5-flash", label: "Google Gemini 2.5 Flash" }, queryKey: ["aiModels"],
{ value: "google/gemini-2.5-flash-lite", label: "Google Gemini 2.5 Flash Lite" }, queryFn: getAIModels,
{ 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(`/prompt-labs/agents/${data.agent_id}`);
// Reset form
setName("");
setSelectedModelId("");
},
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 = () => { const handleCreate = () => {
// TODO: Implementar criação no backend if (!selectedModelId) {
const newAgentId = Math.floor(Math.random() * 10000); // Gerar ID temporário toast({
console.log("Criando agente:", { name, model: selectedModel }); title: "Erro",
description: "Selecione um modelo de IA.",
variant: "destructive",
});
return;
}
toast({ createAgentMutation.mutate({ name, modelId: parseInt(selectedModelId) });
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("");
}; };
return ( return (
@@ -82,14 +105,14 @@ export function CreateAgentDialog({ open, onOpenChange }: CreateAgentDialogProps
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="model">Modelo de IA</Label> <Label htmlFor="model">Modelo de IA</Label>
<Select value={selectedModel} onValueChange={setSelectedModel}> <Select value={selectedModelId} onValueChange={setSelectedModelId} disabled={isLoadingModels}>
<SelectTrigger id="model"> <SelectTrigger id="model">
<SelectValue placeholder="Selecione um modelo" /> <SelectValue placeholder={isLoadingModels ? "Carregando modelos..." : "Selecione um modelo"} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{aiModels.map((model) => ( {aiModels.filter(model => model.is_active === 1).map((model) => (
<SelectItem key={model.value} value={model.value}> <SelectItem key={model.id} value={model.id.toString()}>
{model.label} {model.name}
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>
@@ -102,9 +125,9 @@ export function CreateAgentDialog({ open, onOpenChange }: CreateAgentDialogProps
</Button> </Button>
<Button <Button
onClick={handleCreate} onClick={handleCreate}
disabled={!name || !selectedModel} disabled={!name || !selectedModelId || createAgentMutation.isPending || isLoadingModels}
> >
Criar Agente {createAgentMutation.isPending ? "Criando..." : "Criar Agente"}
</Button> </Button>
</div> </div>
</div> </div>
+16 -1
View File
@@ -1,8 +1,23 @@
import React from "react";
import { AppSidebar } from "./AppSidebar"; import { AppSidebar } from "./AppSidebar";
import { MobileNav } from "./MobileNav"; import { MobileNav } from "./MobileNav";
import { Outlet } from "react-router-dom"; import { Outlet, useLocation } from "react-router-dom";
import { GlobalFunctions } from "@/GlobalFunctions";
export function AppLayout() { export function AppLayout() {
const { pathname } = useLocation();
// ignora layout se for redirecionamento
if (pathname.startsWith("/redir")) {
return <></>;
}
React.useEffect(() => {
console.log('Aqui');
if(!GlobalFunctions.isUsuarioLogado())window.location.replace(import.meta.env.VITE_BASE_URL_HGTX_CORE);
},[]);
return ( return (
<div className="flex h-screen w-full bg-background overflow-hidden"> <div className="flex h-screen w-full bg-background overflow-hidden">
<MobileNav /> <MobileNav />
+4 -2
View File
@@ -10,10 +10,11 @@ import {
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { ThemeToggle } from "./ThemeToggle"; import { ThemeToggle } from "./ThemeToggle";
import { GlobalFunctions } from "@/GlobalFunctions";
const menuItems = [ const menuItems = [
{ title: "Agentes", url: "/", icon: Bot }, { title: "Agentes", url: "/prompt-labs", icon: Bot },
{ title: "Testar Prompt", url: "/test", icon: TestTube }, { title: "Testar Prompt", url: "/prompt-labs/test", icon: TestTube },
]; ];
export function AppSidebar() { export function AppSidebar() {
@@ -134,6 +135,7 @@ export function AppSidebar() {
</div> </div>
<Button <Button
variant="ghost" variant="ghost"
onClick={GlobalFunctions.handleNavigateBack}
className="w-full justify-start gap-2 text-sidebar-foreground" className="w-full justify-start gap-2 text-sidebar-foreground"
> >
<ArrowLeft className="w-4 h-4" /> <ArrowLeft className="w-4 h-4" />
+161
View File
@@ -0,0 +1,161 @@
import api from "./axios";
import type {
AgentDetails,
AgentVersion,
AIModel,
CreateAgentRequest,
CreateAgentResponse,
EditAgentRequest,
EditAgentResponse,
EditAgentNameRequest,
EditAgentNameResponse,
ToggleAgentStatusRequest,
ToggleAgentStatusResponse,
ListAgentsResponse,
} from "../types/agent";
import { GlobalFunctions, TransferAreaProperties } from "@/GlobalFunctions";
const estabelecimentoId = GlobalFunctions.getTransferProperty(TransferAreaProperties.EstabelecimentoCodigo) ?? 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;
};
/**
* Obtém todos os modelos de IA disponíveis
*/
export const getAIModels = async (): Promise<AIModel[]> => {
const response = await api.get<AIModel[]>(
"/webhook/codex/get_models_ia"
);
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;
+64
View File
@@ -0,0 +1,64 @@
import api from "./axios";
import type {
Chat,
ChatMessage,
TestAgentRequest,
TestAgentResponse,
} from "../types/chat";
import { GlobalFunctions, TransferAreaProperties } from "@/GlobalFunctions";
const estabelecimentoId = GlobalFunctions.getTransferProperty(TransferAreaProperties.EstabelecimentoCodigo) ?? 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}`
);
};
+30
View File
@@ -0,0 +1,30 @@
import { AIModel } from "../types/agent";
/**
* Este arquivo contém funções auxiliares para trabalhar com modelos de IA.
* Os modelos agora são buscados dinamicamente da API através da função getAIModels() em @/lib/api/agents
*
* @deprecated AI_MODELS - Use getAIModels() da API ao invés disso
*/
// Função auxiliar para obter o nome do modelo pelo ID
export const getModelNameById = (models: AIModel[], id: number): string => {
const model = models.find((m) => m.id === id);
return model?.name || "Modelo Desconhecido";
};
// Função auxiliar para obter o modelo pelo identifier
export const getModelByIdentifier = (models: AIModel[], identifier: string): AIModel | undefined => {
return models.find((m) => m.model_identifier === identifier);
};
// Função auxiliar para obter o ID pelo identifier
export const getModelIdByIdentifier = (models: AIModel[], identifier: string): number | undefined => {
const model = getModelByIdentifier(models, identifier);
return model?.id;
};
// Função auxiliar para filtrar apenas modelos ativos
export const getActiveModels = (models: AIModel[]): AIModel[] => {
return models.filter((m) => m.is_active === 1);
};
+126
View File
@@ -0,0 +1,126 @@
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;
provider_id: number;
name: string;
model_identifier: string;
cost_input_per_million: string;
cost_output_per_million: string;
is_active: number;
created_at: string;
updated_at: 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 { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App.tsx"; import App from "./App.tsx";
import "./index.css"; 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>
);
+258 -97
View File
@@ -1,11 +1,12 @@
import { useState } from "react"; import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom"; import { useParams, useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; 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 { useToast } from "@/hooks/use-toast";
import { VersionHistoryDialog } from "@/components/agents/VersionHistoryDialog"; import { VersionHistoryDialog } from "@/components/agents/VersionHistoryDialog";
import { SaveVersionDialog } from "@/components/agents/SaveVersionDialog"; import { SaveVersionDialog } from "@/components/agents/SaveVersionDialog";
@@ -20,103 +21,217 @@ import {
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from "@/components/ui/alert-dialog"; } from "@/components/ui/alert-dialog";
import {
getAgentDetails,
editAgent,
editAgentName,
toggleAgentStatus,
getAgentVersions,
getAIModels,
} from "@/lib/api/agents";
export default function AgentDetails() { export default function AgentDetails() {
const { id } = useParams(); const { id } = useParams();
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
const queryClient = useQueryClient();
const [isHistoryOpen, setIsHistoryOpen] = useState(false); const [isHistoryOpen, setIsHistoryOpen] = useState(false);
const [isSaveVersionOpen, setIsSaveVersionOpen] = useState(false); const [isSaveVersionOpen, setIsSaveVersionOpen] = useState(false);
const [isDeactivateDialogOpen, setIsDeactivateDialogOpen] = useState(false); const [isDeactivateDialogOpen, setIsDeactivateDialogOpen] = useState(false);
const [isEditingName, setIsEditingName] = useState(false);
const [tempName, setTempName] = useState("");
const [selectedModelId, setSelectedModelId] = useState<number | undefined>();
const [systemPrompt, setSystemPrompt] = useState("");
// Mock data - substituir por dados reais do backend // Fetch AI models
const [agent, setAgent] = useState<{ const { data: aiModels = [], isLoading: isLoadingModels } = useQuery({
id: string | undefined; queryKey: ["aiModels"],
name: string; queryFn: getAIModels,
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.",
}); });
const [versions] = useState([ // Fetch agent details
{ const {
id: 1, data: agentDetails,
version: "2.1", isLoading,
type: "major" as const, isError,
description: "Melhorias na clareza das respostas", refetch,
model: "Google Gemini 2.5 Flash", } = useQuery({
prompt: "Você é um assistente de atendimento ao cliente. Seja educado, prestativo e objetivo nas suas respostas. Sempre mantenha um tom profissional e cordial.", queryKey: ["agent", id],
createdAt: "2024-01-15 14:30", queryFn: () => getAgentDetails(id!),
author: "João Silva", enabled: !!id,
}, });
{
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",
},
]);
const aiModels = [ // Fetch agent versions for history
{ value: "google/gemini-2.5-pro", label: "Google Gemini 2.5 Pro" }, const {
{ value: "google/gemini-2.5-flash", label: "Google Gemini 2.5 Flash" }, data: versions,
{ value: "google/gemini-2.5-flash-lite", label: "Google Gemini 2.5 Flash Lite" }, isLoading: isLoadingVersions,
{ value: "openai/gpt-5", label: "OpenAI GPT-5" }, } = useQuery({
{ value: "openai/gpt-5-mini", label: "OpenAI GPT-5 Mini" }, queryKey: ["agent-versions", id],
{ value: "openai/gpt-5-nano", label: "OpenAI GPT-5 Nano" }, queryFn: () => getAgentVersions(id!),
]; enabled: !!id && isHistoryOpen,
});
// Update local state when agent details are loaded
useEffect(() => {
if (agentDetails) {
setSelectedModelId(agentDetails.model_id);
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) => { const handleSave = (versionType: "major" | "minor" | "patch", notes: string) => {
// TODO: Implementar salvamento no backend if (!selectedModelId) {
console.log("Saving agent:", agent, "Version type:", versionType, "Notes:", notes); toast({
toast({ title: "Erro",
title: "Agente atualizado", description: "Selecione um modelo de IA.",
description: `Nova versão ${versionType} salva com sucesso.`, variant: "destructive",
});
return;
}
editAgentMutation.mutate({
model_id: selectedModelId,
system_prompt: systemPrompt,
version_type: versionType,
notes,
}); });
}; };
const handleToggleStatus = () => { const handleToggleStatus = () => {
if (agent.status === "active") { if (agentDetails?.status === "ativo") {
setIsDeactivateDialogOpen(true); setIsDeactivateDialogOpen(true);
} else { } else {
// Ativar diretamente sem modal toggleStatusMutation.mutate("ativo");
setAgent({ ...agent, status: "active" });
toast({
title: "Status atualizado",
description: "Agente ativado com sucesso.",
});
} }
}; };
const handleConfirmDeactivate = () => { const handleConfirmDeactivate = () => {
setAgent({ ...agent, status: "inactive" }); toggleStatusMutation.mutate("inativo");
toast({
title: "Status atualizado",
description: "Agente desativado com sucesso. Esta ação foi registrada.",
});
setIsDeactivateDialogOpen(false);
}; };
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 ( return (
<div className="animate-fade-in pb-8"> <div className="animate-fade-in pb-8">
@@ -125,7 +240,7 @@ export default function AgentDetails() {
<Button <Button
variant="ghost" variant="ghost"
className="mb-4 gap-2" className="mb-4 gap-2"
onClick={() => navigate("/")} onClick={() => navigate("/prompt-labs")}
> >
<ArrowLeft className="h-4 w-4" /> <ArrowLeft className="h-4 w-4" />
Voltar para Agentes Voltar para Agentes
@@ -133,21 +248,58 @@ export default function AgentDetails() {
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4"> <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Input {isEditingName ? (
value={agent.name} <div className="flex items-center gap-2">
onChange={(e) => setAgent({ ...agent, name: e.target.value })} <Input
className="text-2xl md:text-3xl font-bold h-auto py-2 max-w-md" value={tempName}
placeholder="Nome do agente" 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 <Badge
variant={agent.status === "active" ? "default" : "secondary"} variant={agentDetails.status === "ativo" ? "default" : "secondary"}
className={ className={
agent.status === "active" agentDetails.status === "ativo"
? "bg-green-600 hover:bg-green-700 text-white" ? "bg-green-600 hover:bg-green-700 text-white"
: "bg-muted text-muted-foreground" : "bg-muted text-muted-foreground"
} }
> >
{agent.status === "active" ? "● Ativo" : "○ Inativo"} {agentDetails.status === "ativo" ? "● Ativo" : "○ Inativo"}
</Badge> </Badge>
</div> </div>
@@ -162,12 +314,17 @@ export default function AgentDetails() {
<span className="sm:hidden">Histórico</span> <span className="sm:hidden">Histórico</span>
</Button> </Button>
<Button <Button
variant={agent.status === "active" ? "destructive" : "default"} variant={agentDetails.status === "ativo" ? "destructive" : "default"}
className={agent.status === "active" ? "gap-2" : "gap-2 bg-green-600 hover:bg-green-700 text-white"} className={agentDetails.status === "ativo" ? "gap-2" : "gap-2 bg-green-600 hover:bg-green-700 text-white"}
onClick={handleToggleStatus} onClick={handleToggleStatus}
disabled={toggleStatusMutation.isPending}
> >
<Power className="h-4 w-4" /> <Power className="h-4 w-4" />
{agent.status === "active" ? "Desativar" : "Ativar"} {toggleStatusMutation.isPending
? "Processando..."
: agentDetails.status === "ativo"
? "Desativar"
: "Ativar"}
</Button> </Button>
<Button className="gap-2" onClick={() => setIsSaveVersionOpen(true)}> <Button className="gap-2" onClick={() => setIsSaveVersionOpen(true)}>
<Save className="h-4 w-4" /> <Save className="h-4 w-4" />
@@ -188,16 +345,17 @@ export default function AgentDetails() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<Select <Select
value={agent.model} value={selectedModelId?.toString()}
onValueChange={(value) => setAgent({ ...agent, model: value })} onValueChange={(value) => setSelectedModelId(parseInt(value))}
disabled={isLoadingModels}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue /> <SelectValue placeholder={isLoadingModels ? "Carregando modelos..." : "Selecione um modelo"} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{aiModels.map((model) => ( {aiModels.filter(model => model.is_active === 1).map((model) => (
<SelectItem key={model.value} value={model.value}> <SelectItem key={model.id} value={model.id.toString()}>
{model.label} {model.name}
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>
@@ -215,8 +373,8 @@ export default function AgentDetails() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<Textarea <Textarea
value={agent.systemPrompt} value={systemPrompt}
onChange={(e) => setAgent({ ...agent, systemPrompt: e.target.value })} onChange={(e) => setSystemPrompt(e.target.value)}
className="min-h-[300px] font-mono text-sm" className="min-h-[300px] font-mono text-sm"
placeholder="Digite o prompt do sistema..." placeholder="Digite o prompt do sistema..."
/> />
@@ -227,8 +385,8 @@ export default function AgentDetails() {
<VersionHistoryDialog <VersionHistoryDialog
open={isHistoryOpen} open={isHistoryOpen}
onOpenChange={setIsHistoryOpen} onOpenChange={setIsHistoryOpen}
agentName={agent.name} agentName={agentDetails.name}
versions={versions} versions={formattedVersions}
/> />
<SaveVersionDialog <SaveVersionDialog
@@ -247,7 +405,10 @@ export default function AgentDetails() {
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel> <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 Desativar
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </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 { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { CreateAgentDialog } from "@/components/agents/CreateAgentDialog"; import { CreateAgentDialog } from "@/components/agents/CreateAgentDialog";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -14,57 +15,55 @@ import {
PaginationNext, PaginationNext,
PaginationPrevious, PaginationPrevious,
} from "@/components/ui/pagination"; } 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() { export default function Agents() {
const navigate = useNavigate(); const navigate = useNavigate();
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false); const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 9; const [itemsPerPage, setItemsPerPage] = useState(6);
const [agents] = useState([ // Debounce search query
{ useEffect(() => {
id: 1, const handler = setTimeout(() => {
name: "Agente de Atendimento", setDebouncedSearch(searchQuery);
status: "active" as const, setCurrentPage(1); // Reset to first page on search
version: "2.1", }, 500);
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",
},
]);
const filteredAgents = agents.filter(agent => return () => {
agent.name.toLowerCase().includes(searchQuery.toLowerCase()) clearTimeout(handler);
); };
}, [searchQuery]);
// Paginação // Fetch agents from API
const totalPages = Math.ceil(filteredAgents.length / itemsPerPage); const {
const startIndex = (currentPage - 1) * itemsPerPage; data: agentsData,
const endIndex = startIndex + itemsPerPage; isLoading,
const paginatedAgents = filteredAgents.slice(startIndex, endIndex); isError,
refetch,
} = useQuery({
queryKey: ["agents", debouncedSearch, currentPage, itemsPerPage],
queryFn: () =>
listAgents(
debouncedSearch || undefined,
currentPage,
itemsPerPage
),
});
// Reset para primeira página quando buscar const agents = agentsData?.data || [];
const handleSearch = (query: string) => { const totalPages = agentsData?.total_pages || 0;
setSearchQuery(query); const totalAgents = agentsData?.total || 0;
setCurrentPage(1);
};
return ( return (
<div className="animate-fade-in"> <div className="animate-fade-in">
@@ -87,34 +86,68 @@ export default function Agents() {
<Input <Input
placeholder="Pesquisar agentes..." placeholder="Pesquisar agentes..."
value={searchQuery} value={searchQuery}
onChange={(e) => handleSearch(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10" className="pl-10"
/> />
</div> </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"> <p className="text-sm text-muted-foreground">
{filteredAgents.length} {filteredAgents.length === 1 ? 'agente encontrado' : 'agentes encontrados'} {totalAgents} {totalAgents === 1 ? 'agente encontrado' : 'agentes encontrados'}
</p> </p>
{totalPages > 1 && ( <div className="flex items-center gap-3">
<p className="text-sm text-muted-foreground"> <div className="flex items-center gap-2">
Página {currentPage} de {totalPages} <span className="text-sm text-muted-foreground whitespace-nowrap">Itens por página:</span>
</p> <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>
</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"> <div className="text-center py-12">
<p className="text-muted-foreground">Nenhum agente encontrado.</p> <p className="text-muted-foreground">Nenhum agente encontrado.</p>
</div> </div>
) : ( ) : (
<> <>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{paginatedAgents.map((agent) => ( {agents.map((agent) => (
<Card <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" 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(`/prompt-labs/agents/${agent.agente_id}`)}
> >
{/* Glow effect on hover */} {/* 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" /> <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" /> <Bot className="h-7 w-7 text-primary" />
</div> </div>
<div className="flex-1 min-w-0"> <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"> <div className="flex items-center gap-2 mt-1">
<Badge variant="outline" className="text-xs"> <Badge variant="outline" className="text-xs">
v{agent.version} v{agent.versao_agente}
</Badge> </Badge>
</div> </div>
</div> </div>
@@ -143,20 +176,20 @@ export default function Agents() {
<CardContent className="relative space-y-3"> <CardContent className="relative space-y-3">
<div className="p-3 rounded-lg bg-muted/50"> <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-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>
<div className="flex items-center justify-between pt-2 border-t"> <div className="flex items-center justify-between pt-2 border-t">
<span className="text-xs text-muted-foreground">Status</span> <span className="text-xs text-muted-foreground">Status</span>
<Badge <Badge
variant={agent.status === "active" ? "default" : "secondary"} variant={agent.status === "ativo" ? "default" : "secondary"}
className={ className={
agent.status === "active" agent.status === "ativo"
? "bg-green-600 hover:bg-green-700 shadow-sm" ? "bg-green-600 hover:bg-green-700 shadow-sm"
: "bg-muted text-muted-foreground hover:bg-muted" : "bg-muted text-muted-foreground hover:bg-muted"
} }
> >
{agent.status === "active" ? "● Ativo" : "○ Inativo"} {agent.status === "ativo" ? "● Ativo" : "○ Inativo"}
</Badge> </Badge>
</div> </div>
</CardContent> </CardContent>
+9 -2
View File
@@ -1,5 +1,6 @@
import { useLocation } from "react-router-dom"; import { useLocation } from "react-router-dom";
import { useEffect } from "react"; import { useEffect } from "react";
import { GlobalFunctions } from "@/GlobalFunctions";
const NotFound = () => { const NotFound = () => {
const location = useLocation(); const location = useLocation();
@@ -13,9 +14,15 @@ const NotFound = () => {
<div className="text-center"> <div className="text-center">
<h1 className="mb-4 text-4xl font-bold">404</h1> <h1 className="mb-4 text-4xl font-bold">404</h1>
<p className="mb-4 text-xl text-gray-600">Oops! Page not found</p> <p className="mb-4 text-xl text-gray-600">Oops! Page not found</p>
<a href="/" className="text-blue-500 underline hover:text-blue-700"> {/* <a href="/" className="text-blue-500 underline hover:text-blue-700">
Return to Home Return to Home
</a> </a> */}
<button
className="text-blue-500 underline hover:text-blue-700"
onClick={GlobalFunctions.handleNavigateBack}
>
Return to Home
</button>
</div> </div>
</div> </div>
); );
+50
View File
@@ -0,0 +1,50 @@
import { GlobalFunctions } from "@/GlobalFunctions";
import { RedirectService } from "./RedirectService";
import React from "react";
import { useNavigate, useParams } from "react-router-dom";
import FullScreenLoader from "@/components/FullScreenLoader";
export default function Redirect() {
const navigate = useNavigate();
let { gsikey } = useParams();
React.useEffect(() => {
let error: number = 0;
sessionStorage.setItem('gsikey', gsikey ?? '0');
RedirectService.loadTransferArea(parseInt(gsikey ?? '0')).then((response) => {
console.log(response);
error = response.data.errorCode;
//msg = response.data.errorMessage;
if(response.data.errorCode == 0){
sessionStorage.setItem('TRANSFER_AREA',JSON.stringify(response.data.areTrs));
sessionStorage.setItem('usuarioLogado',JSON.stringify({
token: response.data.jwt.token,
refreshToken: response.data.jwt.refreshToken
}));
}
// else if(error !== 1401){
// navigate('/',{replace: true});
// }
})
.catch((_err) => {
navigate('/404',{replace: true});
})
.finally(() => {
if(error == 0 || error === 1401){
//navigate(`/${GlobalFunctions.getRedirectComponent()}`,{replace: true});
window.location.replace(`/${GlobalFunctions.getRedirectComponent()}`);
}
// else if(error === 1401){
// navigate({pathname: '/',search:`?p=${window.btoa(msg)}`},{replace: true});
// }
});
}, []);
return (
<FullScreenLoader show={true} text="Carregando...Aguarde..." />
);
}
+32
View File
@@ -0,0 +1,32 @@
import { GlobalFunctions, TransferAreaProperties } from "@/GlobalFunctions";
import axios from "axios";
const endPoint: string = 'v1/redirect/';
export class RedirectService{
public static loadTransferArea(gsikey: number): Promise<any>{
return axios.get(`${import.meta.env.VITE_BASE_URL_HGTX_CORE_API}${endPoint}get_component/${gsikey}/S`);
}
public static async validaAcessoApp(urlDestino: string): Promise<any>{
//let token = await GlobalFunctions.getToken();
let usuLogado = GlobalFunctions.getUsuarioLogado();
let usuCod: string = GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioCodigo);
let estCod: string = usuLogado.EID;
let urlDestinoPost: string = urlDestino;//urlDestino.trim().length < 1 ? GlobalFunctions.getTransferProperty(TransferAreaProperties.urlDestino) : urlDestino;
if(urlDestinoPost.trim().length < 1){
try {
let pathSplit = window.location.pathname.split('/');
urlDestinoPost = `/${pathSplit[pathSplit.length-2]}/${pathSplit[pathSplit.length-1]}`;
} catch (error) {
}
}
//const heads = { headers: {'Content-Type':'application/json; charset=utf-8','Authorization': `Bearer ${token}`} };
const heads = { headers: {'Content-Type':'application/json; charset=utf-8'} };
return axios.post(`${import.meta.env.VITE_BASE_URL_HGTX_CORE_API}v1/aplicativos/validar_acesso_app?usuCod=${usuCod}&estCod=${estCod}`,{
"urlDestino": urlDestinoPost
},heads);
}
}
+293 -112
View File
@@ -1,10 +1,11 @@
import { useState, useRef, useEffect } from "react"; import { useState, useRef, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { ScrollArea } from "@/components/ui/scroll-area"; 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 { useToast } from "@/hooks/use-toast";
import { import {
Select, Select,
@@ -13,62 +14,145 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { listAgents } from "@/lib/api/agents";
type Message = { import { testAgent, listChats, listMessages, deleteChat } from "@/lib/api/chat";
id: string;
role: "user" | "assistant";
content: string;
};
export default function TestPrompt() { export default function TestPrompt() {
const [input, setInput] = useState(""); const [input, setInput] = useState("");
const [messages, setMessages] = useState<Message[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [selectedAgent, setSelectedAgent] = useState(""); const [selectedAgent, setSelectedAgent] = useState("");
const [currentChatId, setCurrentChatId] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
const { toast } = useToast(); const { toast } = useToast();
const queryClient = useQueryClient();
// Mock data de agentes // Fetch active agents from API
const agents = [ const {
{ id: "1", name: "Agente de Atendimento" }, data: agentsData,
{ id: "2", name: "Agente de Vendas" }, isLoading: isLoadingAgents,
{ id: "3", name: "Agente de Análise" }, } = 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(() => { useEffect(() => {
if (scrollRef.current) { if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight; scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
} }
}, [messages]); }, [messages]);
// Limpa a conversa ao trocar de agente const handleNewConversation = () => {
useEffect(() => { if (!selectedAgent) return;
setMessages([]);
}, [selectedAgent]); // 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 = () => { const handleSend = () => {
if (!input.trim() || !selectedAgent) return; if (!input.trim() || !selectedAgent) return;
const userMessage: Message = { // If no chat is selected (new conversation), send chat_id: "0"
id: Date.now().toString(), // The API will return the real chat_id which will be stored in the mutation's onSuccess
role: "user", const chatId = currentChatId || "0";
content: input,
};
setMessages((prev) => [...prev, userMessage]); const message = input.trim();
setInput(""); setInput("");
setIsLoading(true);
setTimeout(() => { sendMessageMutation.mutate({
const aiMessage: Message = { agentId: selectedAgent,
id: (Date.now() + 1).toString(), chatId,
role: "assistant", message,
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);
}; };
const handleKeyPress = (e: React.KeyboardEvent) => { const handleKeyPress = (e: React.KeyboardEvent) => {
@@ -78,34 +162,104 @@ export default function TestPrompt() {
} }
}; };
const handleClearChat = () => { const handleDeleteConversation = (chatId: string) => {
setMessages([]); deleteChatMutation.mutate(chatId);
toast({
title: "Conversa limpa",
description: "O histórico de mensagens foi limpo com sucesso.",
});
}; };
return ( return (
<div className="animate-fade-in h-full flex flex-col max-w-5xl mx-auto"> <div className="animate-fade-in h-full flex gap-4">
<div className="mb-4 md:mb-6"> {/* Sidebar com todas as conversas */}
<h1 className="text-2xl md:text-3xl font-bold text-foreground mb-2">Testar Agente</h1> <Card className="w-80 flex-shrink-0 flex flex-col overflow-hidden">
<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="p-4 border-b border-border"> <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"> <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 Selecione o Agente
</Label> </Label>
<Select value={selectedAgent} onValueChange={setSelectedAgent}> <Select
value={selectedAgent}
onValueChange={setSelectedAgent}
disabled={isLoadingAgents || agents.length === 0}
>
<SelectTrigger id="agent-select"> <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> </SelectTrigger>
<SelectContent> <SelectContent>
{agents.map((agent) => ( {agents.map((agent) => (
@@ -116,71 +270,98 @@ export default function TestPrompt() {
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<Button <div className="pt-6">
variant="outline" <Button
size="default" onClick={handleNewConversation}
onClick={handleClearChat} disabled={!selectedAgent}
disabled={messages.length === 0} className="gap-2"
className="gap-2" >
> <Plus className="h-4 w-4" />
<RotateCcw className="h-4 w-4" /> Nova Conversa
<span className="hidden sm:inline">Nova Conversa</span> </Button>
</Button> </div>
</div> </div>
</div> </div>
{/* Chat Area */} {/* Chat Area */}
<ScrollArea className="flex-1 p-4" ref={scrollRef}> <ScrollArea className="flex-1 p-4" ref={scrollRef}>
<div className="space-y-4"> {!selectedAgent ? (
{messages.length === 0 ? ( <div className="flex items-center justify-center h-full text-muted-foreground">
<div className="flex items-center justify-center h-full text-muted-foreground"> <p>Selecione um agente para começar a conversar</p>
<p>Selecione um agente para começar a conversar</p> </div>
</div> ) : isLoadingMessages ? (
) : ( <div className="flex items-center justify-center h-full">
messages.map((message) => ( <Loader2 className="h-8 w-8 animate-spin text-primary" />
<div </div>
key={message.id} ) : (
className={`flex gap-3 ${ <div className="space-y-4">
message.role === "user" ? "justify-end" : "justify-start" {messages.length === 0 && currentChatId ? (
}`} <div className="flex items-center justify-center h-full text-muted-foreground">
> <p>Carregando mensagens...</p>
{message.role === "assistant" && ( </div>
<div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center flex-shrink-0"> ) : messages.length === 0 ? (
<Bot className="w-5 h-5 text-primary-foreground" /> <div className="flex items-center justify-center h-full text-muted-foreground">
</div> <p>Digite uma mensagem para começar a conversa!</p>
)} </div>
) : (
messages.map((message) => (
<div <div
className={`max-w-[70%] rounded-lg p-3 ${ key={message.id}
message.role === "user" className={`flex gap-3 ${
? "bg-primary text-primary-foreground" message.role === "user" ? "justify-end" : "justify-start"
: "bg-muted text-foreground"
}`} }`}
> >
<p className="text-sm whitespace-pre-wrap">{message.content}</p> {message.role === "assistant" && (
</div> <div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
{message.role === "user" && ( <Bot className="w-5 h-5 text-primary-foreground" />
<div className="w-8 h-8 rounded-full bg-secondary flex items-center justify-center flex-shrink-0"> </div>
<User className="w-5 h-5 text-secondary-foreground" /> )}
<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>
)}
</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> )}
)} </div>
</div> )}
</ScrollArea> </ScrollArea>
{/* Input Area */} {/* Input Area */}
@@ -191,12 +372,12 @@ export default function TestPrompt() {
value={input} value={input}
onChange={(e) => setInput(e.target.value)} onChange={(e) => setInput(e.target.value)}
onKeyPress={handleKeyPress} onKeyPress={handleKeyPress}
disabled={isLoading || !selectedAgent} disabled={sendMessageMutation.isPending || !selectedAgent}
className="flex-1" className="flex-1"
/> />
<Button <Button
onClick={handleSend} onClick={handleSend}
disabled={!input.trim() || isLoading || !selectedAgent} disabled={!input.trim() || sendMessageMutation.isPending || !selectedAgent}
size="icon" size="icon"
> >
<Send className="h-4 w-4" /> <Send className="h-4 w-4" />
+12
View File
@@ -1 +1,13 @@
/// <reference types="vite/client" /> /// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
readonly VITE_API_KEY: string
readonly VITE_USER_EMAIL: string
readonly VITE_ESTABELECIMENTO_ID: string
readonly VITE_BASE_URL_HGTX_CORE_API: string
readonly VITE_BASE_URL_HGTX_CORE: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}