11 Commits

Author SHA1 Message Date
89af0fc53e Sandbox härten (#1043): cap-drop=ALL, no-new-privileges, Nur-Lesen-Wurzel, tmpfs mit Größenlimit für /work, /tmp, /checks; Tests gegen echtes Podman
All checks were successful
release / deb (push) Successful in 3m58s
release / arch (push) Successful in 5m16s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 11:19:01 +01:00
9b0d5e695d Sandbox: Prüfung in frischem Container (#1044), Export mit Zeitlimit, alte Artefaktreste werden entfernt
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 11:13:49 +01:00
53fdf4d060 Referenz: externe Läufe exportieren und importieren, Referenz ohne Rang mit Strich im Ranking, Reiter Referenz; Roadmap 0.1.1
All checks were successful
release / deb (push) Successful in 4m3s
release / arch (push) Successful in 5m33s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 11:04:12 +01:00
bc461a404f ROADMAP/KLICKTESTS: GUI-Überarbeitung nachgezogen, neue Todos #1048-#1050, Klicktests aufgaben2plan und einstellungen2bereitschaft
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:25:52 +01:00
e322a14030 GUI: abgebrochenen oder teils ausgefallenen Batch fortsetzen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:25:25 +01:00
52b13bd269 GUI: Einstellungen mit Bereitschafts-Ampel, einklappbaren Modellkarten und Modell-Liste vom Server
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:25:00 +01:00
10b0b1ce8e GUI: Aufgabenkarten mit Beschreibung, Plan-und-Stand-Matrix, feste Startleiste mit Zeitschätzung, Hinweis bei wenigen Durchläufen, klickbare Ergebnis-Zellen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 17:54:17 +01:00
0832b8c96f GUI: dunkles Theme mit orangem Akzent, Ranking als Karten mit Tok/s, Logo und Icons, Start immer auf Benchmark
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 17:52:14 +01:00
ea4fb724d4 fix: Review-Befunde beheben (Image-Bau, Absturzsicherung, Image-Name, Ausgabelimit)
All checks were successful
release / deb (push) Successful in 3m57s
release / arch (push) Successful in 5m19s
- App baut cb-python selbst: Containerfile eingebettet, Befehle image_status
  und build_image, Live-Ausgabe, Knopf in den Einstellungen. start_batch
  prüft vorher, ob die Images da sind.
- running-Flag wird per Wächter zurückgesetzt, auch nach einem Absturz.
- Ein Fehler in einem Lauf beendet nicht mehr den Batch: Lauf wird als
  sandbox_error gespeichert. endpoint_error und sandbox_error zählen nicht
  in die Bewertung und werden beim Fortsetzen wiederholt.
- Image-Name wird geprüft (kein führendes -, nur erlaubte Zeichen), Podman
  bekommt -- vor dem Image.
- Ausgabe von Befehlen wird auf 1 MiB je Strom begrenzt.
- Abbruch wird auch vor dem Aufwärmen geprüft.
- Fehlerklassen lesbar, Hinweis auf nicht gewertete Läufe.
65 Unit-Tests grün (6 ignorierte Integrationstests); echter Sandbox- und Image-Test grün.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 13:15:11 +01:00
bd5afd44c9 docs: README-Aussage zum Ranking korrigieren
Der Satz nannte ein Intervall, das es nicht gibt (Wilson-Intervall ist
F-12, Phase 2). Gefunden vom Reality-Check-Agenten, im Code bestätigt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 12:39:02 +01:00
78388a67b8 build: Arch-Paket im Workflow wirklich hochladen
Das Paket wurde nach <repo>/src/ kopiert, einem Ordner, den es im Repo schon
gibt (Frontend). Der Upload suchte im Wurzelverzeichnis und fand nichts,
der Job meldete trotzdem Erfolg. Jetzt eigener Ordner dist/ und der Upload
schlägt fehl, wenn keine Datei da ist.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 12:38:50 +01:00
42 changed files with 2916 additions and 371 deletions

View File

@ -50,8 +50,12 @@ jobs:
cp packaging/arch/PKGBUILD /tmp/coding-bench-$VERSION.tar.gz /home/builder/pkg/
chown -R builder:builder /home/builder/pkg
su builder -c "cd /home/builder/pkg && makepkg -s --noconfirm -f"
cp /home/builder/pkg/*.pkg.tar.zst src/
# Eigener Ordner: Im Repo gibt es selbst ein src/ (Frontend), dorthin darf das Paket nicht.
mkdir -p "$GITHUB_WORKSPACE/dist"
cp /home/builder/pkg/*.pkg.tar.zst "$GITHUB_WORKSPACE/dist/"
ls -l "$GITHUB_WORKSPACE/dist/"
- uses: actions/upload-artifact@v3
with:
name: coding-bench-arch
path: src/*.pkg.tar.zst
path: dist/*.pkg.tar.zst
if-no-files-found: error

View File

@ -69,3 +69,37 @@ für einen Block aufweichen; das steht dann im Todo.
| Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- |
| ergebnis2detail.1 | Ergebnisansicht öffnen, Rangliste und Matrix prüfen | Rang, Gesamtscore und Matrix-Farben stimmen mit den Läufen überein | manuell |
## aufgaben2plan
**Zweck:** Vor und während eines Laufs ist sichtbar, was getestet wird, was geplant ist und was schon gelaufen ist.
**Deckt ab:** #1008, #1009
**Voraussetzung:** Modell angebunden, Container-Image gebaut, mindestens ein früherer Batch.
| Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- |
| aufgaben2plan.1 | Reiter „Benchmark“ öffnen, bei einer Aufgabe „Aufgabentext“ klicken | Karte zeigt Titel, Text, Schritt- und Zeitlimit, „zuletzt“ oder „noch nie gelaufen“ | manuell |
| aufgaben2plan.2 | Zwei Modelle und drei Aufgaben wählen, starten | Matrix „Plan und Stand“ zeigt erst „zuletzt“, dann „geplant“, „läuft …“ und den Prozentwert; die Startleiste zeigt Läufe und Zeitschätzung | manuell |
| aufgaben2plan.3 | Lauf abbrechen, dann „Fortsetzen“ klicken | Fertige Zellen zeigen „schon vorhanden“, nur offene Zellen laufen | manuell |
## einstellungen2bereitschaft
**Zweck:** Die Einstellungen sagen, ob alles für einen Benchmark bereit ist, und führen durch die Einrichtung.
**Deckt ab:** #1008
**Voraussetzung:** Podman installiert, ein Modell-Server erreichbar, einer ausgeschaltet.
| Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- |
| einstellungen2bereitschaft.1 | Reiter „Einstellungen“ öffnen | Ampel zeigt je Punkt ✓ oder ○ mit Hinweis; Modellkarten zeigen grünen oder roten Punkt | manuell |
| einstellungen2bereitschaft.2 | Modell öffnen, Feld „Modell-ID“ anklicken | Der Server bietet seine Modelle zur Auswahl an | manuell |
| einstellungen2bereitschaft.3 | Image bauen, danach Ampel ansehen | Image-Zeile wird ✓, Ampel wechselt auf „Bereit“, sobald alle Punkte erfüllt sind | manuell |
## referenz2ranking
**Zweck:** Ein von Hand gelöster Lauf (z. B. Claude Code) wird als Referenz in die Bewertung übernommen.
**Deckt ab:** #1052
**Voraussetzung:** Container-Image gebaut, ein Batch mit lokalen Modellen vorhanden, Claude Code oder ähnliches zur Hand.
| Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- |
| referenz2ranking.1 | Im Reiter „Referenz“ zwei Aufgaben und 1 Durchlauf wählen, „Exportieren“ klicken | Ordner mit je einem Unterordner je Aufgabe und Durchlauf; darin Startdateien und `AUFGABE.md`, keine `check.sh` | manuell |
| referenz2ranking.2 | Eine Aufgabe in Claude Code lösen lassen, Ordner im Reiter „Referenz“ importieren, Modellname und Batch angeben | Meldung „1 Lauf geprüft“; Ergebnis der Prüfung (bestanden oder nicht) stimmt mit dem Ordnerinhalt überein | manuell |
| referenz2ranking.3 | Reiter „Ergebnisse“ des Batches öffnen | Referenz steht getrennt mit Kennzeichnung „extern“; in den Bereichsbalken der lokalen Modelle ist ein Strich beim Wert der Referenz | manuell |

View File

@ -60,7 +60,7 @@ Der Nutzer wählt Aufgaben und Modelle. Jedes Modell löst jede Aufgabe mehrfach
| **Agent-Loop** | Modell und Tools (`read_file`, `write_file`, `list_dir`, `run_shell`, `done`) mit Fehlerklassen. |
| **Sandbox** | Frischer Podman-Container pro Lauf, ohne Netzwerk. |
| **Runner** | Wiederholungen, Abbruch und Fortsetzen eines Batches. |
| **Ranking** | Gesamtscore mit Intervall, Matrix Modell × Test (geplant für 0.2.0: Kategorien, Export). |
| **Ranking** | Bewertung in Prozent je Bereich und als Gesamtnote, Matrix Modell × Aufgabe (geplant für 0.2.0: Konfidenzintervall, Export). |
## How it works

View File

@ -1,8 +1,8 @@
# coding-bench – Anforderungen, Todo und Roadmap
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.
Stand: 2026-11-09 (12:00) · Projekt-ID: offen · Format: 1 · installiert ist noch nichts (Release 0.1.0 offen); Release-Kandidat v0.1.0-rc4 auf srv01 gebaut (deb und Arch als Artefakte, nirgends installiert). Danach GUI-Überarbeitung auf `release/0.1.0`, noch nicht als Kandidat gebaut. 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: #1042.
**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: #1056.
## 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).
@ -34,6 +34,7 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
| #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) |
| #1052 | F-18 Externe Referenz: Export als Ordner, Import mit Prüfung durch `check.sh` | Gespräch 09.11.2026 | ◐ | Gebaut: `external.rs` (Export mit `AUFGABE.md` ohne `check.sh`, Import mit Prüfung im Container, Ersetzen bei Wiederholung), Spalte `external` mit Migration, Referenz ohne Rang im Ranking, Reiter „Referenz“, Strich im Balken. 72 Tests grün, echter Podman-Test `echter_import` grün (richtig 1,0, falsch 0,0, kein Doppelimport). Oberfläche nur als Screenshot mit Beispieldaten gesehen. Klicktests `referenz2ranking.1–.3` offen (→ #1053) |
| #1017 | F-17 Optionale Screenshot-Bewertung durch Vision-Modell | SPEC 12 | ✗ | Phase 3 (→ #1032) |
## 3. Aufträge an Dritte
@ -51,14 +52,21 @@ 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.** 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
- [#1025] **GUI Setup und Batch.** Zweimal neu gebaut (nach deiner Kritik und nach der Agenten-Prüfung): dunkles Theme mit orangem Akzent, Logo und Icons, Start auf „Benchmark“. Benchmark-Tab mit Modell- und Aufgabenkarten (Beschreibung, Limits, „zuletzt“), Matrix „Plan und Stand“ (live), fester Startleiste mit Zeitschätzung, Hinweis bei weniger als 3 Durchläufen und Fortsetzen. Einstellungen mit Bereitschafts-Ampel, einklappbaren Modellkarten, Server-Prüfung und Modell-Liste vom Server (`discover.rs`). Geprüft nur als Screenshot im Headless-Browser mit Beispieldaten und mit Unit-Tests (67 grün), nicht in der echten App. Offen: echte App im Fenster prüfen, Klicktests `batch2fortsetzen.1`, `lauf2ergebnis.2`, `aufgaben2plan.1–.2` und `einstellungen2bereitschaft.1–.2` manuell, laufender Schritt live anzeigen, Gewichte in der Oberfläche ändern (SPEC 9). → #1008
- [#1026] **Rangliste und Matrix.** Gebaut (jetzt als Rangkarten mit Medaillen, Tok/s als Median, klickbare Matrix-Zellen): 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
**P1b – Release 0.1.1, Referenz**
- [#1053] **Externe Referenz-Läufe.** Aufgaben als Ordner exportieren (Startdateien plus `AUFGABE.md`, ohne `check.sh`), von Hand mit Claude Code oder ähnlichem lösen lassen, den Ordner zurückgeben; die App lässt `check.sh` im Container laufen und speichert den Lauf als „extern“. Ergebnisse erscheinen als Referenz mit Strich je Bereich. Tests `referenz2ranking.1–.3`. → #1052 Stand: gebaut und mit Podman geprüft, Klicktests offen. Offen: Dateidialog statt Pfad eintippen, Dauer und Tokens optional eintragen.
**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.** Adapter und Auswahl je Modell sind gebaut (vorgezogen nach 0.1.0, siehe #1041). Offen: Anthropic-kompatibler Adapter, GPU Dispatcher prüfen. → #1013
- [#1048] **Echte Tempo-Messung.** Antworten streamen, Zeit bis zum ersten Token und reine Erzeugungsgeschwindigkeit messen. Heute ist Tok/s Tokens geteilt durch die ganze Laufzeit inklusive Tool- und Prüfzeit. → #1006
- [#1049] **Batches vergleichen.** Zwei Batches nebeneinander (gleiches Modell vor und nach Wechsel, Aufgabenmenge und Wiederholungen sichtbar). → #1009
- [#1050] **Ollama-Modelle direkt anlegen.** Aus der Modell-Liste des Servers per Klick Modelle als Einträge übernehmen, statt die ID zu wählen. → #1008
- [#1055] **Harness-Adapter (Pi, OpenCode).** Das Harness wird eine Auswahl neben dem eigenen von coding-bench: Jedes Ergebnis gehört zu einem Harness, verglichen wird nur innerhalb eines Harness. Die App startet Pi oder OpenCode headless in einem Arbeitsordner und prüft danach wie beim Import (#1053). Vorab ein kleiner Versuch: dieselben zwei Aufgaben mit einem lokalen Modell im eigenen Harness und in Pi, um den Harness-Effekt zu sehen. Offen zu klären: Netz für das Modell im Container, welche Messdaten das Harness liefert, Nutzungsbedingungen für Abo-Zugänge. Blocker: #1053 (Import) muss geprüft sein. → #1052
- [#1031] **Export.** JSON und eigenständiger HTML-Report. → #1014
**P3 – Backlog (Release 0.3.0, Demos)**
@ -75,15 +83,24 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
- [#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
- [#1051] Entschieden am 09.11.2026: Externe Läufe (Claude Code u. ä., von Hand ausgeführt) dienen als Referenz. Die Bewertung bleibt absolut (#1040), Referenzen stehen getrennt und als Strich bei jedem Bereichsbalken, sie zählen nicht im Rang. Import nimmt den Ergebnisordner, die App prüft mit `check.sh` im Container. Gilt ab Release 0.1.1. → #1052
- [#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
- [#1042] Entschieden: Die App baut das Container-Image `cb-python` selbst. Das Containerfile ist in die App eingebettet, in den Einstellungen gibt es „Image bauen“ mit Live-Ausgabe. Ein Paket muss kein Image mitliefern. → #1004
- [#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)
**0.1.0 – Kern.** Todo: #1018, #1019, #1020, #1021, #1022, #1023, #1024, #1025, #1026. Ziel: Zwei Modelle × sechs Tests × drei Wiederholungen laufen durch, die Rangliste erscheint, ein Einzellauf ist nachvollziehbar, Abbruch und Fortsetzen funktionieren.
**0.2.0 – Referenz und Tiefe.** Todo: #1027, #1028, #1029, #1030, #1031. Ziel: Schwere Aufgaben (c-Gruppe, Aider-Teilmenge) laufen, Ranking mit Unsicherheit, OpenAI-Endpunkt und Export.
**0.1.1 – Referenz.** Todo: #1053. Ziel: Ein Abo-Modell (z. B. Claude über Claude Code) lässt sich von Hand als Referenz in die Bewertung einbringen, die lokalen Modelle werden gegen diesen Strich gesehen.
**0.2.0 – Referenz und Tiefe.** Todo: #1027, #1028, #1029, #1030, #1031, #1048, #1049, #1050, #1055. Ziel: Schwere Aufgaben (c-Gruppe, Aider-Teilmenge) laufen, Ranking mit Unsicherheit, OpenAI-Endpunkt und Export.
**0.3.0 – Demos.** Todo: #1032. Ziel: Playwright-Demos und optionale Screenshot-Bewertung.
**Danach.** Ideen ohne Zusage.
## 7. Risiken und Schulden
- [#1037] Modelle ohne Tool-Support liefern `endpoint_error` und werden übersprungen (SPEC 13). → #1003
- [#1038] Vergleichbarkeit mit veröffentlichten Benchmarkzahlen hängt vom Harness ab (Prompt, Tools, Limits). → #1021
- [#1054] Die Referenz misst „Modell plus fremdes Harness“ (eigener System-Prompt, eigene Tools, kein Schrittlimit, Netz erlaubt, von Hand ausgeführt), nicht das Modell im Harness von coding-bench. Der Strich ist ein Orientierungswert, kein Gleichstand der Bedingungen. Gegenmaßnahme: Kennzeichnung „extern“ in der Oberfläche, Anleitung mit „kein Web, nur dieser Ordner“, Aufgabentext unverändert. → #1038
- [#1043] Teilweise behoben am 09.11.2026 (Review vom 07.11.2026): Die Sandbox startet jetzt mit `--cap-drop=ALL`, `--security-opt=no-new-privileges`, `--read-only`; schreibbar sind nur `/work` (256 MB), `/tmp` (128 MB) und `/checks` (64 MB) als tmpfs. Das ersetzt Platten- und Datei-Limits (die Ordner liegen im Arbeitsspeicher und zählen zum Speicherlimit des Containers). Belege: echter Podman-Test `gehaertet_keine_rechte_nur_work_schreibbar_mit_limit` (keine Capabilities, kein Schreiben in `/usr`, 300-MB-Datei scheitert, Export aus dem tmpfs funktioniert) und `pruefungen_laufen_gehaertet` (alle sechs Aufgaben starten und prüfen ohne Rechte-Fehler). Offen: Prozess läuft weiter als Root im Container (rootless, also ohne Rechte auf dem Host), kein eigenes Seccomp-Profil, `check.sh` und Aufgabenordner werden aus dem Aufgabenordner vertraut (fremde Aufgaben-Quellen sind nicht vorgesehen). Nach vorn bringt es: fremde Aufgaben-Quellen oder Phase 2. → #1004
- [#1044] Behoben am 09.11.2026: `check.sh` lief im selben Container wie der Agent, ein Modell hätte Interpreter oder `sh` verändern und so die Bewertung beeinflussen können. Jetzt wird `/work` aus dem Agenten-Container exportiert (mit Zeitlimit 120 s), der Agenten-Container entfernt und die Prüfung in einem frischen Container mit demselben Image gestartet. Scheitert Export oder Start, zählt der Lauf als `sandbox_error` (nicht gewertet, wird beim Fortsetzen wiederholt). Beleg: Test `agenten_container_zustand_gelangt_nicht_in_die_pruefung` (echter Podman-Test): Zustand, den der Agent in `/tmp` und `/checks` hinterlässt, ist im selben Container sichtbar und lässt die Prüfung scheitern, im frischen Container nicht. Das Überschreiben von Systemprogrammen verhindert seit #1043 zusätzlich die Nur-Lesen-Wurzel (ein erster Test, der `grep` überschrieb, belegte vor #1043 den Fehler im alten Weg: falsche Lösung bestand). Offen: Der Export vom Container auf den Host ist die neue Vertrauensgrenze (Sonderdateien und Links, Größe), Größenlimit gehört zu #1043. → #1004
- [#1045] Tauri-CSP ist abgeschaltet (`csp: null`), `api_key_env` und Modell-URL sind frei wählbar. Kein Angriffsweg belegt, die Oberfläche nutzt kein `{@html}`. Eine strenge CSP und eine Prüfung der Variablennamen sind offen. → #1013
- [#1046] Abbruch greift spät: Der Abbruch wird nur zwischen Schritten geprüft, eine laufende Modell-Anfrage läuft bis zum Zeitlimit weiter. Beim Timeout eines Befehls endet nur der `podman exec`-Client, nicht der Prozess im Container. → #1022
- [#1047] Die Messung ist dünn: je Aufgabe eine Wiederholung, zwei Modelle, kein Modell ohne Tool-Support, keine Streuung. Das Ziel „2 Modelle × 6 Aufgaben × 3 Wiederholungen“ ist nicht erreicht. Vor einem Release 0.1.0 nachholen. → #1024

BIN
branding/logo-1024.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

15
branding/logo.svg Normal file
View File

@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ffb470"/>
<stop offset="1" stop-color="#ee8227"/>
</linearGradient>
</defs>
<rect x="32" y="32" width="960" height="960" rx="224" fill="url(#bg)"/>
<g fill="#1a1005">
<rect x="212" y="490" width="170" height="300" rx="44"/>
<rect x="427" y="340" width="170" height="450" rx="44"/>
<rect x="642" y="580" width="170" height="210" rx="44"/>
</g>
<circle cx="512" cy="245" r="46" fill="#1a1005"/>
</svg>

After

Width:  |  Height:  |  Size: 626 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 567 B

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 536 B

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 777 B

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1020 B

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 848 B

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -37,9 +37,19 @@ pub enum ErrorClass {
MaxSteps,
Timeout,
EndpointError,
/// Fehler der Umgebung (Container, Image, Dateien), nicht des Modells.
SandboxError,
CheckFailed,
}
impl ErrorClass {
/// Läufe, die an der Umgebung scheiterten, sagen nichts über das Modell:
/// Sie zählen nicht in die Bewertung und werden beim Fortsetzen wiederholt.
pub fn is_infrastructure(self) -> bool {
matches!(self, ErrorClass::EndpointError | ErrorClass::SandboxError)
}
}
/// Eine Nachricht im Verlauf (Ollama-Format).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Message {

77
src-tauri/src/discover.rs Normal file
View File

@ -0,0 +1,77 @@
//! Fragt einen Modell-Server nach den Modellen, die er anbietet. Das erspart das Abtippen der Modell-ID.
use std::time::Duration;
/// Adresse der Modell-Liste. Ollama: `/api/tags`, OpenAI-kompatibel: `<basis>/models`.
pub fn models_url(adapter: &str, url: &str) -> Result<String, String> {
let t = url.trim().trim_end_matches('/');
if !(t.starts_with("http://") || t.starts_with("https://")) {
return Err("Die Server-URL muss mit http:// oder https:// beginnen.".into());
}
match adapter {
"ollama" => Ok(format!("{t}/api/tags")),
"openai" => {
let base = t.strip_suffix("/chat/completions").unwrap_or(t);
Ok(format!("{base}/models"))
}
other => Err(format!("Unbekannter Adapter {other:?}.")),
}
}
/// Liest die Modellnamen aus der Antwort. Unbekannte Form ergibt eine leere Liste.
pub fn parse_models(adapter: &str, body: &serde_json::Value) -> Vec<String> {
let (list, field) = match adapter {
"ollama" => (body.get("models"), "name"),
_ => (body.get("data"), "id"),
};
let mut names: Vec<String> = list
.and_then(|v| v.as_array())
.map(|a| a.iter().filter_map(|m| m.get(field)?.as_str().map(String::from)).collect())
.unwrap_or_default();
names.sort();
names.dedup();
names
}
/// Fragt den Server ab. `api_key` ist der Wert, nicht der Name der Variable.
pub fn list(adapter: &str, url: &str, api_key: Option<&str>) -> Result<Vec<String>, String> {
let endpoint = models_url(adapter, url)?;
let http = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(8))
.build()
.map_err(|e| format!("HTTP-Client nicht baubar: {e}"))?;
let mut req = http.get(&endpoint);
if let Some(k) = api_key {
req = req.bearer_auth(k);
}
let resp = req.send().map_err(|e| format!("Server nicht erreichbar: {e}"))?;
if !resp.status().is_success() {
return Err(format!("Der Server antwortete mit {}.", resp.status()));
}
let body: serde_json::Value = resp.json().map_err(|e| format!("Antwort nicht lesbar: {e}"))?;
Ok(parse_models(adapter, &body))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn adressen_je_adapter() {
assert_eq!(models_url("ollama", "http://h:11434/").unwrap(), "http://h:11434/api/tags");
assert_eq!(models_url("openai", "http://h:8082/v1").unwrap(), "http://h:8082/v1/models");
assert_eq!(models_url("openai", "http://h/v1/chat/completions").unwrap(), "http://h/v1/models");
assert!(models_url("openai", "ftp://h").is_err());
assert!(models_url("x", "http://h").is_err());
}
#[test]
fn modellnamen_werden_gelesen() {
let o = json!({"models": [{"name": "qwen3:0.6b"}, {"name": "a:1"}, {"name": "a:1"}]});
assert_eq!(parse_models("ollama", &o), vec!["a:1", "qwen3:0.6b"]);
let s = json!({"data": [{"id": "m2"}, {"id": "m1"}]});
assert_eq!(parse_models("openai", &s), vec!["m1", "m2"]);
assert!(parse_models("openai", &json!({"x": 1})).is_empty());
}
}

421
src-tauri/src/external.rs Normal file
View File

@ -0,0 +1,421 @@
//! Externe Referenz-Läufe: Aufgaben als Ordner exportieren, von Hand (Claude Code o. ä.) lösen
//! lassen und den Ergebnisordner zurückgeben. Die Prüfung läuft wie bei jedem Lauf mit `check.sh`
//! im Container. Die Läufe werden als „extern“ gespeichert und zählen nicht im Rang.
//!
//! Ordnerform: `<aufgabe>/run-<n>/arbeit/` (Arbeitsordner, wird importiert) und
//! `<aufgabe>/run-<n>/AUFGABE.md` (Text zum Einfügen, bleibt außerhalb des Arbeitsordners, damit
//! er die Prüfung nicht verfälscht, etwa beim Zählen von Dateien).
use crate::runner::{final_class, run_check, RunConfig};
use crate::agent::ErrorClass;
use crate::sandbox::{container_name, Sandbox};
use crate::store::{RunRecord, Store};
use crate::tasks::{Task, START_DIR};
use serde::Serialize;
use std::fs;
use std::path::{Path, PathBuf};
pub const MANIFEST: &str = "manifest.json";
pub const WORK_SUBDIR: &str = "arbeit";
/// Größte erlaubte Ergebnismenge je Lauf. Schützt vor versehentlich kopierten Abhängigkeitsordnern.
pub const MAX_IMPORT_BYTES: u64 = 50 * 1024 * 1024;
/// Namen, die beim Kopieren in den Container ausgelassen werden. Sie gehören nicht zur Lösung.
const SKIP_NAMES: [&str; 2] = [".claude", ".git"];
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ExportResult {
pub dir: String,
pub folders: usize,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ImportSummary {
pub imported: usize,
pub passed: usize,
/// Ordner, die nicht geprüft wurden, mit Grund.
pub skipped: Vec<String>,
}
fn instructions(repeats: u32, tasks: &[Task]) -> String {
let list: String = tasks.iter().map(|t| format!("- {}: {}", t.meta.id, t.meta.title)).collect::<Vec<_>>().join("\n");
format!(
"# Referenz-Läufe für coding-bench\n\n\
Dieser Ordner enthält {n} Aufgabe(n) mit je {repeats} Durchlauf/Durchläufen:\n\n{list}\n\n\
## So geht es\n\n\
1. Öffne **für jeden Durchlauf eine frische Sitzung** deines Werkzeugs (z. B. Claude Code) im Ordner `<aufgabe>/run-<n>/arbeit/`.\n\
2. Füge den Inhalt von `<aufgabe>/run-<n>/AUFGABE.md` als Auftrag ein. Hilf nicht nach, stelle keine Zwischenfragen.\n\
3. Warte, bis das Werkzeug fertig meldet. Lass **nur** den Ordner `arbeit/` verändern.\n\
4. Wenn alles erledigt ist, gib diesen Ordner in coding-bench unter „Referenz“ zurück.\n\n\
## Regeln, damit der Vergleich fair bleibt\n\n\
- Kein Web, keine Suche, keine Dateien außerhalb von `arbeit/`.\n\
- Keine Hinweise geben, keine Fehlermeldungen aus früheren Durchläufen mitgeben.\n\
- Ein Durchlauf pro Ordner. Wiederholst du einen Durchlauf, lösche die alte Sitzung und beginne im frischen Ordner.\n\
- Es gibt hier kein Schrittlimit und kein Zeitlimit. Das ist ein Unterschied zu den lokalen Modellen und wird in der Bewertung als „extern“ gekennzeichnet.\n\
- Die Prüfdatei (`check.sh`) liegt absichtlich nicht dabei.\n",
n = tasks.len(),
)
}
fn task_file(prompt: &str) -> String {
format!(
"> Hinweis zur Umgebung: Im Text unten heißt das Arbeitsverzeichnis `/work`. Gemeint ist der Ordner, \
in dem du gerade arbeitest (das aktuelle Verzeichnis). Arbeite nur darin. Ein Werkzeug `done` gibt es hier \
nicht: Sage einfach, dass du fertig bist.\n\n{}\n",
prompt.trim_end()
)
}
/// Kopiert einen Ordner rekursiv. Symbolische Links werden übersprungen. Gibt die Bytes zurück.
fn copy_dir(src: &Path, dst: &Path, skip: &[&str]) -> Result<u64, String> {
fs::create_dir_all(dst).map_err(|e| format!("Ordner nicht anlegbar: {e}"))?;
let mut total = 0;
for entry in fs::read_dir(src).map_err(|e| format!("{} nicht lesbar: {e}", src.display()))? {
let entry = entry.map_err(|e| e.to_string())?;
let name = entry.file_name();
if skip.iter().any(|s| name == *s) {
continue;
}
let kind = entry.file_type().map_err(|e| e.to_string())?;
let to = dst.join(&name);
if kind.is_symlink() {
continue;
} else if kind.is_dir() {
total += copy_dir(&entry.path(), &to, skip)?;
} else if kind.is_file() {
total += fs::copy(entry.path(), &to).map_err(|e| format!("Kopieren fehlgeschlagen: {e}"))?;
}
}
Ok(total)
}
/// Größe einer Ordnerstruktur ohne die ausgelassenen Namen und ohne Links.
fn dir_size(dir: &Path, skip: &[&str]) -> u64 {
let Ok(rd) = fs::read_dir(dir) else { return 0 };
let mut total = 0;
for entry in rd.flatten() {
if skip.iter().any(|s| entry.file_name() == *s) {
continue;
}
let Ok(kind) = entry.file_type() else { continue };
if kind.is_dir() {
total += dir_size(&entry.path(), skip);
} else if kind.is_file() {
total += entry.metadata().map(|m| m.len()).unwrap_or(0);
}
}
total
}
/// Legt den Exportordner an. `out_dir` darf nicht existieren oder muss leer sein.
pub fn export(tasks: &[Task], repeats: u32, out_dir: &Path) -> Result<ExportResult, String> {
if tasks.is_empty() {
return Err("Keine Aufgabe gewählt.".into());
}
if repeats == 0 {
return Err("Mindestens ein Durchlauf.".into());
}
if out_dir.exists() && fs::read_dir(out_dir).map(|mut r| r.next().is_some()).unwrap_or(true) {
return Err(format!("{} existiert und ist nicht leer.", out_dir.display()));
}
fs::create_dir_all(out_dir).map_err(|e| format!("Ordner nicht anlegbar: {e}"))?;
let mut folders = 0;
for task in tasks {
let prompt = fs::read_to_string(task.dir.join("prompt.md")).map_err(|e| format!("prompt.md nicht lesbar: {e}"))?;
for n in 1..=repeats {
let run_dir = out_dir.join(&task.meta.id).join(format!("run-{n}"));
let work = run_dir.join(WORK_SUBDIR);
fs::create_dir_all(&work).map_err(|e| format!("Ordner nicht anlegbar: {e}"))?;
let start = task.dir.join(START_DIR);
if start.is_dir() {
copy_dir(&start, &work, &[])?;
}
fs::write(run_dir.join("AUFGABE.md"), task_file(&prompt)).map_err(|e| format!("AUFGABE.md nicht schreibbar: {e}"))?;
folders += 1;
}
}
let ids: Vec<&str> = tasks.iter().map(|t| t.meta.id.as_str()).collect();
fs::write(
out_dir.join(MANIFEST),
serde_json::json!({ "format": 1, "tasks": ids, "repeats": repeats }).to_string(),
)
.map_err(|e| format!("manifest.json nicht schreibbar: {e}"))?;
fs::write(out_dir.join("ANLEITUNG.md"), instructions(repeats, tasks)).map_err(|e| format!("ANLEITUNG.md nicht schreibbar: {e}"))?;
Ok(ExportResult { dir: out_dir.display().to_string(), folders })
}
/// Ein Ergebnisordner: Aufgabe, Durchlauf und Pfad des Arbeitsordners.
#[derive(Debug, Clone, PartialEq)]
pub struct Found {
pub task_id: String,
pub repeat_idx: u32,
pub work: PathBuf,
}
/// Sucht `<aufgabe>/run-<n>/arbeit/` unterhalb von `root`. Unlesbares oder Fremdes wird gemeldet.
pub fn find_runs(root: &Path) -> Result<(Vec<Found>, Vec<String>), String> {
if !root.is_dir() {
return Err(format!("{} ist kein Ordner.", root.display()));
}
let mut found = Vec::new();
let mut notes = Vec::new();
let mut tasks: Vec<PathBuf> = fs::read_dir(root)
.map_err(|e| format!("Ordner nicht lesbar: {e}"))?
.flatten()
.map(|e| e.path())
.filter(|p| p.is_dir())
.collect();
tasks.sort();
for tdir in tasks {
let task_id = tdir.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string();
let mut runs: Vec<PathBuf> = fs::read_dir(&tdir).map(|r| r.flatten().map(|e| e.path()).collect()).unwrap_or_default();
runs.sort();
for rdir in runs.into_iter().filter(|p| p.is_dir()) {
let name = rdir.file_name().and_then(|n| n.to_str()).unwrap_or("");
let Some(n) = name.strip_prefix("run-").and_then(|x| x.parse::<u32>().ok()).filter(|n| *n >= 1) else {
notes.push(format!("{task_id}/{name}: kein Durchlauf-Ordner (erwartet run-<n>)"));
continue;
};
let work = rdir.join(WORK_SUBDIR);
if !work.is_dir() {
notes.push(format!("{task_id}/{name}: Ordner {WORK_SUBDIR}/ fehlt"));
continue;
}
found.push(Found { task_id: task_id.clone(), repeat_idx: n, work });
}
}
Ok((found, notes))
}
/// Prüft die Ergebnisordner und speichert sie als externe Läufe in `batch_id`.
/// Ein bereits importierter Lauf (gleiches Modell, gleiche Aufgabe, gleicher Durchlauf) wird ersetzt.
pub fn import(
store: &mut Store,
cfg: &RunConfig,
tasks: &[Task],
root: &Path,
model: &str,
batch_id: i64,
) -> Result<ImportSummary, String> {
if !store.batch_exists(batch_id)? {
return Err(format!("Batch {batch_id} existiert nicht."));
}
let (found, mut skipped) = find_runs(root)?;
if found.is_empty() {
return Err(format!(
"Keine Ergebnisordner gefunden. Erwartet wird <aufgabe>/run-<n>/{WORK_SUBDIR}/ unter {}.{}",
root.display(),
if skipped.is_empty() { String::new() } else { format!(" Hinweise: {}", skipped.join("; ")) }
));
}
let mut imported = 0;
let mut passed = 0;
for (seq, f) in found.iter().enumerate() {
let label = format!("{}/run-{}", f.task_id, f.repeat_idx);
let Some(task) = tasks.iter().find(|t| t.meta.id == f.task_id) else {
skipped.push(format!("{label}: Aufgabe unbekannt"));
continue;
};
if dir_size(&f.work, &SKIP_NAMES) > MAX_IMPORT_BYTES {
skipped.push(format!("{label}: Ergebnis größer als {} MB", MAX_IMPORT_BYTES / 1024 / 1024));
continue;
}
let name = container_name(&format!("imp-{batch_id}-{seq}"));
crate::sandbox::remove_by_name(&cfg.runtime, &name);
// Ohne die ausgelassenen Namen in einen Zwischenordner kopieren, dann in den Container.
let staging = std::env::temp_dir().join(format!("coding-bench-import-{}-{seq}", std::process::id()));
let _ = fs::remove_dir_all(&staging);
if let Err(e) = copy_dir(&f.work, &staging, &SKIP_NAMES) {
skipped.push(format!("{label}: {e}"));
let _ = fs::remove_dir_all(&staging);
continue;
}
let started = Sandbox::start(&cfg.runtime, &name, &task.meta.image, &cfg.limits, Some(&staging));
let _ = fs::remove_dir_all(&staging);
let sb = match started {
Ok(sb) => sb,
Err(e) => {
skipped.push(format!("{label}: Container nicht startbar ({e})"));
continue;
}
};
let (check, text) = run_check(&sb, task);
if let Err(e) = sb.remove() {
eprintln!("Container {name} nicht entfernt: {e}");
}
let class = final_class(ErrorClass::Ok, &check);
let record = RunRecord {
batch_id,
model: model.to_string(),
task_id: task.meta.id.clone(),
repeat_idx: f.repeat_idx,
error_class: class,
score: check.score,
steps: 0,
prompt_tokens: 0,
completion_tokens: 0,
duration_ms: 0,
tps: None,
ttft_tool_ms: None,
artifact_path: Some(f.work.display().to_string()),
summary: Some("Extern gelöst (von Hand), keine Schritte aufgezeichnet.".into()),
check_output: text,
external: true,
};
store.delete_run(batch_id, model, &record.task_id, record.repeat_idx)?;
store.insert_run(&record, &[])?;
imported += 1;
if check.passed {
passed += 1;
}
}
Ok(ImportSummary { imported, passed, skipped })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tasks::TaskToml;
fn scratch(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("cb-ext-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
fn task_in(dir: &Path, id: &str) -> Task {
fs::create_dir_all(dir.join("start/sub")).unwrap();
fs::write(dir.join("start/info.txt"), "Projektcode: 42").unwrap();
fs::write(dir.join("start/sub/x.txt"), "x").unwrap();
fs::write(dir.join("prompt.md"), "Lies /work/info.txt.\n").unwrap();
fs::write(dir.join("check.sh"), "#!/bin/sh\nexit 0\n").unwrap();
Task {
meta: TaskToml {
id: id.into(),
title: "Titel".into(),
group: "A".into(),
weight: 1.0,
image: "cb-python:latest".into(),
max_steps: 5,
timeout_s: 60,
check_timeout_s: 30,
},
dir: dir.to_path_buf(),
prompt: String::new(),
}
}
#[test]
fn export_legt_ordner_an_ohne_pruefdatei() {
let base = scratch("export");
let task = task_in(&base.join("task"), "a-01");
let out = base.join("out");
let r = export(&[task], 2, &out).unwrap();
assert_eq!(r.folders, 2);
for n in 1..=2 {
let run = out.join(format!("a-01/run-{n}"));
assert!(run.join("arbeit/info.txt").is_file());
assert!(run.join("arbeit/sub/x.txt").is_file());
let md = fs::read_to_string(run.join("AUFGABE.md")).unwrap();
assert!(md.contains("Lies /work/info.txt."), "Aufgabentext bleibt unverändert");
assert!(md.contains("aktuelle Verzeichnis"));
// Weder die Prüfdatei noch die Aufgabendatei liegen im Arbeitsordner.
assert!(!run.join("arbeit/check.sh").exists());
assert!(!run.join("arbeit/AUFGABE.md").exists());
}
assert!(out.join("ANLEITUNG.md").is_file());
assert!(out.join(MANIFEST).is_file());
assert!(!out.join("a-01/check.sh").exists());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn export_verweigert_belegten_ordner() {
let base = scratch("belegt");
let task = task_in(&base.join("task"), "a-01");
let out = base.join("out");
fs::create_dir_all(&out).unwrap();
fs::write(out.join("alt.txt"), "x").unwrap();
assert!(export(&[task], 1, &out).is_err());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn ergebnisordner_werden_gefunden_und_fremdes_gemeldet() {
let base = scratch("find");
fs::create_dir_all(base.join("a-01/run-1/arbeit")).unwrap();
fs::create_dir_all(base.join("a-01/run-2/arbeit")).unwrap();
fs::create_dir_all(base.join("a-01/run-3")).unwrap(); // ohne arbeit/
fs::create_dir_all(base.join("a-01/notizen")).unwrap();
let (found, notes) = find_runs(&base).unwrap();
assert_eq!(found.len(), 2);
assert_eq!(found[0].task_id, "a-01");
assert_eq!(found[1].repeat_idx, 2);
assert_eq!(notes.len(), 2);
assert!(find_runs(&base.join("gibt-es-nicht")).is_err());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn kopieren_laesst_claude_ordner_und_links_aus() {
let base = scratch("copy");
let src = base.join("src");
fs::create_dir_all(src.join(".claude")).unwrap();
fs::write(src.join(".claude/settings.json"), "{}").unwrap();
fs::write(src.join("lösung.py"), "print(1)").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("/etc/passwd", src.join("link")).unwrap();
let dst = base.join("dst");
let bytes = copy_dir(&src, &dst, &SKIP_NAMES).unwrap();
assert_eq!(bytes, 8);
assert!(dst.join("lösung.py").is_file());
assert!(!dst.join(".claude").exists());
assert!(!dst.join("link").exists());
assert_eq!(dir_size(&src, &SKIP_NAMES), 8);
let _ = fs::remove_dir_all(&base);
}
/// Echter Import gegen Podman: `CB_TEST_IMAGE=cb-python:latest cargo test external::tests::echter_import -- --ignored`
#[test]
#[ignore]
fn echter_import() {
use crate::sandbox::Limits;
let image = std::env::var("CB_TEST_IMAGE").unwrap_or_else(|_| "cb-python:latest".into());
let base = scratch("echt");
let mut task = task_in(&base.join("task"), "a-01");
task.meta.image = image;
// Prüfung: ergebnis.txt muss "42" enthalten.
fs::write(base.join("task/check.sh"), "#!/bin/sh\ngrep -qx 42 ergebnis.txt\n").unwrap();
let out = base.join("out");
export(&[task.clone()], 2, &out).unwrap();
fs::write(out.join("a-01/run-1/arbeit/ergebnis.txt"), "42\n").unwrap(); // richtig
fs::write(out.join("a-01/run-2/arbeit/ergebnis.txt"), "43\n").unwrap(); // falsch
fs::create_dir_all(out.join("a-01/run-1/arbeit/.claude")).unwrap();
let mut store = Store::open_in_memory().unwrap();
let batch = store.create_batch("t", 2, "{}").unwrap();
let cfg = RunConfig {
runtime: "podman".into(),
models: Vec::new(),
data_dir: base.join("data"),
limits: Limits::default(),
};
let r = import(&mut store, &cfg, &[task.clone()], &out, "Claude (extern)", batch).unwrap();
assert_eq!(r.imported, 2, "{:?}", r.skipped);
assert_eq!(r.passed, 1);
let runs = store.runs_for_batch(batch).unwrap();
assert!(runs.iter().all(|x| x.external));
assert_eq!(runs.iter().find(|x| x.repeat_idx == 1).unwrap().score, 1.0);
assert_eq!(runs.iter().find(|x| x.repeat_idx == 2).unwrap().score, 0.0);
// Zweiter Import ersetzt die Läufe, es entstehen keine Doppelten.
import(&mut store, &cfg, &[task], &out, "Claude (extern)", batch).unwrap();
assert_eq!(store.runs_for_batch(batch).unwrap().len(), 2);
let _ = fs::remove_dir_all(&base);
}
}

168
src-tauri/src/images.rs Normal file
View File

@ -0,0 +1,168 @@
//! Container-Images, die die App selbst bauen kann.
//!
//! Die Containerfiles sind in die App eingebettet. So braucht ein installiertes Paket keine
//! zusätzlichen Dateien, und die App baut das Image beim ersten Start auf Knopfdruck.
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::thread;
struct Embedded {
/// Name ohne Registry und ohne Tag.
name: &'static str,
containerfile: &'static str,
}
const EMBEDDED: &[Embedded] = &[Embedded {
name: "cb-python",
containerfile: include_str!("../../images/cb-python/Containerfile"),
}];
/// Repository-Name eines Images: ohne Registry-Pfad, ohne Tag und ohne Digest.
fn repo_name(image: &str) -> &str {
let last = image.rsplit('/').next().unwrap_or(image);
last.split(['@', ':']).next().unwrap_or(last)
}
/// Eingebettetes Containerfile für ein Image, falls es eines gibt.
pub fn embedded_containerfile(image: &str) -> Option<&'static str> {
let name = repo_name(image);
EMBEDDED.iter().find(|e| e.name == name).map(|e| e.containerfile)
}
/// Prüft, ob ein Image lokal vorhanden ist. `podman image exists` liefert 0 (ja) oder 1 (nein).
pub fn exists(runtime: &str, image: &str) -> Result<bool, String> {
let out = Command::new(runtime)
.args(["image", "exists", "--", image])
.output()
.map_err(|e| format!("{runtime} nicht startbar: {e}"))?;
match out.status.code() {
Some(0) => Ok(true),
Some(1) => Ok(false),
_ => Err(format!(
"{runtime} image exists schlug fehl: {}",
String::from_utf8_lossy(&out.stderr).trim()
)),
}
}
/// Baut ein eingebettetes Image. Jede Ausgabezeile geht an `on_line`.
pub fn build(runtime: &str, image: &str, on_line: &mut dyn FnMut(&str)) -> Result<(), String> {
let containerfile = embedded_containerfile(image).ok_or_else(|| {
format!("Für {image} gibt es kein eingebautes Containerfile. Das Image muss selbst bereitgestellt werden.")
})?;
crate::tasks::validate_image(image)?;
// Eigener Ordner als Build-Kontext, danach wieder gelöscht.
let dir: PathBuf = std::env::temp_dir().join(format!(
"coding-bench-image-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
std::fs::create_dir_all(&dir).map_err(|e| format!("Build-Ordner nicht anlegbar: {e}"))?;
let result = (|| {
std::fs::write(dir.join("Containerfile"), containerfile)
.map_err(|e| format!("Containerfile nicht schreibbar: {e}"))?;
let mut child = Command::new(runtime)
.arg("build")
.arg("-t")
.arg(image)
.arg(&dir)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("{runtime} build nicht startbar: {e}"))?;
// Beide Ströme in eigenen Threads lesen und über einen Kanal zusammenführen.
let (tx, rx) = mpsc::channel::<String>();
let mut handles = Vec::new();
if let Some(out) = child.stdout.take() {
let tx = tx.clone();
handles.push(thread::spawn(move || {
for line in BufReader::new(out).lines().map_while(Result::ok) {
let _ = tx.send(line);
}
}));
}
if let Some(err) = child.stderr.take() {
let tx = tx.clone();
handles.push(thread::spawn(move || {
for line in BufReader::new(err).lines().map_while(Result::ok) {
let _ = tx.send(line);
}
}));
}
drop(tx);
for line in rx {
on_line(&line);
}
for h in handles {
let _ = h.join();
}
let status = child.wait().map_err(|e| format!("Warten auf den Build schlug fehl: {e}"))?;
if status.success() {
Ok(())
} else {
Err(format!("Der Build von {image} ist fehlgeschlagen (Exit {}).", status.code().map_or("?".into(), |c| c.to_string())))
}
})();
let _ = std::fs::remove_dir_all(&dir);
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn repo_name_ohne_registry_tag_und_digest() {
assert_eq!(repo_name("cb-python:latest"), "cb-python");
assert_eq!(repo_name("localhost/cb-python:1.2"), "cb-python");
assert_eq!(repo_name("docker.io/library/python:3.12-slim"), "python");
assert_eq!(repo_name("cb-python@sha256:abc"), "cb-python");
assert_eq!(repo_name("cb-python"), "cb-python");
}
#[test]
fn eingebettetes_containerfile_wird_gefunden() {
let cf = embedded_containerfile("cb-python:latest").expect("cb-python eingebettet");
assert!(cf.contains("FROM "));
assert!(embedded_containerfile("localhost/cb-python:latest").is_some());
assert!(embedded_containerfile("python:3.12").is_none());
}
#[test]
fn build_fremdes_image_wird_abgelehnt() {
let mut lines = Vec::new();
let err = build("podman", "python:3.12", &mut |l| lines.push(l.to_string())).unwrap_err();
assert!(err.contains("kein eingebautes Containerfile"));
assert!(lines.is_empty());
}
#[test]
fn name_mit_optionszeichen_ist_kein_eingebettetes_image() {
assert!(embedded_containerfile("--cb-python").is_none());
assert!(build("podman", "--cb-python", &mut |_| {}).is_err());
}
/// Echter Build gegen Podman (braucht Netz für das Basis-Image). Ignoriert:
/// `cargo test images::tests::echter_build -- --ignored`
#[test]
#[ignore]
fn echter_build() {
let tag = format!("cb-python:test-{}", std::process::id());
let mut lines = Vec::new();
build("podman", &tag, &mut |l| lines.push(l.to_string())).expect("Build");
assert!(!lines.is_empty());
assert!(exists("podman", &tag).unwrap());
let _ = Command::new("podman").args(["rmi", "-f", &tag]).output();
assert!(!exists("podman", &tag).unwrap());
}
}

View File

@ -1,5 +1,8 @@
mod agent;
mod config;
mod discover;
mod external;
mod images;
mod ranking;
mod runner;
mod sandbox;
@ -19,6 +22,7 @@ use tauri::{Emitter, Manager, State};
pub const DB_FILE: &str = "coding-bench.sqlite";
pub const EVENT_NAME: &str = "batch-event";
pub const IMAGE_EVENT: &str = "image-build";
/// Aufgelöste Pfade, einmal beim Start ermittelt.
pub struct AppPaths(pub Paths);
@ -35,6 +39,18 @@ pub struct RunState {
pub cancel: Arc<AtomicBool>,
/// Gesetzt, solange ein Batch läuft.
pub running: Arc<AtomicBool>,
/// Gesetzt, solange ein Image gebaut wird.
pub building: Arc<AtomicBool>,
}
/// Setzt ein Flag beim Verlassen des Gültigkeitsbereichs zurück, auch nach einem Fehler oder Panic.
/// Ohne diesen Wächter bliebe `running` nach einem abgestürzten Batch-Thread dauerhaft gesetzt.
struct FlagGuard(Arc<AtomicBool>);
impl Drop for FlagGuard {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}
/// Ein Modell für die Oberfläche, mit Hinweis, ob die Schlüssel-Variable gesetzt ist.
@ -156,7 +172,19 @@ async fn test_model(cfg: State<'_, ConfigState>, name: String) -> Result<ModelTe
.map_err(|e| format!("Test abgebrochen: {e}"))
}
/// Fragt einen Server nach seinen Modellen. Der Schlüssel kommt aus der Umgebungsvariable `api_key_env`.
#[tauri::command]
async fn discover_models(adapter: String, url: String, api_key_env: String) -> Result<Vec<String>, String> {
tauri::async_runtime::spawn_blocking(move || {
let key = if api_key_env.trim().is_empty() { None } else { std::env::var(api_key_env.trim()).ok() };
discover::list(&adapter, &url, key.as_deref())
})
.await
.map_err(|e| format!("Abfrage abgebrochen: {e}"))?
}
/// Startet einen Batch mit den angegebenen Modellen (Anzeigenamen) und Aufgaben-IDs.
/// Mit `batch_id` wird ein bestehender Batch fortgesetzt: fertige Läufe werden übersprungen.
/// Fortschritt kommt als Ereignis `batch-event`. Das Ergebnis ist die Zusammenfassung.
#[tauri::command]
async fn start_batch(
@ -168,6 +196,7 @@ async fn start_batch(
task_ids: Vec<String>,
repeats: u32,
note: String,
batch_id: Option<i64>,
) -> Result<BatchSummary, String> {
if models.is_empty() || task_ids.is_empty() {
return Err("Mindestens ein Modell und eine Aufgabe wählen.".into());
@ -200,9 +229,24 @@ async fn start_batch(
return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into());
}
// Fehlt ein Image, scheitert sonst jeder Lauf einzeln. Besser sofort und mit klarer Anleitung.
let mut missing: Vec<String> = Vec::new();
for image in selected.iter().map(|t| t.meta.image.clone()).collect::<std::collections::BTreeSet<_>>() {
if !images::exists(&runtime, &image)? {
missing.push(image);
}
}
if !missing.is_empty() {
return Err(format!(
"Container-Image fehlt: {}. Baue es in den Einstellungen unter „Container-Images“.",
missing.join(", ")
));
}
if run.running.swap(true, Ordering::SeqCst) {
return Err("Ein Batch läuft bereits.".into());
}
let _running_guard = FlagGuard(run.running.clone());
run.cancel.store(false, Ordering::SeqCst);
let jobs = runner::plan(&models, &selected, repeats);
@ -214,27 +258,139 @@ async fn start_batch(
};
let db_path = paths.0.data_dir.join(DB_FILE);
let cancel = run.cancel.clone();
let running = run.running.clone();
let emitter = app.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
let outcome = (|| -> Result<BatchSummary, String> {
let mut store = Store::open(&db_path)?;
let on_event = |e: &Event| {
let _ = emitter.emit(EVENT_NAME, e);
};
runner::run_batch(&mut store, &run_cfg, None, &note, repeats, &jobs, &cancel, &on_event)
})();
running.store(false, Ordering::SeqCst);
outcome
runner::run_batch(&mut store, &run_cfg, batch_id, &note, repeats, &jobs, &cancel, &on_event)
})
.await
.map_err(|e| format!("Batch-Thread abgebrochen: {e}"))?;
run.running.store(false, Ordering::SeqCst);
result
}
/// Legt einen Exportordner für Referenz-Läufe an (von Hand zu lösen, z. B. mit Claude Code).
#[tauri::command]
fn export_external(paths: State<'_, AppPaths>, task_ids: Vec<String>, repeats: u32) -> Result<external::ExportResult, String> {
let selected: Vec<tasks::Task> =
tasks::load_all(&paths.0.tasks_dir).tasks.into_iter().filter(|t| task_ids.contains(&t.meta.id)).collect();
if selected.len() != task_ids.len() {
return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into());
}
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let out = paths.0.data_dir.join("exports").join(format!("referenz-{stamp}"));
external::export(&selected, repeats, &out)
}
/// Prüft Ergebnisordner von Hand gelöster Aufgaben und speichert sie als externe Läufe.
#[tauri::command]
async fn import_external(
paths: State<'_, AppPaths>,
cfg: State<'_, ConfigState>,
run: State<'_, RunState>,
dir: String,
model: String,
batch_id: i64,
) -> Result<external::ImportSummary, String> {
let model = model.trim().to_string();
if model.is_empty() || model.chars().count() > 80 {
return Err("Der Modellname muss 1 bis 80 Zeichen lang sein.".into());
}
let (runtime, limits) = {
let c = cfg.config.lock().map_err(|e| e.to_string())?;
if c.models.iter().any(|m| m.name == model) {
return Err(format!(
"{model:?} ist ein angebundenes Modell. Wähle für die Referenz einen eigenen Namen, z. B. „{model} (extern)“."
));
}
(c.container_runtime.clone(), c.sandbox_limits())
};
let loaded = tasks::load_all(&paths.0.tasks_dir).tasks;
if run.running.swap(true, Ordering::SeqCst) {
return Err("Ein Batch oder Import läuft bereits.".into());
}
let _running_guard = FlagGuard(run.running.clone());
let run_cfg = RunConfig { runtime, models: Vec::new(), data_dir: paths.0.data_dir.clone(), limits };
let db_path = paths.0.data_dir.join(DB_FILE);
tauri::async_runtime::spawn_blocking(move || {
let mut store = Store::open(&db_path)?;
external::import(&mut store, &run_cfg, &loaded, std::path::Path::new(&dir), &model, batch_id)
})
.await
.map_err(|e| format!("Import abgebrochen: {e}"))?
}
/// Zustand eines Container-Images für die Einstellungen.
#[derive(Serialize)]
pub struct ImageStatus {
pub image: String,
pub available: bool,
/// Die App kann es selbst bauen.
pub buildable: bool,
/// Fehlertext, falls die Prüfung selbst scheiterte (z. B. Podman fehlt).
pub error: Option<String>,
}
/// Images, die die Aufgaben brauchen, und ihr Zustand.
#[tauri::command]
fn image_status(paths: State<'_, AppPaths>, cfg: State<'_, ConfigState>) -> Result<Vec<ImageStatus>, String> {
let runtime = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
let mut names: std::collections::BTreeSet<String> = tasks::load_all(&paths.0.tasks_dir)
.tasks
.into_iter()
.map(|t| t.meta.image)
.collect();
// Das eingebaute Standard-Image zeigen wir auch ohne Aufgaben.
names.insert("cb-python:latest".to_string());
Ok(names
.into_iter()
.map(|image| {
let buildable = images::embedded_containerfile(&image).is_some();
match images::exists(&runtime, &image) {
Ok(available) => ImageStatus { image, available, buildable, error: None },
Err(e) => ImageStatus { image, available: false, buildable, error: Some(e) },
}
})
.collect())
}
/// Baut ein eingebettetes Image. Die Ausgabe kommt zeilenweise als Ereignis `image-build`.
#[tauri::command]
async fn build_image(
app: tauri::AppHandle,
cfg: State<'_, ConfigState>,
run: State<'_, RunState>,
image: String,
) -> Result<(), String> {
tasks::validate_image(&image)?;
if images::embedded_containerfile(&image).is_none() {
return Err(format!("Für {image} gibt es kein eingebautes Containerfile."));
}
let runtime = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
if run.building.swap(true, Ordering::SeqCst) {
return Err("Es wird bereits ein Image gebaut.".into());
}
let _guard = FlagGuard(run.building.clone());
let emitter = app.clone();
tauri::async_runtime::spawn_blocking(move || {
let name = image.clone();
images::build(&runtime, &image, &mut |line| {
let _ = emitter.emit(IMAGE_EVENT, serde_json::json!({ "image": name, "line": line }));
})
})
.await
.map_err(|e| format!("Build-Thread abgebrochen: {e}"))?
}
/// Bricht den laufenden Batch ab. Der aktuelle Lauf wird verworfen.
/// Gibt `false` zurück, wenn gerade kein Batch läuft.
#[tauri::command]
@ -347,6 +503,7 @@ pub fn run() {
app.manage(RunState {
cancel: Arc::new(AtomicBool::new(false)),
running: Arc::new(AtomicBool::new(false)),
building: Arc::new(AtomicBool::new(false)),
});
Ok(())
})
@ -356,13 +513,18 @@ pub fn run() {
list_models,
save_models,
test_model,
discover_models,
export_external,
import_external,
start_batch,
cancel_batch,
list_batches,
batch_results,
batch_ranking,
run_steps,
runtime_status
runtime_status,
image_status,
build_image
])
.run(tauri::generate_context!())
.expect("error while running tauri application");

View File

@ -7,6 +7,8 @@
//! - 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.
//! - Läufe, die an Server oder Umgebung scheiterten (`endpoint_error`, `sandbox_error`), sagen
//! nichts über das Modell. Sie zählen nicht mit und werden getrennt gezählt (`excluded_runs`).
use crate::agent::ErrorClass;
use crate::store::RunRecord;
@ -33,7 +35,10 @@ pub struct GroupScore {
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ModelRank {
/// Platz unter den angebundenen Modellen. 0 bei Referenzen (`external`), sie zählen nicht im Rang.
pub rank: usize,
/// Referenz: von Hand außerhalb der App gelöst (z. B. Claude Code).
pub external: bool,
pub model: String,
/// Gesamtnote in Prozent von 0 bis 100.
pub total_percent: f64,
@ -44,6 +49,9 @@ pub struct ModelRank {
pub successes: usize,
pub median_duration_ms: u128,
pub mean_completion_tokens: f64,
/// Median der Tokens pro Sekunde über die Läufe (Tokens geteilt durch die gesamte Laufzeit,
/// also inklusive Tool- und Prüfzeit, nicht die reine Erzeugungsgeschwindigkeit).
pub median_tps: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
@ -71,12 +79,22 @@ pub struct Ranking {
pub cells: Vec<MatrixCell>,
/// Aufgaben des Batches, sortiert nach Bereich und ID.
pub tasks: Vec<TaskColumn>,
/// Läufe, die wegen Server- oder Umgebungsfehlern nicht in die Bewertung eingehen.
pub excluded_runs: usize,
}
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 {
pub fn compute(batch_id: i64, all_runs: &[RunRecord], tasks: &BTreeMap<String, TaskInfo>) -> Ranking {
let valid: Vec<RunRecord> = all_runs
.iter()
.filter(|r| !r.error_class.is_infrastructure())
.cloned()
.collect();
let excluded_runs = all_runs.len() - valid.len();
let runs = valid.as_slice();
let info_of = |task: &str| -> TaskInfo {
tasks.get(task).cloned().unwrap_or(TaskInfo {
group: UNKNOWN_GROUP.into(),
@ -165,8 +183,19 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], tasks: &BTreeMap<String, TaskI
let mean_tokens =
rs.iter().map(|r| r.completion_tokens as f64).sum::<f64>() / rs.len() as f64;
let mut tps: Vec<f64> = rs.iter().filter_map(|r| r.tps).filter(|t| t.is_finite()).collect();
tps.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let median_tps = if tps.is_empty() {
None
} else if tps.len() % 2 == 1 {
Some(tps[tps.len() / 2])
} else {
Some((tps[tps.len() / 2 - 1] + tps[tps.len() / 2]) / 2.0)
};
ModelRank {
rank: 0,
external: rs.iter().any(|r| r.external),
model: model.to_string(),
total_percent,
groups: group_scores,
@ -175,6 +204,7 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], tasks: &BTreeMap<String, TaskI
successes: rs.iter().filter(|r| r.error_class == ErrorClass::Ok).count(),
median_duration_ms: median_u128(&durations),
mean_completion_tokens: mean_tokens,
median_tps,
}
})
.collect();
@ -190,8 +220,15 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], tasks: &BTreeMap<String, TaskI
.unwrap_or(std::cmp::Ordering::Equal),
)
});
for (i, m) in models.iter_mut().enumerate() {
m.rank = i + 1;
// Referenzen stehen in der Liste, bekommen aber keinen Platz.
let mut next = 1;
for m in models.iter_mut() {
if m.external {
m.rank = 0;
} else {
m.rank = next;
next += 1;
}
}
let mut cell_map: BTreeMap<(&str, &str), Vec<&RunRecord>> = BTreeMap::new();
@ -212,7 +249,7 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], tasks: &BTreeMap<String, TaskI
})
.collect();
Ranking { batch_id, groups, models, cells, tasks: task_list }
Ranking { batch_id, groups, models, cells, tasks: task_list, excluded_runs }
}
fn median_u128(sorted: &[u128]) -> u128 {
@ -244,6 +281,7 @@ mod tests {
artifact_path: None,
summary: None,
check_output: String::new(),
external: false,
}
}
@ -253,6 +291,23 @@ mod tests {
.collect()
}
#[test]
fn referenz_bekommt_keinen_platz() {
let mut ext = run("Claude (extern)", "a", 1.0, ErrorClass::Ok, 0, 0);
ext.external = true;
let runs = vec![
run("klein", "a", 0.5, ErrorClass::CheckFailed, 10, 5),
run("groß", "a", 0.8, ErrorClass::CheckFailed, 10, 5),
ext,
];
let r = compute(1, &runs, &infos(&[("a", "A", 1.0)]));
let by = |n: &str| r.models.iter().find(|m| m.model == n).unwrap();
assert!(by("Claude (extern)").external);
assert_eq!(by("Claude (extern)").rank, 0);
assert_eq!(by("groß").rank, 1);
assert_eq!(by("klein").rank, 2);
}
#[test]
fn prozent_je_bereich_und_gesamt() {
// A: a1 (Gewicht 1), B: b1 (Gewicht 3).
@ -337,6 +392,22 @@ mod tests {
assert_eq!(r.groups, vec!["?".to_string()]);
}
#[test]
fn ausfaelle_der_umgebung_zaehlen_nicht_gegen_das_modell() {
let tasks = infos(&[("a1", "A", 1.0), ("a2", "A", 1.0)]);
let runs = vec![
run("m", "a1", 1.0, ErrorClass::Ok, 1, 1),
run("m", "a2", 0.0, ErrorClass::SandboxError, 0, 0),
run("n", "a1", 0.0, ErrorClass::EndpointError, 0, 0),
];
let r = compute(1, &runs, &tasks);
assert_eq!(r.excluded_runs, 2);
// m: nur a1 zählt, 100 %. Modell n hat keine gültigen Läufe und fehlt.
assert_eq!(r.models.len(), 1);
assert!((r.models[0].total_percent - 100.0).abs() < 1e-9);
assert_eq!(r.tasks.len(), 1);
}
#[test]
fn leerer_batch() {
let r = compute(7, &[], &BTreeMap::new());

View File

@ -166,6 +166,10 @@ pub fn run_batch(
}
'models: for model in &models {
if cancel.load(Ordering::SeqCst) {
summary.cancelled = true;
break 'models;
}
let client = make_client(cfg, model)?;
let warm = client.chat(
&[Message::new("user", "ping")],
@ -208,31 +212,21 @@ pub fn run_batch(
let fin = match &unavailable {
// Modell nicht nutzbar: Lauf wird als endpoint_error gespeichert, ohne Container.
Some(reason) => Finished {
record: RunRecord {
batch_id,
model: job.model.clone(),
task_id: job.task.meta.id.clone(),
repeat_idx: job.repeat_idx,
error_class: ErrorClass::EndpointError,
score: 0.0,
steps: 0,
prompt_tokens: 0,
completion_tokens: 0,
duration_ms: 0,
tps: None,
ttft_tool_ms: None,
artifact_path: None,
summary: None,
check_output: reason.clone(),
},
record: infra_record(batch_id, job, ErrorClass::EndpointError, reason),
transcript: vec![],
},
None => match execute_job(cfg, batch_id, i, job, &*client, cancel)? {
JobResult::Cancelled => {
None => match execute_job(cfg, batch_id, i, job, &*client, cancel) {
Ok(JobResult::Cancelled) => {
summary.cancelled = true;
break 'models;
}
JobResult::Finished(f) => f,
Ok(JobResult::Finished(f)) => f,
// Ein Fehler der Umgebung beendet nicht den Batch: Der Lauf wird als
// sandbox_error gespeichert und beim Fortsetzen wiederholt.
Err(message) => Finished {
record: infra_record(batch_id, job, ErrorClass::SandboxError, &message),
transcript: vec![],
},
},
};
@ -256,6 +250,28 @@ pub fn run_batch(
Ok(summary)
}
/// Lauf ohne Ergebnis, weil Umgebung oder Server ausfielen. Zählt nicht gegen das Modell.
fn infra_record(batch_id: i64, job: &Job, class: ErrorClass, message: &str) -> RunRecord {
RunRecord {
batch_id,
model: job.model.clone(),
task_id: job.task.meta.id.clone(),
repeat_idx: job.repeat_idx,
error_class: class,
score: 0.0,
steps: 0,
prompt_tokens: 0,
completion_tokens: 0,
duration_ms: 0,
tps: None,
ttft_tool_ms: None,
artifact_path: None,
summary: None,
check_output: message.to_string(),
external: false,
}
}
struct Finished {
record: RunRecord,
transcript: Vec<Message>,
@ -285,6 +301,57 @@ pub fn client_for(conn: &ModelConn) -> Result<Box<dyn ModelClient>, String> {
}
}
/// Führt `check.sh` im Container aus, außerhalb von /work, und wertet das Ergebnis aus.
pub fn run_check(sb: &Sandbox, task: &Task) -> (CheckResult, String) {
let meta = &task.meta;
let check_output = sb
.exec(&format!("mkdir -p {CHECK_DIR}"), Duration::from_secs(30))
.and_then(|_| sb.copy_in(&task.dir.join(CHECK_FILE), &format!("{CHECK_DIR}/check.sh")))
.and_then(|_| {
sb.exec(
&format!("cd /work && sh {CHECK_DIR}/check.sh"),
Duration::from_secs(meta.check_timeout_s),
)
});
match check_output {
Ok(out) => {
let text = format!(
"exit {}{}\n{}{}",
out.exit_code.map_or("?".into(), |c| c.to_string()),
if out.timed_out { " (Zeitlimit)" } else { "" },
out.stdout,
out.stderr
);
let check = if out.timed_out {
CheckResult { score: 0.0, passed: false }
} else {
evaluate_check(out.exit_code, &out.stdout)
};
(check, text)
}
Err(e) => (CheckResult { score: 0.0, passed: false }, format!("Prüfung nicht ausführbar: {e}")),
}
}
/// Prüft ein Ergebnis in einem frischen Container mit demselben Image, ohne den Agenten-Container.
/// `work` ist der exportierte Arbeitsordner. Scheitert schon der Start, ist das ein Fehler der
/// Umgebung (der Lauf wird dann nicht gewertet und beim Fortsetzen wiederholt).
pub fn check_in_fresh_container(
cfg: &RunConfig,
name: &str,
task: &Task,
work: &std::path::Path,
) -> Result<(CheckResult, String), String> {
remove_by_name(&cfg.runtime, name);
let sb = Sandbox::start(&cfg.runtime, name, &task.meta.image, &cfg.limits, Some(work))
.map_err(|e| format!("Prüf-Container nicht startbar: {e}"))?;
let result = run_check(&sb, task);
if let Err(e) = sb.remove() {
eprintln!("Container {name} nicht entfernt: {e}");
}
Ok(result)
}
fn execute_job(
cfg: &RunConfig,
batch_id: i64,
@ -310,49 +377,31 @@ fn execute_job(
.map_err(|e| format!("prompt.md nicht lesbar: {e}"))?;
let outcome = run_agent_cancellable(client, &ws, &prompt, &limits, cancel);
if outcome.cancelled {
sb.remove()?;
if let Err(e) = sb.remove() {
eprintln!("Container {} nicht entfernt: {e}", name);
}
return Ok(JobResult::Cancelled);
}
// check.sh läuft im selben Container, aber außerhalb von /work.
let check_output = sb
.exec(&format!("mkdir -p {CHECK_DIR}"), Duration::from_secs(30))
.and_then(|_| sb.copy_in(&job.task.dir.join(CHECK_FILE), &format!("{CHECK_DIR}/check.sh")))
.and_then(|_| {
sb.exec(
&format!("cd /work && sh {CHECK_DIR}/check.sh"),
Duration::from_secs(meta.check_timeout_s),
)
});
let (check, check_text) = match check_output {
Ok(out) => {
let text = format!(
"exit {}{}\n{}{}",
out.exit_code.map_or("?".into(), |c| c.to_string()),
if out.timed_out { " (Zeitlimit)" } else { "" },
out.stdout,
out.stderr
);
let check = if out.timed_out {
CheckResult { score: 0.0, passed: false }
} else {
evaluate_check(out.exit_code, &out.stdout)
};
(check, text)
}
Err(e) => (CheckResult { score: 0.0, passed: false }, format!("Prüfung nicht ausführbar: {e}")),
};
// Das Ergebnis geht aus dem Agenten-Container heraus, dann wird dieser entfernt. Die Prüfung
// läuft in einem frischen Container (#1044): Was der Agent im System verändert hat (Interpreter,
// `sh`, Hilfsprogramme), kann die Bewertung so nicht beeinflussen.
let artifact = cfg
.data_dir
.join("runs")
.join(batch_id.to_string())
.join(format!("{}-{}-{}", job.model.replace([':', '/'], "_"), meta.id, job.repeat_idx));
let artifact_path = match sb.export_work(&artifact.join("work")) {
Ok(()) => Some(artifact.join("work").display().to_string()),
Err(_) => None,
};
sb.remove()?;
let work_dir = artifact.join("work");
let _ = std::fs::remove_dir_all(&artifact); // alte Reste eines früheren Versuchs würden sonst einfließen
let exported = sb.export_work(&work_dir);
// Ein fehlschlagendes Aufräumen darf einen fertigen Lauf nicht verwerfen.
if let Err(e) = sb.remove() {
eprintln!("Container {} nicht entfernt: {e}", name);
}
exported.map_err(|e| format!("Ergebnis nicht exportierbar: {e}"))?;
let artifact_path = Some(work_dir.display().to_string());
let check_name = container_name(&format!("{batch_id}-{seq}-check"));
let (check, check_text) = check_in_fresh_container(cfg, &check_name, &job.task, &work_dir)?;
let class = final_class(outcome.class, &check);
let secs = outcome.duration_ms as f64 / 1000.0;
@ -377,6 +426,7 @@ fn execute_job(
artifact_path,
summary: outcome.summary.clone(),
check_output: check_text,
external: false,
};
Ok(JobResult::Finished(Finished {
record,
@ -402,6 +452,7 @@ mod tests {
check_timeout_s: 30,
},
dir: PathBuf::from("/x"),
prompt: String::new(),
}
}
@ -562,6 +613,48 @@ mod tests {
eprintln!("Datenbank: {}", data.join("db.sqlite").display());
}
/// Ein Modell, dessen Server nicht antwortet, bricht den Batch nicht ab. Die Läufe werden als
/// endpoint_error gespeichert, zählen nicht in die Bewertung und werden beim Fortsetzen wiederholt.
/// Braucht weder Podman noch einen Server (Port 1 auf localhost ist geschlossen).
#[test]
fn ausgefallenes_modell_wird_gespeichert_und_beim_fortsetzen_wiederholt() {
let cfg = RunConfig {
runtime: "podman".into(),
models: vec![ModelConn {
name: "weg".into(),
adapter: "ollama".into(),
url: "http://127.0.0.1:1".into(),
model_id: "x".into(),
api_key: None,
}],
data_dir: std::env::temp_dir().join("cb-unused"),
limits: Limits::default(),
};
let jobs = plan(&["weg".to_string()], &[task("a-01"), task("a-02")], 1);
let mut store = Store::open_in_memory().unwrap();
let cancel = AtomicBool::new(false);
let events = std::cell::RefCell::new(Vec::new());
let on = |e: &Event| events.borrow_mut().push(e.clone());
let first = run_batch(&mut store, &cfg, None, "t", 1, &jobs, &cancel, &on).unwrap();
assert_eq!(first.completed, 2);
assert!(events.borrow().iter().any(|e| matches!(e, Event::ModelUnavailable { .. })));
let runs = store.runs_for_batch(first.batch_id).unwrap();
assert_eq!(runs.len(), 2);
assert!(runs.iter().all(|r| r.error_class == ErrorClass::EndpointError));
// Fortsetzen: Ausfälle gelten nicht als fertig und werden wiederholt.
let second = run_batch(&mut store, &cfg, Some(first.batch_id), "", 1, &jobs, &cancel, &on).unwrap();
assert_eq!(second.completed, 2);
assert_eq!(second.skipped, 0);
// Die Bewertung ignoriert die Ausfälle.
let all = store.runs_for_batch(first.batch_id).unwrap();
let r = crate::ranking::compute(first.batch_id, &all, &Default::default());
assert_eq!(r.excluded_runs, 4);
assert!(r.models.is_empty());
}
#[test]
fn klasse_agent_vor_pruefung() {
let ok = CheckResult { score: 1.0, passed: true };
@ -570,4 +663,88 @@ mod tests {
assert_eq!(final_class(ErrorClass::Ok, &bad), ErrorClass::CheckFailed);
assert_eq!(final_class(ErrorClass::Ok, &ok), ErrorClass::Ok);
}
/// Belege für #1044 und #1043 gegen echtes Podman:
/// 1. Ein Agent kann Systemprogramme (hier `grep`) nicht mehr überschreiben (Nur-Lesen-Wurzel).
/// 2. Zustand, den der Agent im Container hinterlässt (`/tmp`, `/checks`), erreicht die Prüfung nicht,
/// weil sie in einem frischen Container läuft.
/// `CB_TEST_IMAGE=cb-python:latest cargo test runner::tests::agenten_container -- --ignored`
#[test]
#[ignore]
fn agenten_container_zustand_gelangt_nicht_in_die_pruefung() {
let image = std::env::var("CB_TEST_IMAGE").unwrap_or_else(|_| "cb-python:latest".into());
let base = std::env::temp_dir().join(format!("cb-fresh-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("task/start")).unwrap();
// Die Prüfung verlangt "42" und verlangt, dass kein Zustand aus dem Lauf übrig ist.
std::fs::write(
base.join("task/check.sh"),
"#!/bin/sh\ntest ! -e /checks/marker && test ! -e /tmp/marker && grep -qx 42 ergebnis.txt\n",
)
.unwrap();
std::fs::write(base.join("task/prompt.md"), "x").unwrap();
let mut t = task("manip");
t.meta.image = image.clone();
t.dir = base.join("task");
let cfg = RunConfig {
runtime: "podman".into(),
models: Vec::new(),
data_dir: base.join("data"),
limits: Limits::default(),
};
let name = container_name(&format!("manip-{}", std::process::id()));
remove_by_name("podman", &name);
let agent = Sandbox::start("podman", &name, &image, &cfg.limits, Some(&base.join("task/start"))).unwrap();
// 1. Das Überschreiben von grep scheitert, die Datei bleibt unverändert.
let tamper = agent
.exec("p=$(command -v grep); printf '#!/bin/sh\\nexit 0\\n' > \"$p\"", Duration::from_secs(30))
.unwrap();
assert_ne!(tamper.exit_code, Some(0), "Systemprogramm darf nicht überschreibbar sein");
let still = agent.exec("grep --version | head -1", Duration::from_secs(30)).unwrap();
assert!(!still.stdout.is_empty(), "grep ist unverändert");
// 2. Der Agent löst richtig und hinterlässt Zustand in beschreibbaren Ordnern.
let out = agent
.exec("echo 42 > /work/ergebnis.txt; touch /tmp/marker /checks/marker", Duration::from_secs(30))
.unwrap();
assert_eq!(out.exit_code, Some(0), "{}", out.stderr);
let (same, _) = run_check(&agent, &t);
assert!(!same.passed, "im selben Container wäre der hinterlassene Zustand sichtbar");
let work = base.join("export");
agent.export_work(&work).unwrap();
agent.remove().unwrap();
let (fresh, text) = check_in_fresh_container(&cfg, &format!("{name}-check"), &t, &work).unwrap();
assert!(fresh.passed, "frischer Container hat keinen Zustand aus dem Lauf: {text}");
let _ = std::fs::remove_dir_all(&base);
}
/// Alle echten Aufgaben: Startzustand im gehärteten Container prüfen. Die Prüfung darf an
/// der Lösung scheitern, aber nicht an der Härtung (Rechte, Nur-Lesen, Größe).
/// `CB_TEST_IMAGE=cb-python:latest cargo test runner::tests::pruefungen_laufen_gehaertet -- --ignored --nocapture`
#[test]
#[ignore]
fn pruefungen_laufen_gehaertet() {
let image = std::env::var("CB_TEST_IMAGE").unwrap_or_else(|_| "cb-python:latest".into());
let tasks_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../tasks");
let report = crate::tasks::load_all(&tasks_dir);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert!(!report.tasks.is_empty());
let cfg = RunConfig { runtime: "podman".into(), models: Vec::new(), data_dir: std::env::temp_dir(), limits: Limits::default() };
for t in &report.tasks {
let name = container_name(&format!("hart-{}-{}", std::process::id(), t.meta.id));
let start = t.dir.join(START_DIR);
remove_by_name("podman", &name);
let sb = Sandbox::start("podman", &name, &image, &cfg.limits, Some(&start)).unwrap();
let (c, text) = run_check(&sb, t);
sb.remove().unwrap();
println!("{}: passed={} score={} :: {}", t.meta.id, c.passed, c.score, text.replace('\n', " | "));
for bad in ["Read-only file system", "Permission denied", "Operation not permitted", "No space left"] {
assert!(!text.contains(bad), "{}: {bad}: {text}", t.meta.id);
}
}
let _ = cfg;
}
}

View File

@ -12,6 +12,12 @@ use std::thread;
use std::time::{Duration, Instant};
pub const WORK_DIR: &str = "/work";
/// Größe der schreibbaren Ordner im Container in MB. Sie zählen zum Speicherlimit des Containers.
pub const WORK_SIZE_MB: u32 = 256;
pub const TMP_SIZE_MB: u32 = 128;
pub const CHECKS_SIZE_MB: u32 = 64;
/// Obergrenze je Ausgabestrom eines Befehls. Mehr wird gelesen und verworfen.
pub const MAX_CAPTURE_BYTES: u64 = 1 << 20;
/// Ressourcenlimits eines Containers.
#[derive(Debug, Clone, PartialEq)]
@ -55,8 +61,22 @@ pub fn run_args(name: &str, image: &str, limits: &Limits) -> Vec<String> {
limits.cpus.clone(),
"--pids-limit".into(),
"512".into(),
// Härtung (#1043): keine Linux-Capabilities, keine neuen Rechte, Wurzeldateisystem nur lesbar.
"--cap-drop=ALL".into(),
"--security-opt=no-new-privileges".into(),
"--read-only".into(),
// Schreibbar sind nur diese Ordner, im Arbeitsspeicher und mit Größenlimit. So kann ein Lauf
// weder die Platte füllen noch das System im Container verändern.
"--tmpfs".into(),
format!("{WORK_DIR}:rw,exec,nosuid,nodev,size={WORK_SIZE_MB}m"),
"--tmpfs".into(),
format!("/tmp:rw,exec,nosuid,nodev,size={TMP_SIZE_MB}m"),
"--tmpfs".into(),
format!("/checks:rw,exec,nosuid,nodev,size={CHECKS_SIZE_MB}m"),
"--label".into(),
"coding-bench=lauf".into(),
// `--` beendet die Optionen: ein Image-Name wird so nie als Option gelesen.
"--".into(),
image.into(),
"sleep".into(),
"infinity".into(),
@ -64,6 +84,9 @@ pub fn run_args(name: &str, image: &str, limits: &Limits) -> Vec<String> {
}
/// Eindeutiger Containername pro Lauf.
/// Höchstdauer für das Herauskopieren von /work.
const EXPORT_TIMEOUT: Duration = Duration::from_secs(120);
pub fn container_name(run_id: &str) -> String {
format!("cb-{run_id}")
}
@ -153,16 +176,8 @@ impl Sandbox {
// Pipes in eigenen Threads lesen, sonst blockiert ein volles Ausgabepuffer.
let mut stdout = child.stdout.take().expect("stdout ist gepiped");
let mut stderr = child.stderr.take().expect("stderr ist gepiped");
let t_out = thread::spawn(move || {
let mut s = String::new();
let _ = stdout.read_to_string(&mut s);
s
});
let t_err = thread::spawn(move || {
let mut s = String::new();
let _ = stderr.read_to_string(&mut s);
s
});
let t_out = thread::spawn(move || read_limited(&mut stdout, MAX_CAPTURE_BYTES));
let t_err = thread::spawn(move || read_limited(&mut stderr, MAX_CAPTURE_BYTES));
let start = Instant::now();
let (status, timed_out) = loop {
@ -190,15 +205,32 @@ impl Sandbox {
std::fs::create_dir_all(dest).map_err(|e| format!("Zielordner nicht anlegbar: {e}"))?;
let src_spec = format!("{}:{WORK_DIR}/.", self.name);
let dst_spec = dest.display().to_string();
let out = Command::new(&self.runtime)
// Mit Zeitlimit: Ein Agent könnte Sonderdateien (z. B. eine Pipe) anlegen, an denen das Kopieren hängt.
let mut child = Command::new(&self.runtime)
.args(["cp", &src_spec, &dst_spec])
.output()
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
if !out.status.success() {
return Err(format!(
"/work nicht exportierbar: {}",
String::from_utf8_lossy(&out.stderr).trim()
));
let deadline = std::time::Instant::now() + EXPORT_TIMEOUT;
let status = loop {
match child.try_wait().map_err(|e| format!("Warten auf podman cp: {e}"))? {
Some(st) => break st,
None if std::time::Instant::now() >= deadline => {
let _ = child.kill();
let _ = child.wait();
return Err(format!("/work nicht exportierbar: Zeitlimit von {} s überschritten", EXPORT_TIMEOUT.as_secs()));
}
None => std::thread::sleep(Duration::from_millis(100)),
}
};
if !status.success() {
let mut err = String::new();
if let Some(mut e) = child.stderr.take() {
use std::io::Read;
let _ = e.read_to_string(&mut err);
}
return Err(format!("/work nicht exportierbar: {}", err.trim()));
}
Ok(())
}
@ -239,6 +271,26 @@ impl Sandbox {
}
}
/// Liest höchstens `limit` Bytes, verwirft den Rest (damit der Prozess nicht an einer vollen Pipe
/// hängt) und wandelt ungültiges UTF-8 in Ersatzzeichen um.
pub fn read_limited<R: Read>(reader: &mut R, limit: u64) -> String {
let mut buf = Vec::new();
let _ = reader.take(limit).read_to_end(&mut buf);
let mut truncated = false;
let mut sink = [0u8; 8192];
loop {
match reader.read(&mut sink) {
Ok(0) | Err(_) => break,
Ok(_) => truncated = true,
}
}
let mut text = String::from_utf8_lossy(&buf).into_owned();
if truncated {
text.push_str("\n[Ausgabe gekürzt]");
}
text
}
/// Entfernt einen Container nach Name, falls ein früherer Lauf ihn hinterlassen hat.
pub fn remove_by_name(runtime: &str, name: &str) {
let _ = Command::new(runtime).args(["rm", "-f", name]).output();
@ -264,6 +316,40 @@ mod tests {
assert!(s.ends_with("img:1 sleep infinity"));
}
#[test]
fn run_args_haerten_den_container() {
let s = run_args("cb-x", "img:1", &Limits::default()).join(" ");
assert!(s.contains("--cap-drop=ALL"));
assert!(s.contains("--security-opt=no-new-privileges"));
assert!(s.contains("--read-only"));
assert!(s.contains("--tmpfs /work:rw,exec,nosuid,nodev,size=256m"));
assert!(s.contains("--tmpfs /checks:"));
assert!(s.contains("--pids-limit 512"));
assert!(!s.contains("--privileged"));
}
#[test]
fn image_steht_nach_doppeltem_strich() {
let args = run_args("cb-x", "img:1", &Limits::default());
let pos = args.iter().position(|a| a == "--").expect("-- fehlt");
assert_eq!(args[pos + 1], "img:1");
}
#[test]
fn ausgabe_wird_begrenzt_und_utf8_ersetzt() {
let mut data = std::io::Cursor::new(vec![b'a'; 100]);
let text = read_limited(&mut data, 10);
assert!(text.starts_with("aaaaaaaaaa"));
assert!(text.contains("[Ausgabe gekürzt]"));
assert!(!text.contains("aaaaaaaaaaa"));
let mut kurz = std::io::Cursor::new(b"ok".to_vec());
assert_eq!(read_limited(&mut kurz, 10), "ok");
let mut kaputt = std::io::Cursor::new(vec![b'x', 0xff, b'y']);
assert_eq!(read_limited(&mut kaputt, 10), "x\u{fffd}y");
}
#[test]
fn containername_ist_praefixiert() {
assert_eq!(container_name("42"), "cb-42");
@ -316,4 +402,46 @@ mod tests {
assert!(String::from_utf8_lossy(&ps.stdout).trim().is_empty(), "Container nicht entfernt");
let _ = std::fs::remove_dir_all(&base);
}
/// Echter Test der Härtung (#1043) gegen Podman. `CB_TEST_IMAGE=cb-python:latest cargo test sandbox::tests::gehaertet -- --ignored`
#[test]
#[ignore]
fn gehaertet_keine_rechte_nur_work_schreibbar_mit_limit() {
let image = std::env::var("CB_TEST_IMAGE").unwrap_or_else(|_| "cb-python:latest".into());
let name = container_name(&format!("hart-{}", std::process::id()));
remove_by_name("podman", &name);
let dir = std::env::temp_dir().join(format!("cb-hart-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("start.txt"), "hallo").unwrap();
std::fs::write(dir.join("lauf.sh"), "#!/bin/sh\necho ausgefuehrt\n").unwrap();
let _ = Command::new("chmod").args(["+x", &dir.join("lauf.sh").display().to_string()]).output();
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), Some(&dir)).unwrap();
let ex = |cmd: &str| sb.exec(cmd, Duration::from_secs(30)).unwrap();
// Keine Capabilities, keine neuen Rechte.
let st = ex("grep -E 'CapEff|NoNewPrivs' /proc/self/status");
assert!(st.stdout.contains("CapEff:\t0000000000000000"), "{}", st.stdout);
assert!(st.stdout.contains("NoNewPrivs:\t1"), "{}", st.stdout);
// Wurzeldateisystem nur lesbar, /work, /tmp und /checks schreibbar.
assert_ne!(ex("touch /usr/neu 2>/dev/null").exit_code, Some(0), "/usr darf nicht schreibbar sein");
assert_eq!(ex("touch /work/a /tmp/a /checks/a").exit_code, Some(0));
// Startdateien sind da, ein ausführbares Skript in /work läuft.
assert_eq!(ex("cat /work/start.txt").stdout.trim(), "hallo");
assert!(ex("/work/lauf.sh").stdout.contains("ausgefuehrt"));
// Größenlimit: 300 MB passen nicht in /work (Limit 256 MB).
let big = ex("dd if=/dev/zero of=/work/gross bs=1M count=300 2>&1; echo exit=$?");
assert!(!big.stdout.contains("exit=0"), "Limit muss greifen: {}", big.stdout);
// Ergebnis lässt sich trotzdem herausholen.
let out = dir.join("export");
sb.export_work(&out).unwrap();
assert!(out.join("start.txt").is_file());
sb.remove().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
}

View File

@ -90,6 +90,8 @@ pub struct RunRecord {
pub artifact_path: Option<String>,
pub summary: Option<String>,
pub check_output: String,
/// Von Hand außerhalb der App gelöst (Referenz), nicht von einem angebundenen Modell.
pub external: bool,
}
pub struct Store {
@ -111,9 +113,40 @@ impl Store {
conn.execute_batch("PRAGMA foreign_keys = ON;")
.and_then(|_| conn.execute_batch(SCHEMA))
.map_err(|e| format!("Schema nicht anlegbar: {e}"))?;
Self::migrate(&conn)?;
Ok(Store { conn })
}
/// Ältere Datenbanken bekommen neue Spalten nachgerüstet.
fn migrate(conn: &Connection) -> Result<(), String> {
let has_external = conn
.prepare("SELECT 1 FROM pragma_table_info('run') WHERE name = 'external'")
.and_then(|mut st| st.exists([]))
.map_err(|e| e.to_string())?;
if !has_external {
conn.execute_batch("ALTER TABLE run ADD COLUMN external INTEGER NOT NULL DEFAULT 0;")
.map_err(|e| format!("Migration fehlgeschlagen: {e}"))?;
}
Ok(())
}
/// Entfernt einen Lauf samt Schritten, damit ein Import ihn ersetzen kann.
pub fn delete_run(&mut self, batch_id: i64, model: &str, task_id: &str, repeat_idx: u32) -> Result<(), String> {
let tx = self.conn.transaction().map_err(|e| e.to_string())?;
tx.execute(
"DELETE FROM step WHERE run_id IN
(SELECT id FROM run WHERE batch_id = ?1 AND model = ?2 AND task_id = ?3 AND repeat_idx = ?4)",
params![batch_id, model, task_id, repeat_idx],
)
.map_err(|e| e.to_string())?;
tx.execute(
"DELETE FROM run WHERE batch_id = ?1 AND model = ?2 AND task_id = ?3 AND repeat_idx = ?4",
params![batch_id, model, task_id, repeat_idx],
)
.map_err(|e| e.to_string())?;
tx.commit().map_err(|e| e.to_string())
}
pub fn create_batch(&self, note: &str, repeats: u32, config_json: &str) -> Result<i64, String> {
self.conn
.execute(
@ -132,11 +165,15 @@ impl Store {
.map_err(|e| e.to_string())
}
/// Schlüssel (Modell, Aufgabe, Wiederholung) aller bereits gespeicherten Läufe eines Batches.
/// Schlüssel (Modell, Aufgabe, Wiederholung) der gültig beendeten Läufe eines Batches.
/// Läufe, die an Server oder Umgebung scheiterten, fehlen hier und werden wiederholt.
pub fn finished_keys(&self, batch_id: i64) -> Result<HashSet<(String, String, u32)>, String> {
let mut stmt = self
.conn
.prepare("SELECT model, task_id, repeat_idx FROM run WHERE batch_id = ?1")
.prepare(
"SELECT model, task_id, repeat_idx FROM run
WHERE batch_id = ?1 AND error_class NOT IN ('endpoint_error', 'sandbox_error')",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![batch_id], |r| {
@ -156,8 +193,8 @@ impl Store {
tx.execute(
"INSERT INTO run (batch_id, model, task_id, repeat_idx, status, error_class, score,
steps, prompt_tokens, completion_tokens, duration_ms, tps, ttft_tool_ms,
artifact_path, summary, check_output)
VALUES (?1, ?2, ?3, ?4, 'done', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
artifact_path, summary, check_output, external)
VALUES (?1, ?2, ?3, ?4, 'done', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
params![
rec.batch_id,
rec.model,
@ -174,6 +211,7 @@ impl Store {
rec.artifact_path,
rec.summary,
rec.check_output,
rec.external as i64,
],
)
.map_err(|e| e.to_string())?;
@ -209,7 +247,7 @@ impl Store {
.prepare(
"SELECT batch_id, model, task_id, repeat_idx, error_class, score, steps,
prompt_tokens, completion_tokens, duration_ms, tps, ttft_tool_ms,
artifact_path, summary, check_output
artifact_path, summary, check_output, external
FROM run WHERE batch_id = ?1 ORDER BY model, task_id, repeat_idx",
)
.map_err(|e| e.to_string())?;
@ -234,6 +272,7 @@ impl Store {
artifact_path: r.get(12)?,
summary: r.get(13)?,
check_output: r.get(14)?,
external: r.get::<_, i64>(15)? != 0,
})
})
.map_err(|e| e.to_string())?;
@ -334,6 +373,7 @@ mod tests {
artifact_path: None,
summary: Some("fertig".into()),
check_output: "ok".into(),
external: false,
}
}
@ -410,6 +450,23 @@ mod tests {
assert!(list[1].models.contains("m1") && list[1].models.contains("m2"));
}
#[test]
fn infrastruktur_laeufe_werden_beim_fortsetzen_wiederholt() {
let mut s = Store::open_in_memory().unwrap();
let b = s.create_batch("", 1, "{}").unwrap();
s.insert_run(&rec(b, "m", "ok-task", 1), &[]).unwrap();
let mut ausfall = rec(b, "m", "sandbox-task", 1);
ausfall.error_class = ErrorClass::SandboxError;
s.insert_run(&ausfall, &[]).unwrap();
let mut server = rec(b, "m", "server-task", 1);
server.error_class = ErrorClass::EndpointError;
s.insert_run(&server, &[]).unwrap();
let keys = s.finished_keys(b).unwrap();
assert!(keys.contains(&("m".to_string(), "ok-task".to_string(), 1)));
assert!(!keys.contains(&("m".to_string(), "sandbox-task".to_string(), 1)));
assert!(!keys.contains(&("m".to_string(), "server-task".to_string(), 1)));
}
#[test]
fn unbekannter_batch_existiert_nicht() {
let s = Store::open_in_memory().unwrap();

View File

@ -45,6 +45,8 @@ pub struct Task {
#[serde(flatten)]
pub meta: TaskToml,
pub dir: PathBuf,
/// Inhalt von `prompt.md`, damit die Oberfläche zeigen kann, was die Aufgabe verlangt.
pub prompt: String,
}
/// Ein Fehler bei einer Aufgabe, mit Ordner und Grund.
@ -61,6 +63,27 @@ pub struct LoadReport {
pub errors: Vec<TaskError>,
}
/// Prüft einen Image-Namen. Erlaubt sind Buchstaben, Ziffern und `. _ - / : @`; er darf nicht
/// mit `-` beginnen. Sonst könnte ein fremder Aufgaben-Ordner Podman-Optionen einschleusen.
pub fn validate_image(image: &str) -> Result<(), String> {
if image.is_empty() {
return Err("image ist leer".into());
}
if image.len() > 200 {
return Err("image ist zu lang".into());
}
if image.starts_with('-') {
return Err(format!("image {image:?} darf nicht mit - beginnen"));
}
if let Some(c) = image
.chars()
.find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/' | ':' | '@')))
{
return Err(format!("image {image:?} enthält das unzulässige Zeichen {c:?}"));
}
Ok(())
}
/// Validiert die Metadaten. Gibt eine Liste aller Verstöße zurück.
pub fn validate_meta(meta: &TaskToml) -> Vec<String> {
let mut errs = Vec::new();
@ -76,8 +99,8 @@ pub fn validate_meta(meta: &TaskToml) -> Vec<String> {
if !meta.weight.is_finite() || meta.weight <= 0.0 {
errs.push("weight muss größer als 0 sein".into());
}
if meta.image.trim().is_empty() {
errs.push("image ist leer".into());
if let Err(e) = validate_image(&meta.image) {
errs.push(e);
}
if meta.max_steps == 0 {
errs.push("max_steps muss größer als 0 sein".into());
@ -143,6 +166,7 @@ pub fn load_one(dir: &Path) -> Result<Task, Vec<String>> {
(Some(meta), true) => Ok(Task {
meta,
dir: dir.to_path_buf(),
prompt: fs::read_to_string(dir.join(PROMPT_FILE)).unwrap_or_default(),
}),
_ => Err(errs),
}
@ -276,6 +300,17 @@ timeout_s = 600
let _ = fs::remove_dir_all(&base);
}
#[test]
fn image_namen_werden_geprueft() {
for ok in ["cb-python:latest", "docker.io/library/python:3.12-slim", "localhost/cb-x@sha256:abc"] {
assert!(validate_image(ok).is_ok(), "{ok}");
}
for bad in ["", "--privileged", "-v", "img name", "img;rm", "img\nx", "a$b", "--mount=type=bind,src=/home"] {
assert!(validate_image(bad).is_err(), "{bad:?} sollte abgelehnt werden");
}
assert!(validate_image(&"a".repeat(201)).is_err());
}
#[test]
fn ungueltige_zahlen_werden_gemeldet() {
let meta: TaskToml = toml::from_str(&GUT.replace("max_steps = 25", "max_steps = 0")).unwrap();

View File

@ -1,15 +1,23 @@
: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;
color-scheme: dark;
--bg: #0f1115;
--bg-glow: rgba(255, 155, 69, 0.10);
--surface: #181b21;
--surface-2: #222630;
--text: #eceff4;
--muted: #9099a8;
--border: #2b303a;
--accent: #ff9b45;
--accent-soft: rgba(255, 155, 69, 0.14);
--accent-text: #1a1005;
--danger: #ff7b72;
--ok: #6fd18a;
--gold: #ffcf5c;
--silver: #c3cad6;
--bronze: #d9915a;
--pct-l: 58%;
--radius: 14px;
--shadow: 0 6px 24px rgba(0, 0, 0, 0.35);
font-family: Inter, "Segoe UI", system-ui, -apple-system, sans-serif;
font-size: 15px;
line-height: 1.5;
@ -18,18 +26,26 @@
-webkit-text-size-adjust: 100%;
}
@media (prefers-color-scheme: dark) {
@media (prefers-color-scheme: light) {
:root {
--bg: #14171b;
--surface: #1d2127;
--surface-2: #272c34;
--text: #e6e9ed;
--muted: #98a2b0;
--border: #353b45;
--accent: #5b9bd5;
--accent-text: #0e1218;
--danger: #ff8a80;
--ok: #7bc47f;
color-scheme: light;
--pct-l: 38%;
--bg: #f6f3ef;
--bg-glow: rgba(255, 155, 69, 0.16);
--surface: #ffffff;
--surface-2: #f0ebe4;
--text: #1d1a17;
--muted: #6b645c;
--border: #e2dbd2;
--accent: #f08a2c;
--accent-soft: rgba(240, 138, 44, 0.14);
--accent-text: #ffffff;
--danger: #c0392b;
--ok: #2e8b57;
--gold: #d49a00;
--silver: #8a93a1;
--bronze: #b8691f;
--shadow: 0 6px 20px rgba(60, 40, 20, 0.10);
}
}
@ -39,7 +55,8 @@
body {
margin: 0;
background: var(--bg);
min-height: 100vh;
background: radial-gradient(ellipse 70rem 28rem at 50% -8rem, var(--bg-glow), transparent), var(--bg);
color: var(--text);
}
@ -47,22 +64,23 @@ h1, h2, h3 {
line-height: 1.25;
margin: 0 0 0.6rem;
}
h2 { font-size: 1.15rem; }
h2 { font-size: 1.25rem; letter-spacing: -0.01em; }
h3 { font-size: 1rem; }
button {
font: inherit;
padding: 0.45rem 0.9rem;
border-radius: 8px;
border-radius: 10px;
border: 1px solid var(--border);
background: var(--surface-2);
transition: border-color 0.12s, transform 0.12s, background 0.12s;
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);
background: linear-gradient(180deg, color-mix(in srgb, var(--accent) 88%, white), var(--accent));
color: var(--accent-text);
border-color: var(--accent);
font-weight: 600;
@ -99,8 +117,9 @@ code, pre {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1rem 1.2rem;
margin-bottom: 1rem;
padding: 1.2rem 1.4rem;
margin-bottom: 1.1rem;
box-shadow: var(--shadow);
}
.muted { color: var(--muted); }
@ -115,6 +134,8 @@ code, pre {
background: var(--surface-2);
border: 1px solid var(--border);
}
.chip.ok { background: color-mix(in srgb, var(--ok) 16%, transparent); border-color: transparent; }
.chip.error { background: color-mix(in srgb, var(--danger) 16%, transparent); border-color: transparent; }
table {
width: 100%;
@ -134,3 +155,6 @@ th {
letter-spacing: 0.03em;
}
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); }
.small { font-size: 0.8rem; }

View File

@ -2,7 +2,8 @@
<html lang="de">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<link rel="icon" type="image/svg+xml" href="%sveltekit.assets%/favicon.svg" />
<link rel="icon" type="image/png" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>coding-bench</title>
%sveltekit.head%

View File

@ -1,7 +1,19 @@
<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";
import {
api,
errorLabel,
fmtPct,
groupLabel,
isInfrastructure,
pctColor,
type BatchEvent,
type LoadReport,
type ModelInfo,
type Ranking,
type TaskInfo,
} from "$lib/api";
let {
models,
@ -25,10 +37,29 @@
let current = $state("");
let finishedBatch = $state<number | null>(null);
let cancelled = $state(false);
let expanded = $state<string[]>([]);
// Was die letzte Messung ergeben hat: Grundlage für „zuletzt“ und die Zeitschätzung.
let last = $state<Ranking | null>(null);
// Stand je Modell und Aufgabe im aktuellen Lauf.
type Cell = { state: "planned" | "running" | "done" | "skipped" | "infra"; n: number; sum: number; cls: string };
let cells = $state<Record<string, Cell>>({});
const key = (model: string, task: string) => `${model}\u0001${task}`;
let unlisten: UnlistenFn | null = null;
async function loadLast() {
try {
const b = await api.batches();
last = b.length > 0 ? await api.ranking(b[0].id) : null;
} catch {
last = null;
}
}
onMount(async () => {
loadLast();
unlisten = await listen<BatchEvent>("batch-event", (ev) => onEvent(ev.payload));
});
onDestroy(() => unlisten?.());
@ -40,20 +71,38 @@
}
if (e.kind === "model_unavailable") {
log.push({ text: `${e.model}: nicht erreichbar (${e.reason})`, cls: "error" });
for (const t of chosenTasks) {
const c = cells[key(e.model, t)];
if (c && c.state !== "done") c.state = "infra";
}
return;
}
const label = `${e.model} · ${e.task} · Durchlauf ${e.repeat}`;
const c = cells[key(e.model, e.task)];
if (e.kind === "run_started") {
current = label;
if (c) c.state = "running";
} else if (e.kind === "run_skipped") {
log.push({ text: `übersprungen: ${label}`, cls: "muted" });
if (c && c.state === "planned") c.state = "skipped";
} else if (e.kind === "run_finished") {
const ok = e.class === "ok";
log.push({
text: `${ok ? "bestanden" : e.class}: ${label}, ${Math.round(e.score * 100)} %`,
text: `${errorLabel(e.class)}: ${label}, ${Math.round(e.score * 100)} %`,
cls: ok ? "ok" : "error",
});
current = "";
if (c) {
if (isInfrastructure(e.class)) {
c.state = "infra";
c.cls = e.class;
} else {
c.n += 1;
c.sum += e.score;
c.state = c.n >= repeats ? "done" : "planned";
c.cls = e.class;
}
}
}
}
@ -73,23 +122,55 @@
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));
chosenTasks = on ? [...new Set([...chosenTasks, ...ids])] : chosenTasks.filter((id) => !ids.includes(id));
}
function allModels(on: boolean) {
chosenModels = on ? models.map((m) => m.name) : [];
}
function lastTask(id: string): { models: number; mean: number } | null {
const cs = last?.cells.filter((c) => c.task_id === id) ?? [];
if (cs.length === 0) return null;
return { models: cs.length, mean: (100 * cs.reduce((a, c) => a + c.mean_score, 0)) / cs.length };
}
function lastCell(model: string, task: string): number | null {
const c = last?.cells.find((c) => c.model === model && c.task_id === task);
return c ? c.mean_score * 100 : null;
}
function lastRank(model: string) {
return last?.models.find((m) => m.model === model) ?? null;
}
let totalRuns = $derived(chosenModels.length * chosenTasks.length * repeats);
let canStart = $derived(!running && chosenModels.length > 0 && chosenTasks.length > 0 && repeats >= 1);
async function start() {
// Geschätzte Dauer aus den Median-Laufzeiten früherer Läufe. Fehlt ein Modell, zählt der Schnitt der übrigen.
let estimate = $derived.by(() => {
const known = chosenModels.map((m) => lastRank(m)?.median_duration_ms).filter((x): x is number => typeof x === "number" && x > 0);
if (known.length === 0 || totalRuns === 0) return null;
const avg = known.reduce((a, b) => a + b, 0) / known.length;
const ms = chosenModels.reduce((sum, m) => sum + (lastRank(m)?.median_duration_ms || avg) * chosenTasks.length * repeats, 0);
return { minutes: Math.max(1, Math.round(ms / 60000)), basis: known.length, of: chosenModels.length };
});
function chosenTaskInfos(): TaskInfo[] {
return (tasks?.tasks ?? []).filter((t) => chosenTasks.includes(t.id));
}
async function start(resumeBatch: number | null = null) {
error = "";
log = [];
progress = null;
finishedBatch = null;
cancelled = false;
cells = {};
for (const m of chosenModels) for (const t of chosenTaskInfos()) cells[key(m, t.id)] = { state: "planned", n: 0, sum: 0, cls: "" };
running = true;
try {
const s = await api.startBatch($state.snapshot(chosenModels), $state.snapshot(chosenTasks), repeats, "");
const s = await api.startBatch($state.snapshot(chosenModels), $state.snapshot(chosenTasks), repeats, "", resumeBatch);
finishedBatch = s.batch_id;
cancelled = s.cancelled;
} catch (e) {
@ -97,31 +178,58 @@
} finally {
running = false;
current = "";
loadLast();
}
}
// Offen ist, was nicht fertig gewertet wurde: abgebrochen oder durch einen Ausfall nicht gewertet.
let openCells = $derived(Object.values(cells).filter((c) => c.state !== "done" && c.state !== "skipped").length);
let canResume = $derived(!running && finishedBatch !== null && openCells > 0);
function cellOf(model: string, task: string): Cell | undefined {
return cells[key(model, task)];
}
</script>
{#if models.length === 0}
<section class="card">
<section class="card empty">
<h2>Noch kein Modell angebunden</h2>
<p class="muted">Bevor ein Benchmark laufen kann, braucht coding-bench mindestens ein Modell.</p>
<ol class="muted steps">
<li>Modell mit Adapter und Server-URL anlegen</li>
<li>Container-Image bauen (einmalig)</li>
<li>Hier Modelle und Aufgaben wählen und starten</li>
</ol>
<button class="primary" onclick={ongotosettings}>Modell in den Einstellungen anlegen</button>
</section>
{:else}
<section class="card">
<div class="head">
<h2>1. Modelle</h2>
<div class="choices">
<button class="link" disabled={running} onclick={() => allModels(true)}>alle</button>
<button class="link" disabled={running} onclick={() => allModels(false)}>keine</button>
</div>
<div class="model-grid">
{#each models as m (m.name)}
<label class="choice">
{@const r = lastRank(m.name)}
<label class="mcard" class:on={chosenModels.includes(m.name)}>
<input
type="checkbox"
checked={chosenModels.includes(m.name)}
disabled={running}
onchange={() => (chosenModels = toggle(chosenModels, m.name))}
/>
<span>
<span class="mtext">
<strong>{m.name}</strong>
<span class="muted">{m.adapter === "ollama" ? "Ollama" : "OpenAI-kompatibel"} · {m.url}</span>
<span class="muted small">{m.adapter === "ollama" ? "Ollama" : "OpenAI-kompatibel"} · {m.url}</span>
{#if r}
<span class="small" style:color={pctColor(r.total_percent)}>zuletzt {fmtPct(r.total_percent)} gesamt</span>
{:else}
<span class="muted small">noch nicht gemessen</span>
{/if}
{#if m.api_key_env && !m.api_key_set}
<span class="error small">Schlüssel-Variable {m.api_key_env} nicht gesetzt</span>
{/if}
</span>
</label>
{/each}
@ -137,23 +245,44 @@
{/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>
<div class="head">
<h3><span class="gbadge">{group}</span> {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>
<div class="task-grid">
{#each list as t (t.id)}
<label class="choice">
{@const lt = lastTask(t.id)}
{@const open = expanded.includes(t.id)}
<div class="tcard" class:on={chosenTasks.includes(t.id)}>
<label class="thead">
<input
type="checkbox"
checked={chosenTasks.includes(t.id)}
disabled={running}
onchange={() => (chosenTasks = toggle(chosenTasks, t.id))}
/>
<span><strong>{t.id}</strong> {t.title}</span>
<span><strong>{t.title}</strong> <span class="muted small">{t.id}</span></span>
</label>
<p class="desc" class:clamp={!open}>{t.prompt.trim() || "Keine Beschreibung."}</p>
<div class="chips">
<span class="chip" title="Höchstzahl der Agentenschritte">≤ {t.max_steps} Schritte</span>
<span class="chip" title="Zeitlimit je Lauf">{t.timeout_s} s</span>
{#if t.weight !== 1}<span class="chip" title="Gewicht in der Bewertung">Gewicht {t.weight}</span>{/if}
<span class="chip" title="Container-Image">{t.image}</span>
</div>
<div class="tfoot">
{#if lt}
<span class="small" style:color={pctColor(lt.mean)}>zuletzt ∅ {fmtPct(lt.mean)} ({lt.models} Modell{lt.models === 1 ? "" : "e"})</span>
{:else}
<span class="muted small">noch nie gelaufen</span>
{/if}
<button class="link" onclick={() => (expanded = toggle(expanded, t.id))}>{open ? "weniger" : "Aufgabentext"}</button>
</div>
</div>
{/each}
</div>
</div>
{/each}
{#if tasks && tasks.errors.length > 0}
<details>
@ -167,35 +296,66 @@
{/if}
</section>
{#if chosenModels.length > 0 && chosenTasks.length > 0}
<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.
<h2>Plan und Stand</h2>
<p class="muted small">
Jede Zelle ist ein Modell bei einer Aufgabe. Vor dem Start steht dort, was zuletzt gemessen wurde. Beim Lauf füllt sie
sich live.
</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>
<div class="scroll">
<table class="plan">
<thead>
<tr>
<th>Modell</th>
{#each chosenTaskInfos() as t (t.id)}<th class="num" title={t.title}>{t.id}</th>{/each}
</tr>
</thead>
<tbody>
{#each chosenModels as m (m)}
<tr>
<td>{m}</td>
{#each chosenTaskInfos() as t (t.id)}
{@const c = cellOf(m, t.id)}
{@const lc = lastCell(m, t.id)}
<td class="num cell" class:running={c?.state === "running"}>
{#if c?.state === "done"}
{@const p = (100 * c.sum) / c.n}
<span class="done" style:background={`color-mix(in srgb, ${pctColor(p)} 30%, transparent)`}>{fmtPct(p)}</span>
{:else if c?.state === "running"}
<span class="pulse">läuft …</span>
{:else if c?.state === "infra"}
<span class="error small" title="Server oder Umgebung ausgefallen, nicht gewertet">nicht gewertet</span>
{:else if c?.state === "skipped"}
<span class="muted small">schon vorhanden</span>
{:else if c?.state === "planned"}
<span class="muted small">geplant{c.n > 0 ? ` ${c.n}/${repeats}` : ""}</span>
{:else if lc !== null}
<span class="muted small">zuletzt {fmtPct(lc)}</span>
{:else}
<span class="muted small">neu</span>
{/if}
{#if current}<p>Läuft: <strong>{current}</strong></p>{/if}
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
</section>
{/if}
{#if log.length > 0 || error || finishedBatch !== null}
<section class="card">
<h2>Verlauf</h2>
{#if error}<p class="error">{error}</p>{/if}
{#if finishedBatch !== null}
<p>
{cancelled ? "Abgebrochen." : "Fertig."}
{cancelled ? "Abgebrochen." : openCells > 0 ? `Fertig, aber ${openCells} Zelle(n) offen oder nicht gewertet.` : "Fertig."}
<button class="link" onclick={() => onfinished(finishedBatch!)}>Ergebnisse ansehen</button>
{#if canResume}
· <button class="link" onclick={() => start(finishedBatch)}>Fortsetzen</button>
{/if}
</p>
{/if}
{#if log.length > 0}
@ -208,67 +368,179 @@
</section>
{/if}
<div class="startbar">
<div class="summary">
{#if totalRuns > 0}
<strong>{totalRuns} Läufe</strong>
<span class="muted">{chosenModels.length} Modell(e) × {chosenTasks.length} Aufgabe(n) × {repeats}</span>
{#if estimate}
<span class="muted" title="Median-Laufzeit früherer Läufe, {estimate.basis} von {estimate.of} Modellen gemessen">
≈ {estimate.minutes} min
</span>
{:else}
<span class="muted">Dauer unbekannt, noch keine Messung</span>
{/if}
{:else}
<span class="muted">Wähle Modelle und Aufgaben.</span>
{/if}
{#if repeats < 3 && totalRuns > 0}
<span class="warn small">Bei weniger als 3 Durchläufen können Unterschiede zwischen Modellen Zufall sein.</span>
{/if}
</div>
<label class="rep">
Durchläufe
<input type="number" min="1" max="20" bind:value={repeats} disabled={running} />
</label>
<button class="primary" onclick={() => start()} disabled={!canStart}>Benchmark starten</button>
<button class="danger" onclick={() => api.cancelBatch()} disabled={!running}>Abbrechen</button>
{#if progress}
<div class="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>
<span class="small muted">{progress.done} von {progress.total}{current ? ` · läuft: ${current}` : ""}</span>
</div>
{/if}
</div>
{/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 {
.head {
display: flex;
align-items: baseline;
gap: 0.8rem;
margin-bottom: 0.6rem;
}
.group-head h3 {
.head h2,
.head h3 {
flex: 1;
margin: 0;
}
.start label {
.small {
font-size: 0.8rem;
}
.warn {
color: var(--accent);
}
.empty .steps {
padding-left: 1.2rem;
}
.model-grid,
.task-grid {
display: grid;
gap: 0.7rem;
}
.model-grid {
grid-template-columns: repeat(auto-fill, minmax(17rem, 1fr));
}
.task-grid {
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
}
.mcard,
.tcard {
border: 1px solid var(--border);
border-radius: 12px;
background: var(--surface-2);
padding: 0.75rem 0.9rem;
transition: border-color 0.12s, background 0.12s;
}
.mcard {
display: flex;
gap: 0.7rem;
align-items: flex-start;
cursor: pointer;
}
.mcard.on,
.tcard.on {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 8%, var(--surface-2));
}
.mtext {
display: flex;
flex-direction: column;
gap: 0.2rem;
width: 12rem;
font-size: 0.85rem;
color: var(--muted);
gap: 0.1rem;
min-width: 0;
overflow-wrap: anywhere;
}
.start input {
color: var(--text);
font-size: 1rem;
.group {
margin-bottom: 1.1rem;
}
.buttons {
.gbadge {
display: inline-grid;
place-items: center;
width: 1.5rem;
height: 1.5rem;
border-radius: 6px;
background: var(--accent);
color: var(--accent-text);
font-size: 0.8rem;
font-weight: 800;
margin-right: 0.3rem;
}
.thead input,
.mcard input {
flex-shrink: 0;
}
.thead .small {
white-space: nowrap;
}
.thead {
display: flex;
gap: 0.6rem;
margin-top: 0.6rem;
align-items: baseline;
cursor: pointer;
}
.bar {
height: 10px;
background: var(--surface-2);
border-radius: 999px;
.desc {
margin: 0.5rem 0;
font-size: 0.88rem;
color: var(--muted);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.desc.clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
margin-top: 1rem;
}
.fill {
height: 100%;
background: var(--accent);
transition: width 0.3s;
.chips {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.tfoot {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-top: 0.5rem;
}
.scroll {
overflow-x: auto;
}
.plan .cell {
white-space: nowrap;
}
.done {
display: inline-block;
padding: 0.05rem 0.5rem;
border-radius: 6px;
font-weight: 600;
}
.pulse {
color: var(--accent);
animation: pulse 1.1s ease-in-out infinite;
}
@keyframes pulse {
50% {
opacity: 0.35;
}
}
.log {
list-style: none;
padding: 0.6rem;
margin: 0.8rem 0 0;
max-height: 18rem;
max-height: 14rem;
overflow-y: auto;
background: var(--bg);
border: 1px solid var(--border);
@ -276,4 +548,56 @@
font-family: ui-monospace, Menlo, monospace;
font-size: 0.85rem;
}
.startbar {
position: sticky;
bottom: 0.8rem;
z-index: 4;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.7rem 1rem;
padding: 0.8rem 1.1rem;
background: color-mix(in srgb, var(--surface) 90%, transparent);
backdrop-filter: blur(10px);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
}
.summary {
flex: 1;
min-width: 14rem;
display: flex;
flex-wrap: wrap;
gap: 0.1rem 0.8rem;
align-items: baseline;
}
.summary .warn {
flex-basis: 100%;
}
.rep {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.85rem;
color: var(--muted);
}
.rep input {
width: 4.2rem;
color: var(--text);
}
.progress {
flex-basis: 100%;
}
.bar {
height: 8px;
background: var(--bg);
border-radius: 999px;
overflow: hidden;
margin-bottom: 0.25rem;
}
.fill {
height: 100%;
background: var(--accent);
transition: width 0.3s;
}
</style>

View File

@ -0,0 +1,269 @@
<script lang="ts">
import { onMount } from "svelte";
import { revealItemInDir } from "@tauri-apps/plugin-opener";
import { api, groupLabel, type BatchInfo, type ExportResult, type ImportSummary, type LoadReport, type TaskInfo } from "$lib/api";
let { tasks, onimported }: { tasks: LoadReport | null; onimported: (batchId: number) => void } = $props();
// 1. Exportieren
let chosen = $state<string[]>([]);
let repeats = $state(1);
let exporting = $state(false);
let exported = $state<ExportResult | null>(null);
let exportError = $state("");
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(id: string) {
chosen = chosen.includes(id) ? chosen.filter((x) => x !== id) : [...chosen, id];
}
async function doExport() {
exporting = true;
exportError = "";
exported = null;
try {
exported = await api.exportExternal($state.snapshot(chosen), repeats);
} catch (e) {
exportError = String(e);
} finally {
exporting = false;
}
}
async function reveal(path: string) {
try {
await revealItemInDir(path);
} catch {
// Ohne Dateimanager bleibt der Pfad als Text sichtbar.
}
}
// 3. Importieren
let batches = $state<BatchInfo[]>([]);
let dir = $state("");
let model = $state("Claude Code (extern)");
let batchId = $state<number | null>(null);
let importing = $state(false);
let summary = $state<ImportSummary | null>(null);
let importError = $state("");
onMount(async () => {
try {
batches = await api.batches();
if (batches.length > 0) batchId = batches[0].id;
} catch {
batches = [];
}
});
// Nach einem Export liegt der Pfad nahe, den wir nach dem Lösen wieder brauchen.
$effect(() => {
if (exported && !dir) dir = exported.dir;
});
async function doImport() {
if (batchId === null) return;
importing = true;
importError = "";
summary = null;
try {
summary = await api.importExternal(dir.trim(), model, batchId);
} catch (e) {
importError = String(e);
} finally {
importing = false;
}
}
</script>
<section class="card">
<h2>Referenz von Hand erzeugen</h2>
<p class="muted">
Modelle, die du nicht anbinden kannst (z. B. Claude über ein Abo), löst du mit einem Werkzeug deiner Wahl, etwa Claude Code.
coding-bench exportiert die Aufgaben als Ordner, prüft deine Ergebnisse mit derselben <code>check.sh</code> wie bei lokalen
Modellen und zeigt das Ergebnis als Referenz im Ranking.
</p>
<p class="notice">
<strong>Achtung, anderes Harness:</strong> Die Referenz misst „Modell plus dein Werkzeug“. Es gibt kein Schrittlimit, kein
Zeitlimit, und das Werkzeug hat eigene Tools und Anweisungen. Der Strich im Ranking ist ein Orientierungswert, kein
Gleichstand der Bedingungen.
</p>
</section>
<section class="card">
<h2>1. Aufgaben exportieren</h2>
{#if !tasks || tasks.tasks.length === 0}
<p class="muted">Keine Aufgaben geladen.</p>
{/if}
{#each byGroup as [group, list] (group)}
<h3><span class="gbadge">{group}</span> {groupLabel(group)}</h3>
<div class="list">
{#each list as t (t.id)}
<label class="choice">
<input type="checkbox" checked={chosen.includes(t.id)} onchange={() => toggle(t.id)} />
<span><strong>{t.title}</strong> <span class="muted small">{t.id}</span></span>
</label>
{/each}
</div>
{/each}
<div class="row">
<label class="rep">
Durchläufe je Aufgabe
<input type="number" min="1" max="10" bind:value={repeats} />
</label>
<span class="muted small">
{chosen.length * repeats} Sitzung(en) von Hand. Mit weniger als 3 Durchläufen ist die Referenz nur ein grober Hinweis.
</span>
<span class="spacer"></span>
<button class="primary" onclick={doExport} disabled={chosen.length === 0 || repeats < 1 || exporting}>
{exporting ? "exportiere …" : "Exportieren"}
</button>
</div>
{#if exportError}<p class="error">{exportError}</p>{/if}
{#if exported}
<p class="ok">
{exported.folders} Ordner angelegt:
<code>{exported.dir}</code>
<button class="link" onclick={() => reveal(exported!.dir)}>im Dateimanager zeigen</button>
</p>
{/if}
</section>
<section class="card">
<h2>2. Lösen lassen</h2>
<ol class="muted steps">
<li>Im Exportordner steht eine <code>ANLEITUNG.md</code>. Lies sie kurz.</li>
<li>
Pro Durchlauf eine frische Sitzung in <code>&lt;aufgabe&gt;/run-&lt;n&gt;/arbeit/</code> starten und den Inhalt von
<code>AUFGABE.md</code> als Auftrag einfügen.
</li>
<li>Kein Web, keine Hinweise, nur den Ordner <code>arbeit/</code> verändern lassen.</li>
</ol>
</section>
<section class="card">
<h2>3. Ergebnis importieren</h2>
<div class="grid">
<label class="wide">
Exportordner mit den Ergebnissen
<input bind:value={dir} placeholder="/home/…/exports/referenz-…" />
</label>
<label>
Name der Referenz
<input bind:value={model} />
</label>
<label>
In welchen Batch?
<select bind:value={batchId} disabled={batches.length === 0}>
{#each batches as b (b.id)}
<option value={b.id}>Batch {b.id} · {b.created_at.slice(0, 16)} · {b.runs} Läufe</option>
{/each}
</select>
</label>
</div>
{#if batches.length === 0}
<p class="muted small">Es gibt noch keinen Batch. Starte zuerst einen Benchmark mit lokalen Modellen, damit die Referenz einen Vergleich hat.</p>
{/if}
<div class="row">
<span class="muted small">Die App kopiert die Ergebnisse in einen Container und lässt dort <code>check.sh</code> laufen. Bereits importierte Läufe mit gleichem Namen werden ersetzt.</span>
<span class="spacer"></span>
<button class="primary" onclick={doImport} disabled={importing || !dir.trim() || !model.trim() || batchId === null}>
{importing ? "prüfe …" : "Prüfen und speichern"}
</button>
</div>
{#if importError}<p class="error">{importError}</p>{/if}
{#if summary}
<p class={summary.imported > 0 ? "ok" : "error"}>
{summary.imported} Lauf/Läufe geprüft, {summary.passed} bestanden.
{#if batchId !== null}<button class="link" onclick={() => onimported(batchId!)}>Ergebnisse ansehen</button>{/if}
</p>
{#if summary.skipped.length > 0}
<details open>
<summary class="error">{summary.skipped.length} Ordner nicht geprüft</summary>
<ul>
{#each summary.skipped as s (s)}<li>{s}</li>{/each}
</ul>
</details>
{/if}
{/if}
</section>
<style>
.notice {
border: 1px solid color-mix(in srgb, var(--accent) 50%, var(--border));
background: var(--accent-soft);
border-radius: 10px;
padding: 0.6rem 0.9rem;
margin: 0.8rem 0 0;
font-size: 0.9rem;
}
.gbadge {
display: inline-grid;
place-items: center;
width: 1.5rem;
height: 1.5rem;
border-radius: 6px;
background: var(--accent);
color: var(--accent-text);
font-size: 0.8rem;
font-weight: 800;
margin-right: 0.3rem;
}
.list {
display: grid;
gap: 0.25rem;
margin-bottom: 0.8rem;
}
.choice {
display: flex;
gap: 0.6rem;
align-items: baseline;
}
.row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.7rem 1rem;
margin-top: 0.9rem;
}
.spacer {
flex: 1;
}
.rep,
.grid label {
display: flex;
flex-direction: column;
gap: 0.2rem;
font-size: 0.85rem;
color: var(--muted);
}
.rep input {
width: 5rem;
color: var(--text);
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.6rem 0.8rem;
}
.grid .wide {
grid-column: 1 / -1;
}
.grid input,
.grid select {
color: var(--text);
font-size: 1rem;
}
.steps {
padding-left: 1.2rem;
margin: 0;
}
</style>

View File

@ -2,8 +2,11 @@
import { onMount, untrack } from "svelte";
import {
api,
errorLabel,
fmtDuration,
fmtPct,
fmtTps,
isInfrastructure,
groupLabel,
pctColor,
type BatchInfo,
@ -63,6 +66,29 @@
detail = { run, steps: await api.steps(selected, run) };
}
// Angebundene Modelle zuerst, dann die Referenzen (von Hand gelöst, ohne Rang).
let ordered = $derived(
ranking ? [...ranking.models.filter((m) => !m.external), ...ranking.models.filter((m) => m.external)] : [],
);
let bestRef = $derived(ranking?.models.find((m) => m.external) ?? null);
function refPct(group: string): number | null {
return bestRef?.groups.find((g) => g.group === group)?.percent ?? null;
}
// Kleinste Zahl gewerteter Durchläufe in einer Zelle der Matrix.
let minRepeats = $derived(ranking && ranking.cells.length > 0 ? Math.min(...ranking.cells.map((c) => c.runs)) : 0);
async function openCell(model: string, task: string) {
const r = rows.find((x) => x.model === model && x.task_id === task);
if (!r) return;
try {
await showSteps(r);
setTimeout(() => document.getElementById("run-detail")?.scrollIntoView({ behavior: "smooth", block: "start" }), 50);
} catch (e) {
error = String(e);
}
}
function cell(model: string, task: string) {
return ranking?.cells.find((c) => c.model === model && c.task_id === task);
}
@ -94,57 +120,85 @@
{#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="board">
{#each ordered as m (m.model)}
<article class="mcard" class:ref={m.external} data-rank={m.rank}>
<div class="badge r{m.external ? 5 : Math.min(m.rank, 4)}" aria-label={m.external ? "Referenz" : `Platz ${m.rank}`}>
{m.external ? "R" : m.rank}
</div>
<div class="mhead">
<h3 class="mname">
{m.model}
{#if m.external}<span class="chip" title="Von Hand außerhalb der App gelöst, anderes Harness, zählt nicht im Rang">Referenz · extern</span>{/if}
</h3>
<div class="stats">
<span title="Bestandene Läufe">✔ {m.successes}/{m.runs}</span>
{#if !m.external}
<span title="Median der Laufzeit">⏱ {fmtDuration(m.median_duration_ms)}</span>
<span title="Tokens pro Sekunde: Tokens geteilt durch die gesamte Laufzeit eines Laufs, also inklusive Tool- und Prüfzeit. Nicht die reine Erzeugungsgeschwindigkeit.">⚡ {fmtTps(m.median_tps)}</span>
<span title="Durchschnittlich erzeugte Tokens je Lauf">∅ {Math.round(m.mean_completion_tokens)} Tokens</span>
{:else}
<span>Zeit und Tokens nicht gemessen</span>
{/if}
</div>
</div>
<div 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>
<div class="label">Gesamt</div>
</div>
<div class="groups">
{#each m.groups as g (g.group)}
<td class="grp">
<div class="g" title={groupLabel(g.group)}>
<div class="gtop">
<span><b>{g.group}</b> {groupLabel(g.group)}</span>
{#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>
<span class="pct" style:color={pctColor(g.percent)}>{fmtPct(g.percent)}</span>
{/if}
</div>
<div class="meter">
{#if g.percent !== null}
<div class="f" style:width="{g.percent}%" style:background={pctColor(g.percent)}></div>
{/if}
{#if !m.external && refPct(g.group) !== null}
<div class="tick" style:left="{refPct(g.group)}%" title="Referenz {bestRef?.model}: {fmtPct(refPct(g.group))}"></div>
{/if}
</div>
{#if g.percent !== null}
<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>
{/each}
</div>
{#if m.weakest_group}
<div class="weak">Schwächster Bereich: {m.weakest_group} · {groupLabel(m.weakest_group)}</div>
{/if}
</article>
{/each}
</div>
{#if bestRef}
<p class="muted small legend">
<span class="tick-demo"></span> Strich im Balken = Referenz <strong>{bestRef.model}</strong> (extern, von Hand gelöst, anderes Harness).
</p>
{/if}
{#if minRepeats < 3}
<p class="notice">
Pro Aufgabe {minRepeats === 1 ? "gab es nur 1 Durchlauf" : `gab es nur ${minRepeats} Durchläufe`}. Dann können Unterschiede
zwischen Modellen Zufall sein, und die Rangfolge ist nur ein Hinweis. Für belastbare Werte mindestens 3 Durchläufe wählen.
</p>
{/if}
{#if ranking.excluded_runs > 0}
<p class="muted">
{ranking.excluded_runs} Lauf/Läufe sind nicht gewertet, weil der Modell-Server oder die Umgebung ausfiel. Sie
fließen nicht in die Prozentwerte ein. Beim Fortsetzen eines Batches werden sie wiederholt.
</p>
{/if}
<details class="how">
<summary>So wird bewertet</summary>
@ -166,7 +220,7 @@
</ul>
</details>
<h3>Aufgaben im Detail</h3>
<h3>Aufgaben im Detail <span class="muted small">Zelle anklicken öffnet den Lauf</span></h3>
<div class="scroll">
<table class="matrix">
<thead>
@ -184,7 +238,8 @@
{#each ranking.tasks as t (t.id)}
{@const c = cell(m.model, t.id)}
<td
class="num"
class="num clickable"
onclick={() => openCell(m.model, t.id)}
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"}
>
@ -222,7 +277,10 @@
<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={r.error_class === "ok" ? "ok" : isInfrastructure(r.error_class) ? "muted" : "error"}>
{errorLabel(r.error_class)}
{#if isInfrastructure(r.error_class)}<span class="chip" title="Zählt nicht in die Bewertung">nicht gewertet</span>{/if}
</td>
<td class="num">{Math.round(r.score * 100)} %</td>
<td class="num">{r.steps}</td>
<td class="num">{fmtDuration(r.duration_ms)}</td>
@ -235,11 +293,14 @@
{/if}
{#if detail}
<div class="detail">
<div class="detail" id="run-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.external}
<p class="muted">Extern gelöst, keine Schritte aufgezeichnet. Der Ergebnisordner steht unter <code>{detail.run.artifact_path ?? "unbekannt"}</code>.</p>
{/if}
{#if detail.run.check_output}
<p class="muted">Prüfung (<code>check.sh</code>):</p>
<pre>{detail.run.check_output}</pre>
@ -279,43 +340,119 @@
overflow-x: auto;
margin-bottom: 1rem;
}
.rank td,
.rank th {
vertical-align: top;
}
.matrix th {
text-transform: none;
}
.rank .total {
min-width: 7.5rem;
.board {
display: grid;
gap: 0.9rem;
margin-bottom: 1.2rem;
}
.rank .grp {
min-width: 6rem;
.mcard {
position: relative;
display: grid;
grid-template-columns: auto 1fr auto;
grid-template-areas:
"badge head total"
"groups groups groups"
"weak weak weak";
gap: 0.4rem 1rem;
align-items: center;
padding: 1rem 1.2rem;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 12px;
}
.gl {
font-weight: 400;
text-transform: none;
letter-spacing: 0;
.mcard[data-rank="1"] {
border-color: color-mix(in srgb, var(--gold) 60%, var(--border));
background: linear-gradient(135deg, color-mix(in srgb, var(--gold) 10%, var(--surface-2)), var(--surface-2) 60%);
}
.badge {
grid-area: badge;
width: 2.6rem;
height: 2.6rem;
border-radius: 50%;
display: grid;
place-items: center;
font-weight: 800;
font-size: 1.15rem;
color: #1a1005;
background: var(--muted);
}
.badge.r1 { background: var(--gold); }
.badge.r2 { background: var(--silver); }
.badge.r3 { background: var(--bronze); }
.badge.r4 { background: var(--surface); color: var(--muted); border: 1px solid var(--border); }
.mhead { grid-area: head; min-width: 0; }
.mname { margin: 0; font-size: 1.1rem; overflow-wrap: anywhere; }
.stats {
display: flex;
flex-wrap: wrap;
gap: 0.2rem 1rem;
color: var(--muted);
font-size: 0.85rem;
font-variant-numeric: tabular-nums;
}
.total { grid-area: total; text-align: right; }
.total .label { font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
.groups {
grid-area: groups;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr));
gap: 0.7rem 1.2rem;
margin-top: 0.6rem;
}
.gtop { display: flex; justify-content: space-between; gap: 0.5rem; font-size: 0.85rem; }
.gtop b { color: var(--accent); }
.weak { grid-area: weak; font-size: 0.8rem; color: var(--muted); }
.pct {
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.pct.big {
font-size: 1.6rem;
line-height: 1.1;
font-size: 2.2rem;
line-height: 1;
}
.meter {
position: relative;
height: 7px;
background: var(--surface-2);
background: var(--bg);
border-radius: 999px;
overflow: hidden;
margin: 0.25rem 0;
}
.meter.small {
height: 5px;
.meter .f {
border-radius: 999px;
}
.meter > div {
.tick,
.tick-demo {
background: var(--text);
border-radius: 2px;
}
.tick {
position: absolute;
top: -3px;
bottom: -3px;
width: 3px;
margin-left: -1px;
}
.tick-demo {
display: inline-block;
width: 3px;
height: 0.9rem;
vertical-align: middle;
}
.legend {
margin: 0 0 0.8rem;
}
.mcard.ref {
border-style: dashed;
}
.badge.r5 {
background: var(--surface);
color: var(--accent);
border: 1px dashed var(--accent);
}
.meter .f {
height: 100%;
}
.n {
@ -325,6 +462,21 @@
.n.few {
color: var(--danger);
}
.notice {
border: 1px solid color-mix(in srgb, var(--accent) 50%, var(--border));
background: var(--accent-soft);
border-radius: 10px;
padding: 0.6rem 0.9rem;
margin: 0 0 1rem;
font-size: 0.9rem;
}
td.clickable {
cursor: pointer;
}
td.clickable:hover {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.how {
margin: 0.5rem 0 1.2rem;
color: var(--muted);

View File

@ -1,5 +1,15 @@
<script lang="ts">
import { api, type ModelEntry, type ModelInfo, type ModelTest, type Paths, type RuntimeStatus } from "$lib/api";
import { onMount, onDestroy } from "svelte";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import {
api,
type ImageStatus,
type ModelEntry,
type ModelInfo,
type ModelTest,
type Paths,
type RuntimeStatus,
} from "$lib/api";
let {
models,
@ -37,12 +47,16 @@
function addModel() {
draft.push({ name: "", adapter: "ollama", url: "", model: "", api_key_env: "" });
open = [...open, draft.length - 1];
markDirty();
}
function removeModel(i: number) {
draft.splice(i, 1);
reach = {};
open = [];
markDirty();
draft.forEach((_, k) => check(k));
}
function hintFor(adapter: string): string {
@ -57,6 +71,7 @@
draft = saved.map(toEntry);
dirty = false;
onsaved(saved);
draft.forEach((_, k) => check(k));
} catch (e) {
saveError = String(e);
} finally {
@ -76,8 +91,117 @@
function savedInfo(name: string): ModelInfo | undefined {
return models.find((m) => m.name === name);
}
let images = $state<ImageStatus[]>([]);
let imagesError = $state("");
let building = $state<string | null>(null);
let buildLog = $state<string[]>([]);
let buildError = $state("");
let unlisten: UnlistenFn | null = null;
// Erreichbarkeit: fragt nur die Modell-Liste des Servers ab, lädt also kein Modell in den Speicher.
type Reach = { state: "prüft" | "ok" | "fehler"; models: string[]; message: string };
let reach = $state<Record<number, Reach>>({});
let open = $state<number[]>([]);
async function check(i: number) {
const m = draft[i];
if (!m || !m.url.trim()) {
reach[i] = { state: "fehler", models: [], message: "Keine Server-URL." };
return;
}
reach[i] = { state: "prüft", models: reach[i]?.models ?? [], message: "" };
try {
const list = await api.discoverModels(m.adapter, m.url, m.api_key_env);
reach[i] = { state: "ok", models: list, message: `${list.length} Modell(e) beim Server` };
} catch (e) {
reach[i] = { state: "fehler", models: [], message: String(e) };
}
}
function toggleOpen(i: number) {
open = open.includes(i) ? open.filter((x) => x !== i) : [...open, i];
}
// Bereitschaft: was fehlt noch, bevor ein Benchmark laufen kann?
let imagesReady = $derived(images.length > 0 && images.every((i) => i.available));
let anyReachable = $derived(Object.values(reach).some((r) => r.state === "ok"));
let checks = $derived([
{
ok: !!runtime?.available,
label: runtime ? (runtime.available ? `Container: ${runtime.program} bereit` : `Container: ${runtime.program} nicht nutzbar`) : "Container: prüfe …",
todo: "Podman installieren oder starten.",
},
{
ok: imagesReady,
label: imagesReady ? "Container-Image vorhanden" : "Container-Image fehlt",
todo: "Unten das Image bauen.",
},
{
ok: models.length > 0,
label: models.length > 0 ? `${models.length} Modell(e) angelegt` : "Noch kein Modell angelegt",
todo: "Ein Modell hinzufügen und speichern.",
},
{
ok: anyReachable,
label: anyReachable ? "Mindestens ein Server antwortet" : "Kein Server geprüft oder erreichbar",
todo: "Server-URL prüfen. Ist der Server an?",
},
]);
let ready = $derived(checks.every((c) => c.ok));
// Container-Images: Zustand, Bauen auf Knopfdruck, Ausgabe live.
async function loadImages() {
try {
images = await api.imageStatus();
imagesError = "";
} catch (e) {
imagesError = String(e);
}
}
async function build(image: string) {
building = image;
buildLog = [];
buildError = "";
try {
await api.buildImage(image);
} catch (e) {
buildError = String(e);
} finally {
building = null;
await loadImages();
}
}
onMount(async () => {
loadImages();
draft.forEach((_, k) => check(k));
unlisten = await listen<{ image: string; line: string }>("image-build", (ev) => {
buildLog.push(ev.payload.line);
if (buildLog.length > 300) buildLog.splice(0, buildLog.length - 300);
});
});
onDestroy(() => unlisten?.());
</script>
<section class="card ready" class:go={ready}>
<div class="ready-head">
<span class="lamp" class:go={ready}></span>
<h2>{ready ? "Bereit für einen Benchmark" : "Noch nicht ganz bereit"}</h2>
</div>
<ul class="checks">
{#each checks as c (c.label)}
<li class:ok={c.ok}>
<span class="mark">{c.ok ? "✓" : "○"}</span>
<span>{c.label}</span>
{#if !c.ok}<span class="muted small">→ {c.todo}</span>{/if}
</li>
{/each}
</ul>
</section>
<section class="card">
<h2>Modelle</h2>
<p class="muted">
@ -90,7 +214,21 @@
{/if}
{#each draft as m, i (i)}
<div class="model">
{@const r = reach[i]}
{@const isOpen = open.includes(i)}
<div class="model" class:open={isOpen}>
<button class="mhead" onclick={() => toggleOpen(i)} aria-expanded={isOpen}>
<span class="dot {r?.state ?? 'unbekannt'}" title={r?.message || "noch nicht geprüft"}></span>
<strong>{m.name || "Neues Modell"}</strong>
<span class="muted small">{ADAPTERS.find((a) => a.id === m.adapter)?.label} · {m.url || "keine URL"}</span>
<span class="spacer"></span>
<span class="muted small">
{r?.state === "ok" ? "erreichbar" : r?.state === "fehler" ? "nicht erreichbar" : r?.state === "prüft" ? "prüfe …" : ""}
</span>
<span class="chev">{isOpen ? "▾" : "▸"}</span>
</button>
{#if isOpen}
<div class="grid">
<label>
Name
@ -106,17 +244,29 @@
</label>
<label class="wide">
Server-URL
<input bind:value={m.url} oninput={markDirty} placeholder={hintFor(m.adapter)} />
<input bind:value={m.url} oninput={markDirty} onchange={() => check(i)} placeholder={hintFor(m.adapter)} />
</label>
<label>
Modell-ID beim Server
<input bind:value={m.model} oninput={markDirty} placeholder="leer = Name" />
<input
bind:value={m.model}
oninput={markDirty}
list={`models-${i}`}
placeholder={r?.models.length ? "aus der Liste wählen oder leer = Name" : "leer = Name"}
/>
<datalist id={`models-${i}`}>
{#each r?.models ?? [] as name (name)}<option value={name}></option>{/each}
</datalist>
</label>
<label>
Schlüssel-Variable
<input bind:value={m.api_key_env} oninput={markDirty} placeholder="leer = kein Schlüssel" />
</label>
</div>
{#if r?.state === "fehler"}<p class="error small">{r.message}</p>{/if}
{#if r?.state === "ok" && r.models.length > 0}
<p class="muted small">Beim Server verfügbar: {r.models.slice(0, 8).join(", ")}{r.models.length > 8 ? " …" : ""}</p>
{/if}
<div class="row">
{#if m.api_key_env && savedInfo(m.name)}
{#if savedInfo(m.name)?.api_key_set}
@ -131,15 +281,21 @@
{:else if tests[m.name]}
{@const t = tests[m.name] as ModelTest}
<span class={t.ok ? "ok" : "error"}>
{t.ok ? "Verbunden" : "Fehler"}: {t.message}
{t.ok ? "Antwort ok" : "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 onclick={() => check(i)}>Server prüfen</button>
<button
onclick={() => test(m.name)}
disabled={dirty || !savedInfo(m.name)}
title={dirty ? "Erst speichern" : "Schickt eine kurze Frage an das Modell und lädt es dabei"}
>
Antwort testen
</button>
<button class="danger" onclick={() => removeModel(i)}>Entfernen</button>
</div>
{/if}
</div>
{/each}
@ -152,6 +308,39 @@
</div>
</section>
<section class="card">
<h2>Container-Images</h2>
<p class="muted">
Jede Aufgabe läuft in einem Container. Das Standard-Image <code>cb-python</code> baut die App selbst. Beim
ersten Mal lädt Podman dafür ein Basis-Image und braucht Netz und ein paar Minuten.
</p>
{#if imagesError}<p class="error">{imagesError}</p>{/if}
{#each images as img (img.image)}
<div class="image-row">
<code>{img.image}</code>
{#if img.error}
<span class="chip error" title={img.error}>Prüfung fehlgeschlagen</span>
{:else if img.available}
<span class="chip ok">vorhanden</span>
{:else}
<span class="chip error">fehlt</span>
{/if}
<span class="spacer"></span>
{#if img.buildable}
<button class="primary" disabled={building !== null || img.available} onclick={() => build(img.image)}>
{building === img.image ? "baut …" : "Image bauen"}
</button>
{:else if !img.available}
<span class="muted">Muss selbst bereitgestellt werden</span>
{/if}
</div>
{/each}
{#if buildError}<p class="error">{buildError}</p>{/if}
{#if buildLog.length > 0}
<pre class="buildlog">{buildLog.join("\n")}</pre>
{/if}
</section>
<section class="card">
<h2>System</h2>
<dl>
@ -181,10 +370,104 @@
<style>
.model {
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.8rem;
margin-bottom: 0.8rem;
background: var(--bg);
border-radius: 12px;
padding: 0.3rem 0.9rem 0.8rem;
margin-bottom: 0.7rem;
background: var(--surface-2);
}
.model:not(.open) {
padding-bottom: 0.3rem;
}
.mhead {
display: flex;
align-items: center;
gap: 0.6rem;
width: 100%;
border: none;
background: none;
padding: 0.55rem 0;
text-align: left;
color: var(--text);
}
.mhead:hover:not(:disabled) {
border-color: transparent;
}
.chev {
color: var(--muted);
}
.small {
font-size: 0.8rem;
}
.dot {
width: 0.7rem;
height: 0.7rem;
border-radius: 50%;
background: var(--muted);
flex-shrink: 0;
}
.dot.ok {
background: var(--ok);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--ok) 25%, transparent);
}
.dot.fehler {
background: var(--danger);
}
.dot.prüft {
background: var(--accent);
animation: blink 1s ease-in-out infinite;
}
@keyframes blink {
50% {
opacity: 0.3;
}
}
.ready {
border-color: color-mix(in srgb, var(--accent) 45%, var(--border));
}
.ready.go {
border-color: color-mix(in srgb, var(--ok) 55%, var(--border));
}
.ready-head {
display: flex;
align-items: center;
gap: 0.7rem;
}
.ready-head h2 {
margin: 0;
}
.lamp {
width: 0.9rem;
height: 0.9rem;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 10px var(--accent);
}
.lamp.go {
background: var(--ok);
box-shadow: 0 0 10px var(--ok);
}
.checks {
list-style: none;
margin: 0.8rem 0 0;
padding: 0;
display: grid;
gap: 0.3rem;
}
.checks li {
display: flex;
gap: 0.6rem;
align-items: baseline;
color: var(--muted);
}
.checks li.ok {
color: var(--text);
}
.checks .mark {
width: 1rem;
color: var(--accent);
}
.checks li.ok .mark {
color: var(--ok);
}
.grid {
display: grid;
@ -216,6 +499,25 @@
.spacer {
flex: 1;
}
.image-row {
display: flex;
align-items: center;
gap: 0.7rem;
padding: 0.4rem 0;
border-bottom: 1px solid var(--border);
}
.buildlog {
max-height: 14rem;
overflow-y: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.6rem;
margin: 0.8rem 0 0;
font-size: 0.8rem;
}
dl {
display: grid;
grid-template-columns: max-content 1fr;

View File

@ -2,7 +2,18 @@ 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 TaskInfo = {
id: string;
title: string;
group: string;
dir: string;
weight: number;
image: string;
max_steps: number;
timeout_s: number;
check_timeout_s: number;
prompt: string;
};
export type TaskError = { dir: string; message: string };
export type LoadReport = { tasks: TaskInfo[]; errors: TaskError[] };
@ -18,6 +29,8 @@ export type ModelTest = { ok: boolean; duration_ms: number; message: string };
export type RuntimeStatus = { program: string; available: boolean; detail: string };
export type ImageStatus = { image: string; available: boolean; buildable: boolean; error: string | null };
export type BatchInfo = {
id: number;
created_at: string;
@ -41,6 +54,8 @@ export type RunRow = {
tps: number | null;
summary: string | null;
check_output: string;
artifact_path: string | null;
external: boolean;
};
export type StepRow = {
@ -54,7 +69,9 @@ export type StepRow = {
export type GroupScore = { group: string; percent: number | null; tasks: number; runs: number };
export type ModelRank = {
/** 0 bei Referenzen. */
rank: number;
external: boolean;
model: string;
total_percent: number;
groups: GroupScore[];
@ -63,6 +80,7 @@ export type ModelRank = {
successes: number;
median_duration_ms: number;
mean_completion_tokens: number;
median_tps: number | null;
};
export type MatrixCell = { model: string; task_id: string; runs: number; successes: number; mean_score: number };
export type TaskColumn = { id: string; group: string };
@ -72,6 +90,8 @@ export type Ranking = {
models: ModelRank[];
cells: MatrixCell[];
tasks: TaskColumn[];
/** Läufe, die wegen Server- oder Umgebungsfehlern nicht in die Bewertung eingehen. */
excluded_runs: number;
};
export type BatchEvent =
@ -81,15 +101,25 @@ export type BatchEvent =
| { kind: "model_unavailable"; model: string; reason: string }
| { kind: "progress"; done: number; total: number };
export type ExportResult = { dir: string; folders: number };
export type ImportSummary = { imported: number; passed: number; skipped: string[] };
export const api = {
paths: () => invoke<Paths>("get_paths"),
tasks: () => invoke<LoadReport>("load_tasks"),
runtime: () => invoke<RuntimeStatus>("runtime_status"),
imageStatus: () => invoke<ImageStatus[]>("image_status"),
buildImage: (image: string) => invoke<void>("build_image", { image }),
models: () => invoke<ModelInfo[]>("list_models"),
saveModels: (models: ModelEntry[]) => invoke<ModelInfo[]>("save_models", { models }),
discoverModels: (adapter: string, url: string, apiKeyEnv: string) =>
invoke<string[]>("discover_models", { adapter, url, apiKeyEnv }),
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 }),
startBatch: (models: string[], taskIds: string[], repeats: number, note: string, batchId: number | null = null) =>
invoke<BatchSummary>("start_batch", { models, taskIds, repeats, note, batchId }),
exportExternal: (taskIds: string[], repeats: number) => invoke<ExportResult>("export_external", { taskIds, repeats }),
importExternal: (dir: string, model: string, batchId: number) =>
invoke<ImportSummary>("import_external", { dir, model, batchId }),
cancelBatch: () => invoke<boolean>("cancel_batch"),
batches: () => invoke<BatchInfo[]>("list_batches"),
results: (batchId: number) => invoke<RunRow[]>("batch_results", { batchId }),
@ -98,6 +128,28 @@ export const api = {
invoke<StepRow[]>("run_steps", { batchId, model: r.model, taskId: r.task_id, repeatIdx: r.repeat_idx }),
};
/** Lesbare Bezeichnung einer Fehlerklasse. */
export function errorLabel(cls: string): string {
const labels: Record<string, string> = {
ok: "bestanden",
check_failed: "Prüfung fehlgeschlagen",
max_steps: "Zu viele Schritte",
timeout: "Zeitlimit überschritten",
loop_detected: "Schleife erkannt",
invalid_tool_json: "Ungültiger Tool-Aufruf",
unknown_tool: "Unbekanntes Werkzeug",
bad_args: "Falsche Argumente",
endpoint_error: "Modell-Server nicht erreichbar",
sandbox_error: "Fehler der Umgebung",
};
return labels[cls] ?? cls;
}
/** Läufe, die nicht am Modell scheiterten und deshalb nicht zählen. */
export function isInfrastructure(cls: string): boolean {
return cls === "endpoint_error" || cls === "sandbox_error";
}
/** Namen der Bereiche (Gruppen aus SPEC 11). */
export const GROUP_LABELS: Record<string, string> = {
A: "Tool-Calling",
@ -114,7 +166,7 @@ export function groupLabel(g: string): string {
/** 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%)`;
return `hsl(${hue} 72% var(--pct-l, 56%))`;
}
export function fmtPct(p: number | null): string {
@ -125,3 +177,7 @@ 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`;
}
export function fmtTps(t: number | null): string {
return t === null ? "–" : `${t < 10 ? t.toFixed(1) : Math.round(t)} Tok/s`;
}

View File

@ -2,10 +2,11 @@
import { onMount } from "svelte";
import { api, type LoadReport, type ModelInfo, type Paths, type RuntimeStatus } from "$lib/api";
import BenchPanel from "$lib/BenchPanel.svelte";
import ReferencePanel from "$lib/ReferencePanel.svelte";
import ResultsPanel from "$lib/ResultsPanel.svelte";
import SettingsPanel from "$lib/SettingsPanel.svelte";
type Tab = "bench" | "results" | "settings";
type Tab = "bench" | "results" | "reference" | "settings";
let tab = $state<Tab>("bench");
let loaded = $state(false);
@ -20,8 +21,6 @@
try {
[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) {
loadError = String(e);
} finally {
@ -37,13 +36,25 @@
const tabs: { id: Tab; label: string }[] = [
{ id: "bench", label: "Benchmark" },
{ id: "results", label: "Ergebnisse" },
{ id: "reference", label: "Referenz" },
{ id: "settings", label: "Einstellungen" },
];
</script>
<header>
<div class="inner">
<span class="logo">coding-bench</span>
<span class="logo">
<svg viewBox="0 0 1024 1024" width="28" height="28" aria-hidden="true">
<rect x="32" y="32" width="960" height="960" rx="224" fill="var(--accent)" />
<g fill="var(--accent-text)">
<rect x="212" y="490" width="170" height="300" rx="44" />
<rect x="427" y="340" width="170" height="450" rx="44" />
<rect x="642" y="580" width="170" height="210" rx="44" />
<circle cx="512" cy="245" r="46" />
</g>
</svg>
coding<b>-bench</b>
</span>
<nav>
{#each tabs as t (t.id)}
<button class="tab" class:active={tab === t.id} onclick={() => (tab = t.id)}>{t.label}</button>
@ -65,6 +76,9 @@
<div hidden={tab !== "results"}>
<ResultsPanel bind:selected={selectedBatch} />
</div>
<div hidden={tab !== "reference"}>
<ReferencePanel {tasks} onimported={showResults} />
</div>
<div hidden={tab !== "settings"}>
<SettingsPanel {models} {paths} {runtime} onsaved={(m) => (models = m)} />
</div>
@ -73,47 +87,59 @@
<style>
header {
background: var(--surface);
background: color-mix(in srgb, var(--bg) 82%, transparent);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--border);
position: sticky;
top: 0;
z-index: 5;
}
.inner {
max-width: 62rem;
max-width: 66rem;
margin: 0 auto;
padding: 0 1rem;
padding: 0.7rem 1rem;
display: flex;
align-items: center;
gap: 2rem;
}
.logo {
display: inline-flex;
align-items: center;
gap: 0.55rem;
font-weight: 600;
font-size: 1.1rem;
letter-spacing: -0.01em;
}
.logo b {
color: var(--accent);
font-weight: 700;
letter-spacing: 0.01em;
margin-left: -0.5rem;
}
nav {
display: flex;
gap: 0.2rem;
gap: 0.3rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.25rem;
}
.tab {
border: none;
border-bottom: 3px solid transparent;
border-radius: 0;
border-radius: 999px;
background: none;
padding: 0.9rem 1rem 0.75rem;
padding: 0.4rem 1.1rem;
color: var(--muted);
}
.tab:hover:not(:disabled) {
color: var(--text);
border-color: transparent;
}
.tab.active {
color: var(--text);
border-bottom-color: var(--accent);
background: var(--accent-soft);
color: var(--accent);
font-weight: 600;
}
main {
max-width: 62rem;
max-width: 66rem;
margin: 0 auto;
padding: 1.2rem 1rem 3rem;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

15
static/favicon.svg Normal file
View File

@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ffb470"/>
<stop offset="1" stop-color="#ee8227"/>
</linearGradient>
</defs>
<rect x="32" y="32" width="960" height="960" rx="224" fill="url(#bg)"/>
<g fill="#1a1005">
<rect x="212" y="490" width="170" height="300" rx="44"/>
<rect x="427" y="340" width="170" height="450" rx="44"/>
<rect x="642" y="580" width="170" height="210" rx="44"/>
</g>
<circle cx="512" cy="245" r="46" fill="#1a1005"/>
</svg>

After

Width:  |  Height:  |  Size: 626 B