192 lines
7.8 KiB
JavaScript
192 lines
7.8 KiB
JavaScript
(() => {
|
|
"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();
|
|
})();
|