maestri-remote/public/traces.html

389 lines
18 KiB
HTML

<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Maestri Remote · Telemetria & Traces</title>
<style>
:root {
--bg: #090d16;
--card-bg: #111827;
--card-border: #1f2937;
--text: #f3f4f6;
--text-muted: #9ca3af;
--accent: #38bdf8;
--accent-hover: #0284c7;
--warning: #fbbf24;
--error: #ef4444;
--success: #34d399;
--code-bg: #030712;
}
* { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; }
body { background-color: var(--bg); color: var(--text); padding: 1.5rem; line-height: 1.5; }
header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 1rem; border-bottom: 1px solid var(--card-border); padding-bottom: 1rem; }
h1 { font-size: 1.25rem; font-weight: 700; color: #fff; display: flex; align-items: center; gap: 0.5rem; }
.badge-retention { background: rgba(56, 189, 248, 0.15); color: var(--accent); padding: 0.2rem 0.6rem; border-radius: 9999px; font-size: 0.75rem; border: 1px solid rgba(56, 189, 248, 0.3); }
.status-stream { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 0.8rem; color: var(--success); }
.pulse-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--success); animation: pulse 1.5s infinite; }
@keyframes pulse { 0% { opacity: 1; transform: scale(1); } 50% { opacity: 0.4; transform: scale(1.2); } 100% { opacity: 1; transform: scale(1); } }
.filters-bar { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 8px; padding: 1rem; display: flex; gap: 0.75rem; flex-wrap: wrap; align-items: center; margin-bottom: 1.5rem; }
.filter-group { display: flex; flex-direction: column; gap: 0.25rem; }
label { font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: 600; letter-spacing: 0.05em; }
input, select { background: var(--code-bg); border: 1px solid var(--card-border); color: var(--text); border-radius: 6px; padding: 0.4rem 0.6rem; font-size: 0.85rem; outline: none; }
input:focus, select:focus { border-color: var(--accent); }
button { background: var(--accent); color: #000; border: none; font-weight: 600; padding: 0.45rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.85rem; transition: background 0.2s; }
button:hover { background: var(--accent-hover); }
button.btn-secondary { background: #374151; color: #fff; }
button.btn-secondary:hover { background: #4b5563; }
.view-modes { display: flex; gap: 0.5rem; margin-bottom: 1rem; }
.tab-btn { background: #1e293b; color: var(--text-muted); padding: 0.4rem 0.8rem; border-radius: 6px; border: 1px solid transparent; cursor: pointer; font-size: 0.85rem; }
.tab-btn.active { background: rgba(56, 189, 248, 0.2); color: var(--accent); border-color: rgba(56, 189, 248, 0.4); font-weight: 600; }
/* Comparador Lado a Lado */
.compare-container { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1.5rem; }
@media (max-width: 900px) { .compare-container { grid-template-columns: 1fr; } }
.compare-card { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 8px; overflow: hidden; }
.compare-header { background: #1f2937; padding: 0.6rem 1rem; font-size: 0.85rem; font-weight: 600; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--card-border); }
.compare-body { padding: 1rem; max-height: 400px; overflow-y: auto; font-family: monospace; font-size: 0.8rem; white-space: pre-wrap; word-break: break-all; }
.mismatch-banner { grid-column: 1 / -1; background: rgba(239, 68, 68, 0.15); border: 1px solid var(--error); color: #fca5a5; padding: 0.75rem 1rem; border-radius: 8px; font-weight: 600; font-size: 0.9rem; display: none; }
/* Tabela de Traces */
.traces-table-container { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 8px; overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 0.8rem; text-align: left; }
th { background: #1f2937; color: var(--text-muted); padding: 0.6rem 0.8rem; font-weight: 600; border-bottom: 1px solid var(--card-border); text-transform: uppercase; font-size: 0.7rem; }
td { padding: 0.6rem 0.8rem; border-bottom: 1px solid #1a2234; vertical-align: top; }
tr:hover { background-color: rgba(255, 255, 255, 0.02); }
.badge { display: inline-block; padding: 0.15rem 0.4rem; border-radius: 4px; font-size: 0.7rem; font-weight: 600; text-transform: uppercase; }
.badge-mobile { background: #3b82f6; color: #fff; }
.badge-gateway { background: #10b981; color: #fff; }
.badge-relay { background: #8b5cf6; color: #fff; }
.badge-thinking { background: var(--warning); color: #000; }
.badge-idle { background: #374151; color: #9ca3af; }
.json-preview { color: var(--accent); cursor: pointer; text-decoration: underline; font-family: monospace; font-size: 0.75rem; }
.details-row { background: var(--code-bg); display: none; }
.details-content { padding: 0.75rem 1rem; font-family: monospace; font-size: 0.75rem; color: #d1d5db; white-space: pre-wrap; word-break: break-all; max-height: 350px; overflow-y: auto; }
</style>
</head>
<body>
<header>
<h1>
<span>📡</span> Maestri Remote · Observabilidade & Traces
<span class="badge-retention">Retenção de 72h</span>
</h1>
<div style="display: flex; align-items: center; gap: 1rem;">
<div id="streamStatus" class="status-stream">
<span class="pulse-dot"></span>
<span id="streamStatusText">SSE Conectado em tempo real</span>
</div>
<button id="btnPauseResume" class="btn-secondary" onclick="toggleStream()">Pausar</button>
</div>
</header>
<div class="filters-bar">
<div class="filter-group">
<label>PIN da Estação</label>
<input type="text" id="filterPin" placeholder="Ex: 1234" style="width: 100px;">
</div>
<div class="filter-group">
<label>Terminal / Agente</label>
<input type="text" id="filterAgent" placeholder="Ex: BotAssistente" style="width: 140px;">
</div>
<div class="filter-group">
<label>Categoria</label>
<select id="filterCategory">
<option value="">Todas</option>
<option value="screen_state">Estado de Tela (App)</option>
<option value="terminal">Saída de Terminal (Daemon)</option>
<option value="chat">Mensagens de Chat</option>
<option value="gateway">Eventos de Gateway</option>
</select>
</div>
<div class="filter-group">
<label>Origem</label>
<select id="filterSource">
<option value="">Todas</option>
<option value="mobile">Mobile App</option>
<option value="gateway">Estação Gateway</option>
<option value="relay">Relay Server</option>
</select>
</div>
<div class="filter-group" style="align-self: flex-end;">
<button onclick="refreshTraces()">Filtrar / Atualizar</button>
</div>
<div class="filter-group" style="align-self: flex-end;">
<button class="btn-secondary" onclick="clearTracesTable()">Limpar Tela</button>
</div>
</div>
<div class="view-modes">
<button class="tab-btn active" id="tabCompare" onclick="switchView('compare')">🔍 Comparador Lado a Lado (Daemon vs Tela Mobile)</button>
<button class="tab-btn" id="tabTable" onclick="switchView('table')">📋 Linha do Tempo de Traces</button>
</div>
<!-- Painel de Comparação Lado a Lado -->
<div id="compareView">
<div id="mismatchBanner" class="mismatch-banner">
⚠️ ATENÇÃO: Divergência detectada entre o Daemon e a Tela do App para o terminal selecionado!
</div>
<div class="compare-container">
<div class="compare-card">
<div class="compare-header">
<span>🖥️ Estação Daemon (Último Output / Activity)</span>
<span id="daemonStatusBadge" class="badge badge-idle">Aguardando</span>
</div>
<div class="compare-body" id="daemonTerminalBody">Nenhuma captura de terminal do daemon recebida ainda.</div>
</div>
<div class="compare-card">
<div class="compare-header">
<span>📱 App Mobile (Snapshot de Estado de Tela)</span>
<span id="mobileStatusBadge" class="badge badge-idle">Aguardando</span>
</div>
<div class="compare-body" id="mobileScreenBody">Nenhum snapshot de estado de tela do app móvel recebido ainda.</div>
</div>
</div>
</div>
<!-- Painel de Tabela Completa de Traces -->
<div id="tableView" style="display: none;">
<div class="traces-table-container">
<table id="tracesTable">
<thead>
<tr>
<th>Horário (Local)</th>
<th>Origem</th>
<th>PIN</th>
<th>Agente / Terminal</th>
<th>Categoria</th>
<th>Ação / Resumo</th>
<th>Detalhes JSON</th>
</tr>
</thead>
<tbody id="tracesBody">
<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 2rem;">Carregando traces...</td></tr>
</tbody>
</table>
</div>
</div>
<script>
let eventSource = null;
let isStreamActive = true;
let traces = [];
let latestDaemonEventByAgent = new Map();
let latestMobileEventByAgent = new Map();
function switchView(mode) {
document.getElementById('compareView').style.display = (mode === 'compare') ? 'block' : 'none';
document.getElementById('tableView').style.display = (mode === 'table') ? 'block' : 'none';
document.getElementById('tabCompare').classList.toggle('active', mode === 'compare');
document.getElementById('tabTable').classList.toggle('active', mode === 'table');
}
function toggleStream() {
const btn = document.getElementById('btnPauseResume');
const text = document.getElementById('streamStatusText');
const dot = document.querySelector('.pulse-dot');
if (isStreamActive) {
if (eventSource) eventSource.close();
isStreamActive = false;
btn.textContent = 'Retomar';
text.textContent = 'Stream Pausado';
text.style.color = 'var(--text-muted)';
dot.style.background = 'var(--text-muted)';
dot.style.animation = 'none';
} else {
initSSE();
isStreamActive = true;
btn.textContent = 'Pausar';
text.textContent = 'SSE Conectado em tempo real';
text.style.color = 'var(--success)';
dot.style.background = 'var(--success)';
dot.style.animation = 'pulse 1.5s infinite';
}
}
function initSSE() {
if (eventSource) eventSource.close();
eventSource = new EventSource('/api/telemetry/stream');
eventSource.onmessage = (e) => {
try {
const ev = JSON.parse(e.data);
addTrace(ev, true);
} catch (_) {}
};
eventSource.onerror = () => {
document.getElementById('streamStatusText').textContent = 'Reconectando stream...';
};
}
async function refreshTraces() {
const pin = document.getElementById('filterPin').value.trim();
const agent = document.getElementById('filterAgent').value.trim();
const cat = document.getElementById('filterCategory').value;
const src = document.getElementById('filterSource').value;
const params = new URLSearchParams();
if (pin) params.set('pin', pin);
if (agent) params.set('agent', agent);
if (cat) params.set('category', cat);
if (src) params.set('source', src);
params.set('limit', '250');
try {
const res = await fetch(`/api/telemetry/traces?${params.toString()}`);
if (!res.ok) throw new Error('Falha ao carregar traces');
const data = await res.json();
traces = data || [];
renderAllTraces();
} catch (err) {
console.error(err);
}
}
function addTrace(ev, isLive = false) {
traces.unshift(ev);
if (traces.length > 500) traces.pop();
// Atualiza mapas para comparação lado a lado
const agentKey = (ev.agentName || 'global').toLowerCase();
if (ev.source === 'gateway' || ev.category === 'terminal') {
latestDaemonEventByAgent.set(agentKey, ev);
} else if (ev.source === 'mobile' || ev.category === 'screen_state') {
latestMobileEventByAgent.set(agentKey, ev);
}
updateComparisonView(ev.agentName);
// Se a tabela estiver visível, insere a linha no topo
const tbody = document.getElementById('tracesBody');
if (tbody) {
const row = createTraceRow(ev);
tbody.insertBefore(row, tbody.firstChild);
}
}
function updateComparisonView(targetAgent) {
const filterAgent = document.getElementById('filterAgent').value.trim().toLowerCase();
const agent = filterAgent || (targetAgent ? targetAgent.toLowerCase() : null);
if (!agent && latestDaemonEventByAgent.size === 0 && latestMobileEventByAgent.size === 0) return;
const key = agent || (latestDaemonEventByAgent.keys().next().value || latestMobileEventByAgent.keys().next().value);
const daemonEv = latestDaemonEventByAgent.get(key);
const mobileEv = latestMobileEventByAgent.get(key);
const daemonBody = document.getElementById('daemonTerminalBody');
const mobileBody = document.getElementById('mobileScreenBody');
const daemonBadge = document.getElementById('daemonStatusBadge');
const mobileBadge = document.getElementById('mobileStatusBadge');
const mismatchBanner = document.getElementById('mismatchBanner');
let daemonThinking = null;
let mobileThinking = null;
if (daemonEv) {
daemonThinking = daemonEv.payload?.isThinking;
daemonBadge.textContent = daemonThinking ? '⚡ Thinking / Executando' : '🟢 Ocioso / Pronto';
daemonBadge.className = daemonThinking ? 'badge badge-thinking' : 'badge badge-idle';
daemonBody.textContent = `[${daemonEv.timestamp}] Agente: ${daemonEv.agentName}\nThinking: ${daemonThinking}\nPaused: ${daemonEv.payload?.isPaused}\n\nSaída Raw / Sanitizada:\n${daemonEv.payload?.output || daemonEv.payload?.rawOutput || JSON.stringify(daemonEv.payload, null, 2)}`;
}
if (mobileEv) {
mobileThinking = mobileEv.payload?.isThinking;
mobileBadge.textContent = mobileThinking ? '⚡ Thinking (Banner Amarelo)' : '🟢 Pronto';
mobileBadge.className = mobileThinking ? 'badge badge-thinking' : 'badge badge-idle';
mobileBody.textContent = `[${mobileEv.timestamp}] Agente: ${mobileEv.agentName}\nThinking no App: ${mobileThinking}\nBanner Text: "${mobileEv.payload?.bannerText || ''}"\nDrawer Ativo: ${mobileEv.payload?.drawerActive}\nMensagens Chat: ${mobileEv.payload?.chatBubblesCount}\nÚltimo Prompt Usuário: ${JSON.stringify(mobileEv.payload?.lastUserMessage)}\nÚltima Resposta Agente: ${JSON.stringify(mobileEv.payload?.lastAgentMessage)}`;
}
// Detecta divergência flagrante (daemon já terminou mas mobile continua thinking)
if (daemonEv && mobileEv && daemonThinking === false && mobileThinking === true) {
mismatchBanner.style.display = 'block';
mismatchBanner.innerHTML = `⚠️ DIVERGÊNCIA IDENTIFICADA: O Daemon da estação informou que ${key} CONCLUIU a execução (isThinking=false), porém o App Mobile ainda exibe o banner amarelo (isThinking=true).`;
} else {
mismatchBanner.style.display = 'none';
}
}
function createTraceRow(ev) {
const tr = document.createElement('tr');
const d = new Date(ev.timestamp);
const timeStr = d.toLocaleTimeString('pt-BR') + '.' + String(d.getMilliseconds()).padStart(3, '0');
let srcClass = 'badge-relay';
if (ev.source === 'mobile') srcClass = 'badge-mobile';
if (ev.source === 'gateway') srcClass = 'badge-gateway';
tr.innerHTML = `
<td style="color: var(--text-muted);">${timeStr}</td>
<td><span class="badge ${srcClass}">${ev.source}</span></td>
<td>${ev.pin || '-'}</td>
<td style="font-weight: 600;">${ev.agentName || '-'}</td>
<td><code>${ev.category}</code></td>
<td>${escapeHtml(ev.action)} · <span style="color: var(--text-muted);">${escapeHtml(ev.summary || '')}</span></td>
<td><span class="json-preview" onclick="toggleDetails('${ev.id}')">expandir</span></td>
`;
const detailsTr = document.createElement('tr');
detailsTr.id = `details-${ev.id}`;
detailsTr.className = 'details-row';
detailsTr.innerHTML = `
<td colspan="7">
<div class="details-content">${escapeHtml(JSON.stringify(ev, null, 2))}</div>
</td>
`;
const frag = document.createDocumentFragment();
frag.appendChild(tr);
frag.appendChild(detailsTr);
return frag;
}
function toggleDetails(id) {
const row = document.getElementById(`details-${id}`);
if (row) {
row.style.display = (row.style.display === 'table-row') ? 'none' : 'table-row';
}
}
function renderAllTraces() {
const tbody = document.getElementById('tracesBody');
tbody.innerHTML = '';
if (traces.length === 0) {
tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 2rem;">Nenhum trace encontrado com os filtros atuais.</td></tr>';
return;
}
for (const ev of traces) {
tbody.appendChild(createTraceRow(ev));
const agentKey = (ev.agentName || 'global').toLowerCase();
if (ev.source === 'gateway' || ev.category === 'terminal') {
latestDaemonEventByAgent.set(agentKey, ev);
} else if (ev.source === 'mobile' || ev.category === 'screen_state') {
latestMobileEventByAgent.set(agentKey, ev);
}
}
updateComparisonView();
}
function clearTracesTable() {
traces = [];
renderAllTraces();
}
function escapeHtml(str) {
if (!str) return '';
return String(str).replace(/[&<>"']/g, (m) => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'
})[m]);
}
// Inicialização
initSSE();
refreshTraces();
</script>
</body>
</html>