Files
omega-ai-proxy/proxy/ui/app.js
T
Stephan RehfeldandClaude Opus 5.5 11dbc1c781 Oberfläche nach Durchsicht: Kalender, Suchen, eigene Verwaltungsseiten, gemeinsame Gruppenkontingente
- Übersicht mit Anfragen diesen Monat; Aufzeichnungen mit Key-Name und Präfix
- Ollama-API zusätzlich unter /ollama; Endpunkte in der Oberfläche einheitlich
- Gruppen & Kontingente nur eigene; Alle Gruppen & Kontingente und Alle Keys
  für Administratoren, Keys meiner Kontingente für Lecturer, jeweils mit Suche
- Kontingentformular: Modelle alle oder ausgewählte (nach Schnittstelle, aus
  GET /omega/api/models), Wochentage zum Anklicken, Uhrzeit- und Datumsfelder,
  je Person oder für die Gruppe gemeinsam (Spalte quotas.shared)
- Auswahl beim Key-Anlegen zeigt, von wem ein Kontingent kommt
- Zeitplan als Wochenkalender wie in den Mockups
- Benutzer mit Suche und Ausblenden gesperrter Konten
- Audit-Log mit deutschen Bezeichnungen, verständlichen Details und Suche
- Gültigkeit um Mitternacht als "bis einschließlich"; start.sh wartet auf die Engines

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:31:05 +01:00

1221 lines
75 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 ----------
const WEEKDAYS = [['mo', 'Mo', 'Mon'], ['di', 'Di', 'Tue'], ['mi', 'Mi', 'Wed'], ['do', 'Do', 'Thu'], ['fr', 'Fr', 'Fri'], ['sa', 'Sa', 'Sat'], ['so', 'So', 'Sun']];
/** Umschalter wie in den Mockups: eine Auswahl aus wenigen Möglichkeiten */
function segmented(name, options, value, onchange) {
const wrap = h('div', { class: 'segmented', role: 'radiogroup' });
for (const [v, label] of options) {
const input = h('input', { type: 'radio', name, value: v, checked: v === value, onchange: () => { update(); if (onchange) onchange(v); } });
wrap.append(h('label', { class: 'seg' }, input, label));
}
function update() { for (const l of wrap.children) l.classList.toggle('on', l.firstChild.checked); }
update();
return wrap;
}
/** Wochentage zum Anklicken; liefert die Auswahl als "mo,mi" */
function dayToggles(id) {
const wrap = h('div', { class: 'days', id, role: 'group', 'aria-label': 'Wochentage' });
for (const [code, label] of WEEKDAYS) {
const b = h('button', { type: 'button', class: 'day', 'aria-pressed': 'false', 'data-day': code,
onclick: () => b.setAttribute('aria-pressed', b.getAttribute('aria-pressed') === 'true' ? 'false' : 'true') }, label);
wrap.append(b);
}
wrap.value = () => [...wrap.querySelectorAll('[aria-pressed=true]')].map((b) => b.dataset.day).join(',');
return wrap;
}
/** Modellauswahl, gruppiert nach Schnittstelle; `multiple` für Kontingente und Zeitfenster */
function modelPicker(models, name, multiple) {
const wrap = h('div', { class: 'model-picker' });
for (const engine of ['ollama', 'llamacpp', 'vllm']) {
const of = models.filter((m) => m.engine === engine);
if (!of.length) continue;
wrap.append(h('fieldset', {}, h('legend', {}, h('span', { class: 'chip ' + engine }, ENGINE[engine]), ' ', h('span', { class: 'mono muted' }, endpointPath(engine))),
of.map((m) => h('label', { class: 'check' },
h('input', { type: multiple ? 'checkbox' : 'radio', name, value: m.id }),
h('span', { class: 'mono' }, m.model), h('span', { class: 'hint' }, m.nodes.join(', '))))));
}
if (!wrap.children.length) wrap.append(h('p', { class: 'empty' }, 'Keine Modelle verfügbar.'));
return wrap;
}
function endpointPath(engine) {
return { ollama: '/ollama', llamacpp: '/llamacpp/v1', vllm: '/vllm/v1' }[engine];
}
function checkedValues(root, name) {
return [...root.querySelectorAll('input[name="' + name + '"]:checked')].map((i) => i.value);
}
/** "2026-11-24T08:00" aus einem Datums-/Zeitfeld → "2026-11-24 08:00" für die API */
const apiTime = (v) => (v ? v.replace('T', ' ') : undefined);
/** Ein Enddatum gilt einschließlich: die API bekommt den Beginn des Folgetags. */
function dayAfter(date) {
if (!date) return undefined;
const [y, m, d] = date.split('-').map(Number);
const next = new Date(y, m - 1, d + 1);
return next.getFullYear() + '-' + String(next.getMonth() + 1).padStart(2, '0') + '-' + String(next.getDate()).padStart(2, '0');
}
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' },
groupkeys: { title: 'Keys meiner Kontingente', icon: 'keys', render: () => keysAdminPage('lecturer'), 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' },
allkeys: { title: 'Alle Keys', icon: 'keys', render: () => keysAdminPage('admin'), section: 'Administration', role: 'admin' },
allgroups: { title: 'Alle Gruppen & Kontingente', icon: 'groups', render: allGroupsPage, 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 personLabel(p) {
if (p.group_total) return 'Gruppe gesamt';
if (p.user) return p.user;
return p.usage ? '(ohne Inhaber)' : 'noch keine Nutzung';
}
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', {}, 'Anfragen diesen Monat'), h('span', { class: 'value' }, num(sum((u) => u.month.requests)))),
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 + (q.owner ? ' · von ' + q.owner : '')),
q.shared ? h('span', { class: 'hint' }, 'Gemeinsam für die ganze Gruppe:') : null,
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));
// Nur die eigenen Kontingente; die anderer stehen für Administratoren auf einer eigenen Seite.
const ownQuotas = me.managed ? me.managed.quotas.filter((q) => q.owner_id === me.user.id) : [];
if (me.managed) {
parts.push(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', {}, 'Meine Kontingente'), h('a', { href: '#/groups' }, 'Gruppen & Kontingente')),
ownQuotas.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', {}, ownQuotas.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' }, personLabel(p)),
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);
// Nutzbar sind Kontingente, die einem zugeteilt sind oder die man selbst verwaltet.
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.owner && q.owner !== me.username ? 'von ' + q.owner : null].filter(Boolean).join(' · '))),
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));
parts.push(recordingsCard(recordings, own));
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.'));
}
/** Keys anderer Personen mit Suche: für Lecturer die gegen ihre Kontingente, für Administratoren alle */
async function keysAdminPage(mode) {
const [keys, quotas] = await Promise.all([api('GET', '/keys'), api('GET', '/quotas')]);
const me = state.me.user;
const ownQuotaIds = new Set(quotas.filter((q) => q.owner_id === me.id).map((q) => q.id));
const list = keys.filter((k) => k.user_id !== me.id && (mode === 'admin' || (k.quota && ownQuotaIds.has(k.quota.id))));
const search = h('input', { type: 'search', class: 'field', placeholder: 'Name, Inhaber, Präfix oder Kontingent', 'aria-label': 'Keys durchsuchen', value: state.keySearch || '' });
const showRevoked = h('input', { type: 'checkbox', id: 'show-revoked', checked: state.keyShowRevoked });
const body = h('tbody', {});
const count = h('span', { class: 'muted' });
function update() {
state.keySearch = search.value;
state.keyShowRevoked = showRevoked.checked;
const q = search.value.trim().toLowerCase();
const shown = list.filter((k) => (showRevoked.checked || !k.revoked)
&& (!q || [k.name, k.owner, k.prefix, k.quota && k.quota.name].some((v) => v && v.toLowerCase().includes(q))));
body.replaceChildren(...shown.map((k) => h('tr', { class: k.revoked ? 'dim' : null },
h('td', { class: 'mono' }, k.name), 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', {}, keyState(k)),
h('td', {}, k.revoked ? null : h('div', { class: 'actions' }, h('button', { class: 'btn small danger', type: 'button', onclick: () => revokeKey(k) }, 'Widerrufen'))))));
count.textContent = shown.length + ' von ' + list.length + ' Keys';
}
search.addEventListener('input', update);
showRevoked.addEventListener('change', update);
update();
const admin = mode === 'admin';
return h('div', { class: 'stack' },
head(admin ? 'Administration' : 'Lehre', admin ? 'Alle Keys' : 'Keys meiner Kontingente',
admin ? 'Keys aller Users und Lecturer, etwa um einen Key zu widerrufen.' : 'Keys, die gegen deine Kontingente abgerechnet werden.'),
h('section', { class: 'card' },
h('div', { class: 'toolbar' }, search, h('label', { class: 'check', for: 'show-revoked' }, showRevoked, 'Widerrufene zeigen'), count),
h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Name'), h('th', {}, 'Inhaber'), h('th', {}, 'Key'), h('th', {}, 'Kontingent'),
h('th', { class: 'num' }, 'Token (Monat)'), h('th', {}, 'Status'), h('th', {}, h('span', { class: 'sr-only' }, 'Aktionen')))),
body))));
}
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, keys) {
const keyLabel = (id) => {
const k = keys.find((x) => x.id === id);
return k ? [h('span', { class: 'mono' }, k.name), ' ', h('span', { class: 'mono muted' }, '(' + k.prefix + '…)')] : '#' + id;
};
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', {}, keyLabel(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 + '/ollama'], ['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. Bestehende Ollama-Anwendungen erreichen die Ollama-API auch weiterhin ohne /ollama.'));
}
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, models] = await Promise.all([api('GET', '/groups'), api('GET', '/quotas'), api('GET', '/models')]);
const me = state.me.user;
const own = groups.filter((g) => g.owner_id === me.id);
const ownQuotas = quotas.filter((q) => q.owner_id === me.id);
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', 'Deine Gruppen und die Kontingente, die du zugeteilt hast.'),
h('div', { class: 'row top' },
h('section', { class: 'card grow' }, h('h2', {}, 'Meine Gruppen'), groupsTable(own, false)),
h('section', { class: 'card grow' }, h('h2', {}, 'Neue Gruppe'), groupForm)),
h('section', { class: 'card' }, h('h2', {}, 'Meine Kontingente'), quotasTable(ownQuotas, false)),
quotaForm(own, null, models));
}
function groupsTable(groups, showOwner) {
return groups.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Gruppe'), h('th', { class: 'num' }, 'Mitglieder'), showOwner ? h('th', {}, 'Verwaltet von') : null)),
h('tbody', {}, groups.map((g) => h('tr', {},
h('td', {}, h('a', { class: 'mono', href: '#/group/' + encodeURIComponent(g.name) }, g.name)), h('td', { class: 'num' }, g.members),
showOwner ? h('td', { class: 'mono' }, g.owner || '–') : null)))))
: h('p', { class: 'empty' }, 'Noch keine Gruppen.');
}
/** Gruppen und Kontingente anderer, etwa wenn eine Lehrkraft krank ist (Administratoren) */
async function allGroupsPage() {
const [groups, quotas, models] = await Promise.all([api('GET', '/groups'), api('GET', '/quotas'), api('GET', '/models')]);
const me = state.me.user;
const others = groups.filter((g) => g.owner_id !== me.id);
const otherQuotas = quotas.filter((q) => q.owner_id !== me.id);
const search = h('input', { type: 'search', class: 'field', placeholder: 'Gruppe oder Lehrkraft', 'aria-label': 'Gruppen durchsuchen' });
const tableWrap = h('div', {});
function update() {
const q = search.value.trim().toLowerCase();
tableWrap.replaceChildren(groupsTable(others.filter((g) => !q || g.name.toLowerCase().includes(q) || (g.owner || '').toLowerCase().includes(q)), true));
}
search.addEventListener('input', update);
update();
return h('div', { class: 'stack' },
head('Administration', 'Alle Gruppen & Kontingente', 'Gruppen und Kontingente anderer verwalten, etwa wenn eine Lehrkraft verhindert ist.'),
h('section', { class: 'card' }, h('h2', {}, 'Gruppen'), h('div', { class: 'toolbar' }, search), tableWrap),
h('section', { class: 'card' }, h('h2', {}, 'Kontingente'), quotasTable(otherQuotas, true)),
quotaForm(others, null, models));
}
function quotasTable(quotas, showOwner) {
return quotas.length ? h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Kontingent'), h('th', {}, 'Zugeteilt'), showOwner ? h('th', {}, 'Von') : null, 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 || '–'), showOwner ? h('td', { class: 'mono' }, q.owner || '–') : null,
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 */
/** Formular für ein neues Kontingent, für eine feste Gruppe oder mit Auswahl */
function quotaForm(groups, fixedGroup, models) {
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 days = dayToggles('q-days');
const picker = h('div', { hidden: true }, modelPicker(models || [], 'q-model', true));
const person = h('div', { class: 'field-group', hidden: true }, h('label', { for: 'q-username' }, 'Benutzername'),
h('input', { id: 'q-username', name: 'username', class: 'field mono' }));
const sharing = h('div', { class: 'field-group' }, h('span', { class: 'label' }, 'Grenzen gelten'),
segmented('q-shared', [['each', 'je Person'], ['shared', 'für die Gruppe gemeinsam']], 'each'));
const target = fixedGroup ? null : h('select', { id: 'q-target', name: 'target', class: 'field', onchange: () => {
person.hidden = target.value !== 'user';
sharing.hidden = target.value === 'user';
} },
groups.map((g) => h('option', { value: 'group:' + g.name }, 'Gruppe ' + g.name)),
h('option', { value: 'user' }, 'Eine Person …'));
if (target && !groups.length) { person.hidden = false; sharing.hidden = true; }
const form = h('form', {
onsubmit: (e) => {
e.preventDefault();
const d = formData(form);
const restricted = form.querySelector('input[name="q-models"]:checked').value === 'some';
const chosen = checkedValues(form, 'q-model');
if (restricted && !chosen.length) { state.flash = { kind: 'error', text: 'Bei begrenzten Modellen mindestens ein Modell auswählen.' }; return render(); }
const weekly = days.value();
if (!!weekly !== !!(d.time_start && d.time_end) && (weekly || d.time_start || d.time_end)) {
state.flash = { kind: 'error', text: 'Für Nutzungszeiten Wochentage und Uhrzeit von–bis angeben.' };
return render();
}
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: restricted ? chosen : undefined,
from: optional(d.valid_from), until: dayAfter(d.valid_until),
weekly: weekly || undefined, time: weekly ? d.time_start + '-' + d.time_end : undefined, note: d.note,
};
const t = fixedGroup || d.target;
if (t.startsWith('group:')) {
body.group = t.slice(6);
body.shared = form.querySelector('input[name="q-shared"]:checked').value === 'shared';
} else 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' })),
target ? h('div', { class: 'field-group' }, h('label', { for: 'q-target' }, 'Zugeteilt an'), target) : null,
person, sharing),
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', {}, 'Modelle'),
segmented('q-models', [['all', 'Alle Modelle'], ['some', 'Nur ausgewählte']], 'all', (v) => { picker.hidden = v !== 'some'; }),
picker),
h('fieldset', {}, h('legend', {}, 'Nutzungszeiten'),
days,
h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 'q-time-start' }, 'von'), h('input', { id: 'q-time-start', name: 'time_start', type: 'time', class: 'field mono' })),
h('div', { class: 'field-group' }, h('label', { for: 'q-time-end' }, 'bis'), h('input', { id: 'q-time-end', name: 'time_end', type: 'time', class: 'field mono' }))),
h('span', { class: 'hint' }, 'Ohne Auswahl jederzeit nutzbar. Endet die Zeit vor dem Beginn, reicht sie über Mitternacht.')),
h('fieldset', {}, h('legend', {}, 'Gültigkeit'),
h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 'q-valid-from' }, 'ab'), h('input', { id: 'q-valid-from', name: 'valid_from', type: 'date', class: 'field mono' })),
h('div', { class: 'field-group' }, h('label', { for: 'q-valid-until' }, 'bis einschließlich'), h('input', { id: 'q-valid-until', name: 'valid_until', type: 'date', class: 'field mono' })),
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 Grenzen heißen unbegrenzt. Tage, Wochen 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, models] = await Promise.all([api('GET', '/groups/' + encodeURIComponent(name)), api('GET', '/models')]);
const back = g.owner_id === state.me.user.id ? '#/groups' : '#/allgroups';
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: back }, '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)); location.hash = back; }, '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: '–' })), false)),
quotaForm([], 'group:' + g.name, models));
}
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(', '));
parts.push(q.shared ? 'für die Gruppe gemeinsam' : 'je Mitglied');
return parts.join('; ');
}
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 ? '#/' : q.owner_id === state.me.user.id ? '#/groups' : '#/allgroups' }, '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' }, personLabel(p)),
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 ----------
const KIND_LABEL = { pin: 'Pin', exclusive: 'Exklusiv', window: 'Zeitfenster' };
function startOfWeek(offset) {
const now = new Date();
const monday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - ((now.getDay() + 6) % 7) + offset * 7);
return monday;
}
function isoWeek(date) {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
}
const hhmm = (d) => String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
function atTime(day, time) {
const [hh, mm] = time.split(':').map(Number);
return new Date(day.getFullYear(), day.getMonth(), day.getDate(), hh, mm);
}
/** Abschnitte eines Eintrags an einem Tag, als [Beginn, Ende], beschnitten auf den Tag und die Gültigkeit */
function occurrences(e, dayStart) {
const dayEnd = new Date(dayStart.getTime() + 86400000);
const from = e.time.from ? new Date(e.time.from * 1000) : null;
const until = e.time.until ? new Date(e.time.until * 1000) : null;
const clip = ([a, b]) => {
const s2 = new Date(Math.max(a, dayStart, from || a));
const e2 = new Date(Math.min(b, dayEnd, until || b));
return e2 > s2 ? [[s2, e2]] : [];
};
const w = e.time.weekly;
if (!w) return clip([dayStart, dayEnd]);
const code = (d) => WEEKDAYS[(d.getDay() + 6) % 7][2];
const result = [];
const start = w.start.slice(0, 5);
const end = w.end.slice(0, 5);
if (w.days.includes(code(dayStart))) {
const a = atTime(dayStart, start);
const b = end > start ? atTime(dayStart, end) : dayEnd;
result.push(...clip([a, b]));
}
// Über Mitternacht: der Rest vom Vortag
const prev = new Date(dayStart.getTime() - 86400000);
if (end < start && w.days.includes(code(prev))) result.push(...clip([dayStart, atTime(dayStart, end)]));
return result;
}
async function schedulePage() {
const [entries, models, groups] = await Promise.all([api('GET', '/schedule'), api('GET', '/models'), api('GET', '/groups')]);
const weekStart = startOfWeek(state.week || 0);
const weekEnd = new Date(weekStart.getTime() + 7 * 86400000);
const label = 'KW ' + isoWeek(weekStart) + ' · ' + weekStart.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' }) + '–'
+ new Date(weekEnd.getTime() - 1).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' });
const permanent = entries.filter((e) => !e.time.from && !e.time.until && !e.time.weekly);
const shiftWeek = (d) => { state.week = d === 0 ? 0 : (state.week || 0) + d; render(); };
// Kalender: eine Spalte je Tag, eine Zeile je Stunde
const HOUR = 22;
const grid = h('div', { class: 'cal' });
grid.append(h('div', { class: 'cal-corner' }));
for (let d = 0; d < 7; d++) {
const day = new Date(weekStart.getTime() + d * 86400000);
const today = day.toDateString() === new Date().toDateString();
grid.append(h('div', { class: 'cal-day' + (today ? ' today' : '') }, WEEKDAYS[d][1], ' ', h('span', { class: 'mono' }, day.getDate() + '.')));
}
const hours = h('div', { class: 'cal-hours mono', style: { height: (24 * HOUR) + 'px' } });
for (let hr = 0; hr < 24; hr += 2) hours.append(h('span', { style: { top: (hr * HOUR) + 'px' } }, String(hr).padStart(2, '0')));
grid.append(hours);
for (let d = 0; d < 7; d++) {
const dayStart = new Date(weekStart.getTime() + d * 86400000);
const col = h('div', { class: 'cal-col', style: { height: (24 * HOUR) + 'px' } });
let lane = 0;
for (const e of entries) {
if (permanent.includes(e)) continue;
for (const [from, to] of occurrences(e, dayStart)) {
const top = (from - dayStart) / 3600000 * HOUR;
const height = Math.max(16, (to - from) / 3600000 * HOUR);
col.append(h('div', { class: 'ev ' + e.kind.kind, style: { top: top + 'px', height: height + 'px', left: (4 + lane * 6) + 'px' }, title: e.subject + ' · ' + e.describe },
h('span', { class: 'ev-kind' }, KIND_LABEL[e.kind.kind]), h('span', { class: 'mono' }, e.subject),
e.note ? h('span', {}, e.note) : null, h('span', { class: 'mono' }, hhmm(from) + '–' + (to.getTime() === dayStart.getTime() + 86400000 ? '24:00' : hhmm(to)))));
lane = (lane + 1) % 3;
}
}
grid.append(col);
}
// Formular wie im Mockup: Art, Gegenstand, Zeit und Wiederholung
const kindBox = h('div', {});
const subject = h('div', { class: 'stack small' });
const repeat = h('select', { id: 's-repeat', name: 'repeat', class: 'field', onchange: () => showTime() },
h('option', { value: 'once' }, 'einmalig'), h('option', { value: 'weekly' }, 'wöchentlich'), h('option', { value: 'permanent' }, 'dauerhaft'));
const days = dayToggles('s-days');
const once = h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 's-from' }, 'Beginn'), h('input', { id: 's-from', name: 'from', type: 'datetime-local', class: 'field mono' })),
h('div', { class: 'field-group' }, h('label', { for: 's-until' }, 'Ende'), h('input', { id: 's-until', name: 'until', type: 'datetime-local', class: 'field mono' })));
const weekly = h('div', { class: 'stack small' }, days,
h('div', { class: 'fields' },
h('div', { class: 'field-group' }, h('label', { for: 's-time-start' }, 'von'), h('input', { id: 's-time-start', name: 'time_start', type: 'time', class: 'field mono' })),
h('div', { class: 'field-group' }, h('label', { for: 's-time-end' }, 'bis'), h('input', { id: 's-time-end', name: 'time_end', type: 'time', class: 'field mono' })),
h('div', { class: 'field-group' }, h('label', { for: 's-valid-from' }, 'erstmals am'), h('input', { id: 's-valid-from', name: 'valid_from', type: 'date', class: 'field mono' })),
h('div', { class: 'field-group' }, h('label', { for: 's-valid-until' }, 'letztmals am'), h('input', { id: 's-valid-until', name: 'valid_until', type: 'date', class: 'field mono' }))));
function showTime() {
once.hidden = repeat.value !== 'once';
weekly.hidden = repeat.value !== 'weekly';
}
let kind = 'pin';
function showSubject() {
if (kind === 'pin') subject.replaceChildren(h('span', { class: 'label' }, 'Modell'), modelPicker(models, 's-model', false));
if (kind === 'exclusive') subject.replaceChildren(h('span', { class: 'label' }, 'Gruppen'),
groups.length ? h('div', { class: 'model-picker' }, groups.map((g) => h('label', { class: 'check' }, h('input', { type: 'checkbox', name: 's-group', value: g.name }), h('span', { class: 'mono' }, g.name), h('span', { class: 'hint' }, g.owner || ''))))
: h('p', { class: 'empty' }, 'Keine Gruppen.'),
h('div', { class: 'field-group' }, h('label', { for: 's-users' }, 'Personen (Benutzernamen)'), h('input', { id: 's-users', name: 'users', class: 'field mono', placeholder: 'hofmannol, mueller' })));
if (kind === 'window') subject.replaceChildren(h('span', { class: 'label' }, 'Nur diese Modelle'), modelPicker(models, 's-model', true));
}
kindBox.append(segmented('s-kind', [['pin', 'Pinnen'], ['exclusive', 'Exklusiv'], ['window', 'Zeitfenster']], 'pin', (v) => { kind = v; showSubject(); }));
showSubject();
showTime();
const form = h('form', {
class: 'card cal-form',
onsubmit: (ev) => {
ev.preventDefault();
const d = formData(form);
const body = { kind, note: d.note };
if (kind === 'pin') {
const m = checkedValues(form, 's-model')[0];
if (!m) { state.flash = { kind: 'error', text: 'Ein Modell auswählen.' }; return render(); }
body.model = m;
const nodes = (models.find((x) => x.id === m) || { nodes: [] }).nodes;
if (nodes.length > 1) body.node = d.node || nodes[0];
}
if (kind === 'exclusive') Object.assign(body, { groups: checkedValues(form, 's-group'), users: list(d.users) });
if (kind === 'window') body.models = checkedValues(form, 's-model');
if (d.repeat === 'once') Object.assign(body, { from: apiTime(d.from), until: apiTime(d.until) });
if (d.repeat === 'weekly') Object.assign(body, { weekly: days.value(), time: d.time_start + '-' + d.time_end, from: optional(d.valid_from), until: dayAfter(d.valid_until) });
act(() => api('POST', '/schedule', body), (e2) => 'Eintrag angelegt: ' + e2.subject + ', ' + e2.describe);
},
},
h('h2', {}, 'Eintrag anlegen'),
h('div', { class: 'field-group' }, h('span', { class: 'label' }, 'Art des Eintrags'), kindBox),
subject,
h('div', { class: 'field-group' }, h('label', { for: 's-repeat' }, 'Wiederholung'), repeat),
once, weekly,
h('div', { class: 'field-group' }, h('label', { for: 's-note' }, 'Anmerkung'), h('input', { id: 's-note', name: 'note', class: 'field', placeholder: 'z. B. Vorlesung KI' })),
h('span', { class: 'hint' }, 'Der Proxy lehnt Einträge ab, die nicht in den Speicher passen oder sich widersprechen, und nennt den Grund.'),
h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Speichern')));
return h('div', { class: 'stack' },
head('Administration', 'Zeitplan', 'Pins, exklusive Nutzung und Modellzeitfenster in einem gemeinsamen Plan.',
h('button', { class: 'btn icon', type: 'button', 'aria-label': 'Vorige Woche', onclick: () => shiftWeek(-1) }, '‹'),
h('span', { class: 'mono' }, label),
h('button', { class: 'btn icon', type: 'button', 'aria-label': 'Nächste Woche', onclick: () => shiftWeek(1) }, '›'),
h('button', { class: 'btn', type: 'button', onclick: () => shiftWeek(0) }, 'Heute')),
h('div', { class: 'toolbar' },
h('span', { class: 'muted' }, 'Dauerhaft'),
permanent.length ? permanent.map((e) => h('span', { class: 'chip ' + (e.kind.kind === 'pin' ? 'accent' : '') + ' mono' }, KIND_LABEL[e.kind.kind] + ' · ' + e.subject)) : h('span', { class: 'muted' }, '–'),
h('span', { class: 'legend' }, ['pin', 'exclusive', 'window'].map((k) => h('span', {}, h('span', { class: 'swatch ev-' + k }), KIND_LABEL[k])))),
h('div', { class: 'row top' }, h('section', { class: 'card cal-card' }, grid), form),
h('section', { class: 'card' }, h('h2', {}, 'Alle 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' : '') }, KIND_LABEL[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.')));
}
// ---------- Benutzer ----------
async function usersPage() {
const users = await api('GET', '/users');
const search = h('input', { type: 'search', class: 'field', placeholder: 'Benutzername, E-Mail oder Gruppe', 'aria-label': 'Benutzer durchsuchen', value: state.userSearch || '' });
const hideBlocked = h('input', { type: 'checkbox', id: 'hide-blocked', checked: state.hideBlocked });
const count = h('span', { class: 'muted' });
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;
const userRows = h('tbody', {});
const page = h('div', { class: 'stack' },
head('Administration', 'Benutzer', users.length + ' Konten'),
h('section', { class: 'card' },
h('div', { class: 'toolbar' }, search, h('label', { class: 'check', for: 'hide-blocked' }, hideBlocked, 'Gesperrte und deaktivierte ausblenden'), count),
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')))),
userRows))),
h('section', { class: 'card' }, h('h2', {}, 'Neuer Benutzer'), form));
function update() {
state.userSearch = search.value;
state.hideBlocked = hideBlocked.checked;
const q = search.value.trim().toLowerCase();
const shown = users.filter((u) => (!hideBlocked.checked || (!u.blocked && u.active))
&& (!q || [u.username, u.email, ...u.groups].some((v) => v && v.toLowerCase().includes(q))));
count.textContent = shown.length + ' von ' + users.length;
userRows.replaceChildren(...shown.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'))))));
}
search.addEventListener('input', update);
hideBlocked.addEventListener('change', update);
update();
return page;
}
// ---------- Audit-Log ----------
async function auditPage() {
const [entries, outbox] = await Promise.all([api('GET', '/audit?limit=1000'), api('GET', '/outbox')]);
const search = h('input', { type: 'search', class: 'field', placeholder: 'Person, Vorgang oder Details', 'aria-label': 'Audit-Log durchsuchen' });
const count = h('span', { class: 'muted' });
const auditRows = h('tbody', {});
function update() {
const q = search.value.trim().toLowerCase();
const shown = entries.filter((e) => !q || [e.actor, e.action, ACTIONS[e.action], e.detail].some((v) => v && v.toLowerCase().includes(q)));
count.textContent = shown.length + ' von ' + entries.length;
auditRows.replaceChildren(...shown.slice(0, 300).map((e) => h('tr', {},
h('td', { class: 'mono muted' }, when(e.ts)), h('td', { class: 'mono' }, actor(e.actor)),
h('td', {}, ACTIONS[e.action] || e.action), h('td', { class: 'wrap' }, e.detail))));
}
search.addEventListener('input', update);
update();
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 1000 Vorgänge, durchsuchbar. 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: 'toolbar' }, search, count),
h('div', { class: 'table-wrap' }, h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'Zeit'), h('th', {}, 'Wer'), h('th', {}, 'Vorgang'), h('th', {}, 'Details'))),
auditRows))));
}
const ACTIONS = {
'login': 'Angemeldet', 'login.failed': 'Anmeldung gescheitert',
'session.create': 'Sitzung angelegt', 'session.revoke': 'Sitzung beendet',
'user.create': 'Benutzer angelegt', 'user.role': 'Rolle geändert', 'user.block': 'Benutzer gesperrt', 'user.unblock': 'Benutzer entsperrt',
'user.deactivate': 'Konto deaktiviert', 'user.activate': 'Konto aktiviert', 'user.password': 'Passwort gesetzt',
'group.create': 'Gruppe angelegt', 'group.delete': 'Gruppe gelöscht', 'group.add': 'Mitglied aufgenommen', 'group.remove': 'Mitglied entfernt',
'quota.create': 'Kontingent angelegt', 'quota.remove': 'Kontingent entfernt',
'key.create': 'Key angelegt', 'key.revoke': 'Key widerrufen', 'key.quota': 'Kontingent eines Keys geändert',
'schedule.add': 'Zeitplan: Eintrag angelegt', 'schedule.remove': 'Zeitplan: Eintrag entfernt',
'model.load': 'Modell geladen', 'model.unload': 'Modell entladen', 'model.load_failed': 'Laden gescheitert', 'pin.load_failed': 'Gepinntes Modell nicht geladen',
'recording.start': 'Aufzeichnung gestartet', 'recording.end': 'Aufzeichnung beendet', 'recording.ready': 'Aufzeichnung bereitgestellt',
'recording.download': 'Aufzeichnung heruntergeladen', 'recording.delete': 'Aufzeichnung gelöscht',
'usage.prune': 'Alte Metadaten gelöscht',
};
const actor = (a) => ({ system: 'System', scheduler: 'Proxy', cli: 'Kommandozeile' }[a] || a);
render();