1 Commits

Author SHA1 Message Date
105a3a11a3 feat: Oberfläche neu, Modell-Adapter wählbar, Bewertung je Bereich
All checks were successful
release / deb (push) Successful in 3m59s
release / arch (push) Successful in 5m23s
Die erste Fassung der Oberfläche war inhaltlich und optisch schwach. Neu:
drei Reiter (Benchmark, Ergebnisse, Einstellungen). Modelle werden in den
Einstellungen mit Adapter (Ollama oder OpenAI-kompatibel), URL, Modell-ID
und Schlüssel-Variable angelegt, mit Verbindungstest. config.toml speichert
die Liste. Bewertung absolut in Prozent: ein Wert je Bereich A bis D und
eine Gesamtnote, gewichtet nach weight. Batch-Verlauf, Schritt-Ansicht,
Erklärung der Bewertung. 55 Unit-Tests grün, svelte-check ohne Fehler.
Im Browser mit Beispieldaten geprüft, nicht in der echten App.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 12:27:23 +01:00
16 changed files with 1878 additions and 625 deletions

View File

@ -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/<gruppe>/<name>/` (`task.toml`, `prompt.md`, `start/`, `check.sh`). Eine installierte Version findet die mitgelieferten Aufgaben unter `/usr/share/coding-bench/tasks`.
## References & Links

View File

@ -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)

View File

@ -644,13 +644,24 @@ pub fn to_openai_messages(messages: &[Message]) -> Vec<Value> {
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<String>) -> Result<OpenAiClient, String> {
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<ChatResponse, ModelError>
{
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'");

View File

@ -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<PathBuf>,
/// 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<ModelEntry>,
/// 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]

View File

@ -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<Config>,
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<AtomicBool>,
}
/// 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<Vec<ModelInfo>, 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<ModelEntry>) -> Result<Vec<ModelInfo>, String> {
let cleaned: Vec<ModelEntry> = 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<ModelTest, String> {
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<String>,
task_ids: Vec<String>,
@ -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<tasks::Task> = 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<Vec<BatchInfo>, 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<Vec<RunRecord>, 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<RuntimeStatus, String> {
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<ranking::Ranking, String> {
let store = Store::open(&paths.0.data_dir.join(DB_FILE))?;
let runs = store.runs_for_batch(batch_id)?;
let weights: std::collections::BTreeMap<String, f64> = tasks::load_all(&paths.0.tasks_dir)
let infos: BTreeMap<String, ranking::TaskInfo> = 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,

View File

@ -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<f64>,
/// 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<GroupScore>,
/// Bereich mit dem niedrigsten Wert, nur wenn das Modell mindestens zwei Bereiche hat.
pub weakest_group: Option<String>,
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<String>,
pub models: Vec<ModelRank>,
pub cells: Vec<MatrixCell>,
pub tasks: Vec<String>,
/// Aufgaben des Batches, sortiert nach Bereich und ID.
pub tasks: Vec<TaskColumn>,
}
/// 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<String, f64>) -> 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<String, TaskInfo>) -> 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<String, String> = 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<TaskColumn> = 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<String> = 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<String, f64
let mut models: Vec<ModelRank> = 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<String, (f64, f64, usize, usize)> = 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<GroupScore> = 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<u128> = 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::<f64>() / 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::<f64>() / 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<String, f64
m.rank = i + 1;
}
// Matrix Modell × Aufgabe.
let mut cell_map: BTreeMap<(&str, &str), Vec<&RunRecord>> = 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<String, f64
})
.collect();
Ranking {
batch_id,
models,
cells,
tasks: task_set.keys().map(|t| t.to_string()).collect(),
}
Ranking { batch_id, groups, models, cells, tasks: task_list }
}
fn median_u128(sorted: &[u128]) -> 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<String, TaskInfo> {
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);
}
}

View File

@ -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<String>,
}
/// 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<String>,
pub models: Vec<ModelConn>,
pub data_dir: PathBuf,
pub limits: Limits,
}
@ -123,8 +133,9 @@ pub fn run_batch(
) -> Result<BatchSummary, String> {
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::<Vec<_>>(),
"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<Box<dyn ModelClient>, 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<Box<dyn ModelClient>, 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<Box<dyn ModelClient>, 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(),
};

View File

@ -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::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}
/// Alle Batches, neueste zuerst.
pub fn list_batches(&self) -> Result<Vec<BatchInfo>, 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::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}
pub fn run_count(&self, batch_id: i64) -> Result<i64, String> {
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();

136
src/app.css Normal file
View File

@ -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; }

View File

@ -1,10 +1,10 @@
<!doctype html>
<html lang="en">
<html lang="de">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tauri + SvelteKit + Typescript App</title>
<title>coding-bench</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">

279
src/lib/BenchPanel.svelte Normal file
View File

@ -0,0 +1,279 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { api, groupLabel, type BatchEvent, type LoadReport, type ModelInfo, type TaskInfo } from "$lib/api";
let {
models,
tasks,
ongotosettings,
onfinished,
}: {
models: ModelInfo[];
tasks: LoadReport | null;
ongotosettings: () => void;
onfinished: (batchId: number) => void;
} = $props();
let chosenModels = $state<string[]>([]);
let chosenTasks = $state<string[]>([]);
let repeats = $state(1);
let running = $state(false);
let error = $state("");
let progress = $state<{ done: number; total: number } | null>(null);
let log = $state<{ text: string; cls: string }[]>([]);
let current = $state("");
let finishedBatch = $state<number | null>(null);
let cancelled = $state(false);
let unlisten: UnlistenFn | null = null;
onMount(async () => {
unlisten = await listen<BatchEvent>("batch-event", (ev) => onEvent(ev.payload));
});
onDestroy(() => unlisten?.());
function onEvent(e: BatchEvent) {
if (e.kind === "progress") {
progress = { done: e.done, total: e.total };
return;
}
if (e.kind === "model_unavailable") {
log.push({ text: `${e.model}: nicht erreichbar (${e.reason})`, cls: "error" });
return;
}
const label = `${e.model} · ${e.task} · Durchlauf ${e.repeat}`;
if (e.kind === "run_started") {
current = label;
} else if (e.kind === "run_skipped") {
log.push({ text: `übersprungen: ${label}`, cls: "muted" });
} else if (e.kind === "run_finished") {
const ok = e.class === "ok";
log.push({
text: `${ok ? "bestanden" : e.class}: ${label}, ${Math.round(e.score * 100)} %`,
cls: ok ? "ok" : "error",
});
current = "";
}
}
// Aufgaben nach Bereich gruppiert.
let byGroup = $derived.by(() => {
const m = new Map<string, TaskInfo[]>();
for (const t of tasks?.tasks ?? []) {
if (!m.has(t.group)) m.set(t.group, []);
m.get(t.group)!.push(t);
}
return [...m.entries()].sort((a, b) => a[0].localeCompare(b[0]));
});
function toggle(list: string[], id: string): string[] {
return list.includes(id) ? list.filter((x) => x !== id) : [...list, id];
}
function groupAll(group: string, on: boolean) {
const ids = (byGroup.find(([g]) => g === group)?.[1] ?? []).map((t) => t.id);
chosenTasks = on
? [...new Set([...chosenTasks, ...ids])]
: chosenTasks.filter((id) => !ids.includes(id));
}
let totalRuns = $derived(chosenModels.length * chosenTasks.length * repeats);
let canStart = $derived(!running && chosenModels.length > 0 && chosenTasks.length > 0 && repeats >= 1);
async function start() {
error = "";
log = [];
progress = null;
finishedBatch = null;
cancelled = false;
running = true;
try {
const s = await api.startBatch($state.snapshot(chosenModels), $state.snapshot(chosenTasks), repeats, "");
finishedBatch = s.batch_id;
cancelled = s.cancelled;
} catch (e) {
error = String(e);
} finally {
running = false;
current = "";
}
}
</script>
{#if models.length === 0}
<section class="card">
<h2>Noch kein Modell angebunden</h2>
<p class="muted">Bevor ein Benchmark laufen kann, braucht coding-bench mindestens ein Modell.</p>
<button class="primary" onclick={ongotosettings}>Modell in den Einstellungen anlegen</button>
</section>
{:else}
<section class="card">
<h2>1. Modelle</h2>
<div class="choices">
{#each models as m (m.name)}
<label class="choice">
<input
type="checkbox"
checked={chosenModels.includes(m.name)}
disabled={running}
onchange={() => (chosenModels = toggle(chosenModels, m.name))}
/>
<span>
<strong>{m.name}</strong>
<span class="muted">{m.adapter === "ollama" ? "Ollama" : "OpenAI-kompatibel"} · {m.url}</span>
</span>
</label>
{/each}
</div>
</section>
<section class="card">
<h2>2. Aufgaben</h2>
{#if !tasks}
<p class="muted">Lade Aufgaben …</p>
{:else if tasks.tasks.length === 0}
<p class="error">Keine gültigen Aufgaben gefunden.</p>
{/if}
{#each byGroup as [group, list] (group)}
<div class="group">
<div class="group-head">
<h3>{group} · {groupLabel(group)} <span class="muted">({list.length})</span></h3>
<button class="link" disabled={running} onclick={() => groupAll(group, true)}>alle</button>
<button class="link" disabled={running} onclick={() => groupAll(group, false)}>keine</button>
</div>
{#each list as t (t.id)}
<label class="choice">
<input
type="checkbox"
checked={chosenTasks.includes(t.id)}
disabled={running}
onchange={() => (chosenTasks = toggle(chosenTasks, t.id))}
/>
<span><strong>{t.id}</strong> {t.title}</span>
</label>
{/each}
</div>
{/each}
{#if tasks && tasks.errors.length > 0}
<details>
<summary class="error">{tasks.errors.length} Aufgabe(n) mit Fehlern</summary>
<ul>
{#each tasks.errors as e (e.dir)}
<li><code>{e.dir}</code>: {e.message}</li>
{/each}
</ul>
</details>
{/if}
</section>
<section class="card">
<h2>3. Starten</h2>
<div class="start">
<label>
Durchläufe je Aufgabe
<input type="number" min="1" max="20" bind:value={repeats} disabled={running} />
</label>
<p class="muted">
{#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.
</p>
<div class="buttons">
<button class="primary" onclick={start} disabled={!canStart}>Benchmark starten</button>
<button class="danger" onclick={() => api.cancelBatch()} disabled={!running}>Abbrechen</button>
</div>
</div>
{#if progress}
<div class="bar" role="progressbar" aria-valuenow={progress.done} aria-valuemax={progress.total}>
<div class="fill" style:width="{progress.total ? (100 * progress.done) / progress.total : 0}%"></div>
</div>
<p class="muted">{progress.done} von {progress.total} Läufen fertig</p>
{/if}
{#if current}<p>Läuft: <strong>{current}</strong></p>{/if}
{#if error}<p class="error">{error}</p>{/if}
{#if finishedBatch !== null}
<p>
{cancelled ? "Abgebrochen." : "Fertig."}
<button class="link" onclick={() => onfinished(finishedBatch!)}>Ergebnisse ansehen</button>
</p>
{/if}
{#if log.length > 0}
<ul class="log">
{#each log as l, i (i)}
<li class={l.cls}>{l.text}</li>
{/each}
</ul>
{/if}
</section>
{/if}
<style>
.choices {
display: grid;
gap: 0.4rem;
}
.choice {
display: flex;
align-items: baseline;
gap: 0.6rem;
padding: 0.25rem 0;
}
.choice .muted {
margin-left: 0.5rem;
font-size: 0.85rem;
}
.group {
margin-bottom: 0.9rem;
}
.group-head {
display: flex;
align-items: baseline;
gap: 0.8rem;
}
.group-head h3 {
flex: 1;
margin: 0;
}
.start label {
display: flex;
flex-direction: column;
gap: 0.2rem;
width: 12rem;
font-size: 0.85rem;
color: var(--muted);
}
.start input {
color: var(--text);
font-size: 1rem;
}
.buttons {
display: flex;
gap: 0.6rem;
margin-top: 0.6rem;
}
.bar {
height: 10px;
background: var(--surface-2);
border-radius: 999px;
overflow: hidden;
margin-top: 1rem;
}
.fill {
height: 100%;
background: var(--accent);
transition: width 0.3s;
}
.log {
list-style: none;
padding: 0.6rem;
margin: 0.8rem 0 0;
max-height: 18rem;
overflow-y: auto;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
font-family: ui-monospace, Menlo, monospace;
font-size: 0.85rem;
}
</style>

352
src/lib/ResultsPanel.svelte Normal file
View File

@ -0,0 +1,352 @@
<script lang="ts">
import { onMount, untrack } from "svelte";
import {
api,
fmtDuration,
fmtPct,
groupLabel,
pctColor,
type BatchInfo,
type Ranking,
type RunRow,
type StepRow,
} from "$lib/api";
let { selected = $bindable(null) }: { selected: number | null } = $props();
let batches = $state<BatchInfo[]>([]);
let ranking = $state<Ranking | null>(null);
let rows = $state<RunRow[]>([]);
let error = $state("");
let loading = $state(false);
let detail = $state<{ run: RunRow; steps: StepRow[] } | null>(null);
let showRuns = $state(false);
async function loadBatches() {
try {
batches = await api.batches();
if (selected === null && batches.length > 0) selected = batches[0].id;
} catch (e) {
error = String(e);
}
}
async function loadBatch(id: number | null) {
ranking = null;
rows = [];
detail = null;
if (id === null) return;
loading = true;
error = "";
try {
[ranking, rows] = await Promise.all([api.ranking(id), api.results(id)]);
} catch (e) {
error = String(e);
} finally {
loading = false;
}
}
onMount(loadBatches);
// Beim Wechsel des Batches neu laden. Neue Batches erscheinen nach dem Lauf in der Liste.
$effect(() => {
const id = selected;
untrack(() => {
loadBatch(id);
if (id !== null && !batches.some((b) => b.id === id)) loadBatches();
});
});
async function showSteps(run: RunRow) {
if (selected === null) return;
detail = { run, steps: await api.steps(selected, run) };
}
function cell(model: string, task: string) {
return ranking?.cells.find((c) => c.model === model && c.task_id === task);
}
function batchLabel(b: BatchInfo): string {
return `Batch ${b.id} · ${b.created_at.slice(0, 16)} · ${b.runs} Läufe`;
}
// Bereiche mit wenigen Aufgaben sind nur grobe Hinweise.
const FEW_TASKS = 3;
</script>
<section class="card">
<div class="head">
<h2>Bewertung</h2>
{#if batches.length > 0}
<select bind:value={selected} aria-label="Batch wählen">
{#each batches as b (b.id)}
<option value={b.id}>{batchLabel(b)}</option>
{/each}
</select>
{/if}
</div>
{#if error}<p class="error">{error}</p>{/if}
{#if batches.length === 0 && !error}
<p class="muted">Noch keine Ergebnisse. Starte im Reiter „Benchmark“ einen Lauf.</p>
{/if}
{#if loading}<p class="muted">Lade …</p>{/if}
{#if ranking && ranking.models.length > 0}
<div class="scroll">
<table class="rank">
<thead>
<tr>
<th class="num">#</th>
<th>Modell</th>
<th class="total">Gesamt</th>
{#each ranking.groups as g (g)}
<th class="grp" title={groupLabel(g)}>{g}<br /><span class="gl">{groupLabel(g)}</span></th>
{/each}
<th>Schwächster Bereich</th>
<th class="num">Bestanden</th>
<th class="num">Median-Dauer</th>
</tr>
</thead>
<tbody>
{#each ranking.models as m (m.model)}
<tr>
<td class="num">{m.rank}</td>
<td><strong>{m.model}</strong></td>
<td class="total">
<div class="pct big" style:color={pctColor(m.total_percent)}>{fmtPct(m.total_percent)}</div>
<div class="meter"><div style:width="{m.total_percent}%" style:background={pctColor(m.total_percent)}></div></div>
</td>
{#each m.groups as g (g.group)}
<td class="grp">
{#if g.percent === null}
<span class="muted">–</span>
{:else}
<div class="pct" style:color={pctColor(g.percent)}>{fmtPct(g.percent)}</div>
<div class="meter small"><div style:width="{g.percent}%" style:background={pctColor(g.percent)}></div></div>
<div class="n" class:few={g.tasks < FEW_TASKS} title={g.tasks < FEW_TASKS ? "Wenige Aufgaben: der Wert ist nur ein grober Hinweis." : ""}>
{g.tasks} Aufg.{g.tasks < FEW_TASKS ? " (grob)" : ""}
</div>
{/if}
</td>
{/each}
<td>
{#if m.weakest_group}
{m.weakest_group} · {groupLabel(m.weakest_group)}
{:else}
<span class="muted">–</span>
{/if}
</td>
<td class="num">{m.successes} / {m.runs}</td>
<td class="num">{fmtDuration(m.median_duration_ms)}</td>
</tr>
{/each}
</tbody>
</table>
</div>
<details class="how">
<summary>So wird bewertet</summary>
<ul>
<li>
Die Bewertung ist <strong>absolut</strong>, nicht im Vergleich zu einem Referenzmodell. 100 % heißt: alle
Prüfungen der Aufgaben bestanden.
</li>
<li>
Je Aufgabe zählt der Mittelwert der Durchläufe. Teilpunkte aus <code>check.sh</code> gehen anteilig ein.
</li>
<li>
Wert je Bereich: gewichteter Mittelwert der Aufgaben im Bereich. Gesamt: gewichteter Mittelwert über alle
Aufgaben des Batches. Die Gewichte stehen als <code>weight</code> in <code>task.toml</code>.
</li>
<li>Fehlt einem Modell ein Bereich, bleibt das Feld leer und zählt nicht in die Gesamtnote.</li>
<li>Die Reihenfolge richtet sich nach der Gesamtnote. Bei Gleichstand gewinnt die kürzere Median-Dauer.</li>
<li>Bereiche mit weniger als {FEW_TASKS} Aufgaben sind nur grobe Hinweise.</li>
</ul>
</details>
<h3>Aufgaben im Detail</h3>
<div class="scroll">
<table class="matrix">
<thead>
<tr>
<th>Modell</th>
{#each ranking.tasks as t (t.id)}
<th class="num" title={groupLabel(t.group)}>{t.id}</th>
{/each}
</tr>
</thead>
<tbody>
{#each ranking.models as m (m.model)}
<tr>
<td>{m.model}</td>
{#each ranking.tasks as t (t.id)}
{@const c = cell(m.model, t.id)}
<td
class="num"
style:background={c ? `color-mix(in srgb, ${pctColor(c.mean_score * 100)} 28%, transparent)` : ""}
title={c ? `${Math.round(c.mean_score * 100)} %, ${c.successes} von ${c.runs} bestanden` : "keine Läufe"}
>
{c ? `${Math.round(c.mean_score * 100)} %` : "–"}
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
<h3>
Einzelne Läufe
<button class="link" onclick={() => (showRuns = !showRuns)}>{showRuns ? "ausblenden" : `anzeigen (${rows.length})`}</button>
</h3>
{#if showRuns}
<div class="scroll">
<table>
<thead>
<tr>
<th>Modell</th>
<th>Aufgabe</th>
<th class="num">Durchlauf</th>
<th>Ergebnis</th>
<th class="num">Score</th>
<th class="num">Schritte</th>
<th class="num">Dauer</th>
<th></th>
</tr>
</thead>
<tbody>
{#each rows as r (`${r.model}|${r.task_id}|${r.repeat_idx}`)}
<tr>
<td>{r.model}</td>
<td>{r.task_id}</td>
<td class="num">{r.repeat_idx}</td>
<td class={r.error_class === "ok" ? "ok" : "error"}>{r.error_class === "ok" ? "bestanden" : r.error_class}</td>
<td class="num">{Math.round(r.score * 100)} %</td>
<td class="num">{r.steps}</td>
<td class="num">{fmtDuration(r.duration_ms)}</td>
<td><button onclick={() => showSteps(r)}>Schritte</button></td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
{#if detail}
<div class="detail">
<h3>
Schritte: {detail.run.model} · {detail.run.task_id} · Durchlauf {detail.run.repeat_idx}
<button class="link" onclick={() => (detail = null)}>schließen</button>
</h3>
{#if detail.run.check_output}
<p class="muted">Prüfung (<code>check.sh</code>):</p>
<pre>{detail.run.check_output}</pre>
{/if}
<ol class="steps">
{#each detail.steps as st (st.idx)}
<li>
<strong>{st.role}</strong>
{#if st.tool_name}<span class="chip">{st.tool_name}</span> <code>{st.tool_args_json ?? ""}</code>{/if}
{#if st.content}<pre>{st.content}</pre>{/if}
</li>
{/each}
</ol>
</div>
{/if}
{:else if ranking && !loading}
<p class="muted">Dieser Batch hat noch keine fertigen Läufe.</p>
{/if}
</section>
<style>
.head {
display: flex;
gap: 1rem;
align-items: center;
flex-wrap: wrap;
margin-bottom: 0.8rem;
}
.head h2 {
margin: 0;
flex: 1;
}
.head select {
max-width: 100%;
}
.scroll {
overflow-x: auto;
margin-bottom: 1rem;
}
.rank td,
.rank th {
vertical-align: top;
}
.matrix th {
text-transform: none;
}
.rank .total {
min-width: 7.5rem;
}
.rank .grp {
min-width: 6rem;
}
.gl {
font-weight: 400;
text-transform: none;
letter-spacing: 0;
}
.pct {
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.pct.big {
font-size: 1.6rem;
line-height: 1.1;
}
.meter {
height: 7px;
background: var(--surface-2);
border-radius: 999px;
overflow: hidden;
margin: 0.25rem 0;
}
.meter.small {
height: 5px;
}
.meter > div {
height: 100%;
}
.n {
font-size: 0.75rem;
color: var(--muted);
}
.n.few {
color: var(--danger);
}
.how {
margin: 0.5rem 0 1.2rem;
color: var(--muted);
}
.how summary {
cursor: pointer;
}
.detail {
margin-top: 1rem;
border-top: 1px solid var(--border);
padding-top: 1rem;
}
.steps pre,
.detail > pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
max-height: 12rem;
overflow-y: auto;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.5rem;
margin: 0.3rem 0;
}
</style>

View File

@ -0,0 +1,232 @@
<script lang="ts">
import { api, type ModelEntry, type ModelInfo, type ModelTest, type Paths, type RuntimeStatus } from "$lib/api";
let {
models,
paths,
runtime,
onsaved,
}: {
models: ModelInfo[];
paths: Paths | null;
runtime: RuntimeStatus | null;
onsaved: (m: ModelInfo[]) => void;
} = $props();
const ADAPTERS = [
{ id: "ollama", label: "Ollama", hint: "http://host:11434" },
{ id: "openai", label: "OpenAI-kompatibel", hint: "http://host:8082/v1" },
];
function toEntry(m: ModelInfo): ModelEntry {
return { name: m.name, adapter: m.adapter, url: m.url, model: m.model, api_key_env: m.api_key_env };
}
// Bearbeitungsstand: Kopie beim Öffnen, bewusst vom Original gelöst. Gilt erst nach „Speichern“.
// svelte-ignore state_referenced_locally
let draft = $state<ModelEntry[]>(models.map(toEntry));
let dirty = $state(false);
let saveError = $state("");
let saving = $state(false);
let tests = $state<Record<string, ModelTest | "läuft">>({});
function markDirty() {
dirty = true;
saveError = "";
}
function addModel() {
draft.push({ name: "", adapter: "ollama", url: "", model: "", api_key_env: "" });
markDirty();
}
function removeModel(i: number) {
draft.splice(i, 1);
markDirty();
}
function hintFor(adapter: string): string {
return ADAPTERS.find((a) => a.id === adapter)?.hint ?? "";
}
async function save() {
saving = true;
saveError = "";
try {
const saved = await api.saveModels($state.snapshot(draft));
draft = saved.map(toEntry);
dirty = false;
onsaved(saved);
} catch (e) {
saveError = String(e);
} finally {
saving = false;
}
}
async function test(name: string) {
tests[name] = "läuft";
try {
tests[name] = await api.testModel(name);
} catch (e) {
tests[name] = { ok: false, duration_ms: 0, message: String(e) };
}
}
function savedInfo(name: string): ModelInfo | undefined {
return models.find((m) => m.name === name);
}
</script>
<section class="card">
<h2>Modelle</h2>
<p class="muted">
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.
</p>
{#if draft.length === 0}
<p class="muted">Noch kein Modell angebunden.</p>
{/if}
{#each draft as m, i (i)}
<div class="model">
<div class="grid">
<label>
Name
<input bind:value={m.name} oninput={markDirty} placeholder="z. B. Qwen3 lokal" />
</label>
<label>
Adapter
<select bind:value={m.adapter} onchange={markDirty}>
{#each ADAPTERS as a (a.id)}
<option value={a.id}>{a.label}</option>
{/each}
</select>
</label>
<label class="wide">
Server-URL
<input bind:value={m.url} oninput={markDirty} placeholder={hintFor(m.adapter)} />
</label>
<label>
Modell-ID beim Server
<input bind:value={m.model} oninput={markDirty} placeholder="leer = Name" />
</label>
<label>
Schlüssel-Variable
<input bind:value={m.api_key_env} oninput={markDirty} placeholder="leer = kein Schlüssel" />
</label>
</div>
<div class="row">
{#if m.api_key_env && savedInfo(m.name)}
{#if savedInfo(m.name)?.api_key_set}
<span class="chip ok">Schlüssel gefunden</span>
{:else}
<span class="chip error">Variable {m.api_key_env} ist nicht gesetzt</span>
{/if}
{/if}
<span class="spacer"></span>
{#if tests[m.name] === "läuft"}
<span class="muted">teste …</span>
{:else if tests[m.name]}
{@const t = tests[m.name] as ModelTest}
<span class={t.ok ? "ok" : "error"}>
{t.ok ? "Verbunden" : "Fehler"}: {t.message}
{#if t.duration_ms}({(t.duration_ms / 1000).toFixed(1)} s){/if}
</span>
{/if}
<button onclick={() => test(m.name)} disabled={dirty || !savedInfo(m.name)} title={dirty ? "Erst speichern" : ""}>
Verbindung testen
</button>
<button class="danger" onclick={() => removeModel(i)}>Entfernen</button>
</div>
</div>
{/each}
<div class="row">
<button onclick={addModel}>Modell hinzufügen</button>
<span class="spacer"></span>
{#if saveError}<span class="error">{saveError}</span>{/if}
{#if dirty}<span class="muted">Ungespeicherte Änderungen</span>{/if}
<button class="primary" onclick={save} disabled={!dirty || saving}>Speichern</button>
</div>
</section>
<section class="card">
<h2>System</h2>
<dl>
<dt>Container</dt>
<dd>
{#if runtime}
{#if runtime.available}
<span class="ok">{runtime.program} bereit, {runtime.detail}</span>
{:else}
<span class="error">{runtime.program} nicht nutzbar: {runtime.detail}</span>
{/if}
{:else}
<span class="muted">Prüfe …</span>
{/if}
</dd>
{#if paths}
<dt>Konfiguration</dt>
<dd><code>{paths.config_file}</code></dd>
<dt>Datenordner</dt>
<dd><code>{paths.data_dir}</code></dd>
<dt>Aufgabenordner</dt>
<dd><code>{paths.tasks_dir}</code></dd>
{/if}
</dl>
</section>
<style>
.model {
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.8rem;
margin-bottom: 0.8rem;
background: var(--bg);
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.6rem 0.8rem;
}
.grid .wide {
grid-column: 1 / -1;
}
label {
display: flex;
flex-direction: column;
gap: 0.2rem;
font-size: 0.85rem;
color: var(--muted);
}
label input,
label select {
color: var(--text);
font-size: 1rem;
}
.row {
display: flex;
align-items: center;
gap: 0.6rem;
margin-top: 0.7rem;
flex-wrap: wrap;
}
.spacer {
flex: 1;
}
dl {
display: grid;
grid-template-columns: max-content 1fr;
gap: 0.4rem 1.2rem;
margin: 0;
}
dt {
color: var(--muted);
}
dd {
margin: 0;
overflow-wrap: anywhere;
}
</style>

127
src/lib/api.ts Normal file
View File

@ -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<Paths>("get_paths"),
tasks: () => invoke<LoadReport>("load_tasks"),
runtime: () => invoke<RuntimeStatus>("runtime_status"),
models: () => invoke<ModelInfo[]>("list_models"),
saveModels: (models: ModelEntry[]) => invoke<ModelInfo[]>("save_models", { models }),
testModel: (name: string) => invoke<ModelTest>("test_model", { name }),
startBatch: (models: string[], taskIds: string[], repeats: number, note: string) =>
invoke<BatchSummary>("start_batch", { models, taskIds, repeats, note }),
cancelBatch: () => invoke<boolean>("cancel_batch"),
batches: () => invoke<BatchInfo[]>("list_batches"),
results: (batchId: number) => invoke<RunRow[]>("batch_results", { batchId }),
ranking: (batchId: number) => invoke<Ranking>("batch_ranking", { batchId }),
steps: (batchId: number, r: RunRow) =>
invoke<StepRow[]>("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<string, string> = {
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`;
}

View File

@ -0,0 +1,6 @@
<script lang="ts">
import "../app.css";
let { children } = $props();
</script>
{@render children()}

View File

@ -1,483 +1,123 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { onMount } from "svelte";
import { api, type LoadReport, type ModelInfo, type Paths, type RuntimeStatus } from "$lib/api";
import BenchPanel from "$lib/BenchPanel.svelte";
import ResultsPanel from "$lib/ResultsPanel.svelte";
import SettingsPanel from "$lib/SettingsPanel.svelte";
type Paths = {
config_file: string;
data_dir: string;
tasks_dir: string;
};
type TaskInfo = { id: string; title: string; group: string; dir: string };
type TaskError = { dir: string; message: string };
type LoadReport = { tasks: TaskInfo[]; errors: TaskError[] };
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 };
type RunRow = {
model: string;
task_id: string;
repeat_idx: number;
error_class: string;
score: number;
steps: number;
duration_ms: number;
tps: number | null;
};
type Tab = "bench" | "results" | "settings";
let tab = $state<Tab>("bench");
let loaded = $state(false);
let loadError = $state("");
let models = $state<ModelInfo[]>([]);
let tasks = $state<LoadReport | null>(null);
let paths = $state<Paths | null>(null);
let error = $state("");
let report = $state<LoadReport | null>(null);
let taskError = $state("");
let modelsText = $state("qwen3:0.6b");
let selected = $state<string[]>([]);
let repeats = $state(1);
let running = $state(false);
let log = $state<string[]>([]);
let progress = $state<{ done: number; total: number } | null>(null);
let batchId = $state<number | null>(null);
let rows = $state<RunRow[]>([]);
type ModelRank = {
rank: number;
model: string;
total_score: number;
runs: number;
successes: number;
median_duration_ms: number;
mean_completion_tokens: number;
};
type MatrixCell = { model: string; task_id: string; runs: number; successes: number; mean_score: number };
type Ranking = { batch_id: number; models: ModelRank[]; cells: MatrixCell[]; tasks: string[] };
let ranking = $state<Ranking | null>(null);
type RuntimeStatus = { program: string; available: boolean; detail: string };
type StepRow = {
idx: number;
role: string;
content: string;
tool_name: string | null;
tool_args_json: string | null;
tool_result: string | null;
};
let runtime = $state<RuntimeStatus | null>(null);
let detail = $state<{ model: string; task_id: string; repeat_idx: number; steps: StepRow[] } | null>(null);
let batchError = $state("");
let unlisten: UnlistenFn | null = null;
let selectedBatch = $state<number | null>(null);
onMount(async () => {
try {
paths = await invoke<Paths>("get_paths");
[models, tasks, paths] = await Promise.all([api.models(), api.tasks(), api.paths()]);
runtime = await api.runtime();
// Ohne Modell beginnt man bei den Einstellungen.
if (models.length === 0) tab = "settings";
} catch (e) {
error = String(e);
}
try {
runtime = await invoke<RuntimeStatus>("runtime_status");
} catch (e) {
runtime = { program: "?", available: false, detail: String(e) };
}
try {
report = await invoke<LoadReport>("load_tasks");
} catch (e) {
taskError = String(e);
}
unlisten = await listen<BatchEvent>("batch-event", (ev) => onEvent(ev.payload));
});
onDestroy(() => {
if (unlisten) unlisten();
});
function onEvent(e: BatchEvent) {
if (e.kind === "progress") {
progress = { done: e.done, total: e.total };
return;
}
if (e.kind === "model_unavailable") {
log = [...log, `Modell ${e.model} nicht nutzbar: ${e.reason}`];
return;
}
const label = `${e.model} · ${e.task} · Wdh. ${e.repeat}`;
if (e.kind === "run_started") log = [...log, `läuft: ${label}`];
if (e.kind === "run_skipped") log = [...log, `übersprungen: ${label}`];
if (e.kind === "run_finished")
log = [...log, `fertig: ${label} → ${e.class}, Score ${e.score.toFixed(2)}`];
}
function toggleTask(id: string) {
selected = selected.includes(id)
? selected.filter((x) => x !== id)
: [...selected, id];
}
function parseModels(): string[] {
return modelsText
.split(/[\n,]/)
.map((m) => m.trim())
.filter((m) => m.length > 0);
}
async function start() {
batchError = "";
rows = [];
ranking = null;
log = [];
progress = null;
batchId = null;
running = true;
try {
const summary = await invoke<{ batch_id: number; cancelled: boolean }>("start_batch", {
models: parseModels(),
taskIds: selected,
repeats,
note: "",
});
batchId = summary.batch_id;
rows = await invoke<RunRow[]>("batch_results", { batchId: summary.batch_id });
ranking = await invoke<Ranking>("batch_ranking", { batchId: summary.batch_id });
if (summary.cancelled) log = [...log, "Batch abgebrochen."];
} catch (e) {
batchError = String(e);
loadError = String(e);
} finally {
running = false;
loaded = true;
}
});
function showResults(batchId: number) {
selectedBatch = batchId;
tab = "results";
}
async function showSteps(r: RunRow) {
if (batchId === null) return;
const steps = await invoke<StepRow[]>("run_steps", {
batchId,
model: r.model,
taskId: r.task_id,
repeatIdx: r.repeat_idx,
});
detail = { model: r.model, task_id: r.task_id, repeat_idx: r.repeat_idx, steps };
}
async function cancel() {
await invoke<boolean>("cancel_batch");
}
const tabs: { id: Tab; label: string }[] = [
{ id: "bench", label: "Benchmark" },
{ id: "results", label: "Ergebnisse" },
{ id: "settings", label: "Einstellungen" },
];
</script>
<main class="container">
<h1>coding-bench</h1>
<header>
<div class="inner">
<span class="logo">coding-bench</span>
<nav>
{#each tabs as t (t.id)}
<button class="tab" class:active={tab === t.id} onclick={() => (tab = t.id)}>{t.label}</button>
{/each}
</nav>
</div>
</header>
<section>
<h2>Setup: Pfade</h2>
{#if error}
<p class="fehler">Fehler: {error}</p>
{:else if paths}
<dl>
<dt>Konfiguration</dt>
<dd><code>{paths.config_file}</code></dd>
<dt>Datenordner</dt>
<dd><code>{paths.data_dir}</code></dd>
<dt>Aufgabenordner</dt>
<dd><code>{paths.tasks_dir}</code></dd>
<dt>Container</dt>
<dd>
{#if runtime}
{#if runtime.available}
<span class="ok">{runtime.program} verfügbar, {runtime.detail}</span>
{:else}
<span class="fehler">{runtime.program} nicht nutzbar: {runtime.detail}</span>
{/if}
{:else}
Prüfe …
{/if}
</dd>
</dl>
{:else}
<p>Lade Pfade …</p>
{/if}
</section>
<section>
<h2>Aufgaben</h2>
{#if taskError}
<p class="fehler">Fehler: {taskError}</p>
{:else if report}
<p>{report.tasks.length} gültig, {report.errors.length} mit Fehlern.</p>
<ul class="tasks">
{#each report.tasks as t (t.dir)}
<li>
<label>
<input
type="checkbox"
checked={selected.includes(t.id)}
onchange={() => toggleTask(t.id)}
disabled={running}
/>
<strong>{t.id}</strong> · {t.title} <span class="gruppe">Gruppe {t.group}</span>
</label>
</li>
{/each}
</ul>
{#if report.errors.length > 0}
<h3>Fehler</h3>
<ul class="fehler">
{#each report.errors as e (e.dir)}
<li><code>{e.dir}</code>: {e.message}</li>
{/each}
</ul>
{/if}
{:else}
<p>Lade Aufgaben …</p>
{/if}
</section>
<section>
<h2>Batch starten</h2>
<label class="feld">
Modelle (Komma oder Zeilenumbruch)
<textarea rows="2" bind:value={modelsText} disabled={running}></textarea>
</label>
<label class="feld">
Wiederholungen
<input type="number" min="1" max="20" bind:value={repeats} disabled={running} />
</label>
<div class="knöpfe">
<button onclick={start} disabled={running || selected.length === 0 || parseModels().length === 0}>
Starten
</button>
<button onclick={cancel} disabled={!running}>Abbrechen</button>
<main>
{#if loadError}
<section class="card"><p class="error">Start fehlgeschlagen: {loadError}</p></section>
{:else if !loaded}
<p class="muted">Lade …</p>
{:else}
<!-- Reiter bleiben gemountet, damit ein laufender Batch beim Wechsel nicht abreißt. -->
<div hidden={tab !== "bench"}>
<BenchPanel {models} {tasks} ongotosettings={() => (tab = "settings")} onfinished={showResults} />
</div>
<div hidden={tab !== "results"}>
<ResultsPanel bind:selected={selectedBatch} />
</div>
<div hidden={tab !== "settings"}>
<SettingsPanel {models} {paths} {runtime} onsaved={(m) => (models = m)} />
</div>
{#if progress}
<p>Fortschritt: {progress.done} von {progress.total}</p>
{/if}
{#if batchError}
<p class="fehler">Fehler: {batchError}</p>
{/if}
{#if log.length > 0}
<ul class="log">
{#each log as line, i (i)}
<li>{line}</li>
{/each}
</ul>
{/if}
</section>
{#if ranking && ranking.models.length > 0}
<section>
<h2>Rangliste, Batch {ranking.batch_id}</h2>
<table>
<thead>
<tr>
<th>Rang</th>
<th>Modell</th>
<th>Score</th>
<th>Erfolge</th>
<th>Median-Dauer</th>
<th>Ø Completion-Tokens</th>
</tr>
</thead>
<tbody>
{#each ranking.models as m (m.model)}
<tr>
<td>{m.rank}</td>
<td>{m.model}</td>
<td>{m.total_score.toFixed(2)}</td>
<td>{m.successes} / {m.runs}</td>
<td>{(m.median_duration_ms / 1000).toFixed(1)} s</td>
<td>{m.mean_completion_tokens.toFixed(0)}</td>
</tr>
{/each}
</tbody>
</table>
<h3>Matrix: Erfolge je Aufgabe</h3>
<table class="matrix">
<thead>
<tr>
<th>Modell</th>
{#each ranking.tasks as t (t)}
<th>{t}</th>
{/each}
</tr>
</thead>
<tbody>
{#each ranking.models as m (m.model)}
<tr>
<td>{m.model}</td>
{#each ranking.tasks as t (t)}
{@const cell = ranking.cells.find((c) => c.model === m.model && c.task_id === t)}
<td
class="zelle"
style={cell ? `background: color-mix(in srgb, #2e7d32 ${Math.round(cell.mean_score * 100)}%, transparent)` : ""}
title={cell ? `Score ${cell.mean_score.toFixed(2)}` : "keine Läufe"}
>
{cell ? `${cell.successes}/${cell.runs}` : "–"}
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
</section>
{/if}
{#if batchId !== null && rows.length > 0}
<section>
<h2>Ergebnisse, Batch {batchId}</h2>
<table>
<thead>
<tr>
<th>Modell</th>
<th>Aufgabe</th>
<th>Wdh.</th>
<th>Klasse</th>
<th>Score</th>
<th>Schritte</th>
<th>Dauer</th>
<th></th>
</tr>
</thead>
<tbody>
{#each rows as r (`${r.model}|${r.task_id}|${r.repeat_idx}`)}
<tr>
<td>{r.model}</td>
<td>{r.task_id}</td>
<td>{r.repeat_idx}</td>
<td>{r.error_class}</td>
<td>{r.score.toFixed(2)}</td>
<td>{r.steps}</td>
<td>{(r.duration_ms / 1000).toFixed(1)} s</td>
<td><button onclick={() => showSteps(r)}>Schritte</button></td>
</tr>
{/each}
</tbody>
</table>
{#if detail}
<h3>Schritte: {detail.model} · {detail.task_id} · Wdh. {detail.repeat_idx}</h3>
<ol class="schritte">
{#each detail.steps as st (st.idx)}
<li>
<strong>{st.role}</strong>
{#if st.tool_name}
· Tool <code>{st.tool_name}</code> <code>{st.tool_args_json ?? ""}</code>
{/if}
{#if st.content}
<pre>{st.content}</pre>
{/if}
{#if st.tool_result}
<pre class="ergebnis">{st.tool_result}</pre>
{/if}
</li>
{/each}
</ol>
{/if}
</section>
{/if}
</main>
<style>
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
color: #0f0f0f;
background-color: #f6f6f6;
-webkit-text-size-adjust: 100%;
header {
background: var(--surface);
border-bottom: 1px solid var(--border);
position: sticky;
top: 0;
z-index: 5;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
}
.container {
.inner {
max-width: 62rem;
margin: 0 auto;
padding: 2rem 1rem;
max-width: 48rem;
padding: 0 1rem;
display: flex;
align-items: center;
gap: 2rem;
}
section {
margin-bottom: 2rem;
.logo {
font-weight: 700;
letter-spacing: 0.01em;
}
dl {
display: grid;
grid-template-columns: max-content 1fr;
gap: 0.4rem 1rem;
nav {
display: flex;
gap: 0.2rem;
}
dt {
.tab {
border: none;
border-bottom: 3px solid transparent;
border-radius: 0;
background: none;
padding: 0.9rem 1rem 0.75rem;
color: var(--muted);
}
.tab:hover:not(:disabled) {
color: var(--text);
border-color: transparent;
}
.tab.active {
color: var(--text);
border-bottom-color: var(--accent);
font-weight: 600;
}
dd {
margin: 0;
overflow-wrap: anywhere;
main {
max-width: 62rem;
margin: 0 auto;
padding: 1.2rem 1rem 3rem;
}
.tasks {
list-style: none;
padding: 0;
}
.feld {
display: flex;
flex-direction: column;
gap: 0.3rem;
margin-bottom: 0.8rem;
}
.knöpfe {
display: flex;
gap: 0.6rem;
margin-bottom: 0.8rem;
}
.log {
max-height: 16rem;
overflow-y: auto;
font-family: monospace;
font-size: 0.85rem;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
text-align: left;
padding: 0.3rem 0.5rem;
border-bottom: 1px solid #8884;
}
.fehler {
color: #c62828;
}
.ok {
color: #2e7d32;
}
.schritte pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
max-height: 12rem;
overflow-y: auto;
background: #8881;
padding: 0.4rem;
margin: 0.3rem 0;
font-size: 0.85rem;
}
.matrix .zelle {
text-align: center;
font-variant-numeric: tabular-nums;
[hidden] {
display: none !important;
}
</style>