Files
junction/web/public/app.js
T
Hermes b71bfb5a0a Dashboard zeigt die letzten Anfragen — Dauer, Cache-Quelle, p95, Trefferquote
Die Zeilen aus dem Anfrage-Log lagen bisher nur in der Datei. Jetzt gibt es sie über den
Steuerkanal (`requests.tail`, Standard 20, Deckel 200) und das Dashboard zeigt sie:
Zeit, Modell, Ziel, Status, Millisekunden, Cache-Quelle, Tokens, Kosten — dazu p95 und
Trefferquote, ausdrücklich nur über die angezeigten Zeilen gerechnet.

Gelesen wird der letzte Block der Datei (256 KB), nicht die ganze: ein Ledger wächst, und
das Dashboard fragt regelmäßig. Die erste, womöglich angeschnittene Zeile fällt weg; bei
mehr Zeilen als gefragt bleiben die neuesten, nicht die ersten (Ringpuffer, geprüft mit
500 Zeilen und count 9999: n=200, erste m300, letzte m499).

Auf n95 live: control-Socket beantwortet requests.tail, Dashboard zeigt vier echte
Anfragen mit 714–751 ms, Karte "Letzte Anfragen" im HTML, app.js liest sie über
/api/requests.

Tests: control.py prüft requests.tail gegen ein vorbereitetes Ledger und den Deckel —
11 statt 9 Prüfungen. make test: PASS, 222 Prüfungen, 154 s.
2026-11-08 12:25:22 +00:00

446 lines
16 KiB
JavaScript

'use strict';
/* Zeichnet, was der Server schickt. Keine Bibliothek: drei Diagrammarten reichen,
* und eine Kurve von Hand zu zeichnen ist weniger Code als das Einbinden einer
* Chart-Bibliothek — und funktioniert ohne Netz. */
const $ = (sel) => document.querySelector(sel);
const fmt = (v, d = 0) => (v === null || v === undefined || Number.isNaN(v))
? '—' : Number(v).toFixed(d);
function css(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
/* ------------------------------------------------------------------ Zeichnen */
function setup(canvas) {
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = Math.max(1, Math.floor(rect.width * dpr));
canvas.height = Math.max(1, Math.floor(Number(canvas.getAttribute('height')) * dpr));
const ctx = canvas.getContext('2d');
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
return { ctx, w: rect.width, h: Number(canvas.getAttribute('height')) };
}
/* Mehrere Reihen übereinander, gemeinsame Skala. Flächen statt Linien: der
* Verlauf zeigt die Menge, die Linie die Bewegung. */
function drawSeries(canvas, rows, opts = {}) {
const { ctx, w, h } = setup(canvas);
const pad = { l: 6, r: 6, t: 8, b: 16 };
const iw = w - pad.l - pad.r;
const ih = h - pad.t - pad.b;
const colors = opts.colors || [css('--accent'), css('--warn'), css('--bad')];
const maxLen = Math.max(...rows.map((r) => r.values.length), 2);
let max = 0;
for (const r of rows) for (const v of r.values) if (v > max) max = v;
if (max <= 0) max = 1;
ctx.clearRect(0, 0, w, h);
// Gitter
ctx.strokeStyle = css('--line');
ctx.globalAlpha = 0.5;
ctx.lineWidth = 1;
for (let i = 0; i <= 3; i++) {
const y = pad.t + (ih / 3) * i;
ctx.beginPath();
ctx.moveTo(pad.l, y);
ctx.lineTo(pad.l + iw, y);
ctx.stroke();
}
ctx.globalAlpha = 1;
const xOf = (i) => pad.l + (iw * i) / Math.max(1, maxLen - 1);
const yOf = (v) => pad.t + ih - (ih * Math.min(v, max)) / max;
// gestapelt zeichnen: unten die erste Reihe
let baseline = rows.map(() => pad.t + ih);
for (let ri = 0; ri < rows.length; ri++) {
const row = rows[ri];
const n = row.values.length;
if (!n) continue;
ctx.beginPath();
ctx.moveTo(xOf(0), yOf(row.values[0]));
for (let i = 1; i < n; i++) ctx.lineTo(xOf(i), yOf(row.values[i]));
ctx.strokeStyle = colors[ri % colors.length];
ctx.lineWidth = 1.6;
ctx.stroke();
ctx.lineTo(xOf(n - 1), pad.t + ih);
ctx.lineTo(xOf(0), pad.t + ih);
ctx.closePath();
const grad = ctx.createLinearGradient(0, pad.t, 0, pad.t + ih);
grad.addColorStop(0, colors[ri % colors.length] + '55');
grad.addColorStop(1, colors[ri % colors.length] + '05');
ctx.fillStyle = grad;
ctx.fill();
}
// Höchstwert als Zahl in der Ecke
ctx.fillStyle = css('--dim');
ctx.font = '11px ui-monospace, monospace';
ctx.fillText(opts.unit ? `${fmt(max, opts.digits || 0)} ${opts.unit}` : fmt(max, opts.digits || 0), pad.l + 2, pad.t + 10);
}
/* ------------------------------------------------------------------ Zustand */
let status = null;
let series = null;
function state() {
const s = status || {};
const reqs = s.requests || {};
const usage = s.usage || {};
const lat = s.latency || {};
return { reqs, usage, lat };
}
function renderHeader() {
const { reqs, usage, lat } = state();
const ser = series || {};
const lastOf = (k) => {
const a = (ser[k] || []);
return a.length ? a[a.length - 1] : null;
};
$('#n-req').textContent = fmt(lastOf('requests'), 2);
$('#n-tok').textContent = fmt((lastOf('tokensIn') || 0) + (lastOf('tokensOut') || 0), 0);
$('#n-lat').textContent = lat.avg_ms >= 0 ? `${fmt(lat.avg_ms, 0)} ms` : '—';
$('#n-cost').textContent = (() => {
const c = lastOf('cost');
return c === null ? '—' : `${fmt(c * 3600, 3)} $`;
})();
$('#n-fail').textContent = fmt(reqs.fail || 0);
$('#n-fail').style.color = (reqs.fail || 0) > 0 ? css('--bad') : '';
const up = status && status.uptime_s !== undefined ? status.uptime_s : null;
$('#uptime').textContent = up === null ? '—' : `läuft ${duration(up)}`;
const dot = $('#state');
dot.className = 'dot ' + (status ? 'live' : 'dead');
}
function duration(s) {
if (s < 60) return `${Math.round(s)} s`;
if (s < 3600) return `${Math.floor(s / 60)} min`;
if (s < 86400) return `${Math.floor(s / 3600)} h ${Math.floor((s % 3600) / 60)} min`;
return `${Math.floor(s / 86400)} d ${Math.floor((s % 86400) / 3600)} h`;
}
function renderCharts() {
if (!series) return;
drawSeries($('#g-requests'), [
{ values: series.requests || [] },
{ values: series.failed || [] },
], { unit: '/s', digits: 2, colors: [css('--accent'), css('--bad')] });
$('#c-req').textContent = `jetzt ${fmt((series.requests || []).slice(-1)[0], 2)}/s · Fehler ${fmt((series.failed || []).slice(-1)[0], 2)}/s`;
drawSeries($('#g-tokens'), [
{ values: series.tokensIn || [] },
{ values: series.tokensOut || [] },
], { unit: 'tok/s', digits: 0, colors: [css('--ok'), css('--accent')] });
const ti = (series.tokensIn || []).slice(-1)[0] || 0;
const to = (series.tokensOut || []).slice(-1)[0] || 0;
$('#c-tok').textContent = `ein ${fmt(ti)}/s · aus ${fmt(to)}/s`;
drawSeries($('#g-latency'), [{ values: (series.latency || []).map((v) => (v < 0 ? 0 : v)) }],
{ unit: 'ms', digits: 0, colors: [css('--warn')] });
drawSeries($('#g-traffic'), [{ values: series.traffic || [] }],
{ unit: 'B/s', digits: 0, colors: [css('--accent')] });
}
function renderEndpoints() {
const body = $('#t-eps tbody');
const eps = (status && status.endpoints) || [];
body.innerHTML = '';
for (const ep of eps) {
const tr = document.createElement('tr');
const state = ep.paused
? '<span class="tag paused">pausiert</span>'
: (ep.offline_s > 0
? `<span class="tag bad">offline ${ep.offline_s}s</span>`
: (ep.exhausted ? '<span class="tag bad">erschöpft</span>' : '<span class="tag ok">bereit</span>'));
tr.innerHTML = `
<td>${escapeHtml(ep.name)}<br><span class="muted" style="font-size:11px">${escapeHtml(ep.kind || '')}</span></td>
<td>${state}</td>
<td class="num">${fmt(ep.ok)}</td>
<td class="num">${fmt(ep.fail)}</td>
<td class="num">${fmt(ep.inflight)}</td>
<td class="num">${fmt(ep.last_ms)}</td>
<td class="num"><button class="ghost" data-ep="${escapeHtml(ep.name)}" data-act="${ep.paused ? 'resume' : 'pause'}">${ep.paused ? 'aufnehmen' : 'pausieren'}</button></td>`;
body.appendChild(tr);
}
for (const btn of body.querySelectorAll('button[data-ep]')) {
btn.onclick = async () => {
await fetch(`/api/endpoint/${encodeURIComponent(btn.dataset.ep)}/${btn.dataset.act}`, { method: 'POST' });
refresh();
};
}
}
function renderMcp(servers, tools) {
const body = $('#t-mcp tbody');
if (!body) return;
body.innerHTML = '';
const list = servers || [];
const toolList = tools || [];
$('#c-mcp').textContent = list.length
? `${list.length} angebunden · ${toolList.length} Werkzeuge`
: 'keiner angebunden';
for (const m of list) {
const tr = document.createElement('tr');
const state = !m.enabled
? '<span class="tag">aus</span>'
: (m.fail > 0 && m.tools === 0
? `<span class="tag bad">${escapeHtml(m.last_error || 'keine Antwort')}</span>`
: '<span class="tag ok">erreichbar</span>');
tr.innerHTML = `
<td>${escapeHtml(m.name)}</td>
<td class="muted" style="font-size:12px">${escapeHtml(m.url)}</td>
<td class="num">${fmt(m.tools)}</td>
<td class="num">${fmt(m.ok)}</td>
<td class="num">${fmt(m.fail)}</td>
<td>${state}</td>`;
body.appendChild(tr);
}
// Werkzeuge nach Server gruppieren: der Präfix vor "__" ist der Server.
const box = $('#mcp-tools');
box.innerHTML = '';
const seen = new Set();
for (const t of toolList) {
const name = t.name || '';
const cut = name.indexOf('__');
const server = cut > 0 ? name.slice(0, cut) : '—';
const short = cut > 0 ? name.slice(cut + 2) : name;
if (seen.has(name)) continue;
seen.add(name);
const el = document.createElement('span');
el.className = 'tool';
el.innerHTML = `<span>${escapeHtml(server)}</span> <b>${escapeHtml(short)}</b>`;
if (t.description) el.title = t.description;
box.appendChild(el);
}
}
function renderVkeys() {
const body = $('#t-vkeys tbody');
if (!body) return;
const keys = (status && status.vkeys) || [];
body.innerHTML = '';
for (const k of keys) {
const tr = document.createElement('tr');
const over = k.budget_usd > 0 && k.spent_usd >= k.budget_usd;
tr.innerHTML = `
<td>${escapeHtml(k.name)}</td>
<td class="muted">${escapeHtml(k.allow || '*')}</td>
<td class="num">${k.rpm > 0 ? k.rpm : '—'}</td>
<td class="num">${k.budget_usd > 0 ? '$' + k.budget_usd.toFixed(2) : '—'}</td>
<td class="num">$${(k.spent_usd || 0).toFixed(4)}</td>
<td class="num">${fmt(k.hits)}</td>
<td class="num">${fmt(k.denied)}${over ? ' <span class="tag bad">erschöpft</span>' : ''}</td>`;
body.appendChild(tr);
}
const refused = (status && status.guard_refused) || 0;
const c = $('#c-spend');
if (c) c.textContent = keys.length
? `${keys.length} Schlüssel${refused ? ' · ' + refused + ' vom Wächter abgelehnt' : ''}`
: 'keine virtuellen Schlüssel';
}
async function loadSpend() {
const box = $('#spend-detail');
if (!box) return;
try {
const r = await fetch('/api/spend').then((x) => x.json());
if (!r.ok || !r.spend) {
box.textContent = r.error || 'keine Auskunft';
return;
}
const sp = r.spend;
if (sp.error) {
box.textContent = sp.error;
return;
}
const models = (sp.models || []).map((m) =>
`<span class="tool">${escapeHtml(m.model)} · $${m.cost_usd.toFixed(4)} · ${fmt(m.requests)}</span>`).join(' ');
box.innerHTML = `<b>${escapeHtml(sp.month)}</b>: $${sp.total_usd.toFixed(4)}`
+ ` über ${fmt(sp.requests)} Anfragen` + (models ? '<br>' + models : '');
} catch (e) {
box.textContent = 'keine Auskunft';
}
}
function renderRules(rules) {
const body = $('#t-rules tbody');
body.innerHTML = '';
$('#c-rules').textContent = `${rules.length} aktiv`;
rules.forEach((r, i) => {
const tr = document.createElement('tr');
const need = [r.need_min >= 0 ? `≥${r.need_min}` : '', r.need_max >= 0 ? `≤${r.need_max}` : '']
.filter(Boolean).join(' ') || '—';
const ctx = [r.ctx_min >= 0 ? `≥${r.ctx_min}` : '', r.ctx_max >= 0 ? `≤${r.ctx_max}` : '']
.filter(Boolean).join(' ') || '—';
tr.innerHTML = `
<td class="num">${r.index ?? i}</td>
<td>${escapeHtml(r.model || '*')}</td>
<td>${escapeHtml(r.path || '*')}</td>
<td>${r.block ? '<span class="tag bad">block</span>' : escapeHtml(r.targets || '')}</td>
<td class="num">${need}</td>
<td class="num">${ctx}</td>
<td class="num"><button class="ghost" data-rule="${r.index ?? i}">löschen</button></td>`;
body.appendChild(tr);
});
for (const btn of body.querySelectorAll('button[data-rule]')) {
btn.onclick = async () => {
await fetch(`/api/rules?index=${encodeURIComponent(btn.dataset.rule)}`, { method: 'DELETE' });
refresh();
};
}
}
async function loadRequests() {
const body = $('#t-req tbody');
if (!body) return;
try {
const r = await fetch('/api/requests?count=25').then((x) => x.json());
const lines = (r.ok && r.requests && r.requests.lines) || [];
body.innerHTML = '';
if (!lines.length) {
const stats = $('#req-stats');
if (stats) stats.textContent = (r.error || 'noch keine Anfragen im Log');
return;
}
for (const l of lines) {
const tr = document.createElement('tr');
const when = l.ts ? new Date(l.ts * 1000).toLocaleTimeString() : '—';
const bad = l.status && l.status >= 400;
tr.innerHTML = `
<td class="muted">${when}</td>
<td>${escapeHtml(l.model || '—')}</td>
<td class="muted">${escapeHtml(l.endpoint || '—')}</td>
<td class="num">${bad ? '<span class="tag bad">' + l.status + '</span>' : (l.status || '—')}</td>
<td class="num">${l.latency_ms ?? '—'}</td>
<td>${escapeHtml(l.cache || '—')}</td>
<td class="num">${fmt(l.tokens_in)}/${fmt(l.tokens_out)}</td>
<td class="num">${(l.cost_usd || 0).toFixed(6)}</td>`;
body.appendChild(tr);
}
/* p95 und Trefferquote über genau diese Zeilen — nicht über den Tag. */
const ms = lines.map((l) => Number(l.latency_ms) || 0).sort((a, b) => a - b);
const p95 = ms.length ? ms[Math.min(ms.length - 1, Math.ceil(ms.length * 0.95) - 1)] : 0;
const hits = lines.filter((l) => ['hit', 'peer', 'joined'].includes(l.cache)).length;
const stats = $('#req-stats');
if (stats) stats.textContent =
`${lines.length} Anfragen · p95 ${p95} ms · Trefferquote ${Math.round(hits / lines.length * 100)} %`;
} catch (e) {
const stats = $('#req-stats');
if (stats) stats.textContent = 'keine Auskunft';
}
}
function escapeHtml(s) {
return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
/* ------------------------------------------------------------------ Daten */
async function refresh() {
try {
const r = await fetch('/api/snapshot');
const data = await r.json();
status = data.ok ? data.status : null;
series = data.series || series;
renderHeader();
renderCharts();
renderEndpoints();
renderRules(data.rules || []);
renderMcp((data.status && data.status.mcp) || [], data.tools || []);
renderVkeys();
loadSpend();
loadRequests();
} catch (e) {
status = null;
renderHeader();
}
}
function listen() {
const es = new EventSource('/api/stream');
es.onmessage = (ev) => {
try {
const data = JSON.parse(ev.data);
status = data.ok ? data.status : null;
if (data.series) series = data.series;
renderHeader();
renderCharts();
renderEndpoints();
renderRules(data.rules || []);
renderMcp((data.status && data.status.mcp) || [], data.tools || []);
renderVkeys();
} catch (e) { /* ein kaputter Rahmen darf die Anzeige nicht anhalten */ }
};
es.onerror = () => {
es.close();
setTimeout(listen, 3000);
};
}
/* ------------------------------------------------------------------ Formulare */
$('#f-rule').onsubmit = async (e) => {
e.preventDefault();
const text = $('#rule-text').value.trim();
if (!text) return;
const r = await fetch('/api/rules', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
}).then((x) => x.json());
const hint = $('#rule-hint');
hint.className = 'hint ' + (r.ok ? 'ok' : 'bad');
hint.textContent = r.ok ? 'gesetzt' : (r.error || 'fehlgeschlagen');
if (r.ok) $('#rule-text').value = '';
refresh();
};
$('#cfg-load').onclick = async () => {
const r = await fetch('/api/config').then((x) => x.json());
const hint = $('#cfg-hint');
if (r.ok) {
$('#config').value = r.text || '';
hint.className = 'hint ok';
hint.textContent = 'geladen';
} else {
hint.className = 'hint bad';
hint.textContent = r.error || 'nicht ladbar';
}
};
$('#cfg-save').onclick = async () => {
const hint = $('#cfg-hint');
hint.className = 'hint';
hint.textContent = 'wird geprüft …';
const r = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: $('#config').value }),
}).then((x) => x.json());
hint.className = 'hint ' + (r.ok ? 'ok' : 'bad');
hint.textContent = r.ok ? 'gespeichert und übernommen' : (r.error || 'abgelehnt');
refresh();
};
window.addEventListener('resize', () => renderCharts());
const mcpUrl = $('#mcp-url');
if (mcpUrl) mcpUrl.textContent = `${location.origin.replace(/:\d+$/, '')}:8090/mcp`;
refresh();
listen();
setInterval(refresh, 5000);