diff --git a/README.md b/README.md index c7acf95..7bfd3b7 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,14 @@ Noch nicht verfügbar. Installationshinweise folgen mit dem ersten Release. ## Build and run -Noch nicht verfügbar. +```bash +git clone ssh://git@git.wlkns.org:2222/wlkns-dev/coding-bench.git +cd coding-bench +make images # Container-Image cb-python bauen (einmalig) +make dev # App im Entwicklungsmodus starten +``` + +`make help` listet alle Ziele (Tests, Release-Build, Arch-Paket). Fertige Pakete (`.deb`, Arch) baut der Gitea-Workflow bei einem Release-Tag; sie sind noch nicht als Release veröffentlicht. ## What it does @@ -61,7 +68,13 @@ Eine Tauri-Oberfläche (Svelte und TypeScript) spricht über Commands mit dem Ru ## How to use / API & Configuration -Noch nicht verfügbar. +Die Oberfläche hat drei Reiter. Sie wurde bisher im Browser mit Beispieldaten angesehen, in der echten App noch nicht abgenommen. + +1. **Einstellungen:** Modelle anlegen. Jedes Modell hat einen **Adapter**: `Ollama` (`/api/chat`) oder `OpenAI-kompatibel` (`/v1/chat/completions`, z. B. strata). Dazu kommen Server-URL, Modell-ID und optional der Name einer Umgebungsvariable mit dem API-Schlüssel. Der Schlüssel selbst steht nie in der Konfiguration. „Verbindung testen“ prüft das Modell mit einer kurzen Anfrage. +2. **Benchmark:** Modelle und Aufgaben wählen, Durchläufe festlegen, starten. Der Fortschritt läuft live, ein Abbruch verwirft den laufenden Lauf. +3. **Ergebnisse:** Pro Batch eine Bewertung in Prozent: ein Wert je Bereich (A Tool-Calling, B kleine Coding-Aufgaben, C Agent im Repo, D Demos) und eine Gesamtnote. Die Bewertung ist absolut und nicht im Vergleich zu einem Referenzmodell. Darunter eine Matrix je Aufgabe und die einzelnen Läufe mit allen Schritten. + +Die Konfiguration liegt in `~/.config/org.wlkns.codingbench/config.toml`. Aufgaben liegen als Ordner unter `tasks///` (`task.toml`, `prompt.md`, `start/`, `check.sh`). Eine installierte Version findet die mitgelieferten Aufgaben unter `/usr/share/coding-bench/tasks`. ## References & Links diff --git a/ROADMAP.md b/ROADMAP.md index c9308da..f99cf2c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,8 +1,8 @@ # coding-bench – Anforderungen, Todo und Roadmap -Stand: 2026-11-06 (18:30) · Projekt-ID: offen · Format: 1 · installiert ist noch nichts (Release 0.1.0 offen); lokal 0 Commits. Quellen dieser Liste: `SPEC.md` (Gespräch vom 06.11.2026), Anforderungskatalog F-01 bis F-17. +Stand: 2026-11-07 (12:40) · Projekt-ID: offen · Format: 1 · installiert ist noch nichts (Release 0.1.0 offen); Release-Kandidat v0.1.0-rc2 auf srv01 im Bau. Quellen dieser Liste: `SPEC.md` (Gespräch vom 06.11.2026), Anforderungskatalog F-01 bis F-17. Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft. -**IDs:** Jeder Punkt in Stand-Tabelle, Todo, Entscheidungen und Risiken hat eine feste ID `#1xxx` (eine Zählung für alles, nie wiederverwendet, am Anfang der Zeile). „→ #…“ nennt die Anforderung, die ein Todo voranbringt. Erledigtes wandert mit ID in „Erledigt (einzeln)“. Nächste freie ID: #1040. +**IDs:** Jeder Punkt in Stand-Tabelle, Todo, Entscheidungen und Risiken hat eine feste ID `#1xxx` (eine Zählung für alles, nie wiederverwendet, am Anfang der Zeile). „→ #…“ nennt die Anforderung, die ein Todo voranbringt. Erledigtes wandert mit ID in „Erledigt (einzeln)“. Nächste freie ID: #1042. ## 1. Leitplanken (von dir festgelegt, gelten für alles) - **Lokal first:** Nur lokale Modelle (Ollama, ab Phase 2 OpenAI-kompatibler Endpunkt im Netz). Cloud-Modelle werden nicht verglichen (Nicht-Ziel v1). @@ -25,12 +25,12 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft. | #1005 | F-05 Runner mit Wiederholungen, Abbruch, Fortsetzen | SPEC 7, 12 | ◐ | `runner.rs`: Plan, Warm-up je Modell, Sandbox pro Lauf, `check.sh`, Abbruch, Fortsetzen über die DB. Ende-zu-Ende gegen srv04 mit `qwen3:0.6b` grün (2 Läufe, dann Fortsetzen überspringt beide). Abbruch im Lauf nicht real getestet. Über Tauri-Befehle `start_batch`, `cancel_batch` angebunden, Ereignisse `batch-event` (→ #1022) | | #1006 | F-06 SQLite inkl. Schritt-Log | SPEC 8, 12 | ◐ | `store.rs`: Tabellen `batch`, `run`, `step` nach SPEC 8, Lauf und Schritte in einer Transaktion. Datei `coding-bench.sqlite` im Datenordner, wird beim Start angelegt. Lesen über `batch_results`. Getestet in-memory und im Batch (→ #1023) | | #1007 | F-07 Tests a-01 bis a-03 und b-04 bis b-06 | SPEC 11, 12 | ◐ | Aufgaben liegen unter `tasks/`, gültig geladen (Test `repo_aufgaben_sind_gueltig`). Musterlösungen bestehen alle Checks, leere Lösung scheitert. Mit `qwen3:0.6b` 0 von 6 bestanden. Mit `qwen3.8-flash-next-q2_0` über strata (OpenAI-Format, LAN) 6 von 6 bestanden, Score 1.00 (Testbericht `testberichte/2026-11-06-strata-lauf.md`) (→ #1024) | -| #1008 | F-08 GUI: Setup, Batch starten, Live-Fortschritt | SPEC 10, 12 | ◐ | Setup zeigt Pfade und Aufgaben, Batch-Start mit Modellen, Wiederholungen, Abbrechen, Fortschritt und Ergebnistabelle gebaut. `svelte-check` 0 Fehler. Nicht im Fenster geprüft; Klicktests `batch2fortsetzen.1–.2` offen (→ #1025) | -| #1009 | F-09 Rangliste und Matrix | SPEC 9, 10, 12 | ◐ | `ranking.rs`: Gesamtscore (gewichtet), Median-Dauer, Tie-Breaker, Matrix Modell × Aufgabe. 5 Unit-Tests grün. Oberfläche zeigt beides nach dem Batch. Ohne Intervall und Kategorie-Ranking (F-12). Klicktest `ergebnis2detail.1` manuell offen (→ #1026) | +| #1008 | F-08 GUI: Setup, Batch starten, Live-Fortschritt | SPEC 10, 12 | ◐ | Oberfläche neu gebaut (Reiter Benchmark, Ergebnisse, Einstellungen): Modell-Liste mit Adapter, Verbindungstest, Aufgaben nach Bereich, Start, Abbrechen, Fortschritt, Batch-Verlauf, Bewertung, Schrittansicht. `svelte-check` 0 Fehler. Im Browser mit Beispieldaten angesehen (Screenshots), nicht in der echten App; Klicktests `batch2fortsetzen.1–.2` offen (→ #1025) | +| #1009 | F-09 Rangliste und Matrix | SPEC 9, 10, 12 | ◐ | `ranking.rs`: absolute Bewertung in Prozent je Bereich (A bis D) und als Gesamtnote, gewichtet nach `weight`; Tie-Breaker Median-Dauer, dann Tokens; schwächster Bereich; Matrix Modell × Aufgabe. 7 Unit-Tests grün. Ohne Wilson-Intervall (F-12). Klicktest `ergebnis2detail.1` manuell offen (→ #1026) | | #1010 | F-10 Tests c-07 bis c-09 | SPEC 11, 12 | ✗ | Phase 2 (→ #1027) | | #1011 | F-11 Adapter Aider-Polyglot-Teilmenge | SPEC 12 | ✗ | Phase 2 (→ #1028) | | #1012 | F-12 Kategorie-Ranking, Wilson-Intervalle, Markierung | SPEC 9, 12 | ✗ | Phase 2 (→ #1029) | -| #1013 | F-13 OpenAI-kompatibler Endpunkt | SPEC 2, 12 | ✗ | Phase 2 (→ #1030) | +| #1013 | F-13 OpenAI-kompatibler Endpunkt | SPEC 2, 12 | ◐ | Adapter `openai` gebaut (`/v1/chat/completions`, Tool-Calls, optionaler Schlüssel aus Umgebungsvariable); Lauf aller sechs Aufgaben über strata erfolgreich. Gewählt wird er je Modell in den Einstellungen. Offen: Anthropic-kompatibler Adapter, weitere Server (→ #1030) | | #1014 | F-14 Export JSON und HTML-Report | SPEC 10, 12 | ✗ | Phase 2 (→ #1031) | | #1015 | F-15 Playwright-Sidecar, Screenshot | SPEC 2, 12 | ✗ | Phase 3 (→ #1032) | | #1016 | F-16 Demos d-10 bis d-12 | SPEC 11, 12 | ✗ | Phase 3 (→ #1032) | @@ -51,14 +51,14 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft. - [#1022] **Runner.** Umgesetzt in `src-tauri/src/runner.rs`, über `start_batch` und `cancel_batch` an die Oberfläche angebunden. Offen: Abbruch in der App real prüfen, Modelle mit eigenem Endpunkt in der Config (Phase 1 hat einen gemeinsamen `ollama_url`). Tests `batch2fortsetzen.1–.2`. → #1005 - [#1023] **SQLite-Speicher.** Umgesetzt in `src-tauri/src/store.rs`, Schema nach SPEC 8. Datei-Datenbank im Datenordner angebunden. Offen: Klicktest `lauf2ergebnis.2` mit Schritt-Ansicht (noch keine Oberfläche dafür). Tests `lauf2ergebnis.2`. → #1006 - [#1024] **Aufgaben a-01 bis a-03, b-04 bis b-06 schreiben.** Geschrieben unter `tasks/`. b-06 mit Mutationstest; ein Fehler im Check (veralteter Bytecode bei Mutanten) ist behoben. Ergebnis: mit `qwen3.8-flash-next-q2_0` über strata 6 von 6 bestanden. Bericht in `testberichte/`. Offen: Zeitlimit von b-04 bei langsamen Modellen prüfen. → #1007 -- [#1025] **GUI Setup und Batch.** Gebaut: Pfade, Container-Status (Podman-Version im Setup), Aufgabenauswahl, Modelle, Wiederholungen, Start, Abbrechen, Live-Log, Ergebnistabelle, Rangliste und Matrix, Schritt-Ansicht je Lauf. Offen: Klicktests `batch2fortsetzen.1` und `lauf2ergebnis.2` manuell, Oberfläche im Fenster ansehen. → #1008 -- [#1026] **Rangliste und Matrix.** Gebaut: Gesamtscore (gewichtet nach `weight`), Median-Dauer als Tie-Breaker, Matrix Modell × Aufgabe mit Erfolgen und Farbe nach Score. Offen: Wilson-Intervall und „nicht unterscheidbar“ (F-12, Phase 2), Lauf-Detail mit Schrittliste, Klicktest `ergebnis2detail.1` manuell. Tests `ergebnis2detail.1`. → #1009 +- [#1025] **GUI Setup und Batch.** Neu gebaut nach deiner Kritik an der ersten Fassung: drei Reiter, Modell-Liste mit Adapter, Verbindungstest, Aufgaben nach Bereich, Fortschrittsbalken, Batch-Verlauf. Offen: echte App im Fenster prüfen, Klicktests `batch2fortsetzen.1` und `lauf2ergebnis.2` manuell, laufender Schritt live anzeigen, Gewichte in der Oberfläche ändern (SPEC 9). → #1008 +- [#1026] **Rangliste und Matrix.** Gebaut: Prozent je Bereich und Gesamtnote (Entscheidung #1040), Schwächster Bereich, Matrix, Hinweis „grob“ bei weniger als 3 Aufgaben je Bereich, Erklärung „So wird bewertet“. Offen: Wilson-Intervall und „nicht unterscheidbar“ (F-12, Phase 2), Klicktest `ergebnis2detail.1` manuell. Tests `ergebnis2detail.1`. → #1009 **P2 – danach (Release 0.2.0, Referenz und Tiefe)** - [#1027] **Tests c-07 bis c-09.** Neuer CLI-Parameter, Refactoring, Stacktrace-Fehler. → #1010 - [#1028] **Aider-Polyglot-Adapter.** 20 bis 30 Aufgaben ins Aufgabenformat übersetzen. → #1011 - [#1029] **Kategorie-Ranking und Wilson-Intervalle.** Markierung „statistisch nicht unterscheidbar“. → #1012 -- [#1030] **OpenAI-kompatibler Endpunkt.** Für den GPU Dispatcher, Typ im Setup wählbar. → #1013 +- [#1030] **OpenAI-kompatibler Endpunkt.** Adapter und Auswahl je Modell sind gebaut (vorgezogen nach 0.1.0, siehe #1041). Offen: Anthropic-kompatibler Adapter, GPU Dispatcher prüfen. → #1013 - [#1031] **Export.** JSON und eigenständiger HTML-Report. → #1014 **P3 – Backlog (Release 0.3.0, Demos)** @@ -74,6 +74,8 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft. - [#1034] Entschieden: Projektname `coding-bench`, Ordner bleibt `llm-arena`. → #1001 - [#1035] Gitea-Adresse für das Remote `origin` (URL oder Repo-Name)? Ohne sie gibt es kein Remote, und die Projekt-ID bleibt `offen`. → #1001 - [#1036] Entschieden: Lizenz wird vorerst nicht festgelegt, die README sagt das ausdrücklich. → #1001 +- [#1040] Entschieden: Bewertet wird absolut in Prozent, ohne Referenzmodell. Wert je Bereich (A bis D) und eine Gesamtnote, beides gewichtet nach `weight` aus `task.toml`; Bereiche ohne Läufe bleiben leer. → #1009 +- [#1041] Entschieden: Modelle werden in der Oberfläche als Liste angelegt, jedes mit Adapter (`ollama` oder `openai`), URL, Modell-ID und Name der Schlüssel-Variable. Die Liste steht in `config.toml`; Schlüssel stehen nie dort. → #1013 - [#1039] Entschieden: Podman (rootless) statt Docker für die Sandbox. Die SPEC ist entsprechend angepasst. Docker ist auf diesem Rechner nicht installiert. → #1004 ## 6. Roadmap (Aufwand grob, ohne Kalenderdaten) diff --git a/src-tauri/src/agent.rs b/src-tauri/src/agent.rs index ba98281..3f84ddf 100644 --- a/src-tauri/src/agent.rs +++ b/src-tauri/src/agent.rs @@ -644,13 +644,24 @@ pub fn to_openai_messages(messages: &[Message]) -> Vec { out } +/// Macht aus einer Basis-URL die Adresse des Chat-Endpunkts. +pub fn openai_chat_url(url: &str) -> String { + let t = url.trim().trim_end_matches('/'); + if t.ends_with("/chat/completions") { + t.to_string() + } else { + format!("{t}/chat/completions") + } +} + impl OpenAiClient { + /// `url` darf die Basis (`…/v1`) oder die volle Adresse (`…/v1/chat/completions`) sein. pub fn new(url: &str, model: &str, api_key: Option) -> Result { let http = reqwest::blocking::Client::builder() .build() .map_err(|e| format!("HTTP-Client nicht baubar: {e}"))?; Ok(OpenAiClient { - url: url.trim_end_matches('/').into(), + url: openai_chat_url(url), model: model.into(), api_key, http, @@ -662,13 +673,16 @@ impl ModelClient for OpenAiClient { fn chat(&self, messages: &[Message], tools: &Value, timeout: Duration) -> Result { - let body = json!({ + let mut body = json!({ "model": self.model, "messages": to_openai_messages(messages), - "tools": tools, "stream": false, "temperature": 0, }); + // Ein leeres tools-Feld lehnen manche Server ab. + if tools.as_array().map_or(false, |a| !a.is_empty()) { + body["tools"] = tools.clone(); + } let mut req = self.http.post(&self.url).timeout(timeout).json(&body); if let Some(key) = &self.api_key { req = req.bearer_auth(key); @@ -1015,6 +1029,16 @@ Rufe danach das Werkzeug done auf."; assert_eq!(out[3]["tool_call_id"], call["id"]); } + #[test] + fn openai_url_wird_ergaenzt() { + assert_eq!(openai_chat_url("http://h:8082/v1"), "http://h:8082/v1/chat/completions"); + assert_eq!(openai_chat_url("http://h:8082/v1/"), "http://h:8082/v1/chat/completions"); + assert_eq!( + openai_chat_url("http://h:8082/v1/chat/completions"), + "http://h:8082/v1/chat/completions" + ); + } + #[test] fn sh_quote_maskiert_apostrophe() { assert_eq!(sh_quote("a'b"), "'a'\\''b'"); diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index bae222c..61bc577 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -13,6 +13,59 @@ pub const CONFIG_FILE_NAME: &str = "config.toml"; /// Aufgaben, die ein Paket installiert. Gilt, wenn weder die Konfiguration noch der Datenordner Aufgaben angeben. pub const SYSTEM_TASKS_DIR: &str = "/usr/share/coding-bench/tasks"; +/// Ein angebundenes Modell: Anzeigename, Adapter und Endpunkt. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ModelEntry { + /// Anzeigename, eindeutig. Erscheint in Ranglisten. + pub name: String, + /// `ollama` oder `openai` (OpenAI-kompatibel, z. B. strata). + pub adapter: String, + /// Basis-URL des Servers, z. B. `http://host:11434` oder `http://host:8082/v1`. + pub url: String, + /// Modell-ID, die an den Server gesendet wird. Leer = Anzeigename. + pub model: String, + /// Name der Umgebungsvariable mit dem API-Schlüssel. Leer = kein Schlüssel. + pub api_key_env: String, +} + +impl Default for ModelEntry { + fn default() -> Self { + ModelEntry { + name: String::new(), + adapter: "ollama".into(), + url: String::new(), + model: String::new(), + api_key_env: String::new(), + } + } +} + +pub const ADAPTERS: [&str; 2] = ["ollama", "openai"]; + +/// Prüft eine Modell-Liste: Namen nicht leer und eindeutig, Adapter bekannt, URL gesetzt. +pub fn validate_models(models: &[ModelEntry]) -> Result<(), String> { + let mut seen = std::collections::HashSet::new(); + for m in models { + if m.name.trim().is_empty() { + return Err("Ein Modell hat keinen Namen.".into()); + } + if !seen.insert(m.name.trim().to_string()) { + return Err(format!("Der Name {:?} kommt doppelt vor.", m.name)); + } + if !ADAPTERS.contains(&m.adapter.as_str()) { + return Err(format!( + "{}: Adapter {:?} unbekannt (erlaubt: ollama, openai).", + m.name, m.adapter + )); + } + if m.url.trim().is_empty() { + return Err(format!("{}: URL fehlt.", m.name)); + } + } + Ok(()) +} + /// Rohe Konfiguration, so wie sie in der Datei steht. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] @@ -23,13 +76,15 @@ pub struct Config { pub tasks_dir: Option, /// Container-Programm für die Sandbox (Podman-CLI). pub container_runtime: String, - /// Modell-Backend: `ollama` oder `openai` (OpenAI-kompatibel, z. B. strata). + /// Angebundene Modelle. Wird in der Oberfläche gepflegt. + pub models: Vec, + /// Veraltet, wird ignoriert. Bleibt nur, damit alte Dateien weiter laden. pub backend: String, - /// Ollama-Endpunkt für alle Modelle (Phase 1). + /// Veraltet, wird ignoriert. pub ollama_url: String, - /// OpenAI-kompatibler Endpunkt, vollständige URL inkl. `/v1/chat/completions`. + /// Veraltet, wird ignoriert. pub openai_url: String, - /// Name der Umgebungsvariable mit dem API-Schlüssel. Der Schlüssel selbst steht nicht in der Datei. + /// Veraltet, wird ignoriert. pub openai_api_key_env: String, /// Speicherlimit pro Lauf, Podman-Schreibweise. pub sandbox_memory: String, @@ -44,10 +99,11 @@ impl Default for Config { data_dir: None, tasks_dir: None, container_runtime: "podman".into(), - backend: "ollama".into(), - ollama_url: "http://127.0.0.1:11434".into(), - openai_url: "http://192.168.12.4:8082/v1/chat/completions".into(), - openai_api_key_env: "STRATA_API_KEY".into(), + models: Vec::new(), + backend: String::new(), + ollama_url: String::new(), + openai_url: String::new(), + openai_api_key_env: String::new(), sandbox_memory: limits.memory, sandbox_cpus: limits.cpus, } @@ -68,15 +124,6 @@ impl Config { toml::from_str(text).map_err(|e| format!("config.toml ist ungültig: {e}")) } - /// Endpunkt des gewählten Backends. - pub fn endpoint_url(&self) -> String { - if self.backend == "openai" { - self.openai_url.clone() - } else { - self.ollama_url.clone() - } - } - /// Ressourcenlimits der Sandbox aus der Konfiguration. pub fn sandbox_limits(&self) -> Limits { Limits { @@ -103,6 +150,14 @@ impl Config { } } +/// Schreibt die Konfiguration zurück. Kommentare der alten Datei gehen dabei verloren. +pub fn save(config_file: &Path, config: &Config) -> Result<(), String> { + let text = toml::to_string_pretty(config) + .map_err(|e| format!("Konfiguration nicht serialisierbar: {e}"))?; + fs::write(config_file, format!("# coding-bench Konfiguration\n{text}")) + .map_err(|e| format!("{} nicht schreibbar: {e}", config_file.display())) +} + /// Lädt die Konfiguration aus `config_dir/config.toml`, legt die Datei bei Bedarf /// mit Standardwerten an und stellt sicher, dass der Datenordner existiert. pub fn load_or_create(config_dir: &Path, default_data_dir: &Path) -> Result<(Paths, Config), String> { @@ -157,10 +212,34 @@ mod tests { } #[test] - fn ollama_url_hat_standard_und_ist_ueberschreibbar() { - assert_eq!(Config::default().ollama_url, "http://127.0.0.1:11434"); - let c = Config::parse("ollama_url = \"http://srv04:11434\"\n").unwrap(); - assert_eq!(c.ollama_url, "http://srv04:11434"); + fn modelle_werden_gelesen_und_geprueft() { + let c = Config::parse( + "[[models]]\nname = \"lokal\"\nadapter = \"ollama\"\nurl = \"http://h:11434\"\nmodel = \"qwen3:0.6b\"\n\n[[models]]\nname = \"strata\"\nadapter = \"openai\"\nurl = \"http://h:8082/v1\"\n", + ) + .unwrap(); + assert_eq!(c.models.len(), 2); + assert_eq!(c.models[1].adapter, "openai"); + assert!(validate_models(&c.models).is_ok()); + } + + #[test] + fn modell_pruefung_findet_fehler() { + let m = |name: &str, adapter: &str, url: &str| ModelEntry { + name: name.into(), + adapter: adapter.into(), + url: url.into(), + ..ModelEntry::default() + }; + assert!(validate_models(&[m("", "ollama", "http://x")]).is_err()); + assert!(validate_models(&[m("a", "ollama", "http://x"), m("a", "ollama", "http://y")]).is_err()); + assert!(validate_models(&[m("a", "gpt", "http://x")]).is_err()); + assert!(validate_models(&[m("a", "ollama", " ")]).is_err()); + } + + #[test] + fn alte_config_mit_veralteten_feldern_laedt_weiter() { + let c = Config::parse("ollama_url = \"http://srv04:11434\"\nbackend = \"openai\"\n").unwrap(); + assert!(c.models.is_empty()); } #[test] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5526621..d4d4735 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -6,11 +6,15 @@ mod sandbox; mod store; mod tasks; -use config::{Config, Paths}; -use runner::{BatchSummary, Event, RunConfig}; +use config::{Config, ModelEntry, Paths}; +use runner::{BatchSummary, Event, ModelConn, RunConfig}; +use serde::Serialize; +use std::collections::BTreeMap; +use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use store::{RunRecord, Store}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use store::{BatchInfo, RunRecord, Store}; use tauri::{Emitter, Manager, State}; pub const DB_FILE: &str = "coding-bench.sqlite"; @@ -19,6 +23,12 @@ pub const EVENT_NAME: &str = "batch-event"; /// Aufgelöste Pfade, einmal beim Start ermittelt. pub struct AppPaths(pub Paths); +/// Die laufende Konfiguration. Die Oberfläche ändert die Modell-Liste, die Datei wird mitgeschrieben. +pub struct ConfigState { + pub config: Mutex, + pub file: PathBuf, +} + /// Steuerung für den laufenden Batch. Es läuft immer nur einer. pub struct RunState { /// Gesetzt, wenn der laufende Batch abbrechen soll. @@ -27,6 +37,36 @@ pub struct RunState { pub running: Arc, } +/// Ein Modell für die Oberfläche, mit Hinweis, ob die Schlüssel-Variable gesetzt ist. +#[derive(Serialize)] +pub struct ModelInfo { + #[serde(flatten)] + pub entry: ModelEntry, + pub api_key_set: bool, +} + +fn model_info(entry: &ModelEntry) -> ModelInfo { + let api_key_set = !entry.api_key_env.is_empty() + && std::env::var(&entry.api_key_env).map_or(false, |v| !v.is_empty()); + ModelInfo { entry: entry.clone(), api_key_set } +} + +/// Löst einen Eintrag in eine Verbindung auf: Modell-ID und Schlüssel aus der Umgebung. +fn conn_of(entry: &ModelEntry) -> ModelConn { + let api_key = if entry.api_key_env.is_empty() { + None + } else { + std::env::var(&entry.api_key_env).ok().filter(|k| !k.is_empty()) + }; + ModelConn { + name: entry.name.clone(), + adapter: entry.adapter.clone(), + url: entry.url.clone(), + model_id: if entry.model.trim().is_empty() { entry.name.clone() } else { entry.model.clone() }, + api_key, + } +} + #[tauri::command] fn get_paths(paths: State<'_, AppPaths>) -> Paths { paths.0.clone() @@ -37,13 +77,92 @@ fn load_tasks(paths: State<'_, AppPaths>) -> tasks::LoadReport { tasks::load_all(&paths.0.tasks_dir) } -/// Startet einen Batch mit den angegebenen Modellen und Aufgaben-IDs. +/// Angebundene Modelle. +#[tauri::command] +fn list_models(cfg: State<'_, ConfigState>) -> Result, String> { + let c = cfg.config.lock().map_err(|e| e.to_string())?; + Ok(c.models.iter().map(model_info).collect()) +} + +/// Ersetzt die Modell-Liste, prüft sie und schreibt `config.toml`. +#[tauri::command] +fn save_models(cfg: State<'_, ConfigState>, models: Vec) -> Result, String> { + let cleaned: Vec = models + .into_iter() + .map(|mut m| { + m.name = m.name.trim().to_string(); + m.url = m.url.trim().to_string(); + m.model = m.model.trim().to_string(); + m.api_key_env = m.api_key_env.trim().to_string(); + m + }) + .collect(); + config::validate_models(&cleaned)?; + let mut c = cfg.config.lock().map_err(|e| e.to_string())?; + let mut next = c.clone(); + next.models = cleaned; + config::save(&cfg.file, &next)?; + *c = next; + Ok(c.models.iter().map(model_info).collect()) +} + +#[derive(Serialize)] +pub struct ModelTest { + pub ok: bool, + pub duration_ms: u128, + pub message: String, +} + +/// Prüft die Verbindung zu einem Modell mit einer kurzen Anfrage. +#[tauri::command] +async fn test_model(cfg: State<'_, ConfigState>, name: String) -> Result { + let entry = { + let c = cfg.config.lock().map_err(|e| e.to_string())?; + c.models + .iter() + .find(|m| m.name == name) + .cloned() + .ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))? + }; + let conn = conn_of(&entry); + tauri::async_runtime::spawn_blocking(move || { + let started = Instant::now(); + let result = runner::client_for(&conn).and_then(|client| { + client + .chat( + &[agent::Message::new("user", "Antworte nur mit: ok")], + &serde_json::json!([]), + Duration::from_secs(90), + ) + .map_err(|e| match e { + agent::ModelError::Timeout => "Zeitlimit überschritten (90 s)".to_string(), + agent::ModelError::Endpoint(m) => m, + }) + }); + let duration_ms = started.elapsed().as_millis(); + match result { + Ok(r) => ModelTest { + ok: true, + duration_ms, + message: format!( + "Antwort erhalten ({} Prompt-, {} Completion-Tokens).", + r.prompt_tokens, r.completion_tokens + ), + }, + Err(message) => ModelTest { ok: false, duration_ms, message }, + } + }) + .await + .map_err(|e| format!("Test abgebrochen: {e}")) +} + +/// Startet einen Batch mit den angegebenen Modellen (Anzeigenamen) und Aufgaben-IDs. /// Fortschritt kommt als Ereignis `batch-event`. Das Ergebnis ist die Zusammenfassung. #[tauri::command] async fn start_batch( app: tauri::AppHandle, paths: State<'_, AppPaths>, - cfg: State<'_, Config>, + cfg: State<'_, ConfigState>, run: State<'_, RunState>, models: Vec, task_ids: Vec, @@ -56,10 +175,20 @@ async fn start_batch( if repeats == 0 { return Err("Wiederholungen müssen mindestens 1 sein.".into()); } - if run.running.swap(true, Ordering::SeqCst) { - return Err("Ein Batch läuft bereits.".into()); - } - run.cancel.store(false, Ordering::SeqCst); + + let (conns, runtime, limits) = { + let c = cfg.config.lock().map_err(|e| e.to_string())?; + let mut conns = Vec::new(); + for name in &models { + let entry = c + .models + .iter() + .find(|m| &m.name == name) + .ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?; + conns.push(conn_of(entry)); + } + (conns, c.container_runtime.clone(), c.sandbox_limits()) + }; let report = tasks::load_all(&paths.0.tasks_dir); let selected: Vec = report @@ -68,17 +197,20 @@ async fn start_batch( .filter(|t| task_ids.contains(&t.meta.id)) .collect(); if selected.len() != task_ids.len() { - run.running.store(false, Ordering::SeqCst); return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into()); } + + if run.running.swap(true, Ordering::SeqCst) { + return Err("Ein Batch läuft bereits.".into()); + } + run.cancel.store(false, Ordering::SeqCst); + let jobs = runner::plan(&models, &selected, repeats); let run_cfg = RunConfig { - runtime: cfg.container_runtime.clone(), - backend: cfg.backend.clone(), - endpoint_url: cfg.endpoint_url(), - api_key: std::env::var(&cfg.openai_api_key_env).ok().filter(|k| !k.is_empty()), + runtime, + models: conns, data_dir: paths.0.data_dir.clone(), - limits: cfg.sandbox_limits(), + limits, }; let db_path = paths.0.data_dir.join(DB_FILE); let cancel = run.cancel.clone(); @@ -114,6 +246,12 @@ fn cancel_batch(run: State<'_, RunState>) -> bool { running } +/// Alle bisherigen Batches, neueste zuerst. +#[tauri::command] +fn list_batches(paths: State<'_, AppPaths>) -> Result, String> { + Store::open(&paths.0.data_dir.join(DB_FILE))?.list_batches() +} + /// Alle gespeicherten Läufe eines Batches. #[tauri::command] fn batch_results(paths: State<'_, AppPaths>, batch_id: i64) -> Result, String> { @@ -135,7 +273,7 @@ fn run_steps( } /// Zustand der Container-Laufzeit (Podman) für das Setup. -#[derive(serde::Serialize)] +#[derive(Serialize)] pub struct RuntimeStatus { pub program: String, pub available: bool, @@ -143,38 +281,48 @@ pub struct RuntimeStatus { } #[tauri::command] -fn runtime_status(cfg: State<'_, Config>) -> RuntimeStatus { - let program = cfg.container_runtime.clone(); - match std::process::Command::new(&program).args(["version", "--format", "{{.Client.Version}}"]).output() { - Ok(out) if out.status.success() => RuntimeStatus { - program, - available: true, - detail: format!("Version {}", String::from_utf8_lossy(&out.stdout).trim()), +fn runtime_status(cfg: State<'_, ConfigState>) -> Result { + let program = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone(); + Ok( + match std::process::Command::new(&program) + .args(["version", "--format", "{{.Client.Version}}"]) + .output() + { + Ok(out) if out.status.success() => RuntimeStatus { + program, + available: true, + detail: format!("Version {}", String::from_utf8_lossy(&out.stdout).trim()), + }, + Ok(out) => RuntimeStatus { + program, + available: false, + detail: String::from_utf8_lossy(&out.stderr).trim().to_string(), + }, + Err(e) => RuntimeStatus { + program, + available: false, + detail: format!("nicht startbar: {e}"), + }, }, - Ok(out) => RuntimeStatus { - program, - available: false, - detail: String::from_utf8_lossy(&out.stderr).trim().to_string(), - }, - Err(e) => RuntimeStatus { - program, - available: false, - detail: format!("nicht startbar: {e}"), - }, - } + ) } -/// Rangliste und Matrix eines Batches. Gewichte kommen aus den Aufgaben. +/// Bewertung je Modell und Bereich für einen Batch. Gruppe und Gewicht kommen aus den Aufgaben. #[tauri::command] fn batch_ranking(paths: State<'_, AppPaths>, batch_id: i64) -> Result { let store = Store::open(&paths.0.data_dir.join(DB_FILE))?; let runs = store.runs_for_batch(batch_id)?; - let weights: std::collections::BTreeMap = tasks::load_all(&paths.0.tasks_dir) + let infos: BTreeMap = tasks::load_all(&paths.0.tasks_dir) .tasks .into_iter() - .map(|t| (t.meta.id, t.meta.weight)) + .map(|t| { + ( + t.meta.id.clone(), + ranking::TaskInfo { group: t.meta.group.clone(), weight: t.meta.weight }, + ) + }) .collect(); - Ok(ranking::compute(batch_id, &runs, &weights)) + Ok(ranking::compute(batch_id, &runs, &infos)) } #[cfg_attr(mobile, tauri::mobile_entry_point)] @@ -193,8 +341,9 @@ pub fn run() { let (paths, cfg) = config::load_or_create(&config_dir, &default_data_dir)?; // Datenbank einmal anlegen, damit Fehler früh sichtbar werden. Store::open(&paths.data_dir.join(DB_FILE))?; + let file = paths.config_file.clone(); app.manage(AppPaths(paths)); - app.manage(cfg); + app.manage(ConfigState { config: Mutex::new(cfg), file }); app.manage(RunState { cancel: Arc::new(AtomicBool::new(false)), running: Arc::new(AtomicBool::new(false)), @@ -204,8 +353,12 @@ pub fn run() { .invoke_handler(tauri::generate_handler![ get_paths, load_tasks, + list_models, + save_models, + test_model, start_batch, cancel_batch, + list_batches, batch_results, batch_ranking, run_steps, diff --git a/src-tauri/src/ranking.rs b/src-tauri/src/ranking.rs index bbb2ffb..fc280aa 100644 --- a/src-tauri/src/ranking.rs +++ b/src-tauri/src/ranking.rs @@ -1,21 +1,45 @@ -//! Rangliste und Matrix aus den Läufen eines Batches (F-09, SPEC Abschnitt 9). +//! Bewertung je Modell und Bereich (F-09, SPEC Abschnitt 9). //! -//! Gesamtscore je Modell: gewichteter Mittelwert der Aufgaben-Scores (`weight` aus -//! `task.toml`). Erfolgsquote je (Modell, Aufgabe): Anteil der Läufe mit Klasse `ok`. -//! Tie-Breaker: Median der Dauer, dann mittlere Completion-Tokens. Wilson-Intervalle -//! und Kategorie-Ranking folgen mit F-12 (Phase 2). +//! Basis ist eine absolute Bewertung, kein Vergleich gegen ein Referenzmodell: +//! - Wert je Bereich (Gruppe A bis D): gewichteter Mittelwert der Aufgaben im Bereich in Prozent. +//! Je Aufgabe zählt der mittlere Score über die Wiederholungen. +//! - Gesamtnote: gewichteter Mittelwert über alle Aufgaben des Batches in Prozent. +//! - Gewichte kommen aus `weight` in `task.toml`. +//! - Bereiche ohne Läufe eines Modells bleiben leer und zählen nicht mit. +//! - Reihenfolge: Gesamtnote absteigend, dann Median der Dauer, dann mittlere Completion-Tokens. use crate::agent::ErrorClass; use crate::store::RunRecord; use serde::Serialize; use std::collections::BTreeMap; +/// Gruppe und Gewicht einer Aufgabe. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskInfo { + pub group: String, + pub weight: f64, +} + +/// Wert eines Modells in einem Bereich. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct GroupScore { + pub group: String, + /// Prozent von 0 bis 100. `None`, wenn das Modell im Bereich keine Läufe hat. + pub percent: Option, + /// Anzahl Aufgaben, die in den Wert eingehen. + pub tasks: usize, + pub runs: usize, +} + #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ModelRank { pub rank: usize, pub model: String, - /// Gewichteter Mittelwert der Aufgaben-Scores, 0.0 bis 1.0. - pub total_score: f64, + /// Gesamtnote in Prozent von 0 bis 100. + pub total_percent: f64, + pub groups: Vec, + /// Bereich mit dem niedrigsten Wert, nur wenn das Modell mindestens zwei Bereiche hat. + pub weakest_group: Option, pub runs: usize, pub successes: usize, pub median_duration_ms: u128, @@ -28,24 +52,53 @@ pub struct MatrixCell { pub task_id: String, pub runs: usize, pub successes: usize, - /// Mittlerer Score über die Wiederholungen. + /// Mittlerer Score über die Wiederholungen, 0.0 bis 1.0. pub mean_score: f64, } +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct TaskColumn { + pub id: String, + pub group: String, +} + #[derive(Debug, Clone, PartialEq, Serialize)] pub struct Ranking { pub batch_id: i64, + /// Bereiche, die im Batch vorkommen, sortiert. + pub groups: Vec, pub models: Vec, pub cells: Vec, - pub tasks: Vec, + /// Aufgaben des Batches, sortiert nach Bereich und ID. + pub tasks: Vec, } -/// Berechnet Rangliste und Matrix. `weights` ordnet jeder Aufgaben-ID ihr Gewicht zu; -/// fehlt eine ID, zählt das Gewicht 1.0. -pub fn compute(batch_id: i64, runs: &[RunRecord], weights: &BTreeMap) -> Ranking { - let weight_of = |task: &str| weights.get(task).copied().unwrap_or(1.0); +const UNKNOWN_GROUP: &str = "?"; + +/// Berechnet Bewertung und Matrix. Unbekannte Aufgaben zählen mit Gewicht 1.0 im Bereich `?`. +pub fn compute(batch_id: i64, runs: &[RunRecord], tasks: &BTreeMap) -> Ranking { + let info_of = |task: &str| -> TaskInfo { + tasks.get(task).cloned().unwrap_or(TaskInfo { + group: UNKNOWN_GROUP.into(), + weight: 1.0, + }) + }; + + // Aufgaben des Batches mit Bereich. + let mut task_cols: BTreeMap = BTreeMap::new(); + for r in runs { + task_cols + .entry(r.task_id.clone()) + .or_insert_with(|| info_of(&r.task_id).group); + } + let mut task_list: Vec = task_cols + .iter() + .map(|(id, group)| TaskColumn { id: id.clone(), group: group.clone() }) + .collect(); + task_list.sort_by(|a, b| a.group.cmp(&b.group).then(a.id.cmp(&b.id))); + let mut groups: Vec = task_list.iter().map(|t| t.group.clone()).collect(); + groups.dedup(); - // Pro Modell: Liste der Läufe. let mut by_model: BTreeMap<&str, Vec<&RunRecord>> = BTreeMap::new(); for r in runs { by_model.entry(r.model.as_str()).or_default().push(r); @@ -54,44 +107,81 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], weights: &BTreeMap = by_model .iter() .map(|(model, rs)| { - // Mittelwert je Aufgabe, dann gewichtet über die Aufgaben. + // Mittel je Aufgabe über die Wiederholungen. let mut per_task: BTreeMap<&str, (f64, usize)> = BTreeMap::new(); for r in rs { let e = per_task.entry(r.task_id.as_str()).or_insert((0.0, 0)); e.0 += r.score; e.1 += 1; } - let (mut wsum, mut wtotal) = (0.0, 0.0); + // Je Bereich: gewichtete Summe, Gewicht, Aufgaben, Läufe. + let mut per_group: BTreeMap = BTreeMap::new(); + let (mut total_sum, mut total_w) = (0.0, 0.0); for (task, (sum, n)) in &per_task { - let w = weight_of(task); - wsum += w * (sum / *n as f64); - wtotal += w; + let info = info_of(task); + let mean = sum / *n as f64; + let g = per_group.entry(info.group.clone()).or_insert((0.0, 0.0, 0, 0)); + g.0 += info.weight * mean; + g.1 += info.weight; + g.2 += 1; + g.3 += *n; + total_sum += info.weight * mean; + total_w += info.weight; } - let total_score = if wtotal > 0.0 { wsum / wtotal } else { 0.0 }; + let total_percent = if total_w > 0.0 { 100.0 * total_sum / total_w } else { 0.0 }; + + let group_scores: Vec = groups + .iter() + .map(|g| match per_group.get(g) { + Some((sum, w, tasks_n, runs_n)) if *w > 0.0 => GroupScore { + group: g.clone(), + percent: Some(100.0 * sum / w), + tasks: *tasks_n, + runs: *runs_n, + }, + _ => GroupScore { group: g.clone(), percent: None, tasks: 0, runs: 0 }, + }) + .collect(); + + let weakest_group = { + let filled: Vec<&GroupScore> = + group_scores.iter().filter(|g| g.percent.is_some()).collect(); + if filled.len() >= 2 { + filled + .iter() + .min_by(|a, b| { + a.percent + .partial_cmp(&b.percent) + .unwrap_or(std::cmp::Ordering::Equal) + }) + .map(|g| g.group.clone()) + } else { + None + } + }; let mut durations: Vec = rs.iter().map(|r| r.duration_ms).collect(); durations.sort_unstable(); - let median = median_u128(&durations); - - let mean_tokens = rs.iter().map(|r| r.completion_tokens as f64).sum::() / rs.len() as f64; - let successes = rs.iter().filter(|r| r.error_class == ErrorClass::Ok).count(); + let mean_tokens = + rs.iter().map(|r| r.completion_tokens as f64).sum::() / rs.len() as f64; ModelRank { rank: 0, model: model.to_string(), - total_score, + total_percent, + groups: group_scores, + weakest_group, runs: rs.len(), - successes, - median_duration_ms: median, + successes: rs.iter().filter(|r| r.error_class == ErrorClass::Ok).count(), + median_duration_ms: median_u128(&durations), mean_completion_tokens: mean_tokens, } }) .collect(); - // Absteigend nach Score, dann Median-Dauer, dann mittlere Completion-Tokens. models.sort_by(|a, b| { - b.total_score - .partial_cmp(&a.total_score) + b.total_percent + .partial_cmp(&a.total_percent) .unwrap_or(std::cmp::Ordering::Equal) .then(a.median_duration_ms.cmp(&b.median_duration_ms)) .then( @@ -104,15 +194,12 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], weights: &BTreeMap> = BTreeMap::new(); - let mut task_set: BTreeMap<&str, ()> = BTreeMap::new(); for r in runs { cell_map .entry((r.model.as_str(), r.task_id.as_str())) .or_default() .push(r); - task_set.insert(r.task_id.as_str(), ()); } let cells = cell_map .iter() @@ -125,12 +212,7 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], weights: &BTreeMap u128 { @@ -165,48 +247,101 @@ mod tests { } } - #[test] - fn gewichteter_score_und_rang() { - let runs = vec![ - run("A", "t1", 1.0, ErrorClass::Ok, 1000, 10), - run("A", "t2", 0.0, ErrorClass::CheckFailed, 1000, 10), - run("B", "t1", 1.0, ErrorClass::Ok, 1000, 10), - run("B", "t2", 1.0, ErrorClass::Ok, 1000, 10), - ]; - let mut w = BTreeMap::new(); - w.insert("t1".to_string(), 1.0); - w.insert("t2".to_string(), 3.0); - let r = compute(1, &runs, &w); - assert_eq!(r.models[0].model, "B"); - assert_eq!(r.models[0].rank, 1); - assert!((r.models[0].total_score - 1.0).abs() < 1e-9); - // A: (1*1 + 3*0) / 4 = 0.25 - assert!((r.models[1].total_score - 0.25).abs() < 1e-9); + fn infos(list: &[(&str, &str, f64)]) -> BTreeMap { + list.iter() + .map(|(id, g, w)| (id.to_string(), TaskInfo { group: g.to_string(), weight: *w })) + .collect() } #[test] - fn gleichstand_nach_median_dauer() { + fn prozent_je_bereich_und_gesamt() { + // A: a1 (Gewicht 1), B: b1 (Gewicht 3). + let tasks = infos(&[("a1", "A", 1.0), ("b1", "B", 3.0)]); let runs = vec![ - run("slow", "t1", 1.0, ErrorClass::Ok, 9000, 10), - run("fast", "t1", 1.0, ErrorClass::Ok, 2000, 10), + run("m", "a1", 1.0, ErrorClass::Ok, 1000, 10), + run("m", "b1", 0.0, ErrorClass::CheckFailed, 1000, 10), ]; - let r = compute(1, &runs, &BTreeMap::new()); - assert_eq!(r.models[0].model, "fast"); + let r = compute(1, &runs, &tasks); + let m = &r.models[0]; + assert_eq!(r.groups, vec!["A".to_string(), "B".to_string()]); + assert_eq!(m.groups[0].percent, Some(100.0)); + assert_eq!(m.groups[1].percent, Some(0.0)); + // Gesamt: (1*1 + 3*0) / 4 = 25 % + assert!((m.total_percent - 25.0).abs() < 1e-9); + assert_eq!(m.weakest_group.as_deref(), Some("B")); } #[test] - fn matrix_zaehlt_erfolge_und_mittelwert() { + fn wiederholungen_werden_je_aufgabe_gemittelt() { + let tasks = infos(&[("a1", "A", 1.0), ("a2", "A", 1.0)]); let runs = vec![ - run("A", "t1", 1.0, ErrorClass::Ok, 1, 1), - run("A", "t1", 0.5, ErrorClass::CheckFailed, 1, 1), - run("A", "t1", 0.0, ErrorClass::MaxSteps, 1, 1), + run("m", "a1", 1.0, ErrorClass::Ok, 1, 1), + run("m", "a1", 0.0, ErrorClass::CheckFailed, 1, 1), + run("m", "a2", 1.0, ErrorClass::Ok, 1, 1), ]; - let r = compute(1, &runs, &BTreeMap::new()); - assert_eq!(r.cells.len(), 1); - assert_eq!(r.cells[0].runs, 3); - assert_eq!(r.cells[0].successes, 1); - assert!((r.cells[0].mean_score - 0.5).abs() < 1e-9); - assert_eq!(r.tasks, vec!["t1".to_string()]); + let r = compute(1, &runs, &tasks); + // a1: 50 %, a2: 100 % -> Bereich A 75 %. Jede Aufgabe zählt gleich viel, egal wie oft sie lief. + assert!((r.models[0].groups[0].percent.unwrap() - 75.0).abs() < 1e-9); + assert_eq!(r.models[0].groups[0].tasks, 2); + assert_eq!(r.models[0].groups[0].runs, 3); + } + + #[test] + fn fehlender_bereich_bleibt_leer_und_zaehlt_nicht() { + let tasks = infos(&[("a1", "A", 1.0), ("b1", "B", 1.0)]); + let runs = vec![ + run("x", "a1", 1.0, ErrorClass::Ok, 1, 1), + run("y", "a1", 1.0, ErrorClass::Ok, 1, 1), + run("y", "b1", 1.0, ErrorClass::Ok, 1, 1), + ]; + let r = compute(1, &runs, &tasks); + let x = r.models.iter().find(|m| m.model == "x").unwrap(); + assert_eq!(x.groups[1].percent, None); + assert_eq!(x.weakest_group, None); + assert!((x.total_percent - 100.0).abs() < 1e-9); + } + + #[test] + fn rang_nach_gesamt_dann_dauer() { + let tasks = infos(&[("a1", "A", 1.0)]); + let runs = vec![ + run("slow", "a1", 1.0, ErrorClass::Ok, 9000, 10), + run("fast", "a1", 1.0, ErrorClass::Ok, 2000, 10), + run("schlecht", "a1", 0.0, ErrorClass::CheckFailed, 100, 10), + ]; + let r = compute(1, &runs, &tasks); + let order: Vec<&str> = r.models.iter().map(|m| m.model.as_str()).collect(); + assert_eq!(order, vec!["fast", "slow", "schlecht"]); + assert_eq!(r.models[2].rank, 3); + } + + #[test] + fn matrix_und_aufgabenliste_nach_bereich_sortiert() { + let tasks = infos(&[("b1", "B", 1.0), ("a1", "A", 1.0)]); + let runs = vec![ + run("m", "b1", 1.0, ErrorClass::Ok, 1, 1), + run("m", "a1", 0.5, ErrorClass::CheckFailed, 1, 1), + ]; + let r = compute(1, &runs, &tasks); + let ids: Vec<&str> = r.tasks.iter().map(|t| t.id.as_str()).collect(); + assert_eq!(ids, vec!["a1", "b1"]); + assert_eq!(r.cells.len(), 2); + let a1 = r.cells.iter().find(|c| c.task_id == "a1").unwrap(); + assert!((a1.mean_score - 0.5).abs() < 1e-9); + assert_eq!(a1.successes, 0); + } + + #[test] + fn unbekannte_aufgabe_landet_im_bereich_fragezeichen() { + let r = compute(1, &[run("m", "alt", 1.0, ErrorClass::Ok, 1, 1)], &BTreeMap::new()); + assert_eq!(r.groups, vec!["?".to_string()]); + } + + #[test] + fn leerer_batch() { + let r = compute(7, &[], &BTreeMap::new()); + assert!(r.models.is_empty() && r.cells.is_empty() && r.tasks.is_empty() && r.groups.is_empty()); + assert_eq!(r.batch_id, 7); } #[test] @@ -215,11 +350,4 @@ mod tests { assert_eq!(median_u128(&[1, 2, 3, 4]), 2); assert_eq!(median_u128(&[]), 0); } - - #[test] - fn leerer_batch_ergibt_leere_rangliste() { - let r = compute(7, &[], &BTreeMap::new()); - assert!(r.models.is_empty() && r.cells.is_empty() && r.tasks.is_empty()); - assert_eq!(r.batch_id, 7); - } } diff --git a/src-tauri/src/runner.rs b/src-tauri/src/runner.rs index ed77a99..f05557d 100644 --- a/src-tauri/src/runner.rs +++ b/src-tauri/src/runner.rs @@ -29,15 +29,25 @@ pub struct Job { pub repeat_idx: u32, } +/// Verbindung zu einem Modell, aufgelöst aus der Konfiguration. +#[derive(Debug, Clone, PartialEq)] +pub struct ModelConn { + /// Anzeigename, wie er in Läufen und Ranglisten steht. + pub name: String, + /// `ollama` oder `openai`. + pub adapter: String, + pub url: String, + /// Modell-ID, die der Server erwartet. + pub model_id: String, + /// Schlüssel, wird nicht gespeichert. + pub api_key: Option, +} + /// Einstellungen für einen Batch. #[derive(Debug, Clone)] pub struct RunConfig { pub runtime: String, - /// `ollama` oder `openai`. - pub backend: String, - pub endpoint_url: String, - /// Schlüssel für den OpenAI-Endpunkt, wird nicht gespeichert. - pub api_key: Option, + pub models: Vec, pub data_dir: PathBuf, pub limits: Limits, } @@ -123,8 +133,9 @@ pub fn run_batch( ) -> Result { let config_json = json!({ "runtime": cfg.runtime, - "backend": cfg.backend, - "endpoint": cfg.endpoint_url, + "models": cfg.models.iter().map(|m| json!({ + "name": m.name, "adapter": m.adapter, "url": m.url, "model_id": m.model_id + })).collect::>(), "limits": { "memory": cfg.limits.memory, "cpus": cfg.limits.cpus }, "system_prompt": crate::agent::SYSTEM_PROMPT, "tool_output_chars": crate::agent::MAX_TOOL_OUTPUT_CHARS, @@ -255,12 +266,22 @@ enum JobResult { Cancelled, } -/// Baut den Modell-Client für das gewählte Backend. -pub fn make_client(cfg: &RunConfig, model: &str) -> Result, String> { - match cfg.backend.as_str() { - "ollama" => Ok(Box::new(OllamaClient::new(&cfg.endpoint_url, model)?)), - "openai" => Ok(Box::new(OpenAiClient::new(&cfg.endpoint_url, model, cfg.api_key.clone())?)), - other => Err(format!("Unbekanntes Backend: {other} (erlaubt: ollama, openai)")), +/// Baut den Modell-Client für den Adapter des Modells. +pub fn make_client(cfg: &RunConfig, name: &str) -> Result, String> { + let conn = cfg + .models + .iter() + .find(|m| m.name == name) + .ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?; + client_for(conn) +} + +/// Baut den Client für eine Verbindung, je nach Adapter. +pub fn client_for(conn: &ModelConn) -> Result, String> { + match conn.adapter.as_str() { + "ollama" => Ok(Box::new(OllamaClient::new(&conn.url, &conn.model_id)?)), + "openai" => Ok(Box::new(OpenAiClient::new(&conn.url, &conn.model_id, conn.api_key.clone())?)), + other => Err(format!("Unbekannter Adapter: {other} (erlaubt: ollama, openai)")), } } @@ -456,9 +477,13 @@ mod tests { let jobs = plan(&[model.clone()], &tasks, 2); let cfg = RunConfig { runtime: "podman".into(), - backend: "ollama".into(), - endpoint_url: url, - api_key: None, + models: vec![ModelConn { + name: model.clone(), + adapter: "ollama".into(), + url, + model_id: model.clone(), + api_key: None, + }], data_dir: base.join("data"), limits: Limits::default(), }; @@ -507,9 +532,13 @@ mod tests { let jobs = plan(&[model.clone()], &tasks, 1); let cfg = RunConfig { runtime: "podman".into(), - backend, - endpoint_url: url, - api_key, + models: vec![ModelConn { + name: model.clone(), + adapter: backend, + url, + model_id: model.clone(), + api_key, + }], data_dir: data.clone(), limits: Limits::default(), }; diff --git a/src-tauri/src/store.rs b/src-tauri/src/store.rs index fd06336..f8a4139 100644 --- a/src-tauri/src/store.rs +++ b/src-tauri/src/store.rs @@ -50,6 +50,18 @@ CREATE TABLE IF NOT EXISTS step ( "; /// Ein abgeschlossener Lauf, so wie er gespeichert wird. +/// Ein Batch in der Übersicht. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BatchInfo { + pub id: i64, + pub created_at: String, + pub note: String, + pub repeats: u32, + pub runs: i64, + /// Modellnamen, durch Komma getrennt. + pub models: String, +} + /// Ein Schritt eines Laufs, für die Anzeige. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct StepRow { @@ -260,6 +272,32 @@ impl Store { rows.collect::, _>>().map_err(|e| e.to_string()) } + /// Alle Batches, neueste zuerst. + pub fn list_batches(&self) -> Result, String> { + let mut stmt = self + .conn + .prepare( + "SELECT b.id, b.created_at, b.note, b.repeats, COUNT(r.id), + COALESCE(group_concat(DISTINCT r.model), '') + FROM batch b LEFT JOIN run r ON r.batch_id = b.id + GROUP BY b.id ORDER BY b.id DESC", + ) + .map_err(|e| e.to_string())?; + let rows = stmt + .query_map([], |r| { + Ok(BatchInfo { + id: r.get(0)?, + created_at: r.get(1)?, + note: r.get(2)?, + repeats: r.get(3)?, + runs: r.get(4)?, + models: r.get(5)?, + }) + }) + .map_err(|e| e.to_string())?; + rows.collect::, _>>().map_err(|e| e.to_string()) + } + pub fn run_count(&self, batch_id: i64) -> Result { self.conn .query_row("SELECT COUNT(*) FROM run WHERE batch_id = ?1", params![batch_id], |r| r.get(0)) @@ -357,6 +395,21 @@ mod tests { assert!(s.steps_for_run(b, "m1", "a-01", 2).unwrap().is_empty()); } + #[test] + fn batches_werden_mit_laeufen_und_modellen_aufgelistet() { + let mut s = Store::open_in_memory().unwrap(); + let b1 = s.create_batch("erster", 1, "{}").unwrap(); + let b2 = s.create_batch("zweiter", 2, "{}").unwrap(); + s.insert_run(&rec(b1, "m1", "a-01", 1), &[]).unwrap(); + s.insert_run(&rec(b1, "m2", "a-01", 1), &[]).unwrap(); + let list = s.list_batches().unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0].id, b2, "neuester zuerst"); + assert_eq!(list[0].runs, 0); + assert_eq!(list[1].runs, 2); + assert!(list[1].models.contains("m1") && list[1].models.contains("m2")); + } + #[test] fn unbekannter_batch_existiert_nicht() { let s = Store::open_in_memory().unwrap(); diff --git a/src/app.css b/src/app.css new file mode 100644 index 0000000..3803d78 --- /dev/null +++ b/src/app.css @@ -0,0 +1,136 @@ +:root { + --bg: #f4f5f7; + --surface: #ffffff; + --surface-2: #eef0f3; + --text: #1b1f24; + --muted: #5d6673; + --border: #d8dce2; + --accent: #2b6cb0; + --accent-text: #ffffff; + --danger: #b3261e; + --ok: #2e7d32; + --radius: 10px; + font-family: Inter, "Segoe UI", system-ui, -apple-system, sans-serif; + font-size: 15px; + line-height: 1.5; + color: var(--text); + background: var(--bg); + -webkit-text-size-adjust: 100%; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #14171b; + --surface: #1d2127; + --surface-2: #272c34; + --text: #e6e9ed; + --muted: #98a2b0; + --border: #353b45; + --accent: #5b9bd5; + --accent-text: #0e1218; + --danger: #ff8a80; + --ok: #7bc47f; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); +} + +h1, h2, h3 { + line-height: 1.25; + margin: 0 0 0.6rem; +} +h2 { font-size: 1.15rem; } +h3 { font-size: 1rem; } + +button { + font: inherit; + padding: 0.45rem 0.9rem; + border-radius: 8px; + border: 1px solid var(--border); + background: var(--surface-2); + color: var(--text); + cursor: pointer; +} +button:hover:not(:disabled) { border-color: var(--accent); } +button:disabled { opacity: 0.5; cursor: not-allowed; } +button.primary { + background: var(--accent); + color: var(--accent-text); + border-color: var(--accent); + font-weight: 600; +} +button.danger { color: var(--danger); } +button.link { + background: none; + border: none; + padding: 0; + color: var(--accent); + text-decoration: underline; +} + +input, select, textarea { + font: inherit; + padding: 0.4rem 0.55rem; + border-radius: 8px; + border: 1px solid var(--border); + background: var(--surface); + color: var(--text); + min-width: 0; +} +input:focus, select:focus, textarea:focus { + outline: 2px solid var(--accent); + outline-offset: -1px; +} + +code, pre { + font-family: ui-monospace, "JetBrains Mono", Menlo, monospace; + font-size: 0.88em; +} + +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 1rem 1.2rem; + margin-bottom: 1rem; +} + +.muted { color: var(--muted); } +.error { color: var(--danger); } +.ok { color: var(--ok); } + +.chip { + display: inline-block; + padding: 0.05rem 0.55rem; + border-radius: 999px; + font-size: 0.8rem; + background: var(--surface-2); + border: 1px solid var(--border); +} + +table { + width: 100%; + border-collapse: collapse; +} +th, td { + text-align: left; + padding: 0.45rem 0.6rem; + border-bottom: 1px solid var(--border); + vertical-align: middle; +} +th { + font-size: 0.8rem; + font-weight: 600; + color: var(--muted); + text-transform: uppercase; + letter-spacing: 0.03em; +} +td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; } diff --git a/src/app.html b/src/app.html index 92e7e33..1365703 100644 --- a/src/app.html +++ b/src/app.html @@ -1,10 +1,10 @@ - + - Tauri + SvelteKit + Typescript App + coding-bench %sveltekit.head% diff --git a/src/lib/BenchPanel.svelte b/src/lib/BenchPanel.svelte new file mode 100644 index 0000000..27e82e8 --- /dev/null +++ b/src/lib/BenchPanel.svelte @@ -0,0 +1,279 @@ + + +{#if models.length === 0} +
+

Noch kein Modell angebunden

+

Bevor ein Benchmark laufen kann, braucht coding-bench mindestens ein Modell.

+ +
+{:else} +
+

1. Modelle

+
+ {#each models as m (m.name)} + + {/each} +
+
+ +
+

2. Aufgaben

+ {#if !tasks} +

Lade Aufgaben …

+ {:else if tasks.tasks.length === 0} +

Keine gültigen Aufgaben gefunden.

+ {/if} + {#each byGroup as [group, list] (group)} +
+
+

{group} · {groupLabel(group)} ({list.length})

+ + +
+ {#each list as t (t.id)} + + {/each} +
+ {/each} + {#if tasks && tasks.errors.length > 0} +
+ {tasks.errors.length} Aufgabe(n) mit Fehlern +
    + {#each tasks.errors as e (e.dir)} +
  • {e.dir}: {e.message}
  • + {/each} +
+
+ {/if} +
+ +
+

3. Starten

+
+ +

+ {#if totalRuns > 0}{totalRuns} Läufe: {chosenModels.length} Modell(e) × {chosenTasks.length} Aufgabe(n) × {repeats}.{:else}Wähle Modelle und Aufgaben.{/if} + Mehr Durchläufe machen die Prozentwerte verlässlicher. +

+
+ + +
+
+ + {#if progress} +
+
+
+

{progress.done} von {progress.total} Läufen fertig

+ {/if} + {#if current}

Läuft: {current}

{/if} + {#if error}

{error}

{/if} + {#if finishedBatch !== null} +

+ {cancelled ? "Abgebrochen." : "Fertig."} + +

+ {/if} + {#if log.length > 0} +
    + {#each log as l, i (i)} +
  • {l.text}
  • + {/each} +
+ {/if} +
+{/if} + + diff --git a/src/lib/ResultsPanel.svelte b/src/lib/ResultsPanel.svelte new file mode 100644 index 0000000..8fad2fe --- /dev/null +++ b/src/lib/ResultsPanel.svelte @@ -0,0 +1,352 @@ + + +
+
+

Bewertung

+ {#if batches.length > 0} + + {/if} +
+ + {#if error}

{error}

{/if} + {#if batches.length === 0 && !error} +

Noch keine Ergebnisse. Starte im Reiter „Benchmark“ einen Lauf.

+ {/if} + {#if loading}

Lade …

{/if} + + {#if ranking && ranking.models.length > 0} +
+ + + + + + + {#each ranking.groups as g (g)} + + {/each} + + + + + + + {#each ranking.models as m (m.model)} + + + + + {#each m.groups as g (g.group)} + + {/each} + + + + + {/each} + +
#ModellGesamt{g}
{groupLabel(g)}
Schwächster BereichBestandenMedian-Dauer
{m.rank}{m.model} +
{fmtPct(m.total_percent)}
+
+
+ {#if g.percent === null} + – + {:else} +
{fmtPct(g.percent)}
+
+
+ {g.tasks} Aufg.{g.tasks < FEW_TASKS ? " (grob)" : ""} +
+ {/if} +
+ {#if m.weakest_group} + {m.weakest_group} · {groupLabel(m.weakest_group)} + {:else} + – + {/if} + {m.successes} / {m.runs}{fmtDuration(m.median_duration_ms)}
+
+ +
+ So wird bewertet +
    +
  • + Die Bewertung ist absolut, nicht im Vergleich zu einem Referenzmodell. 100 % heißt: alle + Prüfungen der Aufgaben bestanden. +
  • +
  • + Je Aufgabe zählt der Mittelwert der Durchläufe. Teilpunkte aus check.sh gehen anteilig ein. +
  • +
  • + Wert je Bereich: gewichteter Mittelwert der Aufgaben im Bereich. Gesamt: gewichteter Mittelwert über alle + Aufgaben des Batches. Die Gewichte stehen als weight in task.toml. +
  • +
  • Fehlt einem Modell ein Bereich, bleibt das Feld leer und zählt nicht in die Gesamtnote.
  • +
  • Die Reihenfolge richtet sich nach der Gesamtnote. Bei Gleichstand gewinnt die kürzere Median-Dauer.
  • +
  • Bereiche mit weniger als {FEW_TASKS} Aufgaben sind nur grobe Hinweise.
  • +
+
+ +

Aufgaben im Detail

+
+ + + + + {#each ranking.tasks as t (t.id)} + + {/each} + + + + {#each ranking.models as m (m.model)} + + + {#each ranking.tasks as t (t.id)} + {@const c = cell(m.model, t.id)} + + {/each} + + {/each} + +
Modell{t.id}
{m.model} + {c ? `${Math.round(c.mean_score * 100)} %` : "–"} +
+
+ +

+ Einzelne Läufe + +

+ {#if showRuns} +
+ + + + + + + + + + + + + + + {#each rows as r (`${r.model}|${r.task_id}|${r.repeat_idx}`)} + + + + + + + + + + + {/each} + +
ModellAufgabeDurchlaufErgebnisScoreSchritteDauer
{r.model}{r.task_id}{r.repeat_idx}{r.error_class === "ok" ? "bestanden" : r.error_class}{Math.round(r.score * 100)} %{r.steps}{fmtDuration(r.duration_ms)}
+
+ {/if} + + {#if detail} +
+

+ Schritte: {detail.run.model} · {detail.run.task_id} · Durchlauf {detail.run.repeat_idx} + +

+ {#if detail.run.check_output} +

Prüfung (check.sh):

+
{detail.run.check_output}
+ {/if} +
    + {#each detail.steps as st (st.idx)} +
  1. + {st.role} + {#if st.tool_name}{st.tool_name} {st.tool_args_json ?? ""}{/if} + {#if st.content}
    {st.content}
    {/if} +
  2. + {/each} +
+
+ {/if} + {:else if ranking && !loading} +

Dieser Batch hat noch keine fertigen Läufe.

+ {/if} +
+ + diff --git a/src/lib/SettingsPanel.svelte b/src/lib/SettingsPanel.svelte new file mode 100644 index 0000000..c4f9bd8 --- /dev/null +++ b/src/lib/SettingsPanel.svelte @@ -0,0 +1,232 @@ + + +
+

Modelle

+

+ Jedes Modell hat einen Adapter. Er bestimmt, wie coding-bench mit dem Server spricht. Ein Schlüssel steht nie in der + Konfiguration: Trage nur den Namen der Umgebungsvariable ein, aus der die App ihn beim Start liest. +

+ + {#if draft.length === 0} +

Noch kein Modell angebunden.

+ {/if} + + {#each draft as m, i (i)} +
+
+ + + + + +
+
+ {#if m.api_key_env && savedInfo(m.name)} + {#if savedInfo(m.name)?.api_key_set} + Schlüssel gefunden + {:else} + Variable {m.api_key_env} ist nicht gesetzt + {/if} + {/if} + + {#if tests[m.name] === "läuft"} + teste … + {:else if tests[m.name]} + {@const t = tests[m.name] as ModelTest} + + {t.ok ? "Verbunden" : "Fehler"}: {t.message} + {#if t.duration_ms}({(t.duration_ms / 1000).toFixed(1)} s){/if} + + {/if} + + +
+
+ {/each} + +
+ + + {#if saveError}{saveError}{/if} + {#if dirty}Ungespeicherte Änderungen{/if} + +
+
+ +
+

System

+
+
Container
+
+ {#if runtime} + {#if runtime.available} + {runtime.program} bereit, {runtime.detail} + {:else} + {runtime.program} nicht nutzbar: {runtime.detail} + {/if} + {:else} + Prüfe … + {/if} +
+ {#if paths} +
Konfiguration
+
{paths.config_file}
+
Datenordner
+
{paths.data_dir}
+
Aufgabenordner
+
{paths.tasks_dir}
+ {/if} +
+
+ + diff --git a/src/lib/api.ts b/src/lib/api.ts new file mode 100644 index 0000000..ee45fed --- /dev/null +++ b/src/lib/api.ts @@ -0,0 +1,127 @@ +import { invoke } from "@tauri-apps/api/core"; + +export type Paths = { config_file: string; data_dir: string; tasks_dir: string }; + +export type TaskInfo = { id: string; title: string; group: string; dir: string; weight: number }; +export type TaskError = { dir: string; message: string }; +export type LoadReport = { tasks: TaskInfo[]; errors: TaskError[] }; + +export type ModelEntry = { + name: string; + adapter: string; + url: string; + model: string; + api_key_env: string; +}; +export type ModelInfo = ModelEntry & { api_key_set: boolean }; +export type ModelTest = { ok: boolean; duration_ms: number; message: string }; + +export type RuntimeStatus = { program: string; available: boolean; detail: string }; + +export type BatchInfo = { + id: number; + created_at: string; + note: string; + repeats: number; + runs: number; + models: string; +}; +export type BatchSummary = { batch_id: number; completed: number; skipped: number; cancelled: boolean }; + +export type RunRow = { + model: string; + task_id: string; + repeat_idx: number; + error_class: string; + score: number; + steps: number; + prompt_tokens: number; + completion_tokens: number; + duration_ms: number; + tps: number | null; + summary: string | null; + check_output: string; +}; + +export type StepRow = { + idx: number; + role: string; + content: string; + tool_name: string | null; + tool_args_json: string | null; + tool_result: string | null; +}; + +export type GroupScore = { group: string; percent: number | null; tasks: number; runs: number }; +export type ModelRank = { + rank: number; + model: string; + total_percent: number; + groups: GroupScore[]; + weakest_group: string | null; + runs: number; + successes: number; + median_duration_ms: number; + mean_completion_tokens: number; +}; +export type MatrixCell = { model: string; task_id: string; runs: number; successes: number; mean_score: number }; +export type TaskColumn = { id: string; group: string }; +export type Ranking = { + batch_id: number; + groups: string[]; + models: ModelRank[]; + cells: MatrixCell[]; + tasks: TaskColumn[]; +}; + +export type BatchEvent = + | { kind: "run_started"; model: string; task: string; repeat: number } + | { kind: "run_finished"; model: string; task: string; repeat: number; class: string; score: number } + | { kind: "run_skipped"; model: string; task: string; repeat: number } + | { kind: "model_unavailable"; model: string; reason: string } + | { kind: "progress"; done: number; total: number }; + +export const api = { + paths: () => invoke("get_paths"), + tasks: () => invoke("load_tasks"), + runtime: () => invoke("runtime_status"), + models: () => invoke("list_models"), + saveModels: (models: ModelEntry[]) => invoke("save_models", { models }), + testModel: (name: string) => invoke("test_model", { name }), + startBatch: (models: string[], taskIds: string[], repeats: number, note: string) => + invoke("start_batch", { models, taskIds, repeats, note }), + cancelBatch: () => invoke("cancel_batch"), + batches: () => invoke("list_batches"), + results: (batchId: number) => invoke("batch_results", { batchId }), + ranking: (batchId: number) => invoke("batch_ranking", { batchId }), + steps: (batchId: number, r: RunRow) => + invoke("run_steps", { batchId, model: r.model, taskId: r.task_id, repeatIdx: r.repeat_idx }), +}; + +/** Namen der Bereiche (Gruppen aus SPEC 11). */ +export const GROUP_LABELS: Record = { + A: "Tool-Calling", + B: "Kleine Coding-Aufgaben", + C: "Agent im Repo", + D: "Demos", + "?": "Unbekannt", +}; + +export function groupLabel(g: string): string { + return GROUP_LABELS[g] ?? g; +} + +/** Farbe für einen Prozentwert: rot bei 0, gelb in der Mitte, grün bei 100. */ +export function pctColor(p: number): string { + const hue = Math.max(0, Math.min(100, p)) * 1.2; + return `hsl(${hue} 60% 42%)`; +} + +export function fmtPct(p: number | null): string { + return p === null ? "–" : `${Math.round(p)} %`; +} + +export function fmtDuration(ms: number): string { + const s = ms / 1000; + return s < 90 ? `${s.toFixed(1)} s` : `${Math.floor(s / 60)} min ${Math.round(s % 60)} s`; +} diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte new file mode 100644 index 0000000..3fa208a --- /dev/null +++ b/src/routes/+layout.svelte @@ -0,0 +1,6 @@ + + +{@render children()} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index bf39d02..d454437 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -1,483 +1,123 @@ -
-

coding-bench

+
+
+ + +
+
-
-

Setup: Pfade

- {#if error} -

Fehler: {error}

- {:else if paths} -
-
Konfiguration
-
{paths.config_file}
-
Datenordner
-
{paths.data_dir}
-
Aufgabenordner
-
{paths.tasks_dir}
-
Container
-
- {#if runtime} - {#if runtime.available} - {runtime.program} verfügbar, {runtime.detail} - {:else} - {runtime.program} nicht nutzbar: {runtime.detail} - {/if} - {:else} - Prüfe … - {/if} -
-
- {:else} -

Lade Pfade …

- {/if} -
- -
-

Aufgaben

- {#if taskError} -

Fehler: {taskError}

- {:else if report} -

{report.tasks.length} gültig, {report.errors.length} mit Fehlern.

-
    - {#each report.tasks as t (t.dir)} -
  • - -
  • - {/each} -
- {#if report.errors.length > 0} -

Fehler

-
    - {#each report.errors as e (e.dir)} -
  • {e.dir}: {e.message}
  • - {/each} -
- {/if} - {:else} -

Lade Aufgaben …

- {/if} -
- -
-

Batch starten

- - -
- - +
+ {#if loadError} +

Start fehlgeschlagen: {loadError}

+ {:else if !loaded} +

Lade …

+ {:else} + + + + - - {#if progress} -

Fortschritt: {progress.done} von {progress.total}

- {/if} - {#if batchError} -

Fehler: {batchError}

- {/if} - {#if log.length > 0} -
    - {#each log as line, i (i)} -
  • {line}
  • - {/each} -
- {/if} -
- - {#if ranking && ranking.models.length > 0} -
-

Rangliste, Batch {ranking.batch_id}

- - - - - - - - - - - - - {#each ranking.models as m (m.model)} - - - - - - - - - {/each} - -
RangModellScoreErfolgeMedian-DauerØ Completion-Tokens
{m.rank}{m.model}{m.total_score.toFixed(2)}{m.successes} / {m.runs}{(m.median_duration_ms / 1000).toFixed(1)} s{m.mean_completion_tokens.toFixed(0)}
- -

Matrix: Erfolge je Aufgabe

- - - - - {#each ranking.tasks as t (t)} - - {/each} - - - - {#each ranking.models as m (m.model)} - - - {#each ranking.tasks as t (t)} - {@const cell = ranking.cells.find((c) => c.model === m.model && c.task_id === t)} - - {/each} - - {/each} - -
Modell{t}
{m.model} - {cell ? `${cell.successes}/${cell.runs}` : "–"} -
-
- {/if} - - {#if batchId !== null && rows.length > 0} -
-

Ergebnisse, Batch {batchId}

- - - - - - - - - - - - - - - {#each rows as r (`${r.model}|${r.task_id}|${r.repeat_idx}`)} - - - - - - - - - - - {/each} - -
ModellAufgabeWdh.KlasseScoreSchritteDauer
{r.model}{r.task_id}{r.repeat_idx}{r.error_class}{r.score.toFixed(2)}{r.steps}{(r.duration_ms / 1000).toFixed(1)} s
- - {#if detail} -

Schritte: {detail.model} · {detail.task_id} · Wdh. {detail.repeat_idx}

-
    - {#each detail.steps as st (st.idx)} -
  1. - {st.role} - {#if st.tool_name} - · Tool {st.tool_name} {st.tool_args_json ?? ""} - {/if} - {#if st.content} -
    {st.content}
    - {/if} - {#if st.tool_result} -
    {st.tool_result}
    - {/if} -
  2. - {/each} -
- {/if} -
{/if}