feat: cria interface web inicial da ATIVA IA

This commit is contained in:
Bruno Viana 2026-10-23 19:40:46 -03:00
parent a75c1f1708
commit 375429e173
16 changed files with 1401 additions and 26 deletions

16
frontend/README.md Normal file
View file

@ -0,0 +1,16 @@
# Frontend ATIVA IA — MVP
Interface estática, sem dependências de runtime ou bibliotecas externas. O Apache serve os arquivos deste diretório; as chamadas da interface usam uma rota relativa na mesma origem (`/api`). O exemplo de rota do reverse proxy está em [contrato do frontend](../docs/frontend/mvp.md).
## Conteúdo
- `index.html`: navegação, visão geral, assistente e painel de fontes.
- `styles.css`: layout responsivo, sem assets remotos.
- `config.js`: prefixo público da API. Não adicionar chaves ou credenciais.
- `app.js`: health check, conversa não persistida e apresentação de fontes.
## Integração e segurança
O navegador não chama Ollama/Qdrant diretamente e não recebe `ATIVA_RAG_API_KEY`. A rota de API precisa ser same-origin e o proxy/BFF precisa proteger o acesso e fornecer a credencial de serviço ao backend sem repassá-la ao cliente. A configuração de autenticação e reverse proxy de produção não foi feita neste lote.
O health check usa `GET /api/health`; o chat usa `POST /api/v1/chat/completions`. Neste momento, a RAG API na porta 8090 não respondeu ao health check a partir do ambiente de desenvolvimento. O frontend mostra a indisponibilidade sem gerar dados de demonstração.

192
frontend/app.js Normal file
View file

@ -0,0 +1,192 @@
(() => {
"use strict";
const API_BASE = String(window.ATIVA_CONFIG?.apiBase || "/api").replace(/\/$/, "");
const state = { messages: [], busy: false, lastSources: [] };
const byId = (id) => document.getElementById(id);
function endpoint(path) {
return `${API_BASE}${path.startsWith("/") ? path : `/${path}`}`;
}
function setServiceStatus(name, value, detail) {
const badge = document.querySelector(`[data-health="${name}"]`);
if (!badge) return;
const ok = value === true;
badge.className = `pill ${ok ? "ok" : "bad"}`;
badge.textContent = ok ? "Disponível" : "Indisponível";
const detailNode = byId(`${name}-detail`);
if (detailNode && detail) detailNode.textContent = detail;
}
async function refreshHealth() {
const overall = byId("overall-status");
overall.className = "status-indicator";
overall.querySelector("span").textContent = "Verificando";
try {
const response = await fetch(endpoint("/health"), {
method: "GET",
credentials: "same-origin",
cache: "no-store",
headers: { Accept: "application/json" },
});
const health = await response.json();
setServiceStatus("api", health.service === "ativa-rag-api", health.service || "/api/health");
setServiceStatus("ollama", health.ollama === true, health.embedding_model || "Ollama");
setServiceStatus("qdrant", health.qdrant === true, health.collection || "Qdrant");
overall.className = `status-indicator ${response.ok && health.status === "ok" ? "ok" : "bad"}`;
overall.querySelector("span").textContent = response.ok && health.status === "ok" ? "Operacional" : "Degradado";
} catch (_error) {
setServiceStatus("api", false, "Sem resposta em /api/health");
setServiceStatus("ollama", false, "Estado via RAG API");
setServiceStatus("qdrant", false, "Estado via RAG API");
overall.className = "status-indicator bad";
overall.querySelector("span").textContent = "Sem conexão";
}
byId("health-updated").textContent = `Atualizado às ${new Date().toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" })}`;
}
function selectView(name) {
const valid = name === "assistant" ? "assistant" : "overview";
document.querySelectorAll(".view").forEach((view) => {
const active = view.id === `view-${valid}`;
view.classList.toggle("active", active);
view.hidden = !active;
});
document.querySelectorAll("[data-view]").forEach((button) => {
const active = button.dataset.view === valid;
if (button.classList.contains("nav-item")) {
button.classList.toggle("active", active);
if (active) button.setAttribute("aria-current", "page");
else button.removeAttribute("aria-current");
}
});
byId("page-title").textContent = valid === "assistant" ? "Assistente" : "Visão geral";
}
function appendMessage(role, text, pending = false) {
byId("welcome-card")?.remove();
const node = document.createElement("div");
node.className = `message ${role}${pending ? " pending" : ""}`;
node.textContent = text;
byId("messages").append(node);
byId("messages").scrollTop = byId("messages").scrollHeight;
return node;
}
function renderSources(sources) {
state.lastSources = Array.isArray(sources) ? sources : [];
const list = byId("sources-list");
list.replaceChildren();
byId("sources-empty").hidden = state.lastSources.length > 0;
byId("sources-caption").textContent = state.lastSources.length
? `${state.lastSources.length} referência(s) recuperada(s)`
: "Nenhuma fonte retornada pela API";
state.lastSources.forEach((source) => {
const card = document.createElement("article");
card.className = "source-card";
const name = document.createElement("div");
name.className = "source-name";
name.textContent = String(source.source || "Fonte sem identificação");
const row = document.createElement("div");
row.className = "score-row";
const label = document.createElement("span");
const score = Number(source.score);
const finiteScore = Number.isFinite(score) ? Math.max(0, Math.min(1, score)) : 0;
label.textContent = Number.isFinite(score) ? `Score ${score.toFixed(3)}` : "Score indisponível";
const track = document.createElement("span");
track.className = "score-track";
track.setAttribute("aria-label", "Pontuação retornada pela busca");
const fill = document.createElement("span");
fill.className = "score-fill";
fill.style.width = `${finiteScore * 100}%`;
track.append(fill);
row.append(label, track);
card.append(name, row);
list.append(card);
});
}
async function submitQuestion(event) {
event.preventDefault();
if (state.busy) return;
const input = byId("question");
const question = input.value.trim();
if (!question) return;
state.busy = true;
byId("send-button").disabled = true;
input.value = "";
state.messages.push({ role: "user", content: question });
appendMessage("user", question);
const pending = appendMessage("assistant", "Consultando as fontes…", true);
renderSources([]);
try {
const response = await fetch(endpoint("/v1/chat/completions"), {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ messages: state.messages, stream: false, temperature: 0.1 }),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const reason = response.status === 401 || response.status === 503
? "Acesso à API indisponível. Verifique a autenticação configurada no proxy."
: `A API respondeu com erro HTTP ${response.status}.`;
throw new Error(reason);
}
const answer = data.choices?.[0]?.message?.content || "A API não retornou uma resposta.";
state.messages.push({ role: "assistant", content: answer });
pending.classList.remove("pending");
pending.textContent = answer;
renderSources(data.x_ativa_sources || []);
} catch (error) {
pending.classList.remove("pending");
pending.textContent = error instanceof Error ? error.message : "Não foi possível consultar a API.";
pending.classList.add("error-message");
state.messages.pop();
} finally {
state.busy = false;
byId("send-button").disabled = false;
input.focus();
byId("messages").scrollTop = byId("messages").scrollHeight;
}
}
document.querySelectorAll("[data-view]").forEach((button) => {
button.addEventListener("click", () => selectView(button.dataset.view));
});
document.querySelectorAll(".suggestion").forEach((button) => {
button.addEventListener("click", () => {
byId("question").value = button.textContent;
byId("question").focus();
});
});
byId("refresh-status").addEventListener("click", refreshHealth);
byId("chat-form").addEventListener("submit", submitQuestion);
byId("clear-chat").addEventListener("click", () => {
state.messages = [];
renderSources([]);
byId("messages").replaceChildren(byId("welcome-card") || createWelcomeCard());
selectView("assistant");
});
function createWelcomeCard() {
const welcome = document.createElement("div");
welcome.className = "welcome-card";
welcome.id = "welcome-card";
const mark = document.createElement("div");
mark.className = "welcome-mark";
mark.textContent = "✳";
const heading = document.createElement("h2");
heading.textContent = "Como posso ajudar?";
const copy = document.createElement("p");
copy.textContent = "Faça uma pergunta sobre os materiais institucionais disponíveis.";
welcome.append(mark, heading, copy);
return welcome;
}
refreshHealth();
})();

5
frontend/config.js Normal file
View file

@ -0,0 +1,5 @@
// Configuração pública da interface. Nunca coloque credenciais neste arquivo.
window.ATIVA_CONFIG = Object.freeze({
// O reverse proxy deve encaminhar este prefixo à RAG API na mesma origem.
apiBase: "/api",
});

95
frontend/index.html Normal file
View file

@ -0,0 +1,95 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<meta name="theme-color" content="#112b3c">
<title>ATIVA IA</title>
<link rel="stylesheet" href="./styles.css">
<script src="./config.js"></script>
<script src="./app.js" defer></script>
</head>
<body>
<div class="shell">
<aside class="sidebar" aria-label="Navegação principal">
<a class="brand" href="#inicio" aria-label="ATIVA IA, início">
<span class="brand-mark" aria-hidden="true">A</span>
<span><strong>ATIVA</strong><small>INTELIGÊNCIA ARTIFICIAL</small></span>
</a>
<div class="nav-label">ESPAÇO DE TRABALHO</div>
<nav class="nav-list">
<button class="nav-item active" type="button" data-view="overview" aria-current="page">
<span class="nav-icon" aria-hidden="true">◫</span> Visão geral
</button>
<button class="nav-item" type="button" data-view="assistant">
<span class="nav-icon" aria-hidden="true">✳</span> Assistente
</button>
</nav>
<div class="sidebar-bottom">
<div class="privacy-note"><span class="privacy-dot"></span><span>Ambiente privado<br><small>Não inclua dados pessoais ou clínicos.</small></span></div>
<div class="sidebar-version">ATIVA IA · MVP</div>
</div>
</aside>
<main class="main-content">
<header class="topbar">
<div class="mobile-brand"><span class="brand-mark" aria-hidden="true">A</span><strong>ATIVA IA</strong></div>
<div class="breadcrumb"><span>Workspace</span><span class="crumb-separator">/</span><strong id="page-title">Visão geral</strong></div>
<div class="topbar-right">
<span class="status-indicator" id="overall-status"><i></i><span>Verificando</span></span>
<button class="icon-button" id="refresh-status" type="button" aria-label="Atualizar status" title="Atualizar status">↻</button>
</div>
</header>
<section class="view active" id="view-overview" aria-labelledby="overview-title">
<div class="page-heading">
<div><p class="eyebrow">PLATAFORMA DE CONHECIMENTO</p><h1 id="overview-title">Visão geral</h1><p class="subtitle">Acompanhe a disponibilidade dos componentes e acesse o assistente.</p></div>
<button class="primary-button" type="button" data-view="assistant"><span aria-hidden="true">✳</span> Abrir assistente</button>
</div>
<section class="section-block" aria-labelledby="services-title">
<div class="section-heading"><div><h2 id="services-title">Serviços</h2><p>Estado informado pela API ATIVA IA.</p></div><span class="updated-at" id="health-updated">Ainda não consultado</span></div>
<div class="service-grid">
<article class="service-card" id="card-api"><div class="service-card-top"><span class="service-symbol api-symbol">API</span><span class="pill pending" data-health="api">Aguardando</span></div><h3>RAG API</h3><p>Chat e recuperação de fontes</p><div class="service-foot" id="api-detail">/api/health</div></article>
<article class="service-card" id="card-ollama"><div class="service-card-top"><span class="service-symbol ollama-symbol">◉</span><span class="pill pending" data-health="ollama">Aguardando</span></div><h3>Ollama</h3><p>Embeddings e geração local</p><div class="service-foot" id="ollama-detail">Modelo de embedding</div></article>
<article class="service-card" id="card-qdrant"><div class="service-card-top"><span class="service-symbol qdrant-symbol">⬡</span><span class="pill pending" data-health="qdrant">Aguardando</span></div><h3>Qdrant</h3><p>Busca vetorial institucional</p><div class="service-foot" id="qdrant-detail">Coleção</div></article>
</div>
</section>
<section class="overview-grid">
<article class="panel assistant-promo">
<div class="promo-copy"><p class="eyebrow">ASSISTENTE INSTITUCIONAL</p><h2>Encontre respostas nas fontes da ATIVA</h2><p>Faça uma pergunta e confira as referências recuperadas junto à resposta.</p><button class="text-button" type="button" data-view="assistant">Iniciar conversa <span aria-hidden="true">→</span></button></div>
<div class="promo-art" aria-hidden="true"><div class="orbit orbit-one"></div><div class="orbit orbit-two"></div><div class="orbit-core">A</div><span class="orbit-node node-one"></span><span class="orbit-node node-two"></span><span class="orbit-node node-three"></span></div>
</article>
<article class="panel metrics-panel"><div class="section-heading"><div><h2>Observabilidade</h2><p>Indicadores disponíveis nesta versão</p></div><span class="coming-soon">EM EVOLUÇÃO</span></div><div class="empty-chart"><div class="chart-icon" aria-hidden="true">▥</div><strong>Sem histórico de métricas</strong><p>A API ainda não expõe séries de uso, latência ou ingestões. Não exibimos dados estimados.</p></div></article>
</section>
<section class="panel roadmap-panel"><div class="roadmap-icon" aria-hidden="true">↗</div><div><strong>Próximos indicadores</strong><p>Execuções de ingestão, documentos sincronizados, latência, taxa de respostas sem fontes e uso por modelo — após definição de retenção e endpoints de métricas.</p></div></section>
</section>
<section class="view" id="view-assistant" aria-labelledby="assistant-title" hidden>
<div class="chat-heading"><div><p class="eyebrow">FONTES INSTITUCIONAIS</p><h1 id="assistant-title">Assistente ATIVA</h1><p class="subtitle">Respostas baseadas no conteúdo recuperado da base de conhecimento.</p></div><button class="secondary-button" id="clear-chat" type="button">Nova conversa</button></div>
<div class="chat-layout">
<section class="chat-panel" aria-label="Conversa com o assistente">
<div class="messages" id="messages" aria-live="polite">
<div class="welcome-card" id="welcome-card"><div class="welcome-mark" aria-hidden="true">✳</div><h2>Como posso ajudar?</h2><p>Faça uma pergunta sobre os materiais institucionais disponíveis.</p><div class="suggestions"><button type="button" class="suggestion">Quais fontes estão disponíveis?</button><button type="button" class="suggestion">Como a busca encontra documentos?</button></div></div>
</div>
<form class="composer" id="chat-form">
<label class="sr-only" for="question">Sua pergunta</label>
<textarea id="question" name="question" rows="1" maxlength="2000" placeholder="Escreva sua pergunta…" required></textarea>
<div class="composer-bottom"><span>Não envie informações pessoais ou clínicas.</span><button class="send-button" id="send-button" type="submit" aria-label="Enviar pergunta" title="Enviar pergunta">↑</button></div>
</form>
<p class="chat-disclaimer">A resposta pode estar incompleta. Confira as fontes e valide informações importantes.</p>
</section>
<aside class="sources-panel" aria-label="Fontes da resposta">
<div class="sources-title"><span class="source-icon" aria-hidden="true">▤</span><div><h2>Fontes</h2><p id="sources-caption">Referências da resposta atual</p></div></div>
<div class="sources-empty" id="sources-empty"><span aria-hidden="true">⌕</span><p>As fontes recuperadas aparecerão aqui depois da consulta.</p></div>
<div class="sources-list" id="sources-list"></div>
</aside>
</div>
</section>
<footer class="page-footer"><span>ATIVA IA</span><span>Ambiente de desenvolvimento · acesso controlado</span></footer>
</main>
</div>
</body>
</html>

1016
frontend/styles.css Normal file

File diff suppressed because it is too large Load diff