Files
omega-ai-proxy/proxy/ui/app.js
T
Stephan RehfeldandClaude Opus 5.5 d753fd9285 Oberfläche: Fehler bei Keys und Zeitplan behoben, Rendertest, Metadaten löschen, Postausgang
- Übersicht und API-Keys brachen für alle Rollen ab, der Zeitplan bei
  vorhandenen Einträgen: Keys und Zeitplaneinträge liegen in der API flach
  im Objekt, nicht in einem Unterobjekt
- tests/ui/render_test.js: rendert jede Seite für admin, dozent und student
  in jsdom gegen den laufenden Proxy und spielt Abläufe durch (Anmelden,
  Key, Aufzeichnung, Gruppe, Mitglied, Kontingent, Zeitplan, Benutzer,
  Metadaten löschen)
- Audit-Log: alte Metadaten löschen und Postausgang
- README und Beispielkonfiguration zur Oberfläche

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:23:36 +01:00

885 lines
55 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Omega AI Proxy – Oberfläche. Eine kleine Single-Page-App ohne Bibliotheken über der
// Verwaltungs-API unter /omega/api. Inhalte vom Server kommen nur als Text ins DOM.
'use strict';
// ---------- Werkzeuge ----------
const app = document.getElementById('app');
const state = { me: null, flash: null };
/** Element bauen: h('div', { class: 'x', onclick: f, style: { width: '5%' } }, kind1, 'Text', …) */
function h(tag, props, ...children) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(props || {})) {
if (v === null || v === undefined || v === false) continue;
if (k === 'class') el.className = v;
else if (k === 'style') Object.assign(el.style, v);
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else if (k === 'value') el.value = v;
else if (k === 'checked' || k === 'selected' || k === 'disabled') el[k] = !!v;
else el.setAttribute(k, v === true ? '' : v);
}
append(el, children);
return el;
}
function append(el, children) {
for (const c of children.flat(Infinity)) {
if (c === null || c === undefined || c === false) continue;
el.append(c instanceof Node ? c : document.createTextNode(String(c)));
}
}
const SVG = 'http://www.w3.org/2000/svg';
const ICONS = {
overview: ['rect 2 2 5 5', 'rect 9 2 5 5', 'rect 2 9 5 5', 'rect 9 9 5 5'],
keys: ['circle 5 11 3', 'path M7.2 8.8 13 3M11 5l2 2'],
account: ['path M8 1.5 13.5 3.5v4c0 3.5-2.4 5.9-5.5 7-3.1-1.1-5.5-3.5-5.5-7v-4z'],
groups: ['circle 6 5.5 2.5', 'path M1.5 14c.5-2.5 2.3-4 4.5-4s4 1.5 4.5 4M10.5 3.2a2.5 2.5 0 0 1 0 4.6M12 10.2c1.4.5 2.3 1.9 2.5 3.8'],
status: ['rect 2 2.5 12 4.5', 'rect 2 9 12 4.5', 'path M4.5 4.75h.01M4.5 11.25h.01'],
schedule: ['rect 2 3 12 11', 'path M2 6.5h12M5.5 1.5v3M10.5 1.5v3'],
users: ['circle 8 5.5 3', 'path M2.5 14.5c.6-3 2.8-4.5 5.5-4.5s4.9 1.5 5.5 4.5'],
audit: ['path M5 4h9M5 8h9M5 12h9M2 4h.01M2 8h.01M2 12h.01'],
public: ['path M2 14h12M4 11V7M8 11V3M12 11V8'],
menu: ['path M2 4h12M2 8h12M2 12h12'],
lock: ['rect 3 7 10 7', 'path M5 7V5a3 3 0 0 1 6 0v2'],
};
function icon(name, size = 16) {
const svg = document.createElementNS(SVG, 'svg');
for (const [k, v] of Object.entries({ width: size, height: size, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor',
'stroke-width': '1.5', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(k, v);
for (const part of ICONS[name] || []) {
const [kind, ...a] = part.split(' ');
const el = document.createElementNS(SVG, kind);
if (kind === 'rect') { el.setAttribute('x', a[0]); el.setAttribute('y', a[1]); el.setAttribute('width', a[2]); el.setAttribute('height', a[3]); el.setAttribute('rx', '1'); }
if (kind === 'circle') { el.setAttribute('cx', a[0]); el.setAttribute('cy', a[1]); el.setAttribute('r', a[2]); }
if (kind === 'path') el.setAttribute('d', a.join(' '));
svg.append(el);
}
return svg;
}
const nf = new Intl.NumberFormat('de-DE');
const num = (n) => nf.format(n || 0);
function tokens(n) {
n = n || 0;
if (n >= 1e6) return (n / 1e6).toLocaleString('de-DE', { maximumFractionDigits: 2 }) + ' M';
if (n >= 1e4) return Math.round(n / 1e3).toLocaleString('de-DE') + ' k';
return num(n);
}
function mb(n) {
if (n === null || n === undefined) return '–';
return n >= 1024 ? (n / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' GB' : num(n) + ' MB';
}
function when(ts) {
if (!ts) return '–';
return new Date(ts * 1000).toLocaleString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
}
function clock(ts) {
return new Date(ts * 1000).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
const tok = (c) => (c ? c.prompt_tokens + c.completion_tokens : 0);
const ROLE = { user: 'User', lecturer: 'Lecturer', admin: 'Administrator' };
const ENGINE = { ollama: 'Ollama', llamacpp: 'llama.cpp', vllm: 'vLLM' };
const PERIOD = { hour: 'Stunde', day: 'Tag', week: 'Woche', month: 'Monat', total: 'gesamt' };
const role = () => (state.me && state.me.user ? state.me.user.role : null);
const atLeast = (r) => ({ user: 1, lecturer: 2, admin: 3 }[role()] || 0) >= ({ user: 1, lecturer: 2, admin: 3 }[r]);
// ---------- Verbindung zur API ----------
class ApiError extends Error {
constructor(status, message) { super(message); this.status = status; }
}
async function api(method, path, body, quiet) {
const res = await fetch('/omega/api' + path, {
method,
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'X-Omega-CSRF': '1' },
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await res.text();
let data = null;
try { data = text ? JSON.parse(text) : null; } catch { data = text; }
if (!res.ok) {
const message = (data && data.error) || res.statusText || 'Fehler';
if (res.status === 401 && !quiet && path !== '/login') { state.me = null; go('login'); }
throw new ApiError(res.status, message);
}
return data;
}
/** Aktion mit Rückmeldung oben auf der Seite; lädt danach die Seite neu. */
async function act(fn, ok) {
try {
const result = await fn();
if (ok) state.flash = { kind: 'ok', text: typeof ok === 'function' ? ok(result) : ok };
await render();
return result;
} catch (e) {
state.flash = { kind: 'error', text: e.message };
await render();
return null;
}
}
function formData(form) {
const data = {};
for (const el of form.elements) {
if (!el.name) continue;
if (el.type === 'checkbox') data[el.name] = el.checked;
else data[el.name] = el.value.trim();
}
return data;
}
const optional = (v) => (v === '' || v === undefined ? undefined : v);
const optNum = (v) => (v === '' || v === undefined ? undefined : Number(v));
const list = (v) => (v ? v.split(/[\s,;]+/).filter(Boolean) : []);
// ---------- Navigation ----------
function route() {
const hash = location.hash.replace(/^#\/?/, '');
const [page, ...rest] = hash.split('/');
return { page: page || '', arg: rest.map(decodeURIComponent).join('/') };
}
function go(page) { location.hash = '#/' + page; }
window.addEventListener('hashchange', () => render());
const PAGES = {
'': { title: 'Übersicht', icon: 'overview', render: overview, section: 'Persönlich' },
keys: { title: 'API-Keys', icon: 'keys', render: keysPage, section: 'Persönlich' },
account: { title: 'Konto & Sicherheit', icon: 'account', render: accountPage, section: 'Persönlich' },
groups: { title: 'Gruppen & Kontingente', icon: 'groups', render: groupsPage, section: 'Lehre', role: 'lecturer' },
group: { render: groupPage, parent: 'groups', role: 'lecturer' },
quota: { render: quotaPage, parent: 'groups' },
status: { title: 'Sparks & Modelle', icon: 'status', render: statusPage, section: 'Administration', role: 'admin' },
schedule: { title: 'Zeitplan', icon: 'schedule', render: schedulePage, section: 'Administration', role: 'admin' },
users: { title: 'Benutzer', icon: 'users', render: usersPage, section: 'Administration', role: 'admin' },
audit: { title: 'Audit-Log', icon: 'audit', render: auditPage, section: 'Administration', role: 'admin' },
public: { title: 'Öffentliches Dashboard', icon: 'public', render: publicPage, section: 'Administration', open: true },
};
function initials(name) {
return name.split(/[^a-zA-Z]/).filter(Boolean).map((p) => p[0]).join('').slice(0, 2).toUpperCase() || name.slice(0, 2).toUpperCase();
}
function shell(current, content) {
const nav = h('nav', { class: 'nav', 'aria-label': 'Hauptnavigation' });
let section = null;
for (const [key, p] of Object.entries(PAGES)) {
if (!p.title || (p.role && !atLeast(p.role))) continue;
// Ohne Administration hängt das öffentliche Dashboard am letzten Bereich.
const sec = key === 'public' && !atLeast('admin') ? section : p.section;
if (sec !== section) { nav.append(h('span', { class: 'cap' }, sec)); section = sec; }
const on = current === key || PAGES[current] && PAGES[current].parent === key;
nav.append(h('a', { href: '#/' + key, class: on ? 'on' : null, 'aria-current': on ? 'page' : null }, icon(p.icon), p.title));
}
const user = state.me.user;
const side = h('aside', { class: 'side' },
h('div', { class: 'brand' },
h('div', { class: 'brand' }, h('div', { class: 'logo' }, 'Ω'), h('div', { class: 'brand-name' }, h('b', {}, 'Omega AI Proxy'), h('span', {}, 'Fakultät EFI'))),
h('button', { class: 'btn icon small menu-toggle', type: 'button', 'aria-label': 'Menü', onclick: () => side.classList.toggle('open') }, icon('menu'))),
nav,
h('div', { class: 'me' },
h('div', { class: 'avatar' }, initials(user.username)),
h('div', { class: 'me-name' }, h('b', {}, user.username), h('span', {}, ROLE[user.role])),
h('button', { class: 'btn small', type: 'button', onclick: logout }, 'Abmelden')));
nav.addEventListener('click', () => side.classList.remove('open'));
return h('div', { class: 'shell' }, side, h('main', { class: 'main' }, flash(), content));
}
function flash() {
if (!state.flash) return null;
const { kind, text } = state.flash;
state.flash = null;
return h('div', { class: 'notice ' + kind, role: kind === 'error' ? 'alert' : 'status' }, text);
}
function head(section, title, sub, ...actions) {
return h('header', { class: 'page-head' },
h('div', {}, h('div', { class: 'cap' }, section), h('h1', {}, title), sub ? h('p', {}, sub) : null),
actions.length ? h('div', { class: 'actions' }, actions) : null);
}
async function render() {
const { page, arg } = route();
const def = PAGES[page] || PAGES[''];
if (!state.me) {
try { state.me = await api('GET', '/me', undefined, true); } catch { state.me = null; }
}
if (!state.me) {
// Ohne Anmeldung gibt es nur das öffentliche Dashboard und die Anmeldung.
if (page === 'public') {
app.replaceChildren(h('main', { class: 'main' }, await publicContent()));
return;
}
return renderLogin();
}
if (page === 'login') return go('');
if (def.role && !atLeast(def.role)) return go('');
let content;
try {
content = await def.render(arg);
} catch (e) {
content = h('div', { class: 'notice error', role: 'alert' }, e.message);
}
app.replaceChildren(shell(page in PAGES ? page : '', content));
document.title = (def.title || 'Omega AI Proxy') + ' · Omega AI Proxy';
}
async function logout() {
try { await api('POST', '/logout'); } catch { /* abgemeldet ist abgemeldet */ }
state.me = null;
go('login');
render();
}
// ---------- Anmeldung ----------
async function renderLogin() {
const error = h('div', { class: 'notice error', role: 'alert', hidden: true });
const form = h('form', {
onsubmit: async (e) => {
e.preventDefault();
const d = formData(form);
try {
await api('POST', '/login', { username: d.username, password: d.password });
state.me = await api('GET', '/me');
go('');
render();
} catch (err) {
error.textContent = err.message;
error.hidden = false;
}
},
},
h('div', { class: 'field-group' }, h('label', { for: 'user' }, 'Benutzername'),
h('input', { id: 'user', name: 'username', class: 'field mono', autocomplete: 'username', required: true, autofocus: true })),
h('div', { class: 'field-group' }, h('label', { for: 'password' }, 'Passwort'),
h('input', { id: 'password', name: 'password', type: 'password', class: 'field', autocomplete: 'current-password', required: true })),
error,
h('button', { class: 'btn primary wide', type: 'submit' }, 'Anmelden'),
h('span', { class: 'hint' }, 'Testbetrieb: Anmeldung mit Passwort. Später mit Passkey, Magic Link oder 2FA-Code.'));
let pub;
try { pub = await publicContent(); } catch { pub = h('p', { class: 'muted' }, 'Auslastung nicht verfügbar.'); }
app.replaceChildren(h('div', { class: 'login' },
h('section', { class: 'login-panel' },
h('div', { class: 'login-box' },
h('div', { class: 'brand' }, h('div', { class: 'logo big' }, 'Ω'),
h('div', { class: 'brand-name' }, h('b', {}, 'Omega AI Proxy'), h('span', {}, 'KI-Modelle der Fakultät EFI'))),
h('div', {}, h('h1', {}, 'Anmelden'), h('p', { class: 'muted' }, 'Mit deinem Benutzernamen der Hochschule.')),
form,
h('p', { class: 'privacy' }, icon('lock'),
'Anfragen und Antworten werden nicht gespeichert. Der Proxy erfasst nur Metadaten wie Modell, Token und Zeitpunkt.'))),
h('section', { class: 'login-public' }, pub)));
document.title = 'Anmelden · Omega AI Proxy';
}
// ---------- Öffentliches Dashboard ----------
/** Balkendiagramm aus Werten; der letzte Balken ist hervorgehoben. */
function bars(values, label, axis) {
const max = Math.max(1, ...values);
return [
h('div', { class: 'chart', role: 'img', 'aria-label': label },
values.map((v, i) => h('div', { class: i === values.length - 1 ? 'now' : null, style: { height: (v / max * 100) + '%' }, title: num(v) }))),
axis ? h('div', { class: 'chart-axis' }, axis.map((a) => h('span', {}, a))) : null,
];
}
async function publicContent() {
const pub = await api('GET', '/public/dashboard?hours=24');
// Letzte Probe je Rechner
const latest = {};
for (const s of pub.samples) latest[s.node] = s;
const nodes = Object.values(latest);
const budget = nodes.reduce((a, s) => a + (s.budget_mb || 0), 0);
const used = nodes.reduce((a, s) => a + s.used_mb, 0);
const share = budget ? Math.round(used / budget * 100) : 0;
const hourly = pub.hourly;
const total = hourly.reduce((a, x) => a + x.requests, 0);
const peak = hourly.reduce((a, x) => (x.requests > a.requests ? x : a), hourly[0] || { requests: 0, hour: '' });
const waiting = nodes.reduce((a, s) => a + s.waiting, 0);
return h('div', { class: 'stack' },
h('div', {}, h('div', { class: 'cap' }, 'Öffentlich · ohne Anmeldung'), h('h1', {}, 'Auslastung')),
h('div', { class: 'kpis' },
h('div', { class: 'kpi' }, h('span', {}, 'Speicher gerade'), h('span', { class: 'value accent' }, share + ' %'), h('span', { class: 'sub' }, mb(used) + ' von ' + mb(budget))),
h('div', { class: 'kpi' }, h('span', {}, 'Anfragen 24 h'), h('span', { class: 'value' }, num(total))),
h('div', { class: 'kpi' }, h('span', {}, 'Meiste Anfragen'), h('span', { class: 'value' }, peak && peak.requests ? peak.hour.slice(11, 16) + ' Uhr' : '–')),
h('div', { class: 'kpi' }, h('span', {}, 'Warteschlange'), h('span', { class: 'value' }, num(waiting)))),
h('figure', { class: 'card' },
h('figcaption', { class: 'card-head' }, h('b', {}, 'Letzte 24 Stunden'), h('span', { class: 'muted' }, 'Anfragen je Stunde')),
bars(hourly.map((x) => x.requests), 'Anfragen je Stunde der letzten 24 Stunden',
hourly.length ? [hourly[0].hour.slice(11, 16), hourly[Math.floor(hourly.length / 2)].hour.slice(11, 16), 'jetzt'] : [])),
h('div', { class: 'row' }, nodes.map((s) => h('div', { class: 'card grow' },
h('div', { class: 'card-head' }, h('h2', { class: 'mono' }, s.node), h('span', { class: 'mono muted' }, mb(s.used_mb) + ' / ' + mb(s.budget_mb))),
meter('Speicher', s.used_mb, s.budget_mb, mb),
h('span', { class: 'muted' }, s.loaded + ' Modelle geladen · ' + s.in_flight + ' Anfragen laufen · ' + s.waiting + ' warten')))));
}
async function publicPage() {
return publicContent();
}
// ---------- Bausteine für Verbrauch ----------
function meter(label, used, limit, fmt = num) {
const share = limit ? Math.min(100, used / limit * 100) : 0;
return h('div', { class: 'meter' },
h('div', { class: 'meter-head' }, h('span', {}, label), h('span', { class: 'mono' }, fmt(used) + (limit ? ' / ' + fmt(limit) : ''))),
h('div', { class: 'track' }, h('div', { class: share >= 90 ? 'full' : null, style: { width: share + '%' } })));
}
/** Fortschritt eines Kontingents für alle begrenzten Zeiträume */
function quotaMeters(q, usage) {
const rows = [];
for (const p of Object.keys(PERIOD)) {
if (q.tokens[p] != null) rows.push(meter('Token · ' + PERIOD[p], tok(usage[p]), q.tokens[p], tokens));
if (q.requests[p] != null) rows.push(meter('Anfragen · ' + PERIOD[p], usage[p].requests, q.requests[p]));
}
if (!rows.length) rows.push(h('span', { class: 'muted' }, 'Ohne Mengengrenzen · ' + tokens(tok(usage.total)) + ' Token insgesamt'));
return rows;
}
function keyState(k) {
if (k.revoked) return h('span', { class: 'muted' }, 'widerrufen');
if (k.recording) return h('span', { class: 'status' }, h('span', { class: 'dot accent' }), k.recording);
return h('span', { class: 'status' }, h('span', { class: 'dot good' }), 'aktiv');
}
function quotaLabel(k) {
if (k.is_super) return h('span', { class: 'chip accent' }, 'Super-Key');
if (!k.quota) return h('span', { class: 'muted' }, 'unbegrenzt');
return k.quota.name;
}
// ---------- Übersicht ----------
async function overview() {
const me = state.me = await api('GET', '/me');
const active = me.keys.filter((k) => !k.revoked);
const sum = (f) => active.reduce((a, k) => a + f(k.usage), 0);
const parts = [
head('Persönlich', 'Übersicht', 'Deine Nutzung über alle Keys.'),
h('div', { class: 'kpis' },
h('div', { class: 'kpi' }, h('span', {}, 'Token heute'), h('span', { class: 'value' }, tokens(sum((u) => tok(u.day))))),
h('div', { class: 'kpi' }, h('span', {}, 'Anfragen heute'), h('span', { class: 'value' }, num(sum((u) => u.day.requests)))),
h('div', { class: 'kpi' }, h('span', {}, 'Token diesen Monat'), h('span', { class: 'value' }, tokens(sum((u) => tok(u.month))))),
h('div', { class: 'kpi' }, h('span', {}, 'Aktive Keys'), h('span', { class: 'value' }, num(active.length)))),
];
const quotaCard = h('section', { class: 'card grow' }, h('h2', {}, 'Kontingente'),
me.quotas.length ? me.quotas.map((q) => h('div', { class: 'meter' },
h('b', {}, q.name), h('span', { class: 'hint' }, q.describe), quotaMeters(q, q.usage[0].usage)))
: h('p', { class: 'empty' }, atLeast('lecturer') ? 'Dir ist kein Kontingent zugeteilt; als ' + ROLE[role()] + ' kannst du unbegrenzte Keys anlegen.'
: 'Dir ist noch kein Kontingent zugeteilt. Sobald dich eine Lehrkraft in eine Gruppe aufnimmt, kannst du Keys anlegen.'));
parts.push(h('div', { class: 'row top' }, keysTableCard(me.keys, true), quotaCard));
if (me.managed) {
parts.push(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', {}, 'Meine Kontingente'), h('a', { href: '#/groups' }, 'Gruppen & Kontingente')),
me.managed.quotas.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Kontingent'), h('th', {}, 'Zugeteilt'), h('th', {}, 'Person'), h('th', { class: 'num' }, 'Token heute'), h('th', { class: 'num' }, 'Anfragen heute'), h('th', { class: 'num' }, 'Token gesamt'))),
h('tbody', {}, me.managed.quotas.flatMap((q) => (q.usage.length ? q.usage : [{ user: null, usage: null }]).map((p) => h('tr', {},
h('td', {}, h('a', { href: '#/quota/' + q.id }, q.name)), h('td', {}, q.target || '–'), h('td', { class: 'mono' }, p.user || (p.usage ? '(ohne Inhaber)' : 'noch keine Nutzung')),
h('td', { class: 'num' }, p.usage ? tokens(tok(p.usage.day)) : '–'), h('td', { class: 'num' }, p.usage ? num(p.usage.day.requests) : '–'),
h('td', { class: 'num' }, p.usage ? tokens(tok(p.usage.total)) : '–')))))))
: h('p', { class: 'empty' }, 'Noch keine Kontingente. Lege unter Gruppen & Kontingente eine Gruppe und ein Kontingent an.')));
}
if (me.system) {
const s = me.system;
parts.push(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', {}, 'System'), h('span', { class: 'muted' }, num(s.users) + ' Benutzer · ' + num(s.keys) + ' aktive Keys')),
h('div', { class: 'kpis' },
h('div', { class: 'kpi' }, h('span', {}, 'Anfragen heute'), h('span', { class: 'value' }, num(s.usage.day.requests))),
h('div', { class: 'kpi' }, h('span', {}, 'Token heute'), h('span', { class: 'value' }, tokens(tok(s.usage.day)))),
h('div', { class: 'kpi' }, h('span', {}, 'Token gesamt'), h('span', { class: 'value' }, tokens(tok(s.usage.total))))),
bars(s.hourly.map((x) => x.requests), 'Anfragen je Stunde der letzten 24 Stunden',
s.hourly.length ? [s.hourly[0].hour.slice(11, 16), s.hourly[12].hour.slice(11, 16), 'jetzt'] : [])));
}
return h('div', { class: 'stack' }, parts);
}
function keysTableCard(keys, compact) {
return h('section', { class: 'card grow' },
h('div', { class: 'card-head' }, h('h2', {}, 'Keys'), compact ? h('a', { href: '#/keys' }, 'Alle Keys verwalten') : null),
keys.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Key'), h('th', {}, 'Kontingent'), h('th', { class: 'num' }, 'Token heute'), h('th', { class: 'num' }, 'Anfragen heute'), h('th', { class: 'num' }, 'Token gesamt'), h('th', {}, 'Status'))),
h('tbody', {}, keys.map((k) => h('tr', { class: k.revoked ? 'dim' : null },
h('td', { class: 'mono' }, k.name), h('td', {}, quotaLabel(k)),
h('td', { class: 'num' }, tokens(tok(k.usage.day))), h('td', { class: 'num' }, num(k.usage.day.requests)),
h('td', { class: 'num' }, tokens(tok(k.usage.total))), h('td', {}, keyState(k)))))))
: h('p', { class: 'empty' }, 'Noch keine Keys.'));
}
// ---------- API-Keys ----------
async function keysPage() {
const [keys, quotas, recordings] = await Promise.all([api('GET', '/keys'), api('GET', '/quotas'), api('GET', '/recordings')]);
const me = state.me.user;
const own = keys.filter((k) => k.user_id === me.id);
const others = keys.filter((k) => k.user_id !== me.id);
const usable = quotas;
const created = state.createdKey;
state.createdKey = null;
const form = h('form', {
onsubmit: (e) => {
e.preventDefault();
const d = formData(form);
const body = { name: d.name };
if (d.kind === 'super') body.is_super = true;
else if (d.kind !== 'none') body.quota_id = Number(d.kind);
act(async () => { state.createdKey = { ...(await api('POST', '/keys', body)), name: d.name }; });
},
},
h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 'key-name' }, 'Name'),
h('input', { id: 'key-name', name: 'name', class: 'field mono', required: true, placeholder: 'z. B. laptop' })),
h('div', { class: 'field-group' }, h('label', { for: 'key-kind' }, 'Abgerechnet gegen'),
h('select', { id: 'key-kind', name: 'kind', class: 'field' },
usable.map((q) => h('option', { value: q.id }, q.name + (q.target ? ' · ' + q.target : ''))),
atLeast('lecturer') ? h('option', { value: 'none' }, 'Unbegrenzt (ohne Kontingent)') : null,
atLeast('admin') ? h('option', { value: 'super' }, 'Super-Key (ohne alle Einschränkungen)') : null))),
h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit', disabled: !usable.length && !atLeast('lecturer') }, 'Key erstellen')));
const parts = [head('Persönlich', 'API-Keys', 'Ein Key gilt für alle Endpunkte: Ollama, llama.cpp und vLLM.')];
if (created) {
parts.push(h('section', { class: 'card' },
h('div', { class: 'notice warn' }, 'Der Key wird nur dieses eine Mal angezeigt. Kopiere ihn jetzt.'),
h('div', { class: 'secret' }, h('code', {}, created.key),
h('button', { class: 'btn small', type: 'button', onclick: (e) => copy(created.key, e.currentTarget) }, 'Kopieren')),
h('span', { class: 'hint' }, 'Key „' + created.name + '“ angelegt.')));
}
parts.push(h('section', { class: 'card' }, h('h2', {}, 'Neuer Key'),
!usable.length && !atLeast('lecturer') ? h('p', { class: 'empty' }, 'Dir ist noch kein Kontingent zugeteilt.') : form));
parts.push(keysManageCard('Meine Keys', own, true));
if (others.length) parts.push(keysManageCard(atLeast('admin') ? 'Keys anderer Personen' : 'Keys gegen meine Kontingente', others, false));
parts.push(recordingsCard(recordings));
parts.push(endpointsCard());
return h('div', { class: 'stack' }, parts);
}
function keysManageCard(title, keys, own) {
return h('section', { class: 'card' }, h('h2', {}, title),
keys.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Name'), own ? null : h('th', {}, 'Inhaber'), h('th', {}, 'Key'), h('th', {}, 'Kontingent'),
h('th', { class: 'num' }, 'Token (Monat)'), h('th', { class: 'num' }, 'Anfragen (Monat)'), h('th', {}, 'Status'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))),
h('tbody', {}, keys.map((k) => h('tr', { class: k.revoked ? 'dim' : null },
h('td', { class: 'mono' }, k.name), own ? null : h('td', { class: 'mono' }, k.owner || '–'),
h('td', { class: 'mono muted' }, k.prefix + '…'), h('td', {}, quotaLabel(k)),
h('td', { class: 'num' }, tokens(tok(k.usage.month))), h('td', { class: 'num' }, num(k.usage.month.requests)),
h('td', {}, keyState(k)),
h('td', {}, k.revoked ? null : h('div', { class: 'actions' },
own && !k.recording ? h('button', { class: 'btn small', type: 'button', onclick: () => startRecording(k) }, 'Aufzeichnen') : null,
own && k.recording ? h('button', { class: 'btn small', type: 'button', onclick: () => act(() => api('POST', '/recordings/stop', { key_id: k.id }), 'Aufzeichnung beendet; sie liegt jetzt zum Herunterladen bereit.') }, 'Aufzeichnung beenden') : null,
h('button', { class: 'btn small danger', type: 'button', onclick: () => revokeKey(k) }, 'Widerrufen'))))))))
: h('p', { class: 'empty' }, 'Keine Keys.'));
}
function revokeKey(k) {
if (!confirm('Key „' + k.name + '“ widerrufen? Anwendungen, die ihn nutzen, werden sofort abgewiesen.')) return;
act(() => api('DELETE', '/keys/' + k.id), 'Key „' + k.name + '“ widerrufen.');
}
function startRecording(k) {
const answer = prompt('Wie viele der nächsten Anfragen von „' + k.name + '“ sollen samt Antworten aufgezeichnet werden? (1 bis 100)', '20');
if (!answer) return;
act(() => api('POST', '/recordings', { key_id: k.id, count: Number(answer) }), 'Aufzeichnung gestartet.');
}
function recordingsCard(recordings) {
return h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', {}, 'Aufzeichnung für Debugging'),
h('span', { class: 'muted' }, 'Verschlüsselt gespeichert, nur für dich abrufbar, eine Stunde bereit, nach dem Download gelöscht.')),
recordings.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Nr.'), h('th', {}, 'Key'), h('th', { class: 'num' }, 'Einträge'), h('th', {}, 'Stand'), h('th', {}, 'Ende'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))),
h('tbody', {}, recordings.slice().reverse().map((r) => h('tr', {},
h('td', { class: 'mono' }, r.id), h('td', { class: 'mono' }, '#' + r.key_id), h('td', { class: 'num' }, r.written + ' / ' + r.count),
h('td', {}, r.state), h('td', { class: 'muted' }, r.end_reason || '–'),
h('td', {}, r.state.startsWith('bereit') ? h('a', { class: 'btn small primary', href: '/omega/api/recordings/' + r.id + '/download', download: 'aufzeichnung-' + r.id + '.jsonl', onclick: () => setTimeout(render, 1500) }, 'JSONL herunterladen') : null))))))
: h('p', { class: 'empty' }, 'Noch keine Aufzeichnungen. Starte eine über „Aufzeichnen“ bei einem deiner Keys.'));
}
function endpointsCard() {
const base = location.origin;
const rows = [['Ollama', base], ['llama.cpp (OpenAI-kompatibel)', base + '/llamacpp/v1'], ['vLLM (OpenAI-kompatibel)', base + '/vllm/v1']];
return h('section', { class: 'card' }, h('h2', {}, 'Endpunkte'),
h('div', { class: 'table-wrap' }, h('table', {}, h('tbody', {}, rows.map(([name, url]) => h('tr', {},
h('td', {}, name), h('td', { class: 'mono' }, url),
h('td', {}, h('button', { class: 'btn small', type: 'button', onclick: (e) => copy(url, e.currentTarget) }, 'Kopieren'))))))),
h('span', { class: 'hint' }, 'Den Key als „Authorization: Bearer …“ mitschicken.'));
}
async function copy(text, button) {
try {
await navigator.clipboard.writeText(text);
button.textContent = 'Kopiert';
} catch {
button.textContent = 'Bitte von Hand kopieren';
}
}
// ---------- Konto ----------
async function accountPage() {
const sessions = await api('GET', '/sessions');
const u = state.me.user;
const pw = h('form', {
onsubmit: (e) => {
e.preventDefault();
const d = formData(pw);
act(() => api('POST', '/users/' + encodeURIComponent(u.username) + '/password', { password: d.password }), 'Passwort geändert.');
},
},
h('div', { class: 'fields' }, h('div', { class: 'field-group' }, h('label', { for: 'pw' }, 'Neues Passwort'),
h('input', { id: 'pw', name: 'password', type: 'password', class: 'field', autocomplete: 'new-password', required: true, minlength: 4 }))),
h('div', { class: 'actions' }, h('button', { class: 'btn', type: 'submit' }, 'Passwort ändern')));
return h('div', { class: 'stack' },
head('Persönlich', 'Konto & Sicherheit'),
h('div', { class: 'row top' },
h('section', { class: 'card grow' }, h('h2', {}, 'Konto'),
h('table', {}, h('tbody', {},
h('tr', {}, h('td', { class: 'muted' }, 'Benutzername'), h('td', { class: 'mono' }, u.username)),
h('tr', {}, h('td', { class: 'muted' }, 'Rolle'), h('td', {}, ROLE[u.role])),
h('tr', {}, h('td', { class: 'muted' }, 'E-Mail'), h('td', {}, u.email || '–')),
h('tr', {}, h('td', { class: 'muted' }, 'Gruppen'), h('td', { class: 'wrap' }, state.me.groups.join(', ') || '–'))))),
h('section', { class: 'card grow' }, h('h2', {}, 'Passwort (Testbetrieb)'),
h('p', { class: 'hint' }, 'Im Betrieb meldest du dich mit Passkey, Magic Link oder 2FA-Code an.'), pw)),
h('section', { class: 'card' }, h('h2', {}, 'Angemeldete Sitzungen'),
h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Sitzung'), h('th', {}, 'Angelegt'), h('th', {}, 'Gültig bis'), h('th', {}, 'Anmerkung'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))),
h('tbody', {}, sessions.slice().reverse().map((s) => h('tr', { class: s.revoked ? 'dim' : null },
h('td', { class: 'mono' }, s.prefix + '…'), h('td', {}, when(s.created_at)), h('td', {}, s.revoked ? 'widerrufen' : when(s.expires_at)), h('td', {}, s.note),
h('td', {}, s.revoked ? null : h('button', { class: 'btn small danger', type: 'button', onclick: () => act(() => api('DELETE', '/sessions/' + s.id), 'Sitzung beendet.') }, 'Beenden')))))))));
}
// ---------- Gruppen & Kontingente ----------
async function groupsPage() {
const [groups, quotas] = await Promise.all([api('GET', '/groups'), api('GET', '/quotas')]);
const me = state.me.user;
const managed = groups.filter((g) => g.owner_id === me.id || atLeast('admin'));
const groupForm = h('form', {
onsubmit: (e) => {
e.preventDefault();
const d = formData(groupForm);
act(async () => { await api('POST', '/groups', { name: d.name }); go('group/' + encodeURIComponent(d.name)); }, 'Gruppe „' + d.name + '“ angelegt.');
},
},
h('div', { class: 'fields' }, h('div', { class: 'field-group' }, h('label', { for: 'group-name' }, 'Name der Gruppe'),
h('input', { id: 'group-name', name: 'name', class: 'field mono', required: true, placeholder: 'z. B. ki-praktikum-ws26' }))),
h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Gruppe anlegen')));
return h('div', { class: 'stack' },
head('Lehre', 'Gruppen & Kontingente', 'Gruppen anlegen, Personen aufnehmen und Kontingente zuteilen.'),
h('div', { class: 'row top' },
h('section', { class: 'card grow' }, h('h2', {}, 'Gruppen'),
managed.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Gruppe'), h('th', { class: 'num' }, 'Mitglieder'), h('th', {}, 'Verwaltet von'))),
h('tbody', {}, managed.map((g) => h('tr', {},
h('td', {}, h('a', { class: 'mono', href: '#/group/' + encodeURIComponent(g.name) }, g.name)), h('td', { class: 'num' }, g.members), h('td', { class: 'mono' }, g.owner || '–'))))))
: h('p', { class: 'empty' }, 'Noch keine Gruppen.')),
h('section', { class: 'card grow' }, h('h2', {}, 'Neue Gruppe'), groupForm)),
h('section', { class: 'card' }, h('h2', {}, 'Kontingente'), quotasTable(quotas)),
quotaForm(managed, null));
}
function quotasTable(quotas) {
return quotas.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Kontingent'), h('th', {}, 'Zugeteilt'), h('th', {}, 'Grenzen'), h('th', { class: 'num' }, 'Keys'))),
h('tbody', {}, quotas.map((q) => h('tr', {},
h('td', {}, h('a', { href: '#/quota/' + q.id }, q.name)), h('td', {}, q.target || '–'), h('td', { class: 'wrap' }, q.describe), h('td', { class: 'num' }, q.keys))))))
: h('p', { class: 'empty' }, 'Noch keine Kontingente.');
}
/** Formular für ein neues Kontingent, für eine feste Gruppe oder mit Auswahl */
function quotaForm(groups, fixedGroup) {
const limit = (name, label) => h('div', { class: 'field-group' }, h('label', { for: 'q-' + name }, label),
h('input', { id: 'q-' + name, name, class: 'field mono', type: 'number', min: 1, inputmode: 'numeric', placeholder: 'unbegrenzt' }));
const form = h('form', {
onsubmit: (e) => {
e.preventDefault();
const d = formData(form);
const body = {
name: d.name,
tokens: { hour: optNum(d.tokens_hour), day: optNum(d.tokens_day), week: optNum(d.tokens_week), month: optNum(d.tokens_month), total: optNum(d.tokens_total) },
requests: { hour: optNum(d.requests_hour), day: optNum(d.requests_day), week: optNum(d.requests_week), month: optNum(d.requests_month), total: optNum(d.requests_total) },
models: d.models ? list(d.models) : undefined,
from: optional(d.from), until: optional(d.until), weekly: optional(d.weekly), time: optional(d.time), note: d.note,
};
const target = fixedGroup || d.target;
if (target.startsWith('group:')) body.group = target.slice(6);
else if (target === 'user') body.user = d.username;
act(() => api('POST', '/quotas', body), (q) => 'Kontingent „' + q.name + '“ angelegt: ' + q.describe);
},
},
h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 'q-name' }, 'Name'), h('input', { id: 'q-name', name: 'name', class: 'field', required: true, placeholder: 'z. B. KI-Praktikum WS 26/27' })),
fixedGroup ? null : h('div', { class: 'field-group' }, h('label', { for: 'q-target' }, 'Zugeteilt an'),
h('select', { id: 'q-target', name: 'target', class: 'field' },
groups.map((g) => h('option', { value: 'group:' + g.name }, 'Gruppe ' + g.name + ' (je Mitglied)')),
h('option', { value: 'user' }, 'Eine Person …'))),
fixedGroup ? null : h('div', { class: 'field-group' }, h('label', { for: 'q-username' }, 'Benutzername (bei einer Person)'),
h('input', { id: 'q-username', name: 'username', class: 'field mono' }))),
h('fieldset', {}, h('legend', {}, 'Token'), h('div', { class: 'fields' },
limit('tokens_hour', 'je Stunde'), limit('tokens_day', 'je Tag'), limit('tokens_week', 'je Woche'), limit('tokens_month', 'je Monat'), limit('tokens_total', 'insgesamt'))),
h('fieldset', {}, h('legend', {}, 'Anfragen'), h('div', { class: 'fields' },
limit('requests_hour', 'je Stunde'), limit('requests_day', 'je Tag'), limit('requests_week', 'je Woche'), limit('requests_month', 'je Monat'), limit('requests_total', 'insgesamt'))),
h('fieldset', {}, h('legend', {}, 'Wann und womit'), h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 'q-models' }, 'Nur diese Modelle'), h('input', { id: 'q-models', name: 'models', class: 'field mono', placeholder: 'ollama/qwen3:0.6b, vllm/…' })),
h('div', { class: 'field-group' }, h('label', { for: 'q-weekly' }, 'Wochentage'), h('input', { id: 'q-weekly', name: 'weekly', class: 'field mono', placeholder: 'mo-fr' })),
h('div', { class: 'field-group' }, h('label', { for: 'q-time' }, 'Uhrzeit'), h('input', { id: 'q-time', name: 'time', class: 'field mono', placeholder: '08:00-18:00' })),
h('div', { class: 'field-group' }, h('label', { for: 'q-from' }, 'Gültig ab'), h('input', { id: 'q-from', name: 'from', class: 'field mono', placeholder: '2026-10-01' })),
h('div', { class: 'field-group' }, h('label', { for: 'q-until' }, 'Gültig bis'), h('input', { id: 'q-until', name: 'until', class: 'field mono', placeholder: '2027-02-15' })),
h('div', { class: 'field-group' }, h('label', { for: 'q-note' }, 'Anmerkung'), h('input', { id: 'q-note', name: 'note', class: 'field' }))),
h('span', { class: 'hint' }, 'Leere Felder heißen unbegrenzt. Ein Gruppenkontingent gilt je Mitglied. Tage und Monate sind Kalenderzeiträume.')),
h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Kontingent anlegen')));
return h('section', { class: 'card' }, h('h2', {}, fixedGroup ? 'Neues Kontingent für diese Gruppe' : 'Neues Kontingent'), form);
}
async function groupPage(name) {
const g = await api('GET', '/groups/' + encodeURIComponent(name));
const add = h('form', {
onsubmit: (e) => {
e.preventDefault();
const users = list(formData(add).usernames);
act(() => api('POST', '/groups/' + encodeURIComponent(name) + '/members', { usernames: users }),
(r) => r.map((x) => x.username + ': ' + ({ New: 'aufgenommen', NoAccount: 'aufgenommen, hat noch kein Konto', Existing: 'war schon Mitglied' }[x.result])).join(' · '));
},
},
h('div', { class: 'field-group' }, h('label', { for: 'members' }, 'Benutzernamen, getrennt durch Komma oder Zeilen'),
h('textarea', { id: 'members', name: 'usernames', class: 'field mono', required: true, placeholder: 'mueller\nmeier' })),
h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Aufnehmen')));
return h('div', { class: 'stack' },
head('Lehre · Gruppe', g.name, 'Verwaltet von ' + (g.owner || '–') + ' · ' + g.members.length + ' Mitglieder',
h('a', { class: 'btn', href: '#/groups' }, 'Zurück'),
h('button', { class: 'btn danger', type: 'button', onclick: () => {
if (confirm('Gruppe „' + g.name + '“ löschen?')) act(async () => { await api('DELETE', '/groups/' + encodeURIComponent(g.name)); go('groups'); }, 'Gruppe gelöscht.');
} }, 'Gruppe löschen')),
h('div', { class: 'row top' },
h('section', { class: 'card grow' }, h('h2', {}, 'Mitglieder'),
g.members.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Benutzer'), h('th', {}, 'Stand'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))),
h('tbody', {}, g.members.map((m) => h('tr', {},
h('td', { class: 'mono' }, m.username),
h('td', {}, m.state === 'noch kein Konto' ? h('span', { class: 'chip' }, 'noch kein Konto') : m.state === 'gesperrt' || m.state === 'deaktiviert' ? h('span', { class: 'chip bad' }, m.state) : ROLE[m.state] || m.state),
h('td', {}, h('div', { class: 'actions' }, h('button', { class: 'btn small danger', type: 'button', onclick: () => act(() => api('DELETE', '/groups/' + encodeURIComponent(g.name) + '/members/' + encodeURIComponent(m.username)), m.username + ' entfernt.') }, 'Entfernen'))))))))
: h('p', { class: 'empty' }, 'Noch keine Mitglieder.')),
h('section', { class: 'card grow' }, h('h2', {}, 'Personen aufnehmen'), add,
h('span', { class: 'hint' }, 'Wer noch kein Konto hat, wird Mitglied, sobald es angelegt ist.'))),
h('section', { class: 'card' }, h('h2', {}, 'Kontingente der Gruppe'),
quotasTable(g.quotas.map((q) => ({ ...q, target: 'Gruppe ' + g.name, describe: describeQuota(q), keys: '–' })))),
quotaForm([], 'group:' + g.name));
}
function describeQuota(q) {
const parts = [];
for (const p of Object.keys(PERIOD)) {
if (q.tokens[p] != null) parts.push(num(q.tokens[p]) + ' Token/' + PERIOD[p]);
if (q.requests[p] != null) parts.push(num(q.requests[p]) + ' Anfragen/' + PERIOD[p]);
}
if (q.models) parts.push('Modelle: ' + q.models.join(', '));
return parts.join('; ') || 'ohne Mengengrenzen';
}
async function quotaPage(id) {
const q = await api('GET', '/quotas/' + id);
const manages = atLeast('admin') || q.owner_id === state.me.user.id;
return h('div', { class: 'stack' },
head('Kontingent', q.name, (q.target ? q.target + ' · ' : '') + 'verwaltet von ' + (q.owner || '–'),
h('a', { class: 'btn', href: manages ? '#/groups' : '#/' }, 'Zurück'),
manages ? h('button', { class: 'btn danger', type: 'button', onclick: () => {
if (confirm('Kontingent „' + q.name + '“ entfernen? Das geht nur, wenn keine Keys mehr daran hängen.')) act(async () => { await api('DELETE', '/quotas/' + q.id); go('groups'); }, 'Kontingent entfernt.');
} }, 'Entfernen') : null),
h('section', { class: 'card' }, h('h2', {}, 'Grenzen'), h('p', {}, q.describe), q.note ? h('p', { class: 'muted' }, q.note) : null),
h('section', { class: 'card' }, h('h2', {}, manages ? 'Verbrauch je Person' : 'Dein Verbrauch'),
q.usage.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Person'), Object.values(PERIOD).map((p) => h('th', { class: 'num' }, 'Token ' + p)), h('th', { class: 'num' }, 'Anfragen heute'))),
h('tbody', {}, q.usage.map((p) => h('tr', {},
h('td', { class: 'mono' }, p.user || '(ohne Inhaber)'),
Object.keys(PERIOD).map((k) => h('td', { class: 'num' }, tokens(tok(p.usage[k])) + (q.tokens[k] != null ? ' / ' + tokens(q.tokens[k]) : ''))),
h('td', { class: 'num' }, num(p.usage.day.requests) + (q.requests.day != null ? ' / ' + num(q.requests.day) : '')))))))
: h('p', { class: 'empty' }, 'Noch keine Nutzung.')));
}
// ---------- Sparks & Modelle ----------
async function statusPage() {
const status = await api('GET', '/status');
const loaded = status.nodes.reduce((a, n) => a + n.models.length, 0);
const waiting = status.nodes.reduce((a, n) => a + n.models.reduce((b, m) => b + m.waiting, 0), 0);
const running = status.nodes.reduce((a, n) => a + n.models.reduce((b, m) => b + m.in_flight, 0), 0);
const issues = status.nodes.reduce((a, n) => a + n.issues.length, 0);
return h('div', { class: 'stack' },
head('Administration', 'Sparks & Modelle', status.nodes.length + ' Rechner · ' + loaded + ' Modelle geladen · ' + waiting + ' Anfragen warten',
h('button', { class: 'btn', type: 'button', onclick: () => render() }, 'Aktualisieren')),
h('div', { class: 'kpis' },
h('div', { class: 'kpi' }, h('span', {}, 'Laufende Anfragen'), h('span', { class: 'value' }, num(running))),
h('div', { class: 'kpi' }, h('span', {}, 'Warteschlange'), h('span', { class: 'value' + (waiting ? ' accent' : '') }, num(waiting))),
h('div', { class: 'kpi' }, h('span', {}, 'Geladene Modelle'), h('span', { class: 'value' }, num(loaded))),
h('div', { class: 'kpi' }, h('span', {}, 'Hinweise zu Engines'), h('span', { class: 'value' + (issues ? ' bad' : '') }, num(issues)))),
h('div', { class: 'row top' }, status.nodes.map(nodeCard)),
h('div', { class: 'legend' },
h('span', {}, h('span', { class: 'swatch ollama' }), 'Ollama'), h('span', {}, h('span', { class: 'swatch llamacpp' }), 'llama.cpp'),
h('span', {}, h('span', { class: 'swatch vllm' }), 'vLLM'), h('span', {}, h('span', { class: 'swatch free' }), 'frei')));
}
function nodeCard(n) {
const budget = n.budget_mb || 0;
const models = n.models.slice().sort((a, b) => b.mb - a.mb);
const state = (m) => {
if (m.state === 'loading') return h('span', { class: 'muted' }, 'wird geladen');
if (m.state === 'unloading') return h('span', { class: 'muted' }, 'wird entladen');
if (m.in_flight) return h('span', { class: 'status' }, h('span', { class: 'dot accent' }), m.in_flight + (m.in_flight === 1 ? ' laufende Anfrage' : ' laufende Anfragen'));
return h('span', { class: 'muted' }, 'Leerlauf ' + Math.round(m.idle_secs / 60) + ' min');
};
return h('section', { class: 'card grow' },
h('div', { class: 'card-head' },
h('div', { class: 'actions' }, h('h2', { class: 'mono' }, n.name),
n.budget_mb == null ? h('span', { class: 'chip bad' }, 'Speicher unbekannt') : h('span', { class: 'chip good' }, 'erreichbar')),
h('span', { class: 'mono muted' }, mb(n.used_mb) + ' / ' + mb(n.budget_mb))),
h('div', { class: 'membar', role: 'img', 'aria-label': 'Speicherbelegung ' + n.name + ': ' + models.map((m) => m.model + ' ' + mb(m.mb)).join(', ') },
models.map((m) => h('div', { class: m.engine + (m.state === 'loaded' ? '' : ' loading'), style: { width: (budget ? m.mb / budget * 100 : 0) + '%' }, title: m.model + ' · ' + mb(m.mb) }, m.model))),
n.issues.map((i) => h('div', { class: 'notice warn' }, i)),
models.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Modell'), h('th', {}, 'Engine'), h('th', { class: 'num' }, 'Speicher'), h('th', {}, 'Status'), h('th', { class: 'num' }, 'Wartend'))),
h('tbody', {}, models.map((m) => h('tr', {},
h('td', { class: 'mono' }, m.model), h('td', {}, h('span', { class: 'chip ' + m.engine }, ENGINE[m.engine] || m.engine)),
h('td', { class: 'num' }, mb(m.mb)), h('td', {}, m.pinned ? h('span', { class: 'chip accent' }, 'gepinnt') : null, ' ', state(m)),
h('td', { class: 'num' }, m.waiting || '–'))))))
: h('p', { class: 'empty' }, 'Kein Modell geladen.'),
n.events.length ? h('details', {}, h('summary', {}, 'Ereignisse der Engines (' + n.events.length + ')'),
h('ol', { class: 'events' }, n.events.map((e) => h('li', {}, h('span', { class: 'mono' }, clock(e.ts)), h('span', {}, e.message))))) : null,
h('details', {}, h('summary', {}, 'Empfohlene Einstellungen der Engines'),
(n.engines || []).map((e) => h('pre', { class: 'settings' }, ENGINE[e.engine] + '\n' + e.settings.join('\n')))));
}
// ---------- Zeitplan ----------
async function schedulePage() {
const entries = await api('GET', '/schedule');
const kindSel = h('select', { id: 's-kind', name: 'kind', class: 'field', onchange: () => update() },
h('option', { value: 'pin' }, 'Pin: Modell garantiert im Speicher'),
h('option', { value: 'exclusive' }, 'Exklusiv: nur bestimmte Gruppen oder Personen'),
h('option', { value: 'window' }, 'Modellzeitfenster: nur bestimmte Modelle'));
const field = (name, label, placeholder, hint) => h('div', { class: 'field-group', 'data-for': hint },
h('label', { for: 's-' + name }, label), h('input', { id: 's-' + name, name, class: 'field mono', placeholder }));
const form = h('form', {
onsubmit: (e) => {
e.preventDefault();
const d = formData(form);
const body = { kind: d.kind, from: optional(d.from), until: optional(d.until), weekly: optional(d.weekly), time: optional(d.time), note: d.note };
if (d.kind === 'pin') Object.assign(body, { model: d.model, node: optional(d.node) });
if (d.kind === 'exclusive') Object.assign(body, { groups: list(d.groups), users: list(d.users) });
if (d.kind === 'window') body.models = list(d.models);
act(() => api('POST', '/schedule', body), (e2) => 'Eintrag angelegt: ' + e2.subject + ', ' + e2.describe);
},
},
h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 's-kind' }, 'Art'), kindSel),
field('model', 'Modell', 'ollama/qwen3:0.6b', 'pin'),
field('node', 'Rechner (bei mehreren)', 'spark1', 'pin'),
field('groups', 'Gruppen', 'ki-2026', 'exclusive'),
field('users', 'Personen', 'hofmannol', 'exclusive'),
field('models', 'Modelle', 'ollama/qwen3:0.6b, vllm/…', 'window')),
h('div', { class: 'fields' },
field('from', 'Beginn', '2026-11-24 08:00 oder +10m'), field('until', 'Ende', '2026-11-24 12:00'),
field('weekly', 'Wochentage', 'mo,mi'), field('time', 'Uhrzeit', '08:00-11:15'), field('note', 'Anmerkung', 'Vorlesung KI')),
h('span', { class: 'hint' }, 'Ohne Zeitangaben gilt ein Eintrag dauerhaft. Der Proxy lehnt Einträge ab, die nicht in den Speicher passen oder sich widersprechen.'),
h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Eintrag anlegen')));
function update() {
for (const el of form.querySelectorAll('[data-for]')) {
const kind = el.getAttribute('data-for');
if (kind !== 'undefined') el.hidden = kind !== kindSel.value;
}
}
update();
const kinds = { pin: 'Pin', exklusiv: 'Exklusiv', fenster: 'Zeitfenster' };
return h('div', { class: 'stack' },
head('Administration', 'Zeitplan', 'Pins, exklusive Nutzung und Modellzeitfenster in einem Plan.'),
h('section', { class: 'card' }, h('h2', {}, 'Einträge'),
entries.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Art'), h('th', {}, 'Was'), h('th', {}, 'Wann'), h('th', {}, 'Stand'), h('th', {}, 'Anmerkung'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))),
h('tbody', {}, entries.map((e) => h('tr', {},
h('td', {}, h('span', { class: 'chip' + (e.kind.kind === 'pin' ? ' accent' : '') }, kinds[e.kind.kind] || e.kind.kind)),
h('td', { class: 'mono wrap' }, e.subject), h('td', { class: 'wrap' }, e.describe),
h('td', {}, e.active ? h('span', { class: 'status' }, h('span', { class: 'dot good' }), 'aktiv') : h('span', { class: 'muted' }, 'inaktiv')),
h('td', { class: 'wrap' }, e.note),
h('td', {}, h('button', { class: 'btn small danger', type: 'button', onclick: () => act(() => api('DELETE', '/schedule/' + e.id), 'Eintrag entfernt.') }, 'Entfernen')))))))
: h('p', { class: 'empty' }, 'Der Zeitplan ist leer.')),
h('section', { class: 'card' }, h('h2', {}, 'Neuer Eintrag'), form));
}
// ---------- Benutzer ----------
async function usersPage() {
const users = await api('GET', '/users');
const patch = (u, body, done) => act(() => api('PATCH', '/users/' + encodeURIComponent(u.username), body), done);
const form = h('form', {
onsubmit: (e) => {
e.preventDefault();
const d = formData(form);
act(async () => {
await api('POST', '/users', { username: d.username, email: optional(d.email), role: d.role });
if (d.password) await api('POST', '/users/' + encodeURIComponent(d.username) + '/password', { password: d.password });
}, 'Benutzer ' + d.username + ' angelegt.');
},
},
h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 'u-name' }, 'Benutzername'), h('input', { id: 'u-name', name: 'username', class: 'field mono', required: true })),
h('div', { class: 'field-group' }, h('label', { for: 'u-mail' }, 'E-Mail'), h('input', { id: 'u-mail', name: 'email', type: 'email', class: 'field' })),
h('div', { class: 'field-group' }, h('label', { for: 'u-role' }, 'Rolle'),
h('select', { id: 'u-role', name: 'role', class: 'field' }, Object.entries(ROLE).map(([v, l]) => h('option', { value: v }, l)))),
h('div', { class: 'field-group' }, h('label', { for: 'u-pw' }, 'Passwort (Testbetrieb)'), h('input', { id: 'u-pw', name: 'password', type: 'password', class: 'field', autocomplete: 'new-password' }))),
h('span', { class: 'hint' }, 'Im Betrieb registrieren sich Personen selbst mit dem Login der Hochschule (LDAP).'),
h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Benutzer anlegen')));
const me = state.me.user;
return h('div', { class: 'stack' },
head('Administration', 'Benutzer', users.length + ' Konten'),
h('section', { class: 'card' }, h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Benutzer'), h('th', {}, 'E-Mail'), h('th', {}, 'Rolle'), h('th', {}, 'Gruppen'), h('th', {}, 'Stand'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))),
h('tbody', {}, users.map((u) => h('tr', { class: u.blocked || !u.active ? 'dim' : null },
h('td', { class: 'mono' }, u.username), h('td', {}, u.email || '–'),
h('td', {}, h('select', { class: 'field', 'aria-label': 'Rolle von ' + u.username, onchange: (e) => patch(u, { role: e.target.value }, u.username + ' ist jetzt ' + ROLE[e.target.value] + '.') },
Object.entries(ROLE).map(([v, l]) => h('option', { value: v, selected: v === u.role }, l)))),
h('td', { class: 'wrap' }, u.groups.join(', ') || '–'),
h('td', {}, u.blocked ? h('span', { class: 'chip bad' }, 'gesperrt') : !u.active ? h('span', { class: 'chip bad' }, 'deaktiviert') : h('span', { class: 'chip good' }, 'aktiv')),
h('td', {}, u.id === me.id ? null : h('div', { class: 'actions' },
h('button', { class: 'btn small' + (u.blocked ? '' : ' danger'), type: 'button', onclick: () => patch(u, { blocked: !u.blocked }, u.username + (u.blocked ? ' entsperrt.' : ' gesperrt; seine Keys werden abgewiesen.')) }, u.blocked ? 'Entsperren' : 'Sperren'))))))))),
h('section', { class: 'card' }, h('h2', {}, 'Neuer Benutzer'), form));
}
// ---------- Audit-Log ----------
async function auditPage() {
const [entries, outbox] = await Promise.all([api('GET', '/audit?limit=300'), api('GET', '/outbox')]);
const prune = h('form', {
onsubmit: (e) => {
e.preventDefault();
const days = Number(formData(prune).days);
if (!confirm('Alle Einzeleinträge der Nutzung löschen, die älter als ' + days + ' Tage sind? Kontingentstände bleiben erhalten.')) return;
act(() => api('POST', '/usage/prune', { older_than_days: days }), (r) => num(r.deleted) + ' Einträge gelöscht. Die Kontingentstände bleiben erhalten.');
},
},
h('div', { class: 'fields' }, h('div', { class: 'field-group' }, h('label', { for: 'prune-days' }, 'Älter als (Tage)'),
h('input', { id: 'prune-days', name: 'days', type: 'number', min: 0, class: 'field mono', value: '180', required: true }))),
h('span', { class: 'hint' }, 'Löscht Zeitpunkt, Key, Modell und Token einzelner Anfragen. Die Zähler der Kontingente und Keys bleiben, damit verbuchte Stände stimmen.'),
h('div', { class: 'actions' }, h('button', { class: 'btn danger', type: 'submit' }, 'Metadaten löschen')));
return h('div', { class: 'stack' },
head('Administration', 'Audit-Log', 'Die letzten 300 Vorgänge. Inhalte von Anfragen und Antworten stehen hier nie.'),
h('div', { class: 'row top' },
h('section', { class: 'card grow' }, h('h2', {}, 'Alte Metadaten löschen'), prune),
h('section', { class: 'card grow' }, h('h2', {}, 'Postausgang'),
h('span', { class: 'hint' }, 'Benachrichtigungen, bis es einen Mailversand gibt. Sie enthalten nie Inhalte von Anfragen.'),
outbox.length ? h('ol', { class: 'events' }, outbox.slice().reverse().map((m) => h('li', {},
h('span', { class: 'mono' }, when(m.ts)), h('span', {}, h('b', {}, m.subject), ' an ', h('span', { class: 'mono' }, m.to || '(keine Adresse)')))))
: h('p', { class: 'empty' }, 'Keine Benachrichtigungen.'))),
h('section', { class: 'card' }, h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Zeit'), h('th', {}, 'Wer'), h('th', {}, 'Vorgang'), h('th', {}, 'Details'))),
h('tbody', {}, entries.map((e) => h('tr', {},
h('td', { class: 'mono muted' }, when(e.ts)), h('td', { class: 'mono' }, e.actor), h('td', { class: 'mono' }, e.action), h('td', { class: 'wrap mono' }, e.detail))))))));
}
render();