From 11dbc1c78168c1675278a6987f9e10b7755ce777 Mon Sep 17 00:00:00 2001 From: Stephan Rehfeld Date: Fri, 20 Nov 2026 18:31:05 +0100 Subject: [PATCH] =?UTF-8?q?Oberfl=C3=A4che=20nach=20Durchsicht:=20Kalender?= =?UTF-8?q?,=20Suchen,=20eigene=20Verwaltungsseiten,=20gemeinsame=20Gruppe?= =?UTF-8?q?nkontingente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Ü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 --- README.md | 5 +- proxy/src/accounts.rs | 25 +- proxy/src/api.rs | 17 +- proxy/src/cli.rs | 10 +- proxy/src/db.rs | 76 +++-- proxy/src/main.rs | 3 + proxy/src/quota.rs | 9 +- proxy/src/recording.rs | 15 +- proxy/src/routes.rs | 36 ++- proxy/src/schedule.rs | 30 +- proxy/src/scheduler.rs | 33 +- proxy/src/service.rs | 36 ++- proxy/ui/app.css | 38 +++ proxy/ui/app.js | 540 ++++++++++++++++++++++++++------- tests/multispark/quota_test.py | 20 ++ tests/multispark/start.sh | 5 +- tests/multispark/ui_test.py | 5 + tests/ui/render_test.js | 66 +++- 18 files changed, 805 insertions(+), 164 deletions(-) diff --git a/README.md b/README.md index e24077e..7cc1c6b 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ KEY=omega-… curl -H "Authorization: Bearer $KEY" http://server:8000/api/chat \ -d '{"model":"qwen3:0.6b","messages":[{"role":"user","content":"Hallo"}]}' +# Ollama auch unter http://server:8000/ollama (die Wurzel bleibt für bestehende Anwendungen) # llama.cpp: OpenAI-kompatibel, Basis-URL http://server:8000/llamacpp/v1 curl -H "Authorization: Bearer $KEY" http://server:8000/llamacpp/v1/chat/completions \ -d '{"model":"qwen3-0.6b","messages":[{"role":"user","content":"Hallo"}]}' @@ -132,7 +133,9 @@ Gruppe oder einer Person zu; Keys werden gegen ein Kontingent abgerechnet. Ein K Kontingent ist unbegrenzt (nur Lecturer und Administratoren). **Die Grenzen eines Gruppenkontingents gelten je Mitglied:** Bei 20 000 Token am Tag hat jedes -Mitglied 20 000, nicht alle zusammen. Mehrere Keys derselben Person teilen sich ihren Anteil. +Mitglied 20 000, nicht alle zusammen. Mehrere Keys derselben Person teilen sich ihren Anteil. Mit +`--shared` (in der Oberfläche „für die Gruppe gemeinsam“) gelten sie für alle Mitglieder +zusammen; gezählt wird dann zusätzlich je Person, damit der Verbrauch sichtbar bleibt. ```sh # Praktikum: 20 000 Token am Tag, 60 Anfragen in der Stunde, nur werktags 8-18 Uhr, diff --git a/proxy/src/accounts.rs b/proxy/src/accounts.rs index 27638ca..35b97c6 100644 --- a/proxy/src/accounts.rs +++ b/proxy/src/accounts.rs @@ -68,6 +68,14 @@ impl Role { } } + pub fn label(self) -> &'static str { + match self { + Role::User => "User", + Role::Lecturer => "Lecturer", + Role::Admin => "Administrator", + } + } + pub fn parse(s: &str) -> Result { match s { "user" => Ok(Role::User), @@ -220,7 +228,7 @@ impl Db { .with_context(|| format!("Benutzer {username} anlegen"))?; let id = conn.last_insert_rowid(); drop(conn); - self.audit(actor, "user.create", &format!("id={id} {username} role={}", role.as_str()))?; + self.audit(actor, "user.create", &format!("{username} als {} angelegt", role.label()))?; Ok(id) } @@ -270,7 +278,7 @@ impl Db { bail!("{username} ist der letzte Administrator"); } self.conn().execute("UPDATE users SET role = ?1 WHERE id = ?2", params![role.as_str(), user.id])?; - self.audit(actor, "user.role", &format!("{username} {} -> {}", user.role.as_str(), role.as_str())) + self.audit(actor, "user.role", &format!("{username}: {} → {}", user.role.label(), role.label())) } /// Sperren durch einen Administrator @@ -301,7 +309,7 @@ impl Db { .with_context(|| format!("Gruppe {name} anlegen"))?; let id = conn.last_insert_rowid(); drop(conn); - self.audit(actor, "group.create", &format!("id={id} {name}"))?; + self.audit(actor, "group.create", &format!("Gruppe {name} (#{id})"))?; Ok(id) } @@ -343,7 +351,7 @@ impl Db { conn.execute("DELETE FROM group_members WHERE group_id = ?1", params![group.id])?; conn.execute("DELETE FROM groups WHERE id = ?1", params![group.id])?; drop(conn); - self.audit(actor, "group.delete", &group.name) + self.audit(actor, "group.delete", &format!("Gruppe {}", group.name)) } pub fn add_member(&self, actor: &str, group: &Group, username: &str) -> Result { @@ -352,7 +360,7 @@ impl Db { params![group.id, username, now()], )? > 0; if added { - self.audit(actor, "group.add", &format!("{} {username}", group.name))?; + self.audit(actor, "group.add", &format!("{username} in Gruppe {}", group.name))?; } Ok(added) } @@ -363,7 +371,7 @@ impl Db { params![group.id, username], )? > 0; if removed { - self.audit(actor, "group.remove", &format!("{} {username}", group.name))?; + self.audit(actor, "group.remove", &format!("{username} aus Gruppe {}", group.name))?; } Ok(removed) } @@ -425,7 +433,7 @@ impl Db { )?; let id = conn.last_insert_rowid(); drop(conn); - self.audit(&user.username, "session.create", &format!("id={id} days={days}"))?; + self.audit(&user.username, "session.create", &format!("Sitzung #{id}, gültig {days} Tage ({note})"))?; Ok((id, token)) } @@ -472,7 +480,7 @@ impl Db { params![now(), id, user.id], )?; if changed > 0 { - self.audit(&user.username, "session.revoke", &format!("id={id}"))?; + self.audit(&user.username, "session.revoke", &format!("Sitzung #{id}"))?; } Ok(changed > 0) } @@ -512,6 +520,7 @@ mod tests { owner_id: Some(owner), group_id: group, user_id: user, + shared: false, } } diff --git a/proxy/src/api.rs b/proxy/src/api.rs index e789f9e..ea9dc20 100644 --- a/proxy/src/api.rs +++ b/proxy/src/api.rs @@ -79,6 +79,7 @@ pub fn router(state: AppState) -> Router { .route("/keys", get(list_keys).post(create_key)) .route("/keys/{id}", delete(revoke_key)) .route("/keys/{id}/quota", put(set_key_quota)) + .route("/models", get(models)) .route("/quotas", get(list_quotas).post(create_quota)) .route("/quotas/{id}", get(show_quota).delete(remove_quota)) .route("/schedule", get(list_schedule).post(add_schedule)) @@ -169,12 +170,12 @@ async fn login(State(st): State, Json(input): Json) -> Api return Err(crate::service::forbidden("Die Anmeldung mit Passwort ist ausgeschaltet").into()); } let Some(user) = st.db.check_password(&input.username, &input.password)? else { - st.db.audit(&input.username, "login.failed", "Passwort")?; + st.db.audit(&input.username, "login.failed", "Anmeldung mit Passwort gescheitert")?; return Ok((StatusCode::UNAUTHORIZED, Json(json!({ "error": "Benutzername oder Passwort falsch" }))).into_response()); }; let days = st.ui.session_days.clamp(1, 365); let (_, token) = st.db.create_session(&user, days, "Anmeldung im Browser")?; - st.db.audit(&user.username, "login", "Passwort")?; + st.db.audit(&user.username, "login", "Anmeldung mit Passwort")?; let cookie = session_cookie(&st, &token, i64::from(days) * 86_400); Ok(([(header::SET_COOKIE, cookie)], Json(json!({ "user": user }))).into_response()) } @@ -311,6 +312,18 @@ async fn set_key_quota( done() } +/// Angebotene Modelle je Schnittstelle, für die Auswahl in Kontingenten und im Zeitplan +async fn models(State(st): State, Extension(actor): Extension) -> ApiResult { + actor.require(Role::Lecturer)?; + let list: Vec = st + .sched + .catalog_entries() + .into_iter() + .map(|(engine, model, nodes)| json!({ "engine": engine.as_str(), "model": model, "id": format!("{}/{model}", engine.as_str()), "nodes": nodes })) + .collect(); + ok(list) +} + // Kontingente async fn list_quotas(State(st): State, Extension(actor): Extension) -> ApiResult { diff --git a/proxy/src/cli.rs b/proxy/src/cli.rs index c27c2f6..03e8876 100644 --- a/proxy/src/cli.rs +++ b/proxy/src/cli.rs @@ -233,12 +233,13 @@ pub async fn schedule(config: Config, db: Arc, actor: &Actor, cmd: ScheduleC pub async fn quota(config: Config, db: Arc, actor: &Actor, cmd: QuotaCommand) -> Result<()> { let svc = Service::new(&db, actor); match cmd { - QuotaCommand::Create { name, group, user, limits, models, time } => { + QuotaCommand::Create { name, group, user, shared, limits, models, time } => { actor.require(Role::Lecturer).context("Kontingente teilen Lecturer zu")?; let input = QuotaInput { name, group: group.clone(), user: user.clone(), + shared, tokens: Limits { hour: limits.tokens_hour, day: limits.tokens_day, @@ -264,6 +265,7 @@ pub async fn quota(config: Config, db: Arc, actor: &Actor, cmd: QuotaCommand }; let q = svc.create_quota(&sched, &input)?; let target = match (group, user) { + (Some(g), _) if shared => format!(" für Gruppe {g} (gemeinsam)"), (Some(g), _) => format!(" für Gruppe {g} (je Mitglied)"), (_, Some(u)) => format!(" für {u}"), _ => String::new(), @@ -289,7 +291,11 @@ pub async fn quota(config: Config, db: Arc, actor: &Actor, cmd: QuotaCommand println!("{} (#{id}), verwaltet von {}: {}", q.name, d.info.owner.as_deref().unwrap_or("-"), d.info.describe); println!("{:<14} {:<10} {:>12} {:>12} {:>10} {:>10} endet", "Person", "Zeitraum", "Token", "Grenze", "Anfragen", "Grenze"); for person in &d.usage { - let name = person.user.clone().unwrap_or_else(|| "(ohne Inhaber)".into()); + let name = match (&person.user, person.group_total) { + (_, true) => "Gruppe gesamt".to_string(), + (Some(u), _) => u.clone(), + (None, _) => "(ohne Inhaber)".into(), + }; let u = &person.usage; for (p, c) in [ (crate::quota::Period::Hour, u.hour), diff --git a/proxy/src/db.rs b/proxy/src/db.rs index 756ed33..3a1336d 100644 --- a/proxy/src/db.rs +++ b/proxy/src/db.rs @@ -158,7 +158,8 @@ impl Db { requests_hour INTEGER, requests_day INTEGER, requests_week INTEGER, requests_month INTEGER, requests_total INTEGER, note TEXT NOT NULL, - created_at INTEGER NOT NULL + created_at INTEGER NOT NULL, + shared INTEGER NOT NULL DEFAULT 0 ); -- Verbrauch je Key bzw. Kontingent und Zeitraum (z. B. day:2026-11-20). Die Zähler -- bleiben erhalten, wenn alte Einträge in usage gelöscht werden. @@ -296,7 +297,16 @@ impl Db { )?; let id = conn.last_insert_rowid(); drop(conn); - self.audit(actor, "key.create", &format!("id={id} name={name} super={is_super} quota={quota_id:?} user={user_id:?}"))?; + let owner = match user_id { + Some(u) => self.user(u)?.map(|u| u.username).unwrap_or_else(|| format!("#{u}")), + None => "den Betreiber".into(), + }; + let kind = match (is_super, quota_id) { + (true, _) => "Super-Key".to_string(), + (false, Some(q)) => format!("Kontingent »{}«", self.quota(q)?.map(|q| q.name).unwrap_or_default()), + (false, None) => "unbegrenzt".into(), + }; + self.audit(actor, "key.create", &format!("Key »{name}« (#{id}) für {owner}, {kind}"))?; Ok((id, key)) } @@ -323,12 +333,13 @@ impl Db { } pub fn revoke_key(&self, actor: &str, id: i64) -> Result { + let name = self.key(id)?.map(|k| k.name).unwrap_or_default(); let changed = self.conn().execute( "UPDATE api_keys SET revoked_at = ?1 WHERE id = ?2 AND revoked_at IS NULL", params![now(), id], )?; if changed > 0 { - self.audit(actor, "key.revoke", &format!("id={id}"))?; + self.audit(actor, "key.revoke", &format!("Key »{name}« (#{id})"))?; } Ok(changed > 0) } @@ -462,7 +473,7 @@ impl Db { self.audit( actor, "schedule.add", - &format!("id={id} {} {} {}", e.kind_name(), e.subject(), e.time.describe()), + &format!("{} {}, {} (#{id})", e.kind_label(), e.subject(), e.time.describe()), )?; Ok(id) } @@ -546,7 +557,7 @@ impl Db { pub fn remove_schedule(&self, actor: &str, id: i64) -> Result { let changed = self.conn().execute("DELETE FROM schedule WHERE id = ?1", params![id])?; if changed > 0 { - self.audit(actor, "schedule.remove", &format!("id={id}"))?; + self.audit(actor, "schedule.remove", &format!("Eintrag #{id}"))?; } Ok(changed > 0) } @@ -564,7 +575,11 @@ impl Db { if changed == 0 { bail!("kein Key mit ID {key_id}, oder es ist ein Super-Key"); } - self.audit(actor, "key.quota", &format!("id={key_id} quota={quota_id:?}")) + let quota = match quota_id { + Some(q) => format!("Kontingent »{}«", self.quota(q)?.map(|q| q.name).unwrap_or_default()), + None => "unbegrenzt".into(), + }; + self.audit(actor, "key.quota", &format!("Key #{key_id}: {quota}")) } pub fn create_quota(&self, actor: &str, q: &Quota) -> Result { @@ -586,22 +601,22 @@ impl Db { conn.execute( "INSERT INTO quotas (name, valid_from, valid_until, days, time_start, time_end, models, tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note, created_at, - owner_id, group_id, user_id) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22)", + owner_id, group_id, user_id, shared) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23)", params![ q.name, q.time.from, q.time.until, days, start, end, models, limits[0], limits[1], limits[2], limits[3], limits[4], limits[5], limits[6], limits[7], limits[8], limits[9], q.note, now(), - q.owner_id, q.group_id, q.user_id + q.owner_id, q.group_id, q.user_id, q.shared ], )?; let id = conn.last_insert_rowid(); drop(conn); let target = match (q.group_id, q.user_id) { - (Some(g), _) => format!(" group={g}"), - (_, Some(u)) => format!(" user={u}"), + (Some(g), _) => format!(" für Gruppe {}", self.group(g)?.map(|g| g.name).unwrap_or_default()), + (_, Some(u)) => format!(" für {}", self.user(u)?.map(|u| u.username).unwrap_or_default()), _ => String::new(), }; - self.audit(actor, "quota.create", &format!("id={id} {}{target}: {}", q.name, q.describe()))?; + self.audit(actor, "quota.create", &format!("Kontingent »{}« (#{id}){target}: {}", q.name, q.describe()))?; Ok(id) } @@ -609,7 +624,7 @@ impl Db { let conn = self.conn(); let mut stmt = conn.prepare(&format!( "SELECT id, name, valid_from, valid_until, days, time_start, time_end, models, tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note, - owner_id, group_id, user_id + owner_id, group_id, user_id, shared FROM quotas {filter} ORDER BY id" ))?; let mut rows = stmt.query(args)?; @@ -639,6 +654,7 @@ impl Db { owner_id: r.get(19)?, group_id: r.get(20)?, user_id: r.get(21)?, + shared: r.get(22)?, }); } Ok(list) @@ -654,6 +670,7 @@ impl Db { /// Nur ein Kontingent, an dem keine Keys mehr hängen, kann entfernt werden. pub fn remove_quota(&self, actor: &str, id: i64) -> Result<()> { + let name = self.quota(id)?.map(|q| q.name).unwrap_or_default(); let conn = self.conn(); let keys: i64 = conn.query_row("SELECT count(*) FROM api_keys WHERE quota_id = ?1", params![id], |r| r.get(0))?; if keys > 0 { @@ -664,7 +681,7 @@ impl Db { } conn.execute("DELETE FROM usage_counters WHERE scope = 'quota' AND scope_id = ?1", params![id])?; drop(conn); - self.audit(actor, "quota.remove", &format!("id={id}")) + self.audit(actor, "quota.remove", &format!("Kontingent »{name}« (#{id})")) } /// Verbrauch in den Zeiträumen, in die t fällt @@ -724,9 +741,22 @@ impl Db { Ok(()) } - fn scopes(key_id: i64, user_id: Option, quota_id: Option) -> Vec { + /// Wo eine Anfrage gezählt wird: im System, beim Key und beim Kontingent je Person. Ein + /// gemeinsames Gruppenkontingent zählt zusätzlich im Topf der Gruppe (Benutzer 0). + fn scopes(conn: &Connection, key_id: i64, user_id: Option, quota_id: Option) -> Result> { let user = user_id.unwrap_or(0); - [Scope::System, Scope::Key(key_id)].into_iter().chain(quota_id.map(|q| Scope::Quota(q, user))).collect() + let mut scopes = vec![Scope::System, Scope::Key(key_id)]; + if let Some(q) = quota_id { + scopes.push(Scope::Quota(q, user)); + let shared: bool = conn + .query_row("SELECT shared FROM quotas WHERE id = ?1", params![q], |r| r.get(0)) + .optional()? + .unwrap_or(false); + if shared && user != 0 { + scopes.push(Scope::Quota(q, 0)); + } + } + Ok(scopes) } /// Prüft das Kontingent und zählt die Anfrage, in einer Transaktion, damit gleichzeitige @@ -742,11 +772,12 @@ impl Db { let mut conn = self.conn(); let tx = conn.transaction()?; if let Some(q) = quota - && let Err(denial) = q.check_usage(&Self::counters(&tx, Scope::Quota(q.id, user_id.unwrap_or(0)), t)?, t) + && let Err(denial) = + q.check_usage(&Self::counters(&tx, Scope::Quota(q.id, if q.shared { 0 } else { user_id.unwrap_or(0) }), t)?, t) { return Ok(Err(denial)); } - for scope in Self::scopes(key_id, user_id, quota.map(|q| q.id)) { + for scope in Self::scopes(&tx, key_id, user_id, quota.map(|q| q.id))? { Self::add(&tx, scope, t, 1, 0, 0)?; } tx.commit()?; @@ -757,7 +788,7 @@ impl Db { pub fn refund_request(&self, key_id: i64, user_id: Option, quota_id: Option, t: DateTime) -> Result<()> { let mut conn = self.conn(); let tx = conn.transaction()?; - for scope in Self::scopes(key_id, user_id, quota_id) { + for scope in Self::scopes(&tx, key_id, user_id, quota_id)? { Self::add(&tx, scope, t, -1, 0, 0)?; } Ok(tx.commit()?) @@ -775,7 +806,7 @@ impl Db { ) -> Result<()> { let mut conn = self.conn(); let tx = conn.transaction()?; - for scope in Self::scopes(key_id, user_id, quota_id) { + for scope in Self::scopes(&tx, key_id, user_id, quota_id)? { Self::add(&tx, scope, t, 0, prompt as i64, completion as i64)?; } Ok(tx.commit()?) @@ -786,7 +817,7 @@ impl Db { pub fn prune_usage(&self, actor: &str, days: u32) -> Result { let cutoff = now() - i64::from(days) * 86_400; let deleted = self.conn().execute("DELETE FROM usage WHERE ts < ?1", params![cutoff])?; - self.audit(actor, "usage.prune", &format!("older_than_days={days} deleted={deleted}"))?; + self.audit(actor, "usage.prune", &format!("{deleted} Einträge älter als {days} Tage gelöscht"))?; Ok(deleted) } @@ -838,6 +869,9 @@ fn migrate(conn: &Connection) -> Result<()> { if !has_column(conn, "api_keys", "user_id")? { conn.execute("ALTER TABLE api_keys ADD COLUMN user_id INTEGER REFERENCES users(id)", [])?; } + if !has_column(conn, "quotas", "shared")? { + conn.execute("ALTER TABLE quotas ADD COLUMN shared INTEGER NOT NULL DEFAULT 0", [])?; + } for column in ["owner_id", "group_id", "user_id"] { if !has_column(conn, "quotas", column)? { conn.execute(&format!("ALTER TABLE quotas ADD COLUMN {column} INTEGER"), [])?; diff --git a/proxy/src/main.rs b/proxy/src/main.rs index ef9028f..ff3bf43 100644 --- a/proxy/src/main.rs +++ b/proxy/src/main.rs @@ -277,6 +277,9 @@ enum QuotaCommand { /// Person, die das Kontingent nutzt #[arg(long)] user: Option, + /// Bei einer Gruppe: Grenzen für alle Mitglieder zusammen statt je Mitglied + #[arg(long, requires = "group")] + shared: bool, #[command(flatten)] limits: LimitArgs, /// Nur diese Modelle, als engine/modell, z. B. "ollama/qwen3:0.6b,vllm/qwen2.5-0.5b" diff --git a/proxy/src/quota.rs b/proxy/src/quota.rs index b1ec432..93f8d63 100644 --- a/proxy/src/quota.rs +++ b/proxy/src/quota.rs @@ -143,9 +143,12 @@ pub struct Quota { pub note: String, /// Lecturer, der das Kontingent angelegt hat pub owner_id: Option, - /// Zugeteilt an eine Gruppe (die Grenzen gelten dann je Mitglied) oder an einen Benutzer + /// Zugeteilt an eine Gruppe oder an einen Benutzer pub group_id: Option, pub user_id: Option, + /// Bei einer Gruppe: Die Grenzen gelten für alle Mitglieder zusammen statt je Mitglied. + #[serde(default)] + pub shared: bool, } /// Warum eine Anfrage nicht starten darf @@ -225,6 +228,9 @@ impl Quota { if let Some(models) = &self.models { parts.push(format!("Modelle: {}", models.join(", "))); } + if self.group_id.is_some() { + parts.push(if self.shared { "für die Gruppe gemeinsam" } else { "je Mitglied" }.into()); + } parts.join("; ") } } @@ -250,6 +256,7 @@ mod tests { owner_id: None, group_id: None, user_id: None, + shared: false, } } diff --git a/proxy/src/recording.rs b/proxy/src/recording.rs index 39f78cd..473dd8b 100644 --- a/proxy/src/recording.rs +++ b/proxy/src/recording.rs @@ -259,7 +259,8 @@ impl Db { )?; let id = conn.last_insert_rowid(); drop(conn); - self.audit(actor, "recording.start", &format!("id={id} key={key_id} count={count}"))?; + let key = self.key(key_id)?.map(|k| k.name).unwrap_or_default(); + self.audit(actor, "recording.start", &format!("Aufzeichnung #{id} für Key »{key}«: die nächsten {count} Anfragen"))?; Ok(id) } @@ -348,7 +349,7 @@ impl Db { return Ok(()); } let rec = self.recording(id)?.context("Aufzeichnung verschwunden")?; - self.audit(actor, "recording.end", &format!("id={id} entries={} reason={reason}", rec.written))?; + self.audit(actor, "recording.end", &format!("Aufzeichnung #{id} beendet ({reason}), {} Einträge", rec.written))?; // Die Benachrichtigung enthält keine Inhalte, nur den Hinweis und den Link. let key = self.key(rec.key_id)?.map(|k| k.name).unwrap_or_default(); let user = self.user(rec.user_id)?; @@ -366,7 +367,11 @@ impl Db { "INSERT INTO outbox (ts, to_addr, subject, body) VALUES (?1, ?2, ?3, ?4)", params![t, to, subject, body], )?; - self.audit("system", "recording.ready", &format!("id={id} until={ready_until} notify={}", to.as_deref().unwrap_or("-"))) + self.audit( + "system", + "recording.ready", + &format!("Aufzeichnung #{id} bereit bis {}, Benachrichtigung an {}", fmt(ready_until), to.as_deref().unwrap_or("(keine Adresse)")), + ) } /// Entschlüsselt die Einträge für den Download, als Zeilen JSONL. @@ -389,12 +394,12 @@ impl Db { params![now(), id], )?; drop(conn); - self.audit(actor, "recording.delete", &format!("id={id} reason={reason}")) + self.audit(actor, "recording.delete", &format!("Aufzeichnung #{id} gelöscht ({reason})")) } pub fn recording_downloaded(&self, actor: &str, id: i64) -> Result<()> { self.conn().execute("UPDATE recordings SET downloaded_at = ?1 WHERE id = ?2", params![now(), id])?; - self.audit(actor, "recording.download", &format!("id={id}"))?; + self.audit(actor, "recording.download", &format!("Aufzeichnung #{id} heruntergeladen"))?; self.delete_recording(actor, id, "heruntergeladen") } diff --git a/proxy/src/routes.rs b/proxy/src/routes.rs index c683005..69b1efb 100644 --- a/proxy/src/routes.rs +++ b/proxy/src/routes.rs @@ -40,6 +40,8 @@ pub fn router(state: AppState) -> Router { let proxy = Router::new() .route("/omega/status", get(status)) .route("/llamacpp/{*rest}", any(llamacpp)) + .route("/ollama", any(ollama_prefixed)) + .route("/ollama/{*rest}", any(ollama_prefixed)) .route("/vllm/{*rest}", any(vllm)) .fallback(ollama) .layer(middleware::from_fn_with_state(state.clone(), auth)); @@ -73,7 +75,9 @@ pub fn engine_error(engine: Engine, status: StatusCode, message: &str) -> Respon async fn auth(State(st): State, mut req: Request, next: Next) -> Response { // Ollama-Clients prüfen mit "/" und /api/version, ob der Server läuft. let path = req.uri().path(); - if matches!(*req.method(), Method::GET | Method::HEAD) && (path == "/" || path == "/api/version") { + if matches!(*req.method(), Method::GET | Method::HEAD) + && matches!(path, "/" | "/api/version" | "/ollama" | "/ollama/" | "/ollama/api/version") + { return next.run(req).await; } @@ -159,6 +163,34 @@ async fn ollama( { return axum::response::Redirect::temporary("/omega/").into_response(); } + ollama_at(st, caller, method, path, uri.query(), headers, body).await +} + +/// Die Ollama-API unter /ollama, wie llama.cpp und vLLM unter ihren Pfaden. An der Wurzel bleibt +/// sie für bestehende Anwendungen erhalten. +async fn ollama_prefixed( + State(st): State, + caller: Option>, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + let rest = uri.path().strip_prefix("/ollama").unwrap_or(""); + let path = if rest.is_empty() { "/".to_string() } else { rest.to_string() }; + ollama_at(st, caller, method, path, uri.query(), headers, body).await +} + +#[allow(clippy::too_many_arguments)] +async fn ollama_at( + st: AppState, + caller: Option>, + method: Method, + path: String, + query: Option<&str>, + headers: HeaderMap, + body: Bytes, +) -> Response { if path.starts_with("/api/blobs") || matches!(path.as_str(), "/api/pull" | "/api/push" | "/api/delete" | "/api/copy" | "/api/create") { @@ -176,7 +208,7 @@ async fn ollama( _ => {} } } - handle(st, caller.map(|c| c.0), Engine::Ollama, path, uri.query(), method, headers, body).await + handle(st, caller.map(|c| c.0), Engine::Ollama, path, query, method, headers, body).await } async fn llamacpp( diff --git a/proxy/src/schedule.rs b/proxy/src/schedule.rs index 4797727..85199ee 100644 --- a/proxy/src/schedule.rs +++ b/proxy/src/schedule.rs @@ -140,6 +140,22 @@ fn fmt_ts(ts: i64) -> String { Local.timestamp_opt(ts, 0).single().map(|t| t.format(format).to_string()).unwrap_or_default() } +/// Ein Beginn um Mitternacht ist ein ganzer Tag: "2026-10-01" statt "2026-10-01 00:00". +fn fmt_from(ts: i64) -> String { + match Local.timestamp_opt(ts, 0).single() { + Some(t) if t.time() == NaiveTime::MIN => t.format("%Y-%m-%d").to_string(), + _ => fmt_ts(ts), + } +} + +/// Ein Ende um Mitternacht schließt den Vortag ein: "bis einschließlich 2027-02-15". +fn fmt_until(ts: i64) -> String { + match Local.timestamp_opt(ts, 0).single() { + Some(t) if t.time() == NaiveTime::MIN => format!("einschließlich {}", (t - Duration::days(1)).format("%Y-%m-%d")), + _ => fmt_ts(ts), + } +} + impl Weekly { fn overnight(&self) -> bool { self.end < self.start @@ -210,9 +226,9 @@ impl TimeSpec { parts.push(format!("wöchentlich {} {}-{}", days_str(&w.days), w.start.format("%H:%M"), w.end.format("%H:%M"))); } match (self.from, self.until) { - (Some(f), Some(u)) => parts.push(format!("{} bis {}", fmt_ts(f), fmt_ts(u))), - (Some(f), None) => parts.push(format!("ab {}", fmt_ts(f))), - (None, Some(u)) => parts.push(format!("bis {}", fmt_ts(u))), + (Some(f), Some(u)) => parts.push(format!("{} bis {}", fmt_from(f), fmt_until(u))), + (Some(f), None) => parts.push(format!("ab {}", fmt_from(f))), + (None, Some(u)) => parts.push(format!("bis {}", fmt_until(u))), (None, None) if self.weekly.is_none() => parts.push("dauerhaft".into()), (None, None) => {} } @@ -233,6 +249,14 @@ impl Entry { } } + pub fn kind_label(&self) -> &'static str { + match self.kind { + Kind::Pin { .. } => "Pin", + Kind::Exclusive { .. } => "Exklusive Nutzung", + Kind::Window { .. } => "Modellzeitfenster", + } + } + pub fn subject(&self) -> String { match &self.kind { Kind::Pin { node, engine, model } => format!("{engine}/{model} auf {node}"), diff --git a/proxy/src/scheduler.rs b/proxy/src/scheduler.rs index 237db1c..7d37bc2 100644 --- a/proxy/src/scheduler.rs +++ b/proxy/src/scheduler.rs @@ -167,6 +167,25 @@ impl Scheduler { } } + /// Alle angebotenen Modelle mit den Rechnern, die sie anbieten + pub fn catalog_entries(&self) -> Vec<(Engine, String, Vec)> { + let inner = self.lock(); + let mut entries: Vec<(Engine, String, Vec)> = Vec::new(); + for ((node, engine), models) in &inner.catalog { + for model in models.keys() { + match entries.iter_mut().find(|(e, m, _)| e == engine && m == model) { + Some((_, _, nodes)) => nodes.push(self.nodes[*node].name.clone()), + None => entries.push((*engine, model.clone(), vec![self.nodes[*node].name.clone()])), + } + } + } + for (_, _, nodes) in &mut entries { + nodes.sort(); + } + entries.sort_by(|a, b| (a.0.as_str(), &a.1).cmp(&(b.0.as_str(), &b.1))); + entries + } + /// Alle angebotenen Modelle einer Engine pub fn catalog_models(&self, engine: Engine) -> Vec { let inner = self.lock(); @@ -453,7 +472,7 @@ impl Scheduler { tracing::warn!("{}: Laden von {} gescheitert: {e:#}", node.name, key.model); self.lock().slots.remove(&key); self.notify.notify_waiters(); - self.audit("model.load_failed", &format!("{} {} {}: {e:#}", node.name, key.engine.as_str(), key.model)); + self.audit("model.load_failed", &format!("{} ({}) auf {} nicht geladen: {e:#}", key.model, key.engine.as_str(), node.name)); return Err(format!("{e:#}")); } @@ -492,7 +511,13 @@ impl Scheduler { tracing::info!("{}: {} geladen in {secs:.1} s, {mb} MB", node.name, key.model); self.audit( "model.load", - &format!("{} {} {} mb={mb} measured={measured:?} secs={secs:.1}", node.name, key.engine.as_str(), key.model), + &format!( + "{} ({}) auf {} geladen in {secs:.1} s, {mb} MB{}", + key.model, + key.engine.as_str(), + node.name, + if measured.is_some() { " gemessen" } else { "" } + ), ); Ok(()) } @@ -504,7 +529,7 @@ impl Scheduler { let ok = match engines::unload(&self.http, node, key.engine, &key.model).await { Ok(()) => { self.lock().slots.remove(&key); - self.audit("model.unload", &format!("{} {} {}", node.name, key.engine.as_str(), key.model)); + self.audit("model.unload", &format!("{} ({}) auf {} entladen", key.model, key.engine.as_str(), node.name)); true } Err(e) => { @@ -834,7 +859,7 @@ impl Scheduler { // Wie eine Anfrage: wartet auf Platz und gibt das Modell sofort wieder frei. if let Err(e) = sched.acquire(key.clone(), false).await { tracing::warn!("{name}: gepinntes Modell {} nicht geladen: {e}", key.model); - sched.audit("pin.load_failed", &format!("{name} {} {}: {e}", key.engine.as_str(), key.model)); + sched.audit("pin.load_failed", &format!("gepinntes Modell {} ({}) auf {name} nicht geladen: {e}", key.model, key.engine.as_str())); } }); } diff --git a/proxy/src/service.rs b/proxy/src/service.rs index 0ed48e4..9d85eb6 100644 --- a/proxy/src/service.rs +++ b/proxy/src/service.rs @@ -215,6 +215,9 @@ pub struct QuotaInput { pub name: String, pub group: Option, pub user: Option, + /// Bei einer Gruppe: Grenzen für alle zusammen statt je Mitglied + #[serde(default)] + pub shared: bool, #[serde(default)] pub tokens: Limits, #[serde(default)] @@ -237,8 +240,11 @@ pub struct QuotaInfo { #[derive(Serialize)] pub struct PersonUsage { - /// None für Keys ohne Inhaber + /// None für Keys ohne Inhaber und für den gemeinsamen Topf einer Gruppe pub user: Option, + /// Gemeinsamer Verbrauch der ganzen Gruppe; dagegen wird bei gemeinsamen Kontingenten geprüft + #[serde(default)] + pub group_total: bool, pub usage: Periods, } @@ -631,6 +637,12 @@ impl<'a> Service<'a> { if input.group.is_some() && input.user.is_some() { return Err(invalid("ein Kontingent gilt für eine Gruppe oder eine Person, nicht beides")); } + if input.shared && input.group.is_none() { + return Err(invalid("gemeinsam für alle geht nur bei einem Gruppenkontingent")); + } + if input.models.as_ref().is_some_and(|m| m.is_empty()) { + return Err(invalid("bei begrenzten Modellen mindestens ein Modell auswählen")); + } let group_id = input.group.as_deref().map(|g| self.managed_group(g).map(|g| g.id)).transpose()?; let user_id = input.user.as_deref().map(|u| self.user(u).map(|u| u.id)).transpose()?; let models = input.models.as_ref().map(|m| checked_models(sched, m)).transpose()?; @@ -645,6 +657,7 @@ impl<'a> Service<'a> { owner_id: self.actor.user_id(), group_id, user_id, + shared: input.shared, }; let id = self.db.create_quota(self.who(), "a).map_err(|e| invalid(format!("{e:#}")))?; self.quota_info(self.quota(id)?) @@ -685,11 +698,17 @@ impl<'a> Service<'a> { } else { vec![self.actor.user_id().unwrap_or(0)] }; + // Bei einem gemeinsamen Kontingent steht der Topf der Gruppe unter Benutzer 0 vorn. + let mut users = users; + if q.shared { + users.retain(|u| *u != 0); + users.insert(0, 0); + } let usage = users .into_iter() .map(|u| { let user = if u == 0 { None } else { self.username(Some(u))? }; - Ok(PersonUsage { user, usage: self.db.usage_of(Scope::Quota(id, u), now)?.into() }) + Ok(PersonUsage { user, group_total: q.shared && u == 0, usage: self.db.usage_of(Scope::Quota(id, u), now)?.into() }) }) .collect::>()?; Ok(QuotaDetail { info: self.quota_info(q)?, usage }) @@ -925,10 +944,17 @@ impl<'a> Service<'a> { (q.user_id.is_some() && q.user_id == self.actor.user_id()) || q.group_id.is_some_and(|g| mine.contains(&g)) }) .map(|q| { - let usage = vec![PersonUsage { + // Bei einem gemeinsamen Kontingent zählt der Topf der Gruppe. + let me = self.actor.user_id().unwrap_or(0); + let mut usage = Vec::new(); + if q.shared { + usage.push(PersonUsage { user: None, group_total: true, usage: self.db.usage_of(Scope::Quota(q.id, 0), now)?.into() }); + } + usage.push(PersonUsage { user: user.as_ref().map(|u| u.username.clone()), - usage: self.db.usage_of(Scope::Quota(q.id, self.actor.user_id().unwrap_or(0)), now)?.into(), - }]; + group_total: false, + usage: self.db.usage_of(Scope::Quota(q.id, me), now)?.into(), + }); Ok(QuotaDetail { info: self.quota_info(q)?, usage }) }) .collect::>()?; diff --git a/proxy/ui/app.css b/proxy/ui/app.css index b8e3fba..91d8336 100644 --- a/proxy/ui/app.css +++ b/proxy/ui/app.css @@ -203,3 +203,41 @@ pre.settings { margin: 8px 0 0; background: var(--sunken); border: 1px solid var .main { padding: 20px 16px 40px; } .login-public { padding: 32px 16px; } } + +/* Umschalter, Wochentage, Modellauswahl, Werkzeugleiste */ +.label { font-size: 13px; color: var(--text-3); } +.stack.small { gap: 10px; } +.segmented { display: flex; gap: 3px; padding: 3px; border: 1px solid var(--line-3); border-radius: 7px; background: var(--sunken); } +.seg { flex: 1; display: flex; align-items: center; justify-content: center; min-height: 36px; padding: 0 10px; border-radius: 5px; font-size: 13px; color: var(--text-2); cursor: pointer; text-align: center; } +.seg:hover { color: var(--text); } +.seg.on { background: var(--accent-bg); color: var(--accent-text); } +.seg input { position: absolute; opacity: 0; pointer-events: none; } +.seg:focus-within { outline: 2px solid var(--accent); outline-offset: 1px; } +.days { display: flex; flex-wrap: wrap; gap: 6px; } +.day { font: 500 13px var(--sans); min-width: 44px; min-height: 36px; border-radius: 6px; border: 1px solid var(--line-3); background: var(--raised); color: var(--text-2); cursor: pointer; } +.day:hover { background: var(--hover); } +.day[aria-pressed="true"] { background: var(--accent-bg); border-color: #8a5a32; color: var(--accent-text); } +.model-picker { display: flex; flex-direction: column; gap: 10px; } +.model-picker fieldset { gap: 6px; } +.model-picker .check { gap: 10px; min-height: 28px; } +.model-picker .hint { margin-left: auto; } +.toolbar { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; } +.toolbar input[type=search] { flex: 1 1 260px; max-width: 420px; } +input[type=date].field, input[type=time].field, input[type=datetime-local].field { color-scheme: dark; } + +/* Wochenkalender */ +.cal-card { flex: 999 1 640px; overflow-x: auto; } +.cal-form { flex: 1 1 340px; max-width: 460px; } +.cal { display: grid; grid-template-columns: 40px repeat(7, minmax(92px, 1fr)); column-gap: 6px; min-width: 720px; } +.cal-corner { height: 32px; } +.cal-day { height: 32px; display: flex; align-items: center; justify-content: center; gap: 4px; font-size: 13px; color: var(--text-2); border-bottom: 1px solid var(--line); } +.cal-day.today { color: var(--accent); font-weight: 600; } +.cal-hours { position: relative; font-size: 11px; color: var(--muted); } +.cal-hours span { position: absolute; right: 4px; transform: translateY(-1px); } +.cal-col { position: relative; border-left: 1px solid var(--line); background-image: repeating-linear-gradient(to bottom, transparent 0 43px, var(--raised) 43px 44px); } +.ev { position: absolute; right: 4px; border-radius: 6px; padding: 4px 6px; font-size: 11px; line-height: 1.3; overflow: hidden; display: flex; flex-direction: column; gap: 1px; } +.ev .ev-kind { font-weight: 600; } +.ev.pin, .swatch.ev-pin { background: #2c2117; border: 1px solid #8a5a32; color: #ffe2c6; } +.ev.exclusive, .swatch.ev-exclusive { background: rgba(180,140,240,.16); border: 1px solid rgba(180,140,240,.55); color: #e3d6fb; } +.ev.window, .swatch.ev-window { background: rgba(79,209,197,.12); border: 1px solid rgba(79,209,197,.5); color: #b8f0ea; } +.toolbar .legend { margin-left: auto; } diff --git a/proxy/ui/app.js b/proxy/ui/app.js index 60c156e..2372691 100644 --- a/proxy/ui/app.js +++ b/proxy/ui/app.js @@ -139,6 +139,65 @@ 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('/'); @@ -152,11 +211,14 @@ const PAGES = { 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 }, }; @@ -344,6 +406,12 @@ function quotaMeters(q, usage) { 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); @@ -368,21 +436,26 @@ async function overview() { 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), quotaMeters(q, q.usage[0].usage))) + 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')), - me.managed.quotas.length ? h('div', { class: 'table-wrap' }, h('table', {}, + 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', {}, me.managed.quotas.flatMap((q) => (q.usage.length ? q.usage : [{ user: null, usage: null }]).map((p) => h('tr', {}, - h('td', {}, h('a', { href: '#/quota/' + q.id }, q.name)), h('td', {}, q.target || '–'), h('td', { class: 'mono' }, p.user || (p.usage ? '(ohne Inhaber)' : 'noch keine Nutzung')), + h('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.'))); @@ -419,7 +492,7 @@ async function keysPage() { const [keys, quotas, recordings] = await Promise.all([api('GET', '/keys'), api('GET', '/quotas'), api('GET', '/recordings')]); const me = state.me.user; const own = keys.filter((k) => k.user_id === me.id); - const others = keys.filter((k) => k.user_id !== me.id); + // Nutzbar sind Kontingente, die einem zugeteilt sind oder die man selbst verwaltet. const usable = quotas; const created = state.createdKey; state.createdKey = null; @@ -439,7 +512,7 @@ async function keysPage() { h('input', { id: 'key-name', name: 'name', class: 'field mono', required: true, placeholder: 'z. B. laptop' })), h('div', { class: 'field-group' }, h('label', { for: 'key-kind' }, 'Abgerechnet gegen'), h('select', { id: 'key-kind', name: 'kind', class: 'field' }, - usable.map((q) => h('option', { value: q.id }, q.name + (q.target ? ' · ' + q.target : ''))), + 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'))); @@ -455,8 +528,7 @@ async function keysPage() { parts.push(h('section', { class: 'card' }, h('h2', {}, 'Neuer Key'), !usable.length && !atLeast('lecturer') ? h('p', { class: 'empty' }, 'Dir ist noch kein Kontingent zugeteilt.') : form)); parts.push(keysManageCard('Meine Keys', own, true)); - if (others.length) parts.push(keysManageCard(atLeast('admin') ? 'Keys anderer Personen' : 'Keys gegen meine Kontingente', others, false)); - parts.push(recordingsCard(recordings)); + parts.push(recordingsCard(recordings, own)); parts.push(endpointsCard()); return h('div', { class: 'stack' }, parts); } @@ -478,6 +550,43 @@ function keysManageCard(title, keys, own) { : 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.'); @@ -489,14 +598,18 @@ function startRecording(k) { act(() => api('POST', '/recordings', { key_id: k.id, count: Number(answer) }), 'Aufzeichnung gestartet.'); } -function recordingsCard(recordings) { +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', { class: 'mono' }, '#' + r.key_id), h('td', { class: 'num' }, r.written + ' / ' + r.count), + 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.')); @@ -504,12 +617,12 @@ function recordingsCard(recordings) { function endpointsCard() { const base = location.origin; - const rows = [['Ollama', base], ['llama.cpp (OpenAI-kompatibel)', base + '/llamacpp/v1'], ['vLLM (OpenAI-kompatibel)', base + '/vllm/v1']]; + 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.')); + 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) { @@ -558,9 +671,10 @@ async function accountPage() { // ---------- Gruppen & Kontingente ---------- async function groupsPage() { - const [groups, quotas] = await Promise.all([api('GET', '/groups'), api('GET', '/quotas')]); + const [groups, quotas, models] = await Promise.all([api('GET', '/groups'), api('GET', '/quotas'), api('GET', '/models')]); const me = state.me.user; - const managed = groups.filter((g) => g.owner_id === me.id || atLeast('admin')); + 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(); @@ -572,74 +686,129 @@ async function groupsPage() { h('input', { id: 'group-name', name: 'name', class: 'field mono', required: true, placeholder: 'z. B. ki-praktikum-ws26' }))), h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Gruppe anlegen'))); return h('div', { class: 'stack' }, - head('Lehre', 'Gruppen & Kontingente', 'Gruppen anlegen, Personen aufnehmen und Kontingente zuteilen.'), + 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', {}, 'Gruppen'), - managed.length ? h('div', { class: 'table-wrap' }, h('table', {}, - h('thead', {}, h('tr', {}, h('th', {}, 'Gruppe'), h('th', { class: 'num' }, 'Mitglieder'), h('th', {}, 'Verwaltet von'))), - h('tbody', {}, managed.map((g) => h('tr', {}, - h('td', {}, h('a', { class: 'mono', href: '#/group/' + encodeURIComponent(g.name) }, g.name)), h('td', { class: 'num' }, g.members), h('td', { class: 'mono' }, g.owner || '–')))))) - : h('p', { class: 'empty' }, 'Noch keine Gruppen.')), + h('section', { class: 'card grow' }, h('h2', {}, 'Meine Gruppen'), groupsTable(own, false)), h('section', { class: 'card grow' }, h('h2', {}, 'Neue Gruppe'), groupForm)), - h('section', { class: 'card' }, h('h2', {}, 'Kontingente'), quotasTable(quotas)), - quotaForm(managed, null)); + h('section', { class: 'card' }, h('h2', {}, 'Meine Kontingente'), quotasTable(ownQuotas, false)), + quotaForm(own, null, models)); } -function quotasTable(quotas) { +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'), h('th', {}, 'Grenzen'), h('th', { class: 'num' }, 'Keys'))), + 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 || '–'), h('td', { class: 'wrap' }, q.describe), h('td', { class: 'num' }, q.keys)))))) + 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) { +/** 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: d.models ? list(d.models) : undefined, - from: optional(d.from), until: optional(d.until), weekly: optional(d.weekly), time: optional(d.time), note: d.note, + 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 target = fixedGroup || d.target; - if (target.startsWith('group:')) body.group = target.slice(6); - else if (target === 'user') body.user = d.username; + 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' })), - fixedGroup ? null : h('div', { class: 'field-group' }, h('label', { for: 'q-target' }, 'Zugeteilt an'), - h('select', { id: 'q-target', name: 'target', class: 'field' }, - groups.map((g) => h('option', { value: 'group:' + g.name }, 'Gruppe ' + g.name + ' (je Mitglied)')), - h('option', { value: 'user' }, 'Eine Person …'))), - fixedGroup ? null : h('div', { class: 'field-group' }, h('label', { for: 'q-username' }, 'Benutzername (bei einer Person)'), - h('input', { id: 'q-username', name: 'username', class: 'field mono' }))), + 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', {}, 'Wann und womit'), h('div', { class: 'fields' }, - h('div', { class: 'field-group' }, h('label', { for: 'q-models' }, 'Nur diese Modelle'), h('input', { id: 'q-models', name: 'models', class: 'field mono', placeholder: 'ollama/qwen3:0.6b, vllm/…' })), - h('div', { class: 'field-group' }, h('label', { for: 'q-weekly' }, 'Wochentage'), h('input', { id: 'q-weekly', name: 'weekly', class: 'field mono', placeholder: 'mo-fr' })), - h('div', { class: 'field-group' }, h('label', { for: 'q-time' }, 'Uhrzeit'), h('input', { id: 'q-time', name: 'time', class: 'field mono', placeholder: '08:00-18:00' })), - h('div', { class: 'field-group' }, h('label', { for: 'q-from' }, 'Gültig ab'), h('input', { id: 'q-from', name: 'from', class: 'field mono', placeholder: '2026-10-01' })), - h('div', { class: 'field-group' }, h('label', { for: 'q-until' }, 'Gültig bis'), h('input', { id: 'q-until', name: 'until', class: 'field mono', placeholder: '2027-02-15' })), - h('div', { class: 'field-group' }, h('label', { for: 'q-note' }, 'Anmerkung'), h('input', { id: 'q-note', name: 'note', class: 'field' }))), - h('span', { class: 'hint' }, 'Leere Felder heißen unbegrenzt. Ein Gruppenkontingent gilt je Mitglied. Tage und Monate sind Kalenderzeiträume.')), + h('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 = await api('GET', '/groups/' + encodeURIComponent(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(); @@ -653,9 +822,9 @@ async function groupPage(name) { h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Aufnehmen'))); return h('div', { class: 'stack' }, head('Lehre · Gruppe', g.name, 'Verwaltet von ' + (g.owner || '–') + ' · ' + g.members.length + ' Mitglieder', - h('a', { class: 'btn', href: '#/groups' }, 'Zurück'), + h('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)); go('groups'); }, 'Gruppe gelöscht.'); + 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'), @@ -669,8 +838,8 @@ async function groupPage(name) { h('section', { class: 'card grow' }, h('h2', {}, 'Personen aufnehmen'), add, h('span', { class: 'hint' }, 'Wer noch kein Konto hat, wird Mitglied, sobald es angelegt ist.'))), h('section', { class: 'card' }, h('h2', {}, 'Kontingente der Gruppe'), - quotasTable(g.quotas.map((q) => ({ ...q, target: 'Gruppe ' + g.name, describe: describeQuota(q), keys: '–' })))), - quotaForm([], 'group:' + g.name)); + quotasTable(g.quotas.map((q) => ({ ...q, target: 'Gruppe ' + g.name, describe: describeQuota(q), keys: '–' })), false)), + quotaForm([], 'group:' + g.name, models)); } function describeQuota(q) { @@ -680,7 +849,8 @@ function describeQuota(q) { if (q.requests[p] != null) parts.push(num(q.requests[p]) + ' Anfragen/' + PERIOD[p]); } if (q.models) parts.push('Modelle: ' + q.models.join(', ')); - return parts.join('; ') || 'ohne Mengengrenzen'; + parts.push(q.shared ? 'für die Gruppe gemeinsam' : 'je Mitglied'); + return parts.join('; '); } async function quotaPage(id) { @@ -688,7 +858,7 @@ async function quotaPage(id) { const manages = atLeast('admin') || q.owner_id === state.me.user.id; return h('div', { class: 'stack' }, head('Kontingent', q.name, (q.target ? q.target + ' · ' : '') + 'verwaltet von ' + (q.owner || '–'), - h('a', { class: 'btn', href: manages ? '#/groups' : '#/' }, 'Zurück'), + 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), @@ -697,7 +867,7 @@ async function quotaPage(id) { q.usage.length ? h('div', { class: 'table-wrap' }, h('table', {}, h('thead', {}, h('tr', {}, h('th', {}, 'Person'), Object.values(PERIOD).map((p) => h('th', { class: 'num' }, 'Token ' + p)), h('th', { class: 'num' }, 'Anfragen heute'))), h('tbody', {}, q.usage.map((p) => h('tr', {}, - h('td', { class: 'mono' }, p.user || '(ohne Inhaber)'), + 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.'))); @@ -757,64 +927,184 @@ function nodeCard(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 = await api('GET', '/schedule'); - const kindSel = h('select', { id: 's-kind', name: 'kind', class: 'field', onchange: () => update() }, - h('option', { value: 'pin' }, 'Pin: Modell garantiert im Speicher'), - h('option', { value: 'exclusive' }, 'Exklusiv: nur bestimmte Gruppen oder Personen'), - h('option', { value: 'window' }, 'Modellzeitfenster: nur bestimmte Modelle')); - const field = (name, label, placeholder, hint) => h('div', { class: 'field-group', 'data-for': hint }, - h('label', { for: 's-' + name }, label), h('input', { id: 's-' + name, name, class: 'field mono', placeholder })); + const [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', { - onsubmit: (e) => { - e.preventDefault(); + class: 'card cal-form', + onsubmit: (ev) => { + ev.preventDefault(); const d = formData(form); - const body = { kind: d.kind, from: optional(d.from), until: optional(d.until), weekly: optional(d.weekly), time: optional(d.time), note: d.note }; - if (d.kind === 'pin') Object.assign(body, { model: d.model, node: optional(d.node) }); - if (d.kind === 'exclusive') Object.assign(body, { groups: list(d.groups), users: list(d.users) }); - if (d.kind === 'window') body.models = list(d.models); + 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('div', { class: 'fields' }, - h('div', { class: 'field-group' }, h('label', { for: 's-kind' }, 'Art'), kindSel), - field('model', 'Modell', 'ollama/qwen3:0.6b', 'pin'), - field('node', 'Rechner (bei mehreren)', 'spark1', 'pin'), - field('groups', 'Gruppen', 'ki-2026', 'exclusive'), - field('users', 'Personen', 'hofmannol', 'exclusive'), - field('models', 'Modelle', 'ollama/qwen3:0.6b, vllm/…', 'window')), - h('div', { class: 'fields' }, - field('from', 'Beginn', '2026-11-24 08:00 oder +10m'), field('until', 'Ende', '2026-11-24 12:00'), - field('weekly', 'Wochentage', 'mo,mi'), field('time', 'Uhrzeit', '08:00-11:15'), field('note', 'Anmerkung', 'Vorlesung KI')), - h('span', { class: 'hint' }, 'Ohne Zeitangaben gilt ein Eintrag dauerhaft. Der Proxy lehnt Einträge ab, die nicht in den Speicher passen oder sich widersprechen.'), - h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Eintrag anlegen'))); - function update() { - for (const el of form.querySelectorAll('[data-for]')) { - const kind = el.getAttribute('data-for'); - if (kind !== 'undefined') el.hidden = kind !== kindSel.value; - } - } - update(); - const kinds = { pin: 'Pin', exklusiv: 'Exklusiv', fenster: 'Zeitfenster' }; + 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 Plan.'), - h('section', { class: 'card' }, h('h2', {}, 'Einträge'), + 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' : '') }, kinds[e.kind.kind] || e.kind.kind)), + 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.')), - h('section', { class: 'card' }, h('h2', {}, 'Neuer Eintrag'), form)); + : 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) => { @@ -835,25 +1125,54 @@ async function usersPage() { h('span', { class: 'hint' }, 'Im Betrieb registrieren sich Personen selbst mit dem Login der Hochschule (LDAP).'), h('div', { class: 'actions' }, h('button', { class: 'btn primary', type: 'submit' }, 'Benutzer anlegen'))); const me = state.me.user; - return h('div', { class: 'stack' }, + const userRows = h('tbody', {}); + const page = h('div', { class: 'stack' }, head('Administration', 'Benutzer', users.length + ' Konten'), - h('section', { class: 'card' }, h('div', { class: 'table-wrap' }, h('table', {}, + 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')))), - h('tbody', {}, users.map((u) => h('tr', { class: u.blocked || !u.active ? 'dim' : null }, + 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'))))))))), - h('section', { class: 'card' }, h('h2', {}, 'Neuer Benutzer'), form)); + 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=300'), api('GET', '/outbox')]); + 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(); @@ -867,7 +1186,7 @@ async function auditPage() { h('span', { class: 'hint' }, 'Löscht Zeitpunkt, Key, Modell und Token einzelner Anfragen. Die Zähler der Kontingente und Keys bleiben, damit verbuchte Stände stimmen.'), h('div', { class: 'actions' }, h('button', { class: 'btn danger', type: 'submit' }, 'Metadaten löschen'))); return h('div', { class: 'stack' }, - head('Administration', 'Audit-Log', 'Die letzten 300 Vorgänge. Inhalte von Anfragen und Antworten stehen hier nie.'), + 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'), @@ -875,10 +1194,27 @@ async function auditPage() { outbox.length ? h('ol', { class: 'events' }, outbox.slice().reverse().map((m) => h('li', {}, h('span', { class: 'mono' }, when(m.ts)), h('span', {}, h('b', {}, m.subject), ' an ', h('span', { class: 'mono' }, m.to || '(keine Adresse)'))))) : h('p', { class: 'empty' }, 'Keine Benachrichtigungen.'))), - h('section', { class: 'card' }, h('div', { class: 'table-wrap' }, h('table', {}, + h('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'))), - h('tbody', {}, entries.map((e) => h('tr', {}, - h('td', { class: 'mono muted' }, when(e.ts)), h('td', { class: 'mono' }, e.actor), h('td', { class: 'mono' }, e.action), h('td', { class: 'wrap mono' }, e.detail)))))))); + 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(); diff --git a/tests/multispark/quota_test.py b/tests/multispark/quota_test.py index 4a4c93f..f28224b 100644 --- a/tests/multispark/quota_test.py +++ b/tests/multispark/quota_test.py @@ -212,4 +212,24 @@ check("vllm/smollm2-360m" in spark1() and "llamacpp/qwen3-0.6b" in spark1(), "beide gepinnten Modelle sind wieder geladen") check(counters("key", int(cli("key", "list")[1][-1].split()[0]))[0] >= 1, "Super-Key zählt beim Key") +print("9) Gemeinsames Gruppenkontingent: die Grenze gilt für alle Mitglieder zusammen") +for name in ("gruppen-dozent", "mitglied1", "mitglied2"): + cli("user", "add", name, "--role", "lecturer" if name == "gruppen-dozent" else "user") +code, out = cli("--as", "gruppen-dozent", "group", "create", "team") +code, out = cli("--as", "gruppen-dozent", "group", "add", "team", "mitglied1", "mitglied2") +code, out = cli("--as", "gruppen-dozent", "quota", "create", "team-topf", "--group", "team", "--shared", "--requests-hour", "2") +print(f" {out[-1]}") +qt = int(out[-1].split()[1].rstrip(":")) +_, M1 = key("m1", "--quota", str(qt), "--owner", "mitglied1") +_, M2 = key("m2", "--quota", str(qt), "--owner", "mitglied2") +codes = [ask("ollama", "smollm2:135m", key=k)[0] for k in (M1, M2, M1)] +print(f" mitglied1, mitglied2, mitglied1: {codes}") +check(codes == [200, 200, 429], "nach zwei Anfragen der Gruppe ist der gemeinsame Topf erschöpft") +code, out = cli("--as", "gruppen-dozent", "quota", "show", str(qt)) +hour = [line for line in out if " hour " in line] +print(" " + "\n ".join(hour)) +requests = {line.split()[0]: line.split()[-4] for line in hour} +check(requests.get("Gruppe") == "2" and requests.get("mitglied1") == "1" and requests.get("mitglied2") == "1", + f"dozent sieht den Topf der Gruppe (2) und beide Personen (je 1): {requests}") + print("ERGEBNIS:", "alles bestanden" if not failures else f"{len(failures)} Fehler: {failures}") diff --git a/tests/multispark/start.sh b/tests/multispark/start.sh index d2bcfc4..2a89dc5 100755 --- a/tests/multispark/start.sh +++ b/tests/multispark/start.sh @@ -32,7 +32,10 @@ $B/omega-agent -c agent1.toml > run/agent1.log 2>&1 & echo "agent1 $!" >> run/pids $B/omega-agent -c agent2.toml > run/agent2.log 2>&1 & echo "agent2 $!" >> run/pids -sleep 3 +# Warten, bis die Engines antworten (höchstens 30 s), statt fest zu schlafen +for url in http://127.0.0.1:11441/api/version http://127.0.0.1:11442/api/version http://127.0.0.1:11443/api/version http://127.0.0.1:8181/models; do + for _ in $(seq 60); do curl -sf -o /dev/null "$url" && break; sleep 0.5; done +done $B/omega-proxy -c proxy.toml --as admin key create test | awk '{print $NF}' > run/key.txt $B/omega-proxy -c proxy.toml serve > run/proxy.log 2>&1 & echo "proxy $!" >> run/pids diff --git a/tests/multispark/ui_test.py b/tests/multispark/ui_test.py index ec2cdaa..76e995b 100644 --- a/tests/multispark/ui_test.py +++ b/tests/multispark/ui_test.py @@ -29,6 +29,11 @@ check(st in (302, 307) and hdrs.get("location") == "/omega/", f"Browser wird nac st, _, body = request("GET", "/") check(st == 200 and b"Ollama is running" in body, "Ollama-Clients bekommen weiter die Ollama-Antwort") +st, _, body = request("GET", "/ollama") +check(st == 200 and b"Ollama is running" in body, "Ollama-API auch unter /ollama") +st, _, body = request("GET", "/ollama/api/tags") +check(st == 401, "/ollama/api/tags braucht einen Key") + print("2) Oberfläche ohne externe Quellen") st, hdrs, index = request("GET", "/omega/") csp = hdrs.get("content-security-policy", "") diff --git a/tests/ui/render_test.js b/tests/ui/render_test.js index ded57a3..67dfbe7 100644 --- a/tests/ui/render_test.js +++ b/tests/ui/render_test.js @@ -16,8 +16,8 @@ const html = fs.readFileSync(path.join(UI, 'index.html'), 'utf8').replace(/ w.document.querySelector(sel); const text = (w) => w.document.body.textContent; +function check(w, sel) { + const el = $(w, sel); + if (!el) throw new Error('Auswahl fehlt: ' + sel); + el.checked = true; + el.dispatchEvent(new w.Event('change', { bubbles: true })); +} +function local(date) { + const p = (n) => String(n).padStart(2, '0'); + return date.getFullYear() + '-' + p(date.getMonth() + 1) + '-' + p(date.getDate()) + 'T' + p(date.getHours()) + ':' + p(date.getMinutes()); +} function set(w, sel, value) { const el = $(w, sel); if (!el) throw new Error('Feld fehlt: ' + sel); @@ -208,18 +218,60 @@ async function flows(fail) { }); const admin = await login('admin'); - await step('admin legt einen Zeitplaneintrag an und entfernt ihn', async () => { + await step('admin legt im Kalender ein Modellzeitfenster an und entfernt es', async () => { const { w } = browser(admin, '#/schedule'); await settle(w); - set(w, '#s-kind', 'window'); - set(w, '#s-models', 'ollama/smollm2:135m'); - set(w, '#s-until', '+1m'); + check(w, 'input[name="s-kind"][value="window"]'); + check(w, 'input[name="s-model"][value="ollama/smollm2:135m"]'); + const now = new Date(); + set(w, '#s-from', local(new Date(now.getTime() + 3600000))); + set(w, '#s-until', local(new Date(now.getTime() + 2 * 3600000))); set(w, '#s-note', 'flow-' + tag); - await submit(w, '#s-kind'); + await submit(w, '#s-note'); expect([...w.document.querySelectorAll('tbody tr')].some((tr) => tr.textContent.includes('flow-' + tag)), 'Eintrag fehlt: ' + summary(w).errorsOnPage.join()); + expect([...w.document.querySelectorAll('.cal .ev.window')].some((e) => e.textContent.includes('flow-' + tag)), 'Eintrag fehlt im Kalender'); await click(w, 'Entfernen', 'flow-' + tag); expect(![...w.document.querySelectorAll('tbody tr')].some((tr) => tr.textContent.includes('flow-' + tag)), 'Eintrag noch da'); }); + await step('dozent teilt ein gemeinsames Kontingent mit Modellen, Wochentagen und Gültigkeit zu', async () => { + const { w } = browser(dozent, '#/group/ki-praktikum'); + await settle(w); + set(w, '#q-name', 'flow-gemeinsam-' + tag); + set(w, '#q-requests_day', '50'); + check(w, 'input[name="q-shared"][value="shared"]'); + check(w, 'input[name="q-models"][value="some"]'); + check(w, 'input[name="q-model"][value="ollama/smollm2:135m"]'); + for (const d of ['mo', 'mi']) w.document.querySelector('#q-days [data-day="' + d + '"]').click(); + set(w, '#q-time-start', '08:00'); + set(w, '#q-time-end', '18:00'); + set(w, '#q-valid-until', '2027-02-15'); + await submit(w, '#q-name'); + const t = text(w); + expect(t.includes('flow-gemeinsam-' + tag + '“ angelegt'), 'nicht angelegt: ' + summary(w).errorsOnPage.join()); + expect(['für die Gruppe gemeinsam', 'Modelle: ollama/smollm2:135m', 'wöchentlich mo,mi 08:00-18:00', 'bis einschließlich 2027-02-15'].every((x) => t.includes(x)), + 'Angaben fehlen in: ' + (w.document.querySelector('.notice') || {}).textContent); + }); + await step('admin sucht unter Alle Keys und in den Benutzern', async () => { + const { w } = browser(admin, '#/allkeys'); + await settle(w); + const search = w.document.querySelector('input[type=search]'); + search.value = 'flow-' + tag; + search.dispatchEvent(new w.Event('input')); + const rows = w.document.querySelectorAll('tbody tr'); + expect(rows.length === 1 && rows[0].textContent.includes('student'), rows.length + ' Treffer'); + const u = browser(admin, '#/users').w; + await settle(u); + const s2 = u.document.querySelector('input[type=search]'); + s2.value = 'dozent'; + s2.dispatchEvent(new u.Event('input')); + expect(u.document.querySelectorAll('tbody tr').length === 1, 'Suche nach dozent'); + }); + await step('Audit-Log mit deutschen Bezeichnungen', async () => { + const { w } = browser(admin, '#/audit'); + await settle(w); + const t = text(w); + expect(t.includes('Key angelegt') && t.includes('Key »flow-' + tag + '«') && t.includes('Gruppe angelegt'), 'Bezeichnungen fehlen'); + }); await step('admin löscht alte Metadaten (älter als 3650 Tage, also nichts)', async () => { const { w } = browser(admin, '#/audit'); await settle(w);