// 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, vorausgewählt `selected` (Kürzel); liefert die Auswahl als "mo,mi" */ function dayToggles(id, selected = []) { 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': String(selected.includes(code)), '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() { closeOverlays(); 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) { const hide = h('input', { type: 'checkbox', id: 'hide-revoked', checked: state.hideRevoked ?? true }); const revoked = keys.filter((k) => k.revoked).length; const body = h('tbody', {}); function update() { state.hideRevoked = hide.checked; body.replaceChildren(...keys.filter((k) => !hide.checked || !k.revoked).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')))))); } hide.addEventListener('change', update); update(); return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', {}, title), revoked ? h('label', { class: 'check', for: 'hide-revoked' }, hide, 'Widerrufene ausblenden (' + revoked + ')') : null), 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')))), body)) : 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; }; // Vergangen: läuft nicht mehr und hat keine Daten mehr zum Herunterladen const past = (r) => !r.state.startsWith('zeichnet') && !r.state.startsWith('bereit'); const pastCount = recordings.filter(past).length; const hide = h('input', { type: 'checkbox', id: 'hide-past-recordings', checked: state.hidePastRecordings ?? true }); const body = h('tbody', {}); const empty = h('p', { class: 'empty' }); function update() { state.hidePastRecordings = hide.checked; const shown = recordings.slice().reverse().filter((r) => !hide.checked || !past(r)); body.replaceChildren(...shown.map((r) => h('tr', { class: past(r) ? 'dim' : null }, 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)))); empty.hidden = shown.length > 0; empty.textContent = recordings.length ? 'Keine laufenden oder bereitliegenden Aufzeichnungen.' : 'Noch keine Aufzeichnungen. Starte eine über „Aufzeichnen“ bei einem deiner Keys.'; table.hidden = !shown.length; } const table = 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')))), body)); hide.addEventListener('change', update); update(); return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', {}, 'Aufzeichnung für Debugging'), pastCount ? h('label', { class: 'check', for: 'hide-past-recordings' }, hide, 'Vergangene ausblenden (' + pastCount + ')') : null), h('span', { class: 'hint' }, 'Verschlüsselt gespeichert, nur für dich abrufbar, eine Stunde bereit, nach dem Download gelöscht.'), table, empty); } 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 */ 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', WEEKDAYS.map(([code]) => code)); 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 wide' }, 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) { state.flash = { kind: 'error', text: 'Mindestens einen Wochentag auswählen.' }; return render(); } if (!d.time_start !== !d.time_end) { state.flash = { kind: 'error', text: 'Für die Uhrzeit Beginn und Ende angeben.' }; return render(); } const time = d.time_start ? d.time_start + '-' + d.time_end : undefined; // Alle Tage ohne Uhrzeit heißt: jederzeit const always = weekly.split(',').length === 7 && !time; 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: always ? undefined : weekly, time, 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 Uhrzeit ganztags. Endet die Uhrzeit 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]; // Alle n Wochen: zählt die Woche, in der ein Abschnitt beginnt, ab der Woche des Beginns const monday = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate() - ((d.getDay() + 6) % 7)); const inRhythm = (day) => w.every <= 1 || !from || Math.round((monday(day) - monday(from)) / (7 * 86400000)) % w.every === 0; const result = []; const start = w.start.slice(0, 5); const end = w.end.slice(0, 5); if (w.days.includes(code(dayStart)) && inRhythm(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)) && inRhythm(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(); }; const newEntry = (preset) => openOverlay('Neuer Eintrag', (close) => scheduleForm(models, groups, preset, close)); const editEntry = (e) => openOverlay('Eintrag bearbeiten', (close) => scheduleForm(models, groups, null, close, e)); const creator = (e) => e.creator || (e.created_by ? '#' + e.created_by : 'Kommandozeile'); // Kalender: eine Spalte je Tag, eine Zeile je Stunde. Ziehen markiert einen Zeitraum, ein Klick eine Stunde. const HOUR = 22; const SLOT = 30; 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' }, title: 'Zeitraum aufziehen, um einen Eintrag anzulegen' }); 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('button', { type: 'button', class: 'ev ' + e.kind.kind, style: { top: top + 'px', height: height + 'px', left: (4 + lane * 6) + 'px' }, title: e.subject + ' · ' + e.describe + ' · von ' + creator(e), onpointerdown: (ev) => ev.stopPropagation(), onclick: () => showEntry(e) }, 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: 'ev-by' }, 'von ' + creator(e)), h('span', { class: 'mono' }, hhmm(from) + '–' + (to.getTime() === dayStart.getTime() + 86400000 ? '24:00' : hhmm(to))))); lane = (lane + 1) % 3; } } // Minuten seit Tagesbeginn an der Zeigerposition, auf halbe Stunden gerastert const minutes = (ev, round) => { const y = ev.clientY - col.getBoundingClientRect().top; return Math.min(24 * 60, Math.max(0, round(y / HOUR * 60 / SLOT) * SLOT)); }; let drag = null; const sel = h('div', { class: 'cal-sel', hidden: true }); col.append(sel); const show = () => { const [a, b] = [Math.min(drag.start, drag.end), Math.max(drag.start, drag.end)]; Object.assign(sel.style, { top: (a / 60 * HOUR) + 'px', height: ((b - a) / 60 * HOUR) + 'px' }); sel.textContent = mm(a) + '–' + mm(b); sel.hidden = false; }; col.addEventListener('pointerdown', (ev) => { if (ev.button !== 0) return; ev.preventDefault(); if (col.setPointerCapture && ev.pointerId !== undefined) col.setPointerCapture(ev.pointerId); const start = minutes(ev, Math.floor); drag = { start, end: Math.min(24 * 60, start + 60) }; show(); }); col.addEventListener('pointermove', (ev) => { if (!drag) return; const m = minutes(ev, Math.ceil); // Nach oben gezogen: der Beginn rastet nach unten ab drag.end = m > drag.start ? m : Math.max(0, minutes(ev, Math.floor)); if (drag.end === drag.start) drag.end = drag.start + SLOT; show(); }); col.addEventListener('pointerup', () => { if (!drag) return; const [a, b] = [Math.min(drag.start, drag.end), Math.max(drag.start, drag.end)]; drag = null; newEntry({ day: dayStart, start: a, end: b }); sel.hidden = true; }); col.addEventListener('pointercancel', () => { drag = null; sel.hidden = true; }); grid.append(col); } function showEntry(e) { openOverlay(KIND_LABEL[e.kind.kind] + ': ' + e.subject, (close) => h('div', { class: 'stack small' }, h('dl', { class: 'facts' }, h('dt', {}, 'Wann'), h('dd', {}, e.describe), h('dt', {}, 'Stand'), h('dd', {}, e.active ? 'gerade aktiv' : 'gerade nicht aktiv'), h('dt', {}, 'Angelegt von'), h('dd', { class: 'mono' }, creator(e)), e.note ? [h('dt', {}, 'Anmerkung'), h('dd', {}, e.note)] : null), h('div', { class: 'actions' }, h('button', { class: 'btn', type: 'button', onclick: close }, 'Schließen'), e.editable ? h('button', { class: 'btn', type: 'button', onclick: () => editEntry(e) }, 'Bearbeiten') : null, h('button', { class: 'btn danger', type: 'button', onclick: () => { close(); act(() => api('DELETE', '/schedule/' + e.id), 'Eintrag entfernt.'); } }, 'Entfernen')))); } return h('div', { class: 'stack' }, head('Administration', 'Zeitplan', 'Pins, exklusive Nutzung und Modellzeitfenster in einem gemeinsamen Plan. Zum Anlegen einen Zeitraum im Kalender aufziehen.', 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('button', { class: 'btn primary', type: 'button', onclick: () => newEntry(null) }, 'Neuer Eintrag')), h('div', { class: 'toolbar' }, h('span', { class: 'muted' }, 'Dauerhaft'), permanent.length ? permanent.map((e) => h('button', { type: 'button', class: 'chip ' + (e.kind.kind === 'pin' ? 'accent' : '') + ' mono', onclick: () => showEntry(e) }, 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('section', { class: 'card cal-card' }, grid), 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', {}, 'Von'), 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', { class: 'mono' }, creator(e)), h('td', {}, h('div', { class: 'actions' }, e.editable ? h('button', { class: 'btn small', type: 'button', onclick: () => editEntry(e) }, 'Bearbeiten') : null, 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.'))); } const mm = (m) => String(Math.floor(m / 60)).padStart(2, '0') + ':' + String(m % 60).padStart(2, '0'); /** Datum und Minuten seit Tagesbeginn als Wert für ein datetime-local-Feld */ function localValue(day, minutes) { const d = new Date(day.getFullYear(), day.getMonth(), day.getDate(), 0, minutes); const p = (n) => String(n).padStart(2, '0'); return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + 'T' + p(d.getHours()) + ':' + p(d.getMinutes()); } const dateOf = (v) => v.slice(0, 10); const timeOf = (v) => v.slice(11, 16); const fromUnix = (ts) => { const d = new Date(ts * 1000); return localValue(d, d.getHours() * 60 + d.getMinutes()); }; /** Beginn und Ende eines bestehenden Eintrags für das Formular: bei wöchentlichen der erste Termin */ function entryTimes(e) { const w = e.time.weekly; if (!w) return { from: e.time.from ? fromUnix(e.time.from) : '', until: e.time.until ? fromUnix(e.time.until) : '' }; const first = e.time.from ? new Date(e.time.from * 1000) : new Date(); const [sh, sm] = w.start.split(':').map(Number); const [eh, em] = w.end.split(':').map(Number); const start = sh * 60 + sm; let end = eh * 60 + em; if (end <= start) end += 24 * 60; // über Mitternacht oder ganztags const repeatUntil = e.time.until ? dateOf(localValue(new Date((e.time.until - 86400) * 1000), 0)) : ''; return { from: localValue(first, start), until: localValue(first, end), repeatUntil }; } /** Formular für einen Zeitplaneintrag: neu (mit dem im Kalender markierten Zeitraum) oder ein eigener zum Bearbeiten */ function scheduleForm(models, groups, preset, close, entry) { const error = h('div', { class: 'notice error', role: 'alert', hidden: true }); const fail = (text) => { error.textContent = text; error.hidden = false; }; const k = entry ? entry.kind : null; const times = entry ? entryTimes(entry) : { from: preset ? localValue(preset.day, preset.start) : '', until: preset ? localValue(preset.day, preset.end) : '', repeatUntil: '', }; const w = entry && entry.time.weekly; const weekdayOf = (v) => (v ? WEEKDAYS[(new Date(dateOf(v) + 'T00:00').getDay() + 6) % 7][0] : null); const preDays = w ? WEEKDAYS.filter(([, , en]) => w.days.includes(en)).map(([code]) => code) : [weekdayOf(times.from)].filter(Boolean); const fromInput = h('input', { id: 's-from', name: 'from', type: 'datetime-local', class: 'field mono', required: true, value: times.from }); const untilInput = h('input', { id: 's-until', name: 'until', type: 'datetime-local', class: 'field mono', required: true, value: times.until }); const repeat = h('select', { id: 's-repeat', name: 'repeat', class: 'field', onchange: () => showRepeat() }, h('option', { value: 'none', selected: !w }, 'keine'), h('option', { value: 'weekly', selected: !!w }, 'wöchentlich')); const days = dayToggles('s-days', preDays); const every = h('select', { id: 's-every', name: 'every', class: 'field' }, [[1, 'jede Woche'], [2, 'alle 2 Wochen (14-tägig)'], [3, 'alle 3 Wochen'], [4, 'alle 4 Wochen']] .map(([n, label]) => h('option', { value: n, selected: (w ? w.every : 1) === n }, label))); const weekly = h('div', { class: 'stack small' }, h('div', { class: 'field-group' }, h('span', { class: 'label' }, 'an'), days), h('div', { class: 'fields' }, h('div', { class: 'field-group' }, h('label', { for: 's-every' }, 'Rhythmus'), every), h('div', { class: 'field-group' }, h('label', { for: 's-repeat-until' }, 'wiederholen bis einschließlich'), h('input', { id: 's-repeat-until', name: 'repeat_until', type: 'date', class: 'field mono', value: times.repeatUntil || '' }))), h('span', { class: 'hint' }, 'Uhrzeit wie bei Beginn und Ende. Der Rhythmus zählt ab der Woche des Beginns. Ohne Enddatum wiederholt sich der Eintrag unbegrenzt.')); function showRepeat() { weekly.hidden = repeat.value !== 'weekly'; } // Beim Ändern des Beginns: Ende mitziehen und, solange nur ein Tag gewählt ist, den Wochentag anpassen let lastFrom = fromInput.value; fromInput.addEventListener('change', () => { const a = new Date(lastFrom); const b = new Date(fromInput.value); const u = new Date(untilInput.value); if (lastFrom && untilInput.value && !isNaN(b)) { const moved = new Date(u.getTime() + (b - a)); untilInput.value = localValue(moved, moved.getHours() * 60 + moved.getMinutes()); } const pressed = [...days.querySelectorAll('[aria-pressed=true]')]; if (pressed.length <= 1 && fromInput.value) { for (const btn of days.children) btn.setAttribute('aria-pressed', String(btn.dataset.day === weekdayOf(fromInput.value))); } lastFrom = fromInput.value; }); // Gegenstand: Modell (Pin), Gruppen und Personen (Exklusiv), Modelle (Zeitfenster) const subject = h('div', { class: 'stack small' }); let kind = k ? k.kind : 'pin'; function showSubject() { if (kind === 'pin') { const nodeBox = h('div', { class: 'field-group', hidden: true }); const picker = modelPicker(models, 's-model', false); const showNodes = () => { const m = models.find((x) => x.id === checkedValues(picker, 's-model')[0]); nodeBox.hidden = !m || m.nodes.length < 2; if (!m) return; const chosen = k && k.kind === 'pin' && m.id === k.engine + '/' + k.model ? k.node : m.nodes[0]; nodeBox.replaceChildren(h('label', { for: 's-node' }, 'auf Rechner'), h('select', { id: 's-node', name: 'node', class: 'field mono' }, m.nodes.map((n) => h('option', { value: n, selected: n === chosen }, n)))); }; picker.addEventListener('change', showNodes); if (k && k.kind === 'pin') { for (const i of picker.querySelectorAll('input')) i.checked = i.value === k.engine + '/' + k.model; } showNodes(); subject.replaceChildren(h('span', { class: 'label' }, 'Modell'), picker, nodeBox); } if (kind === 'exclusive') { const names = (entry && entry.names) || { users: [], groups: [] }; 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, checked: names.groups.includes(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', value: names.users.join(', ') }))); } if (kind === 'window') { const picker = modelPicker(models, 's-model', true); if (k && k.kind === 'window') for (const i of picker.querySelectorAll('input')) i.checked = k.models.includes(i.value); subject.replaceChildren(h('span', { class: 'label' }, 'Nur diese Modelle'), picker); } } showSubject(); showRepeat(); const form = h('form', { class: 'stack small', onsubmit: async (ev) => { ev.preventDefault(); error.hidden = true; const d = formData(form); const body = { kind, note: d.note }; if (kind === 'pin') { const m = checkedValues(form, 's-model')[0]; if (!m) return fail('Ein Modell auswählen.'); 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 (k && k.kind === 'exclusive' && k.keys.length) body.keys = k.keys; } if (kind === 'window') { body.models = checkedValues(form, 's-model'); if (!body.models.length) return fail('Mindestens ein Modell auswählen.'); } if (!d.from || !d.until) return fail('Beginn und Ende angeben.'); const span = new Date(d.until) - new Date(d.from); if (span <= 0) return fail('Das Ende muss nach dem Beginn liegen.'); if (d.repeat === 'none') Object.assign(body, { from: apiTime(d.from), until: apiTime(d.until) }); else { if (span > 86400000) return fail('Ein wöchentlicher Termin dauert höchstens 24 Stunden.'); if (!days.value()) return fail('Mindestens einen Wochentag auswählen.'); if (d.repeat_until && d.repeat_until < dateOf(d.from)) return fail('„Wiederholen bis“ liegt vor dem Beginn.'); const wholeDay = span === 86400000 && timeOf(d.from) === '00:00'; if (span === 86400000 && !wholeDay) return fail('Ein wöchentlicher Termin über 24 Stunden muss um 00:00 beginnen (ganztags).'); Object.assign(body, { weekly: days.value(), time: wholeDay ? undefined : timeOf(d.from) + '-' + timeOf(d.until), every: Number(d.every), from: dateOf(d.from), until: dayAfter(d.repeat_until), }); } // Fehler bleiben im Overlay, damit die Eingaben erhalten bleiben try { const saved = await api(entry ? 'PUT' : 'POST', '/schedule' + (entry ? '/' + entry.id : ''), body); close(); state.flash = { kind: 'ok', text: (entry ? 'Eintrag geändert: ' : 'Eintrag angelegt: ') + saved.subject + ', ' + saved.describe }; render(); } catch (e) { fail(e.message); } }, }, h('div', { class: 'field-group' }, h('span', { class: 'label' }, 'Art des Eintrags'), segmented('s-kind', [['pin', 'Pinnen'], ['exclusive', 'Exklusiv'], ['window', 'Zeitfenster']], kind, (v) => { kind = v; showSubject(); })), subject, h('div', { class: 'fields' }, h('div', { class: 'field-group' }, h('label', { for: 's-from' }, 'Beginn'), fromInput), h('div', { class: 'field-group' }, h('label', { for: 's-until' }, 'Ende'), untilInput)), h('div', { class: 'field-group' }, h('label', { for: 's-repeat' }, 'Wiederholung'), repeat), 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', value: entry ? entry.note : '' })), h('span', { class: 'hint' }, 'Der Proxy lehnt Einträge ab, die nicht in den Speicher passen oder sich widersprechen, und nennt den Grund.'), error, h('div', { class: 'actions' }, h('button', { class: 'btn', type: 'button', onclick: close }, 'Abbrechen'), h('button', { class: 'btn primary', type: 'submit' }, entry ? 'Änderungen speichern' : 'Speichern'))); return form; } /** Overlay über der Seite; schließt mit Escape, Klick daneben oder close() */ function openOverlay(title, content) { closeOverlays(); const previous = document.activeElement; const titleId = 'overlay-title'; const backdrop = h('div', { class: 'overlay' }); const close = () => { backdrop.remove(); document.removeEventListener('keydown', onKey); if (previous && previous.focus) previous.focus(); }; const onKey = (e) => { if (e.key === 'Escape') close(); }; const dialog = h('div', { class: 'dialog card', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId }, h('div', { class: 'card-head' }, h('h2', { id: titleId }, title), h('button', { class: 'btn icon', type: 'button', 'aria-label': 'Schließen', onclick: close }, '×')), content(close)); backdrop.append(dialog); backdrop.addEventListener('pointerdown', (e) => { if (e.target === backdrop) close(); }); document.addEventListener('keydown', onKey); backdrop.close = close; document.body.append(backdrop); const first = dialog.querySelector('input:not([type=hidden]), select, textarea, button:not(.icon)'); if (first) first.focus(); return close; } function closeOverlays() { for (const o of document.querySelectorAll('.overlay')) o.close(); } // ---------- 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.update': 'Zeitplan: Eintrag geändert', '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();