9 Commits

Author SHA1 Message Date
c8290aeb94 feat: Runner und SQLite-Speicher
runner.rs: Plan in Reihenfolge Modell/Aufgabe/Wiederholung, Aufwärmen je
Modell, frische Sandbox pro Lauf, check.sh im selben Container, Abbruch
und Fortsetzen über die Datenbank. store.rs: Schema nach SPEC 8, Lauf und
Schritte in einer Transaktion. Agent-Loop bekommt Abbruchflag.
Ende-zu-Ende gegen srv04 mit qwen3:0.6b grün; Fortsetzen überspringt
fertige Läufe. 38 Unit-Tests grün.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:35:02 +01:00
e69f3be35b test: Agent-Lauf gegen Ollama auf srv04 mit qwen3:0.6b
Ignorierter Test ollama_lauf_schreibt_datei_und_beendet bestanden:
Modell schreibt out.txt und ruft done auf (1 Schritt, 496/219 Tokens, 20 s
inkl. Modell-Ladezeit).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +01:00
a02f57b469 feat: Agent-Loop mit Tools und Fehlerklassen
agent.rs: fünf Tools (read_file, write_file, list_dir, run_shell, done),
Pfadprüfung auf /work, Fehlerklassen nach SPEC 5, Schleifenerkennung,
Limits für Schritte und Zeit, Metriken. Ollama-Client über /api/chat.
31 Unit-Tests mit Mock-Modell grün; Werkzeuge gegen echte Sandbox grün.
Echter Modelllauf steht aus, weil Ollama nicht läuft und keine Modelle da sind.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:24:08 +01:00
173be01279 feat: Sandbox-Limits in config.toml und Image cb-python
Speicher-, CPU- und Runtime-Angabe in config.toml, Standard podman, 2g, 2.
Containerfile für cb-python (Python 3.12, pytest). Echter Sandbox-Test
mit cb-python:latest grün.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:15:04 +01:00
e7e0ad558d feat: Podman-Sandbox pro Lauf
sandbox.rs startet einen Container ohne Netz (--network none, Speicher-
und CPU-Limit, PID-Limit), kopiert die Aufgabe nach /work, führt Befehle
mit Timeout aus, exportiert /work und entfernt den Container beim Verwerfen.
Echter Test gegen Podman grün (ignoriert, braucht CB_TEST_IMAGE). Noch
nicht an Commands angebunden; Config-Limits und cb-python-Image offen.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:13:18 +01:00
304a7a644c docs: Sandbox auf Podman umstellen
Entscheidung #1039: Podman (rootless) statt Docker, weil nur Podman
installiert ist. SPEC, README, ROADMAP und KLICKTESTS angepasst.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:11:23 +01:00
e16788a3cb feat: Aufgaben laden und validieren
tasks/<gruppe>/<name>/ wird eingelesen. Pflichtdateien, task.toml-Werte
und ausführbares check.sh werden geprüft, fehlerhafte Aufgaben mit Grund
gemeldet. Setup zeigt gültige Aufgaben und Fehler. cargo test: 13 Tests
grün. Klicktests aufgabe2validierung.1-.2 noch manuell offen.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 19:06:06 +01:00
3bd5197867 feat: TOML-Config und Datenordner anlegen
config.toml im App-Konfigurationsordner, Standard wird beim ersten Start
angelegt. Datenordner und Aufgabenordner werden aufgelöst und im Setup
angezeigt. Standard-Startseite ersetzt durch Pfad-Ansicht.
cargo test: 6 Tests grün. Klicktests start2app.1-.2 noch manuell offen.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 18:49:29 +01:00
57fbc57a54 feat: Tauri-2-Gerüst mit Svelte und TypeScript anlegen
create-tauri-app, Template svelte-ts. npm run build und cargo check laufen
durch. App nicht gestartet, Datenordner und TOML-Config folgen (#1018).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-06 18:37:40 +01:00
50 changed files with 9795 additions and 29 deletions

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

7
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
"recommendations": [
"svelte.svelte-vscode",
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"svelte.enable-ts-plugin": true
}

View File

@ -33,12 +33,12 @@ für einen Block aufweichen; das steht dann im Todo.
## lauf2sandbox ## lauf2sandbox
**Zweck:** Ein Lauf startet in einem frischen Container ohne Netz und räumt danach auf. **Zweck:** Ein Lauf startet in einem frischen Container ohne Netz und räumt danach auf.
**Deckt ab:** #1004 **Deckt ab:** #1004
**Voraussetzung:** Docker läuft, Image `cb-python:latest` vorhanden. **Voraussetzung:** Podman läuft, Image `cb-python:latest` vorhanden.
| Test | Schritte | Erwartet | Art | | Test | Schritte | Erwartet | Art |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| lauf2sandbox.1 | Einen Lauf starten, im Agenten `curl` auf eine externe Adresse ausführen lassen | Netzwerk ist nicht erreichbar | manuell | | lauf2sandbox.1 | Einen Lauf starten, im Agenten `curl` auf eine externe Adresse ausführen lassen | Netzwerk ist nicht erreichbar | manuell |
| lauf2sandbox.2 | Nach Lauf-Ende Docker-Containerliste prüfen | Kein Container des Laufs mehr vorhanden, `/work` liegt als Artefakt vor | manuell | | lauf2sandbox.2 | Nach Lauf-Ende Podman-Containerliste prüfen | Kein Container des Laufs mehr vorhanden, `/work` liegt als Artefakt vor | manuell |
## lauf2ergebnis ## lauf2ergebnis
**Zweck:** Ein Agentenlauf wird bewertet und mit Schritten gespeichert. **Zweck:** Ein Agentenlauf wird bewertet und mit Schritten gespeichert.

View File

@ -16,9 +16,9 @@ Getestet auf: nichts. Die Zielplattform ist Linux (Pop!_OS), dort ist noch nicht
## Before you use it ## Before you use it
**Ausführung von Modellbefehlen:** Das Modell darf im Container Shell-Befehle ausführen. Die Läufe sind dafür per Docker abgeschottet (kein Netzwerk). Trotzdem sollten Aufgaben-Ordner vor dem Start geprüft werden. **Ausführung von Modellbefehlen:** Das Modell darf im Container Shell-Befehle ausführen. Die Läufe sind dafür per Podman abgeschottet (kein Netzwerk). Trotzdem sollten Aufgaben-Ordner vor dem Start geprüft werden.
**Docker nötig:** Jeder Lauf braucht Docker. Ohne Docker startet kein Lauf. **Podman nötig:** Jeder Lauf braucht Podman (rootless). Ohne Podman startet kein Lauf.
**Disclaimer:** coding-bench ist nicht verbunden mit oder gesponsert von Dritten. Das Projekt wird im Ist-Zustand und ohne Garantie bereitgestellt. **Disclaimer:** coding-bench ist nicht verbunden mit oder gesponsert von Dritten. Das Projekt wird im Ist-Zustand und ohne Garantie bereitgestellt.
@ -33,7 +33,7 @@ Noch nicht verfügbar. Installationshinweise folgen mit dem ersten Release.
## Requirements ## Requirements
* Linux (Pop!_OS als Zielplattform) * Linux (Pop!_OS als Zielplattform)
* Docker * Podman (rootless)
* Rust-Toolchain und Node.js (für den Build, Details folgen) * Rust-Toolchain und Node.js (für den Build, Details folgen)
* Ollama mit Modellen, die Tool-Calling unterstützen * Ollama mit Modellen, die Tool-Calling unterstützen
@ -51,7 +51,7 @@ Der Nutzer wählt Aufgaben und Modelle. Jedes Modell löst jede Aufgabe mehrfach
| :--- | :--- | | :--- | :--- |
| **Aufgaben** | Ordner mit Prompt, Startdateien und `check.sh`, beim Laden validiert. | | **Aufgaben** | Ordner mit Prompt, Startdateien und `check.sh`, beim Laden validiert. |
| **Agent-Loop** | Modell und Tools (`read_file`, `write_file`, `list_dir`, `run_shell`, `done`) mit Fehlerklassen. | | **Agent-Loop** | Modell und Tools (`read_file`, `write_file`, `list_dir`, `run_shell`, `done`) mit Fehlerklassen. |
| **Sandbox** | Frischer Docker-Container pro Lauf, ohne Netzwerk. | | **Sandbox** | Frischer Podman-Container pro Lauf, ohne Netzwerk. |
| **Runner** | Wiederholungen, Abbruch und Fortsetzen eines Batches. | | **Runner** | Wiederholungen, Abbruch und Fortsetzen eines Batches. |
| **Ranking** | Gesamtscore mit Intervall, Matrix Modell × Test (geplant für 0.2.0: Kategorien, Export). | | **Ranking** | Gesamtscore mit Intervall, Matrix Modell × Test (geplant für 0.2.0: Kategorien, Export). |
@ -67,7 +67,7 @@ Noch nicht verfügbar.
* **[Ollama](https://ollama.com)** – lokale Modelle mit Tool-Calling über `/api/chat`. * **[Ollama](https://ollama.com)** – lokale Modelle mit Tool-Calling über `/api/chat`.
* **[Tauri](https://tauri.app)** – Desktop-Framework mit Rust-Backend. * **[Tauri](https://tauri.app)** – Desktop-Framework mit Rust-Backend.
* **[Docker](https://www.docker.com)** – Sandbox pro Lauf. * **[Podman](https://podman.io)** – Sandbox pro Lauf.
## License ## License

View File

@ -2,11 +2,11 @@
Stand: 2026-11-06 (18:30) · Projekt-ID: offen · Format: 1 · installiert ist noch nichts (Release 0.1.0 offen); lokal 0 Commits. Quellen dieser Liste: `SPEC.md` (Gespräch vom 06.11.2026), Anforderungskatalog F-01 bis F-17. Stand: 2026-11-06 (18:30) · Projekt-ID: offen · Format: 1 · installiert ist noch nichts (Release 0.1.0 offen); lokal 0 Commits. Quellen dieser Liste: `SPEC.md` (Gespräch vom 06.11.2026), Anforderungskatalog F-01 bis F-17.
Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft. 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: #1039. **IDs:** Jeder Punkt in Stand-Tabelle, Todo, Entscheidungen und Risiken hat eine feste ID `#1xxx` (eine Zählung für alles, nie wiederverwendet, am Anfang der Zeile). „→ #…“ nennt die Anforderung, die ein Todo voranbringt. Erledigtes wandert mit ID in „Erledigt (einzeln)“. Nächste freie ID: #1040.
## 1. Leitplanken (von dir festgelegt, gelten für alles) ## 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). - **Lokal first:** Nur lokale Modelle (Ollama, ab Phase 2 OpenAI-kompatibler Endpunkt im Netz). Cloud-Modelle werden nicht verglichen (Nicht-Ziel v1).
- **Sandbox:** Jeder Lauf in einem frischen Docker-Container mit `--network none`. Der Agent arbeitet nur unter `/work`. - **Sandbox:** Jeder Lauf in einem frischen Podman-Container mit `--network none`. Der Agent arbeitet nur unter `/work`.
- **Sequentiell:** Modelle laufen nacheinander, weil ein Modell die GPU belegt. Parallelität nur, wenn du `parallel > 1` setzt. - **Sequentiell:** Modelle laufen nacheinander, weil ein Modell die GPU belegt. Parallelität nur, wenn du `parallel > 1` setzt.
- **Versionierung:** System-Prompt und Limits werden pro Batch in `config_json` mitgespeichert, damit Läufe vergleichbar bleiben. - **Versionierung:** System-Prompt und Limits werden pro Batch in `config_json` mitgespeichert, damit Läufe vergleichbar bleiben.
- **Plattform und Stack:** Linux (Pop!_OS) zuerst. Tauri 2, Rust-Backend, Svelte mit TypeScript fürs Frontend, SQLite für Ergebnisse. - **Plattform und Stack:** Linux (Pop!_OS) zuerst. Tauri 2, Rust-Backend, Svelte mit TypeScript fürs Frontend, SQLite für Ergebnisse.
@ -18,12 +18,12 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
| ID | Anforderung | Quelle | Stand | Anmerkung | | ID | Anforderung | Quelle | Stand | Anmerkung |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| #1001 | F-01 Tauri-Grundgerüst, Datenordner, Config | SPEC 12 | ✗ | noch nicht begonnen (→ #1018) | | #1001 | F-01 Tauri-Grundgerüst, Datenordner, Config | SPEC 12 | ◐ | Umgesetzt: Gerüst, TOML-Config mit Standardanlage, Datenordner, Setup zeigt Pfade. `cargo test` 6/6, `npm run build` grün. Klicktests `start2app.1–.2` manuell noch nicht ✓ (→ #1018) |
| #1002 | F-02 Aufgaben laden und validieren | SPEC 4, 12 | ✗ | noch nicht begonnen (→ #1019) | | #1002 | F-02 Aufgaben laden und validieren | SPEC 4, 12 | ◐ | Umgesetzt: Laden, Validierung (Pflichtdateien, TOML, Werte, `check.sh` ausführbar), Fehler im Setup. `cargo test` 13/13. Klicktests `aufgabe2validierung.1–.2` manuell offen (→ #1019) |
| #1003 | F-03 Agent-Loop gegen Ollama mit Tools und Fehlerklassen | SPEC 5, 12 | ✗ | noch nicht begonnen (→ #1021) | | #1003 | F-03 Agent-Loop gegen Ollama mit Tools und Fehlerklassen | SPEC 5, 12 | ◐ | Loop, Tools, Pfadprüfung, Fehlerklassen und Metriken in `agent.rs`. 31 Unit-Tests grün (Mock-Modell). Werkzeuge gegen echte Sandbox grün. Echter Lauf gegen Ollama auf srv04 mit `qwen3:0.6b` bestanden (ignorierter Test `ollama_lauf_schreibt_datei_und_beendet`: Datei geschrieben, `done` aufgerufen). Offen: größere Modelle, Klicktests `lauf2ergebnis.1–.3` (→ #1021) |
| #1004 | F-04 Docker-Sandbox pro Lauf | SPEC 6, 12 | ✗ | noch nicht begonnen (→ #1020) | | #1004 | F-04 Podman-Sandbox pro Lauf | SPEC 6, 12 | ◐ | Modul `sandbox.rs` steht: Start ohne Netz, Limits, Kopieren nach `/work`, `exec` mit Timeout, Export, Entfernen. Limits und Runtime kommen aus `config.toml`. Echter Lauf gegen Podman mit Image `cb-python:latest` bestanden (ignorierter Test). Noch nicht an den Runner angebunden (#1022); Klicktests `lauf2sandbox.1–.2` manuell offen (→ #1020) |
| #1005 | F-05 Runner mit Wiederholungen, Abbruch, Fortsetzen | SPEC 7, 12 | ✗ | noch nicht begonnen (→ #1022) | | #1005 | F-05 Runner mit Wiederholungen, Abbruch, Fortsetzen | SPEC 7, 12 | ◐ | `runner.rs`: Plan, Warm-up je Modell, Sandbox pro Lauf, `check.sh`, Abbruch, Fortsetzen über die DB. Ende-zu-Ende gegen srv04 mit `qwen3:0.6b` grün (2 Läufe, dann Fortsetzen überspringt beide). Abbruch im Lauf nicht real getestet. Noch nicht an Commands/GUI angebunden (→ #1022) |
| #1006 | F-06 SQLite inkl. Schritt-Log | SPEC 8, 12 | ✗ | noch nicht begonnen (→ #1023) | | #1006 | F-06 SQLite inkl. Schritt-Log | SPEC 8, 12 | ◐ | `store.rs`: Tabellen `batch`, `run`, `step` nach SPEC 8, Lauf und Schritte in einer Transaktion. Getestet in-memory. Datei-Datenbank im Datenordner noch nicht angebunden (→ #1023) |
| #1007 | F-07 Tests a-01 bis a-03 und b-04 bis b-06 | SPEC 11, 12 | ✗ | noch nicht begonnen (→ #1024) | | #1007 | F-07 Tests a-01 bis a-03 und b-04 bis b-06 | SPEC 11, 12 | ✗ | noch nicht begonnen (→ #1024) |
| #1008 | F-08 GUI: Setup, Batch starten, Live-Fortschritt | SPEC 10, 12 | ✗ | noch nicht begonnen (→ #1025) | | #1008 | F-08 GUI: Setup, Batch starten, Live-Fortschritt | SPEC 10, 12 | ✗ | noch nicht begonnen (→ #1025) |
| #1009 | F-09 Rangliste und Matrix | SPEC 9, 10, 12 | ✗ | noch nicht begonnen (→ #1026) | | #1009 | F-09 Rangliste und Matrix | SPEC 9, 10, 12 | ✗ | noch nicht begonnen (→ #1026) |
@ -44,14 +44,14 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
## 4. Todo (nach Priorität, Stand 2026-11-06) ## 4. Todo (nach Priorität, Stand 2026-11-06)
**P1 – als Nächstes (Release 0.1.0, Phase 1 Kern)** **P1 – als Nächstes (Release 0.1.0, Phase 1 Kern)**
- [#1018] **Gerüst anlegen.** Tauri 2 mit Svelte und TypeScript, Rust-Backend, Datenordner, TOML-Config. Tests `start2app.1–.2`. → #1001 - [#1018] **Gerüst anlegen.** Tauri 2 mit Svelte und TypeScript, Rust-Backend, Datenordner, TOML-Config. Gerüst (`create-tauri-app`, svelte-ts) und Config-/Datenordner-Logik (`src-tauri/src/config.rs`) sind gebaut; `cargo test` 6/6 grün. Offen: die Klicktests `start2app.1–.2` vom Menschen manuell ausführen lassen. Erst dann gilt #1018 als fertig. Tests `start2app.1–.2`. → #1001
- [#1019] **Aufgaben laden und validieren.** Ordner `tasks/<gruppe>/<name>/`, Pflichtdateien, TOML, ausführbares `check.sh`, Fehler in der GUI. Tests `aufgabe2validierung.1–.2`. → #1002 - [#1019] **Aufgaben laden und validieren.** Umgesetzt in `src-tauri/src/tasks.rs`, `cargo test` 13/13. Offen: Klicktests `aufgabe2validierung.1–.2` manuell ausführen lassen. Tests `aufgabe2validierung.1–.2`. → #1002
- [#1020] **Docker-Sandbox pro Lauf.** Frischer Container, `--network none`, Speicher-/CPU-Limit, `/work` als Artefakt, Container entfernen. Tests `lauf2sandbox.1–.2`. → #1004 - [#1020] **Podman-Sandbox pro Lauf.** Modul gebaut (`src-tauri/src/sandbox.rs`). Echter Test `CB_TEST_IMAGE=docker.io/library/python:3.12-slim cargo test -- --ignored` grün: Startdatei in `/work`, Netz aus, Timeout erkannt, Export, Container entfernt. Limits und Runtime aus der Config. Image `cb-python` gebaut (`images/cb-python/Containerfile`, Python 3.12 und pytest). Der Test lief mit `CB_TEST_IMAGE=cb-python:latest` grün. Offen: Anbindung an den Runner (#1022), Klicktests `lauf2sandbox.1–.2` manuell. Tests `lauf2sandbox.1–.2`. → #1004
- [#1021] **Agent-Loop gegen Ollama.** Tools `read_file`, `write_file`, `list_dir`, `run_shell`, `done`; Pfade auf `/work`; Fehlerklassen und Metriken. Tests `lauf2ergebnis.1–.3`. → #1003 - [#1021] **Agent-Loop gegen Ollama.** Umgesetzt in `src-tauri/src/agent.rs`: fünf Tools, Pfade auf `/work`, Fehlerklassen, Schleifenerkennung, Metriken, Ollama-Client (`/api/chat`, ohne Streaming, Temperatur 0). Offen: echter Lauf gegen Ollama (Dienst starten, Modell laden), Klicktests `lauf2ergebnis.1–.3`. Tests `lauf2ergebnis.1–.3`. → #1003
- [#1022] **Runner.** Wiederholungen, sequentiell pro Modell, Aufwärmen, Abbruch und Fortsetzen. Tests `batch2fortsetzen.1–.2`. → #1005 - [#1022] **Runner.** Umgesetzt in `src-tauri/src/runner.rs`. Offen: Abbruch über die GUI real prüfen, Anbindung an Tauri-Commands und Events, Modelle mit eigenem Endpunkt in der Config. Tests `batch2fortsetzen.1–.2`. → #1005
- [#1023] **SQLite-Speicher.** Tabellen `batch`, `run`, `step` nach Abschnitt 8. Tests `lauf2ergebnis.2`. → #1006 - [#1023] **SQLite-Speicher.** Umgesetzt in `src-tauri/src/store.rs`, Schema nach SPEC 8. Offen: Datei-Datenbank im Datenordner anlegen und an den Runner anbinden. Tests `lauf2ergebnis.2`. → #1006
- [#1024] **Aufgaben a-01 bis a-03, b-04 bis b-06 schreiben.** Mindestens je ein lauffähiges Beispiel, Mutation bei b-06. Tests: je Aufgabe ein Lauf mit Bericht. → #1007 - [#1024] **Aufgaben a-01 bis a-03, b-04 bis b-06 schreiben.** Mindestens je ein lauffähiges Beispiel, Mutation bei b-06. Tests: je Aufgabe ein Lauf mit Bericht. → #1007
- [#1025] **GUI Setup und Batch.** Modelle, Docker-Status, Datenordner, Aufgabenauswahl, Start, Live-Fortschritt mit Schritt-Log. Tests `batch2fortsetzen.1`. → #1008 - [#1025] **GUI Setup und Batch.** Modelle, Podman-Status, Datenordner, Aufgabenauswahl, Start, Live-Fortschritt mit Schritt-Log. Tests `batch2fortsetzen.1`. → #1008
- [#1026] **Rangliste und Matrix.** Gesamtscore mit Intervall, Matrix Modell × Test nach Erfolgsquote, Lauf-Detail. Tests `ergebnis2detail.1`. → #1009 - [#1026] **Rangliste und Matrix.** Gesamtscore mit Intervall, Matrix Modell × Test nach Erfolgsquote, Lauf-Detail. Tests `ergebnis2detail.1`. → #1009
**P2 – danach (Release 0.2.0, Referenz und Tiefe)** **P2 – danach (Release 0.2.0, Referenz und Tiefe)**
@ -74,6 +74,7 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
- [#1034] Entschieden: Projektname `coding-bench`, Ordner bleibt `llm-arena`. → #1001 - [#1034] Entschieden: Projektname `coding-bench`, Ordner bleibt `llm-arena`. → #1001
- [#1035] Gitea-Adresse für das Remote `origin` (URL oder Repo-Name)? Ohne sie gibt es kein Remote, und die Projekt-ID bleibt `offen`. → #1001 - [#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 - [#1036] Entschieden: Lizenz wird vorerst nicht festgelegt, die README sagt das ausdrücklich. → #1001
- [#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) ## 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.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.

14
SPEC.md
View File

@ -20,7 +20,7 @@ Der Nutzer wählt 1..n Tests und 1..m Modelle. Die App lässt jedes Modell jeden
| Frontend | Svelte oder React + TypeScript, schlicht, Tabellen und Heatmap | | Frontend | Svelte oder React + TypeScript, schlicht, Tabellen und Heatmap |
| HTTP | `reqwest` + `tokio` | | HTTP | `reqwest` + `tokio` |
| Modell-API | Ollama `/api/chat` mit `tools`; zusätzlich OpenAI-kompatibler Endpunkt (GPU Dispatcher) | | Modell-API | Ollama `/api/chat` mit `tools`; zusätzlich OpenAI-kompatibler Endpunkt (GPU Dispatcher) |
| Sandbox | Docker über `bollard` oder Docker-CLI | | Sandbox | Podman (rootless), Aufruf über die Podman-CLI |
| Speicher | SQLite (`rusqlite`), Artefakte als Dateien im Datenordner | | Speicher | SQLite (`rusqlite`), Artefakte als Dateien im Datenordner |
| Config | TOML (`serde`, `toml`) | | Config | TOML (`serde`, `toml`) |
| Playwright-Sidecar | Kleines Node-Skript, wird von der App als Prozess gestartet (nur Demo-Tests, ab Phase 3) | | Playwright-Sidecar | Kleines Node-Skript, wird von der App als Prozess gestartet (nur Demo-Tests, ab Phase 3) |
@ -36,7 +36,7 @@ Backend (Rust)
├─ config Modelle, Endpunkte, Pfade ├─ config Modelle, Endpunkte, Pfade
├─ tasks Laden/Validieren der Aufgabenordner ├─ tasks Laden/Validieren der Aufgabenordner
├─ agent Agent-Loop (Modell <-> Tools) ├─ agent Agent-Loop (Modell <-> Tools)
├─ sandbox Docker-Container pro Lauf, Tool-Ausführung ├─ sandbox Podman-Container pro Lauf, Tool-Ausführung
├─ runner Job-Queue, Wiederholungen, Abbruch ├─ runner Job-Queue, Wiederholungen, Abbruch
├─ scoring Auswertung, Ranking, Statistik ├─ scoring Auswertung, Ranking, Statistik
└─ store SQLite + Artefakte └─ store SQLite + Artefakte
@ -62,7 +62,7 @@ id = "b-05-bugfix-parser"
title = "Bug im Parser finden und fixen" title = "Bug im Parser finden und fixen"
group = "B" # A, B, C, D group = "B" # A, B, C, D
weight = 1.0 # Gewicht im Gesamtscore weight = 1.0 # Gewicht im Gesamtscore
image = "cb-python:latest" # Docker-Image image = "cb-python:latest" # Container-Image
max_steps = 25 # max. Modell-Antworten max_steps = 25 # max. Modell-Antworten
timeout_s = 600 # Gesamtzeit pro Lauf timeout_s = 600 # Gesamtzeit pro Lauf
check_timeout_s = 120 check_timeout_s = 120
@ -105,9 +105,9 @@ Pfade sind auf `/work` beschränkt.
- Ein frischer Container pro Lauf, Image aus `task.toml`. - Ein frischer Container pro Lauf, Image aus `task.toml`.
- `start/` wird nach `/work` kopiert. - `start/` wird nach `/work` kopiert.
- Netzwerk aus (`--network none`), Speicher-/CPU-Limit konfigurierbar. - Netzwerk aus (`--network none`), Speicher-/CPU-Limit konfigurierbar.
- Tool-Ausführung per `docker exec`, `check.sh` im selben Container. - Tool-Ausführung per `podman exec`, `check.sh` im selben Container.
- Nach dem Lauf wird `/work` als Artefakt nach `runs/<run_id>/work/` kopiert, dann wird der Container entfernt. - Nach dem Lauf wird `/work` als Artefakt nach `runs/<run_id>/work/` kopiert, dann wird der Container entfernt.
- Mitgelieferte Images (Dockerfiles im Repo): `cb-python` (Python 3 + pytest), `cb-node` (Node + npm), `cb-rust` (Rust-Toolchain), `cb-web` (Node + Playwright, nur Phase 3). - Mitgelieferte Images (Containerfiles im Repo): `cb-python` (Python 3 + pytest), `cb-node` (Node + npm), `cb-rust` (Rust-Toolchain), `cb-web` (Node + Playwright, nur Phase 3).
--- ---
@ -147,7 +147,7 @@ step(id, run_id, idx, role, content, tool_name, tool_args_json,
## 10. GUI ## 10. GUI
1. **Setup:** Modelle (Name, Endpunkt, Typ Ollama oder OpenAI-kompatibel), Docker-Status, Datenordner, Aufgabenordner mit Validierungsstatus. 1. **Setup:** Modelle (Name, Endpunkt, Typ Ollama oder OpenAI-kompatibel), Podman-Status, Datenordner, Aufgabenordner mit Validierungsstatus.
2. **Batch starten:** Tests und Modelle ankreuzen, Wiederholungen, Start. Live-Fortschritt mit laufendem Schritt-Log des aktuellen Laufs. 2. **Batch starten:** Tests und Modelle ankreuzen, Wiederholungen, Start. Live-Fortschritt mit laufendem Schritt-Log des aktuellen Laufs.
3. **Ergebnisse:** 3. **Ergebnisse:**
- Rangliste (Rang, Modell, Gesamtscore mit Intervall, Score je Gruppe, Median-Zeit, Tokens) - Rangliste (Rang, Modell, Gesamtscore mit Intervall, Score je Gruppe, Median-Zeit, Tokens)
@ -192,7 +192,7 @@ Jede Anforderung hat eine feste ID.
- F-01 Tauri-Projekt mit Rust-Backend und Frontend-Grundgerüst, Datenordner und Config - F-01 Tauri-Projekt mit Rust-Backend und Frontend-Grundgerüst, Datenordner und Config
- F-02 Aufgaben laden und validieren (Abschnitt 4) - F-02 Aufgaben laden und validieren (Abschnitt 4)
- F-03 Agent-Loop gegen Ollama mit allen Tools und Fehlerklassifikation (Abschnitt 5) - F-03 Agent-Loop gegen Ollama mit allen Tools und Fehlerklassifikation (Abschnitt 5)
- F-04 Docker-Sandbox pro Lauf (Abschnitt 6) - F-04 Podman-Sandbox pro Lauf (Abschnitt 6)
- F-05 Runner mit Wiederholungen, Abbruch und Fortsetzen (Abschnitt 7) - F-05 Runner mit Wiederholungen, Abbruch und Fortsetzen (Abschnitt 7)
- F-06 SQLite-Speicherung inkl. Schritt-Log (Abschnitt 8) - F-06 SQLite-Speicherung inkl. Schritt-Log (Abschnitt 8)
- F-07 Tests a-01 bis a-03 und b-04 bis b-06 - F-07 Tests a-01 bis a-03 und b-04 bis b-06

View File

@ -0,0 +1,8 @@
# cb-python: Python 3 mit pytest für Aufgaben der Gruppen A bis C.
# Bauen: podman build -t cb-python:latest images/cb-python
FROM docker.io/library/python:3.12-slim
RUN pip install --no-cache-dir pytest \
&& mkdir -p /work
WORKDIR /work

1605
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

30
package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "coding-bench",
"version": "0.1.0",
"description": "",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri"
},
"license": "MIT",
"dependencies": {
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.65.1",
"@sveltejs/vite-plugin-svelte": "^7.1.2",
"svelte": "^5.56.3",
"svelte-check": "^4.6.0",
"typescript": "~6.0.3",
"vite": "^8.0.16",
"@tauri-apps/cli": "^2"
}
}

7
src-tauri/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

5388
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

38
src-tauri/Cargo.toml Normal file
View File

@ -0,0 +1,38 @@
[package]
name = "coding-bench"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "coding_bench_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.8"
reqwest = { version = "0.12", features = ["blocking", "json"] }
base64 = "0.22"
rusqlite = { version = "0.32", features = ["bundled"] }
uuid = { version = "1", features = ["v4"] }
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
[profile.release]
codegen-units = 1
lto = true
opt-level = 3
panic = "abort"
strip = true

3
src-tauri/build.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@ -0,0 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default"
]
}

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 567 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 536 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 777 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1020 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 848 B

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

823
src-tauri/src/agent.rs Normal file
View File

@ -0,0 +1,823 @@
//! Agent-Loop (F-03, SPEC Abschnitt 5).
//!
//! Das Modell bekommt die Aufgabe und fünf Tools. Antwortet es mit Tool-Calls,
//! werden sie ausgeführt und die Ergebnisse zurückgegeben. Der Lauf endet bei
//! `done`, bei einer Antwort ohne Tool-Calls, bei Limits oder bei einem Fehler,
//! der nach der Spec den Lauf beendet.
//!
//! Modell und Workspace sind Traits, damit der Loop ohne Ollama und ohne Podman
//! testbar ist. Die echten Implementierungen sind `OllamaClient` und
//! `SandboxWorkspace`.
use crate::sandbox::Sandbox;
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
pub const WORK_DIR: &str = "/work";
pub const MAX_TOOL_OUTPUT_CHARS: usize = 20_000;
pub const SHELL_TIMEOUT: Duration = Duration::from_secs(60);
pub const LOOP_REPEATS: u32 = 3;
pub const SYSTEM_PROMPT: &str = "Du bist ein Coding-Agent. Dein Arbeitsverzeichnis ist /work. \
Du hast die Werkzeuge read_file, write_file, list_dir und run_shell. \
Wenn du fertig bist, rufe das Werkzeug done mit einer kurzen Zusammenfassung auf.";
/// Fehlerklassen eines Laufs (SPEC 5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorClass {
Ok,
InvalidToolJson,
UnknownTool,
BadArgs,
LoopDetected,
MaxSteps,
Timeout,
EndpointError,
CheckFailed,
}
/// Eine Nachricht im Verlauf (Ollama-Format).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Message {
pub role: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub content: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tool_calls: Vec<ToolCall>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_name: Option<String>,
}
impl Message {
pub fn new(role: &str, content: &str) -> Message {
Message {
role: role.into(),
content: content.into(),
tool_calls: vec![],
tool_name: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCall {
pub function: FunctionCall,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionCall {
pub name: String,
pub arguments: Value,
}
/// Antwort eines Modells mit Token-Zählern.
#[derive(Debug, Clone, PartialEq)]
pub struct ChatResponse {
pub message: Message,
pub prompt_tokens: u32,
pub completion_tokens: u32,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ModelError {
Timeout,
Endpoint(String),
}
/// Ein Chat-Modell. Die Implementierung entscheidet, wie es erreicht wird.
pub trait ModelClient {
fn chat(&self, messages: &[Message], tools: &Value, timeout: Duration)
-> Result<ChatResponse, ModelError>;
}
/// Die Arbeitsumgebung der Tools. In der App ist das die Sandbox, in Tests eine Attrappe.
pub trait Workspace {
fn read_file(&self, path: &str) -> Result<String, String>;
fn write_file(&self, path: &str, content: &str) -> Result<(), String>;
fn list_dir(&self, path: &str) -> Result<String, String>;
/// Liefert Ausgabe und Exit-Code als Text, oder einen Fehler bei Problemen mit dem Befehl selbst.
fn run_shell(&self, command: &str) -> Result<String, String>;
}
#[derive(Debug, Clone, PartialEq)]
pub struct AgentLimits {
pub max_steps: u32,
pub timeout: Duration,
}
/// Ergebnis eines Agentenlaufs, vor der Bewertung durch `check.sh`.
#[derive(Debug, Clone, PartialEq)]
pub struct RunOutcome {
pub class: ErrorClass,
pub summary: Option<String>,
pub steps: u32,
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub duration_ms: u128,
pub time_to_first_tool_ms: Option<u128>,
pub transcript: Vec<Message>,
/// Gesetzt, wenn der Lauf von außen abgebrochen wurde. Dann ist das Ergebnis nicht gültig.
pub cancelled: bool,
}
/// Werkzeug-Schema für Ollama.
pub fn tool_schemas() -> Value {
json!([
tool("read_file", "Liest eine Datei unter /work.", json!({
"path": {"type": "string", "description": "Pfad, relativ zu /work oder absolut unter /work"}
}), &["path"]),
tool("write_file", "Schreibt eine Datei unter /work, legt sie bei Bedarf an.", json!({
"path": {"type": "string", "description": "Pfad unter /work"},
"content": {"type": "string", "description": "Neuer Inhalt der Datei"}
}), &["path", "content"]),
tool("list_dir", "Listet Einträge eines Ordners unter /work mit Typ (d = Ordner, f = Datei).", json!({
"path": {"type": "string", "description": "Ordner unter /work"}
}), &["path"]),
tool("run_shell", "Führt einen Shell-Befehl in /work aus (60 s Limit).", json!({
"command": {"type": "string", "description": "Shell-Befehl"}
}), &["command"]),
tool("done", "Beendet den Lauf. Rufe es auf, wenn die Aufgabe erledigt ist.", json!({
"summary": {"type": "string", "description": "Kurze Zusammenfassung"}
}), &["summary"]),
])
}
fn tool(name: &str, description: &str, properties: Value, required: &[&str]) -> Value {
json!({
"type": "function",
"function": {
"name": name,
"description": description,
"parameters": {
"type": "object",
"properties": properties,
"required": required,
}
}
})
}
/// Prüft einen Pfad und gibt den absoluten Pfad unter `/work` zurück.
/// Erlaubt sind relative Pfade und absolute Pfade unter `/work`. `..` ist verboten.
pub fn resolve_work_path(path: &str) -> Result<String, String> {
let trimmed = path.trim();
if trimmed.is_empty() {
return Err("Pfad ist leer".into());
}
if trimmed.contains('\0') {
return Err("Pfad enthält ein Nullbyte".into());
}
let rel = if let Some(rest) = trimmed.strip_prefix(WORK_DIR) {
if !(rest.is_empty() || rest.starts_with('/')) {
return Err(format!("Pfad liegt außerhalb von {WORK_DIR}"));
}
rest
} else if trimmed.starts_with('/') {
return Err(format!("Pfad liegt außerhalb von {WORK_DIR}"));
} else {
trimmed
};
let mut parts = Vec::new();
for comp in rel.split('/') {
match comp {
"" | "." => {}
".." => return Err("Pfad darf kein .. enthalten".into()),
c => parts.push(c),
}
}
if parts.is_empty() {
Ok(WORK_DIR.into())
} else {
Ok(format!("{WORK_DIR}/{}", parts.join("/")))
}
}
fn truncate(text: &str) -> String {
if text.chars().count() <= MAX_TOOL_OUTPUT_CHARS {
return text.to_string();
}
let head: String = text.chars().take(MAX_TOOL_OUTPUT_CHARS).collect();
format!("{head}\n[... gekürzt, {} Zeichen insgesamt]", text.chars().count())
}
/// Fehler, die den Lauf beenden (Tool-Name unbekannt, Argumente kaputt).
enum Fatal {
Class(ErrorClass),
}
/// Holt die Argumente als Objekt. Manche Modelle liefern sie als JSON-Text.
fn arguments_object(v: &Value) -> Result<serde_json::Map<String, Value>, Fatal> {
match v {
Value::Object(m) => Ok(m.clone()),
Value::String(s) => match serde_json::from_str::<Value>(s) {
Ok(Value::Object(m)) => Ok(m),
_ => Err(Fatal::Class(ErrorClass::InvalidToolJson)),
},
Value::Null => Ok(serde_json::Map::new()),
_ => Err(Fatal::Class(ErrorClass::InvalidToolJson)),
}
}
fn required_str(args: &serde_json::Map<String, Value>, key: &str) -> Result<String, Fatal> {
match args.get(key) {
Some(Value::String(s)) => Ok(s.clone()),
_ => Err(Fatal::Class(ErrorClass::BadArgs)),
}
}
/// Führt einen Tool-Call aus. Gibt das Ergebnis als Text zurück, oder einen Fatal-Fehler.
/// `done` gibt `Ok(Err(summary))`-artig über `Done` zurück.
enum Step {
Result(String),
Done(String),
}
fn execute(call: &FunctionCall, ws: &dyn Workspace) -> Result<Step, Fatal> {
let args = arguments_object(&call.arguments)?;
match call.name.as_str() {
"read_file" => {
let path = required_str(&args, "path")?;
Ok(Step::Result(match resolve_work_path(&path) {
Err(e) => format!("Fehler: {e}"),
Ok(p) => match ws.read_file(&p) {
Ok(text) => truncate(&text),
Err(e) => format!("Fehler: {e}"),
},
}))
}
"write_file" => {
let path = required_str(&args, "path")?;
let content = required_str(&args, "content")?;
Ok(Step::Result(match resolve_work_path(&path) {
Err(e) => format!("Fehler: {e}"),
Ok(p) => match ws.write_file(&p, &content) {
Ok(()) => format!("geschrieben: {p}"),
Err(e) => format!("Fehler: {e}"),
},
}))
}
"list_dir" => {
let path = required_str(&args, "path")?;
Ok(Step::Result(match resolve_work_path(&path) {
Err(e) => format!("Fehler: {e}"),
Ok(p) => match ws.list_dir(&p) {
Ok(text) => truncate(&text),
Err(e) => format!("Fehler: {e}"),
},
}))
}
"run_shell" => {
let command = required_str(&args, "command")?;
Ok(Step::Result(match ws.run_shell(&command) {
Ok(out) => truncate(&out),
Err(e) => format!("Fehler: {e}"),
}))
}
"done" => {
let summary = required_str(&args, "summary")?;
Ok(Step::Done(summary))
}
_ => Err(Fatal::Class(ErrorClass::UnknownTool)),
}
}
/// Führt den Agenten-Loop aus.
pub fn run_agent(
model: &dyn ModelClient,
ws: &dyn Workspace,
prompt: &str,
limits: &AgentLimits,
) -> RunOutcome {
run_agent_cancellable(model, ws, prompt, limits, &AtomicBool::new(false))
}
/// Wie `run_agent`, bricht aber ab, sobald `cancel` gesetzt ist. Der Lauf gilt dann als `cancelled`.
pub fn run_agent_cancellable(
model: &dyn ModelClient,
ws: &dyn Workspace,
prompt: &str,
limits: &AgentLimits,
cancel: &AtomicBool,
) -> RunOutcome {
let started = Instant::now();
let tools = tool_schemas();
let mut messages = vec![Message::new("system", SYSTEM_PROMPT), Message::new("user", prompt)];
let mut out = RunOutcome {
class: ErrorClass::Ok,
summary: None,
steps: 0,
prompt_tokens: 0,
completion_tokens: 0,
duration_ms: 0,
time_to_first_tool_ms: None,
transcript: vec![],
cancelled: false,
};
// Letzter Tool-Call und Anzahl gleicher Wiederholungen mit gleichem Ergebnis.
let mut last: Option<(String, Value, String)> = None;
let mut repeats: u32 = 0;
let class = loop {
if cancel.load(Ordering::SeqCst) {
out.cancelled = true;
break ErrorClass::Ok;
}
if out.steps >= limits.max_steps {
break ErrorClass::MaxSteps;
}
let elapsed = started.elapsed();
if elapsed >= limits.timeout {
break ErrorClass::Timeout;
}
out.steps += 1;
let resp = match model.chat(&messages, &tools, limits.timeout - elapsed) {
Ok(r) => r,
Err(ModelError::Timeout) => break ErrorClass::Timeout,
Err(ModelError::Endpoint(_)) => break ErrorClass::EndpointError,
};
out.prompt_tokens += resp.prompt_tokens;
out.completion_tokens += resp.completion_tokens;
messages.push(resp.message.clone());
// Keine Tool-Calls: implizites Ende.
if resp.message.tool_calls.is_empty() {
out.summary = Some(resp.message.content.clone());
break ErrorClass::Ok;
}
let mut finished = None;
for call in &resp.message.tool_calls {
if out.time_to_first_tool_ms.is_none() {
out.time_to_first_tool_ms = Some(started.elapsed().as_millis());
}
match execute(&call.function, ws) {
Err(Fatal::Class(c)) => {
finished = Some(c);
break;
}
Ok(Step::Done(summary)) => {
finished = Some(ErrorClass::Ok);
out.summary = Some(summary);
break;
}
Ok(Step::Result(result)) => {
let key = (
call.function.name.clone(),
call.function.arguments.clone(),
result.clone(),
);
if last.as_ref() == Some(&key) {
repeats += 1;
} else {
repeats = 1;
}
last = Some(key);
if repeats >= LOOP_REPEATS {
finished = Some(ErrorClass::LoopDetected);
break;
}
messages.push(Message {
role: "tool".into(),
content: result,
tool_calls: vec![],
tool_name: Some(call.function.name.clone()),
});
}
}
}
if let Some(c) = finished {
break c;
}
};
out.class = class;
out.duration_ms = started.elapsed().as_millis();
out.transcript = messages;
out
}
/// Workspace auf einer laufenden Sandbox. Dateioperationen laufen als Shell-Befehle im Container.
pub struct SandboxWorkspace<'a> {
pub sandbox: &'a Sandbox,
}
fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', "'\\''"))
}
impl Workspace for SandboxWorkspace<'_> {
fn read_file(&self, path: &str) -> Result<String, String> {
let out = self
.sandbox
.exec(&format!("cat -- {}", sh_quote(path)), SHELL_TIMEOUT)?;
if out.exit_code == Some(0) {
Ok(out.stdout)
} else {
Err(first_line(&out.stderr, out.exit_code))
}
}
fn write_file(&self, path: &str, content: &str) -> Result<(), String> {
let encoded = base64::engine::general_purpose::STANDARD.encode(content);
let parent = match path.rfind('/') {
Some(0) | None => WORK_DIR,
Some(i) => &path[..i],
};
let cmd = format!(
"mkdir -p -- {} && printf %s {} | base64 -d > {}",
sh_quote(parent),
sh_quote(&encoded),
sh_quote(path)
);
let out = self.sandbox.exec(&cmd, SHELL_TIMEOUT)?;
if out.exit_code == Some(0) {
Ok(())
} else {
Err(first_line(&out.stderr, out.exit_code))
}
}
fn list_dir(&self, path: &str) -> Result<String, String> {
let cmd = format!(
"find {} -mindepth 1 -maxdepth 1 -printf '%y %f\\n' | sort",
sh_quote(path)
);
let out = self.sandbox.exec(&cmd, SHELL_TIMEOUT)?;
if out.exit_code == Some(0) {
Ok(if out.stdout.is_empty() { "(leer)".into() } else { out.stdout })
} else {
Err(first_line(&out.stderr, out.exit_code))
}
}
fn run_shell(&self, command: &str) -> Result<String, String> {
let out = self.sandbox.exec(command, SHELL_TIMEOUT)?;
if out.timed_out {
return Ok(format!("Befehl nach {} s abgebrochen.", SHELL_TIMEOUT.as_secs()));
}
let code = out.exit_code.map_or("?".to_string(), |c| c.to_string());
Ok(format!(
"exit {code}\n{}{}",
out.stdout,
if out.stderr.is_empty() {
String::new()
} else {
format!("\nstderr:\n{}", out.stderr)
}
))
}
}
fn first_line(stderr: &str, code: Option<i32>) -> String {
let line = stderr.lines().next().unwrap_or("").trim();
if line.is_empty() {
format!("Exit {}", code.map_or("?".into(), |c| c.to_string()))
} else {
line.to_string()
}
}
/// Modell über die Ollama-API `/api/chat` (ohne Streaming).
pub struct OllamaClient {
pub base_url: String,
pub model: String,
http: reqwest::blocking::Client,
}
#[derive(Deserialize)]
struct OllamaResponse {
message: Message,
#[serde(default)]
prompt_eval_count: u32,
#[serde(default)]
eval_count: u32,
}
impl OllamaClient {
pub fn new(base_url: &str, model: &str) -> Result<OllamaClient, String> {
let http = reqwest::blocking::Client::builder()
.build()
.map_err(|e| format!("HTTP-Client nicht baubar: {e}"))?;
Ok(OllamaClient {
base_url: base_url.trim_end_matches('/').into(),
model: model.into(),
http,
})
}
}
impl ModelClient for OllamaClient {
fn chat(&self, messages: &[Message], tools: &Value, timeout: Duration)
-> Result<ChatResponse, ModelError>
{
let body = json!({
"model": self.model,
"messages": messages,
"tools": tools,
"stream": false,
"options": { "temperature": 0 },
});
let resp = self
.http
.post(format!("{}/api/chat", self.base_url))
.timeout(timeout)
.json(&body)
.send()
.map_err(|e| {
if e.is_timeout() {
ModelError::Timeout
} else {
ModelError::Endpoint(e.to_string())
}
})?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().unwrap_or_default();
return Err(ModelError::Endpoint(format!("HTTP {status}: {text}")));
}
let parsed: OllamaResponse = resp
.json()
.map_err(|e| ModelError::Endpoint(format!("Antwort nicht lesbar: {e}")))?;
Ok(ChatResponse {
message: parsed.message,
prompt_tokens: parsed.prompt_eval_count,
completion_tokens: parsed.eval_count,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
struct MockModel {
script: RefCell<VecDeque<Result<ChatResponse, ModelError>>>,
}
impl MockModel {
fn new(script: Vec<Result<ChatResponse, ModelError>>) -> MockModel {
MockModel { script: RefCell::new(script.into()) }
}
}
impl ModelClient for MockModel {
fn chat(&self, _m: &[Message], _t: &Value, _to: Duration) -> Result<ChatResponse, ModelError> {
self.script
.borrow_mut()
.pop_front()
.unwrap_or(Err(ModelError::Endpoint("Skript leer".into())))
}
}
#[derive(Default)]
struct MockWs {
files: RefCell<HashMap<String, String>>,
}
impl Workspace for MockWs {
fn read_file(&self, path: &str) -> Result<String, String> {
self.files
.borrow()
.get(path)
.cloned()
.ok_or_else(|| "No such file".to_string())
}
fn write_file(&self, path: &str, content: &str) -> Result<(), String> {
self.files.borrow_mut().insert(path.into(), content.into());
Ok(())
}
fn list_dir(&self, _path: &str) -> Result<String, String> {
Ok("f a.txt".into())
}
fn run_shell(&self, command: &str) -> Result<String, String> {
Ok(format!("exit 0\nran: {command}"))
}
}
fn call(name: &str, args: Value) -> ToolCall {
ToolCall { function: FunctionCall { name: name.into(), arguments: args } }
}
fn reply(calls: Vec<ToolCall>) -> Result<ChatResponse, ModelError> {
Ok(ChatResponse {
message: Message {
role: "assistant".into(),
content: String::new(),
tool_calls: calls,
tool_name: None,
},
prompt_tokens: 10,
completion_tokens: 5,
})
}
fn limits() -> AgentLimits {
AgentLimits { max_steps: 25, timeout: Duration::from_secs(60) }
}
#[test]
fn done_beendet_den_lauf_mit_zusammenfassung() {
let m = MockModel::new(vec![reply(vec![call("done", json!({"summary": "fertig"}))])]);
let out = run_agent(&m, &MockWs::default(), "Aufgabe", &limits());
assert_eq!(out.class, ErrorClass::Ok);
assert_eq!(out.summary.as_deref(), Some("fertig"));
assert_eq!(out.steps, 1);
assert_eq!(out.prompt_tokens, 10);
}
#[test]
fn datei_lesen_schreiben_und_done() {
let ws = MockWs::default();
let m = MockModel::new(vec![
reply(vec![call("write_file", json!({"path": "out.txt", "content": "hi"}))]),
reply(vec![call("read_file", json!({"path": "/work/out.txt"}))]),
reply(vec![call("done", json!({"summary": "ok"}))]),
]);
let out = run_agent(&m, &ws, "Aufgabe", &limits());
assert_eq!(out.class, ErrorClass::Ok);
assert_eq!(ws.files.borrow().get("/work/out.txt").map(String::as_str), Some("hi"));
assert!(out.transcript.iter().any(|m| m.role == "tool" && m.content == "hi"));
assert!(out.time_to_first_tool_ms.is_some());
}
#[test]
fn tool_fehler_bricht_den_lauf_nicht_ab() {
let m = MockModel::new(vec![
reply(vec![call("read_file", json!({"path": "fehlt.txt"}))]),
reply(vec![call("done", json!({"summary": "nichts gefunden"}))]),
]);
let out = run_agent(&m, &MockWs::default(), "Aufgabe", &limits());
assert_eq!(out.class, ErrorClass::Ok);
assert!(out.transcript.iter().any(|m| m.content.starts_with("Fehler: No such file")));
}
#[test]
fn unbekanntes_tool_ist_klassifiziert() {
let m = MockModel::new(vec![reply(vec![call("fly", json!({}))])]);
let out = run_agent(&m, &MockWs::default(), "A", &limits());
assert_eq!(out.class, ErrorClass::UnknownTool);
}
#[test]
fn fehlende_argumente_sind_bad_args() {
let m = MockModel::new(vec![reply(vec![call("read_file", json!({}))])]);
let out = run_agent(&m, &MockWs::default(), "A", &limits());
assert_eq!(out.class, ErrorClass::BadArgs);
}
#[test]
fn argumente_als_kaputter_text_sind_invalid_tool_json() {
let m = MockModel::new(vec![reply(vec![call("read_file", Value::String("{kaputt".into()))])]);
let out = run_agent(&m, &MockWs::default(), "A", &limits());
assert_eq!(out.class, ErrorClass::InvalidToolJson);
}
#[test]
fn argumente_als_json_text_werden_akzeptiert() {
let ws = MockWs::default();
ws.files.borrow_mut().insert("/work/a.txt".into(), "x".into());
let m = MockModel::new(vec![
reply(vec![call("read_file", Value::String("{\"path\": \"a.txt\"}".into()))]),
reply(vec![call("done", json!({"summary": "ok"}))]),
]);
assert_eq!(run_agent(&m, &ws, "A", &limits()).class, ErrorClass::Ok);
}
#[test]
fn gleicher_aufruf_dreimal_ist_schleife() {
let c = || reply(vec![call("list_dir", json!({"path": "."}))]);
let m = MockModel::new(vec![c(), c(), c(), c()]);
let out = run_agent(&m, &MockWs::default(), "A", &limits());
assert_eq!(out.class, ErrorClass::LoopDetected);
assert_eq!(out.steps, 3);
}
#[test]
fn max_steps_endet_den_lauf() {
let m = MockModel::new(
(0..5).map(|i| reply(vec![call("run_shell", json!({"command": format!("echo {i}")}))])).collect(),
);
let lim = AgentLimits { max_steps: 2, timeout: Duration::from_secs(60) };
let out = run_agent(&m, &MockWs::default(), "A", &lim);
assert_eq!(out.class, ErrorClass::MaxSteps);
assert_eq!(out.steps, 2);
}
#[test]
fn modell_timeout_und_endpoint_fehler() {
let m = MockModel::new(vec![Err(ModelError::Timeout)]);
assert_eq!(run_agent(&m, &MockWs::default(), "A", &limits()).class, ErrorClass::Timeout);
let m = MockModel::new(vec![Err(ModelError::Endpoint("down".into()))]);
assert_eq!(run_agent(&m, &MockWs::default(), "A", &limits()).class, ErrorClass::EndpointError);
}
#[test]
fn implizites_ende_ohne_tool_calls() {
let m = MockModel::new(vec![Ok(ChatResponse {
message: Message::new("assistant", "Ich bin fertig."),
prompt_tokens: 1,
completion_tokens: 1,
})]);
let out = run_agent(&m, &MockWs::default(), "A", &limits());
assert_eq!(out.class, ErrorClass::Ok);
assert_eq!(out.summary.as_deref(), Some("Ich bin fertig."));
}
#[test]
fn pfade_bleiben_in_work() {
assert_eq!(resolve_work_path("a/b.txt").unwrap(), "/work/a/b.txt");
assert_eq!(resolve_work_path("./a.txt").unwrap(), "/work/a.txt");
assert_eq!(resolve_work_path("/work/x").unwrap(), "/work/x");
assert_eq!(resolve_work_path("/work").unwrap(), "/work");
assert!(resolve_work_path("../etc/passwd").is_err());
assert!(resolve_work_path("a/../../b").is_err());
assert!(resolve_work_path("/etc/passwd").is_err());
assert!(resolve_work_path("/workbench/x").is_err());
assert!(resolve_work_path("").is_err());
}
#[test]
fn ollama_antwort_wird_gelesen() {
let text = r#"{"message":{"role":"assistant","content":"","tool_calls":[{"function":{"name":"done","arguments":{"summary":"ok"}}}]},"prompt_eval_count":12,"eval_count":7}"#;
let parsed: OllamaResponse = serde_json::from_str(text).unwrap();
assert_eq!(parsed.message.tool_calls[0].function.name, "done");
assert_eq!(parsed.prompt_eval_count, 12);
assert_eq!(parsed.eval_count, 7);
}
/// Alle Tools gegen eine echte Sandbox. Braucht Podman und ein Image mit
/// Python, sh, find und base64: `CB_TEST_IMAGE=cb-python:latest cargo test -- --ignored`.
#[test]
#[ignore]
fn werkzeuge_gegen_echte_sandbox() {
use crate::sandbox::{container_name, Limits};
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
let name = container_name(&format!("agent-{}", std::process::id()));
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), None).expect("Start");
let ws = SandboxWorkspace { sandbox: &sb };
ws.write_file("/work/ordner/a.txt", "Hallo 'Welt'\n").unwrap();
assert_eq!(ws.read_file("/work/ordner/a.txt").unwrap(), "Hallo 'Welt'\n");
assert!(ws.read_file("/work/fehlt.txt").is_err());
let listing = ws.list_dir("/work").unwrap();
assert!(listing.contains("d ordner"), "{listing}");
let out = ws.run_shell("cat ordner/a.txt | wc -l").unwrap();
assert!(out.starts_with("exit 0"), "{out}");
assert!(out.contains('1'), "{out}");
// Ende-zu-Ende mit Mock-Modell gegen die echte Sandbox.
let m = MockModel::new(vec![
reply(vec![call("run_shell", json!({"command": "python3 -c 'print(6*7)'"}))]),
reply(vec![call("done", json!({"summary": "42"}))]),
]);
let out = run_agent(&m, &ws, "Rechne", &limits());
assert_eq!(out.class, ErrorClass::Ok);
assert!(out.transcript.iter().any(|m| m.content.contains("42")));
drop(ws);
sb.remove().unwrap();
}
/// Echter Modelllauf gegen Ollama und Podman. Braucht laufenden Ollama-Dienst
/// mit dem Modell und ein Image: `CB_OLLAMA_URL=http://host:11434 CB_OLLAMA_MODEL=qwen3:0.6b
/// CB_TEST_IMAGE=cb-python:latest cargo test ollama_lauf -- --ignored`.
#[test]
#[ignore]
fn ollama_lauf_schreibt_datei_und_beendet() {
use crate::sandbox::{container_name, Limits};
let url = std::env::var("CB_OLLAMA_URL").expect("CB_OLLAMA_URL setzen");
let model = std::env::var("CB_OLLAMA_MODEL").expect("CB_OLLAMA_MODEL setzen");
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
let name = container_name(&format!("ollama-{}", std::process::id()));
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), None).expect("Start");
let ws = SandboxWorkspace { sandbox: &sb };
let client = OllamaClient::new(&url, &model).unwrap();
let lim = AgentLimits { max_steps: 10, timeout: Duration::from_secs(600) };
let prompt = "Erstelle die Datei out.txt mit dem Inhalt hallo (ohne Zeilenumbruch). \
Rufe danach das Werkzeug done auf.";
let out = run_agent(&client, &ws, prompt, &lim);
eprintln!("Lauf: {:?} Schritte={} Tokens={}/{} Dauer={}ms", out.class, out.steps,
out.prompt_tokens, out.completion_tokens, out.duration_ms);
for m in &out.transcript {
eprintln!("[{}] {} {:?}", m.role, m.content.chars().take(200).collect::<String>(), m.tool_calls);
}
let content = ws.read_file("/work/out.txt").unwrap_or_default();
sb.remove().unwrap();
assert_eq!(out.class, ErrorClass::Ok, "Lauf endete mit {:?}", out.class);
assert_eq!(content.trim(), "hallo", "out.txt: {content:?}");
}
#[test]
fn sh_quote_maskiert_apostrophe() {
assert_eq!(sh_quote("a'b"), "'a'\\''b'");
}
}

173
src-tauri/src/config.rs Normal file
View File

@ -0,0 +1,173 @@
//! Konfiguration (TOML) und Datenordner (F-01).
//!
//! Die Datei `config.toml` liegt im App-Konfigurationsordner. Fehlt sie, wird sie
//! mit Standardwerten angelegt. Pfade in der Datei sind optional; ohne Angabe
//! gilt der Standardordner der App bzw. `<datenordner>/tasks`.
use crate::sandbox::Limits;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
pub const CONFIG_FILE_NAME: &str = "config.toml";
/// Rohe Konfiguration, so wie sie in der Datei steht.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// Datenordner (Ergebnisse, Artefakte, Datenbank). Leer = Standard der App.
pub data_dir: Option<PathBuf>,
/// Aufgabenordner. Leer = `<datenordner>/tasks`.
pub tasks_dir: Option<PathBuf>,
/// Container-Programm für die Sandbox (Podman-CLI).
pub container_runtime: String,
/// Speicherlimit pro Lauf, Podman-Schreibweise.
pub sandbox_memory: String,
/// CPU-Anteil pro Lauf.
pub sandbox_cpus: String,
}
impl Default for Config {
fn default() -> Self {
let limits = Limits::default();
Config {
data_dir: None,
tasks_dir: None,
container_runtime: "podman".into(),
sandbox_memory: limits.memory,
sandbox_cpus: limits.cpus,
}
}
}
/// Aufgelöste Pfade, die die App tatsächlich verwendet.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Paths {
pub config_file: PathBuf,
pub data_dir: PathBuf,
pub tasks_dir: PathBuf,
}
impl Config {
/// Liest die Konfiguration aus einem TOML-Text.
pub fn parse(text: &str) -> Result<Config, String> {
toml::from_str(text).map_err(|e| format!("config.toml ist ungültig: {e}"))
}
/// Ressourcenlimits der Sandbox aus der Konfiguration.
pub fn sandbox_limits(&self) -> Limits {
Limits {
memory: self.sandbox_memory.clone(),
cpus: self.sandbox_cpus.clone(),
}
}
/// Löst die Pfade auf. `default_data_dir` ist der Standardordner der App.
pub fn resolve(&self, config_file: &Path, default_data_dir: &Path) -> Paths {
let data_dir = self
.data_dir
.clone()
.unwrap_or_else(|| default_data_dir.to_path_buf());
let tasks_dir = self
.tasks_dir
.clone()
.unwrap_or_else(|| data_dir.join("tasks"));
Paths {
config_file: config_file.to_path_buf(),
data_dir,
tasks_dir,
}
}
}
/// Lädt die Konfiguration aus `config_dir/config.toml`, legt die Datei bei Bedarf
/// mit Standardwerten an und stellt sicher, dass der Datenordner existiert.
pub fn load_or_create(config_dir: &Path, default_data_dir: &Path) -> Result<(Paths, Config), String> {
fs::create_dir_all(config_dir)
.map_err(|e| format!("Konfigurationsordner {} nicht anlegbar: {e}", config_dir.display()))?;
let config_file = config_dir.join(CONFIG_FILE_NAME);
let config = if config_file.exists() {
let text = fs::read_to_string(&config_file)
.map_err(|e| format!("{} nicht lesbar: {e}", config_file.display()))?;
Config::parse(&text)?
} else {
let defaults = Config::default();
let text = toml::to_string_pretty(&defaults)
.map_err(|e| format!("Standard-Config nicht serialisierbar: {e}"))?;
fs::write(&config_file, format!("# coding-bench Konfiguration\n{text}"))
.map_err(|e| format!("{} nicht schreibbar: {e}", config_file.display()))?;
defaults
};
let paths = config.resolve(&config_file, default_data_dir);
fs::create_dir_all(&paths.data_dir)
.map_err(|e| format!("Datenordner {} nicht anlegbar: {e}", paths.data_dir.display()))?;
Ok((paths, config))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn leere_datei_ergibt_standardwerte() {
let c = Config::parse("").unwrap();
assert_eq!(c, Config::default());
}
#[test]
fn pfade_werden_gelesen() {
let c = Config::parse("data_dir = \"/x/daten\"\ntasks_dir = \"/x/aufgaben\"\n").unwrap();
assert_eq!(c.data_dir, Some(PathBuf::from("/x/daten")));
assert_eq!(c.tasks_dir, Some(PathBuf::from("/x/aufgaben")));
}
#[test]
fn sandbox_limits_werden_gelesen() {
let c = Config::parse("sandbox_memory = \"4g\"\nsandbox_cpus = \"1\"\n").unwrap();
assert_eq!(c.sandbox_limits(), Limits { memory: "4g".into(), cpus: "1".into() });
assert_eq!(c.container_runtime, "podman");
}
#[test]
fn unbekannter_schluessel_ist_fehler() {
assert!(Config::parse("unbekannt = 1\n").is_err());
}
#[test]
fn tasks_standard_liegt_im_datenordner() {
let p = Config::default().resolve(Path::new("/c/config.toml"), Path::new("/d"));
assert_eq!(p.data_dir, PathBuf::from("/d"));
assert_eq!(p.tasks_dir, PathBuf::from("/d/tasks"));
}
#[test]
fn angegebener_datenordner_gilt_auch_fuer_tasks() {
let c = Config::parse("data_dir = \"/x\"\n").unwrap();
let p = c.resolve(Path::new("/c/config.toml"), Path::new("/d"));
assert_eq!(p.data_dir, PathBuf::from("/x"));
assert_eq!(p.tasks_dir, PathBuf::from("/x/tasks"));
}
#[test]
fn load_or_create_legt_datei_und_ordner_an() {
let base = std::env::temp_dir().join(format!("cb-config-test-{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
let cfg_dir = base.join("cfg");
let data_dir = base.join("data");
let (paths, _) = load_or_create(&cfg_dir, &data_dir).unwrap();
assert!(cfg_dir.join(CONFIG_FILE_NAME).exists());
assert!(data_dir.is_dir());
assert_eq!(paths.tasks_dir, data_dir.join("tasks"));
// Zweiter Aufruf liest die vorhandene Datei, ohne sie zu verändern.
let before = fs::read_to_string(cfg_dir.join(CONFIG_FILE_NAME)).unwrap();
load_or_create(&cfg_dir, &data_dir).unwrap();
let after = fs::read_to_string(cfg_dir.join(CONFIG_FILE_NAME)).unwrap();
assert_eq!(before, after);
let _ = fs::remove_dir_all(&base);
}
}

45
src-tauri/src/lib.rs Normal file
View File

@ -0,0 +1,45 @@
mod agent;
mod config;
mod runner;
mod store;
mod sandbox;
mod tasks;
use config::Paths;
use tauri::{Manager, State};
/// Aufgelöste Pfade, einmal beim Start ermittelt.
pub struct AppPaths(pub Paths);
#[tauri::command]
fn get_paths(paths: State<'_, AppPaths>) -> Paths {
paths.0.clone()
}
#[tauri::command]
fn load_tasks(paths: State<'_, AppPaths>) -> tasks::LoadReport {
tasks::load_all(&paths.0.tasks_dir)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.setup(|app| {
let config_dir = app
.path()
.app_config_dir()
.map_err(|e| format!("Konfigurationsordner nicht ermittelbar: {e}"))?;
let default_data_dir = app
.path()
.app_data_dir()
.map_err(|e| format!("Datenordner nicht ermittelbar: {e}"))?;
let (paths, cfg) = config::load_or_create(&config_dir, &default_data_dir)?;
app.manage(AppPaths(paths));
app.manage(cfg);
Ok(())
})
.invoke_handler(tauri::generate_handler![get_paths, load_tasks])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

6
src-tauri/src/main.rs Normal file
View File

@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
coding_bench_lib::run()
}

480
src-tauri/src/runner.rs Normal file
View File

@ -0,0 +1,480 @@
//! Runner: Batch aus Modellen, Aufgaben und Wiederholungen (F-05, SPEC Abschnitt 7).
//!
//! Die Modelle laufen nacheinander, weil ein Modell die GPU belegt. Jeder Lauf
//! bekommt eine frische Sandbox, der Agent läuft, danach läuft `check.sh` im
//! selben Container. Fertige Läufe stehen in der Datenbank und werden beim
//! Fortsetzen übersprungen. Ein abgebrochener Lauf wird verworfen und nicht gespeichert.
use crate::agent::{
run_agent_cancellable, AgentLimits, ErrorClass, Message, ModelClient, ModelError,
OllamaClient, SandboxWorkspace,
};
use crate::sandbox::{container_name, remove_by_name, Limits, Sandbox};
use crate::store::{RunRecord, Store};
use crate::tasks::{Task, CHECK_FILE, START_DIR};
use serde::Serialize;
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
pub const CHECK_DIR: &str = "/checks";
pub const WARMUP_TIMEOUT: Duration = Duration::from_secs(300);
/// Ein einzelner Lauf im Plan.
#[derive(Debug, Clone, PartialEq)]
pub struct Job {
pub model: String,
pub task: Task,
pub repeat_idx: u32,
}
/// Einstellungen für einen Batch.
#[derive(Debug, Clone)]
pub struct RunConfig {
pub runtime: String,
pub endpoint_url: String,
pub data_dir: PathBuf,
pub limits: Limits,
}
/// Ereignisse für die Oberfläche.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Event {
RunStarted { model: String, task: String, repeat: u32 },
RunFinished { model: String, task: String, repeat: u32, class: ErrorClass, score: f64 },
RunSkipped { model: String, task: String, repeat: u32 },
ModelUnavailable { model: String, reason: String },
Progress { done: usize, total: usize },
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BatchSummary {
pub batch_id: i64,
pub completed: usize,
pub skipped: usize,
pub cancelled: bool,
}
/// Plan in fester Reihenfolge: Modell, dann Aufgabe, dann Wiederholung.
pub fn plan(models: &[String], tasks: &[Task], repeats: u32) -> Vec<Job> {
let mut jobs = Vec::new();
for model in models {
for task in tasks {
for repeat_idx in 1..=repeats {
jobs.push(Job {
model: model.clone(),
task: task.clone(),
repeat_idx,
});
}
}
}
jobs
}
/// Ergebnis der Prüfung durch `check.sh`.
#[derive(Debug, Clone, PartialEq)]
pub struct CheckResult {
pub score: f64,
pub passed: bool,
}
/// Wertet `check.sh` aus. Letzte Zeile als JSON `{"score": …}` gewinnt, sonst zählt der Exit-Code.
pub fn evaluate_check(exit: Option<i32>, stdout: &str) -> CheckResult {
let last = stdout.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("");
if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(last.trim()) {
if let Some(score) = obj.get("score").and_then(Value::as_f64) {
let score = score.clamp(0.0, 1.0);
return CheckResult { score, passed: score >= 1.0 };
}
}
let passed = exit == Some(0);
CheckResult { score: if passed { 1.0 } else { 0.0 }, passed }
}
/// Fehlerklasse eines fertigen Laufs: zuerst die Agentenklasse, dann die Prüfung.
pub fn final_class(agent: ErrorClass, check: &CheckResult) -> ErrorClass {
if agent != ErrorClass::Ok {
agent
} else if !check.passed {
ErrorClass::CheckFailed
} else {
ErrorClass::Ok
}
}
/// Startet einen Batch oder setzt einen bestehenden fort.
/// `batch_id = None` legt einen neuen Batch an. Fertige Läufe werden übersprungen.
pub fn run_batch(
store: &mut Store,
cfg: &RunConfig,
batch_id: Option<i64>,
note: &str,
repeats: u32,
jobs: &[Job],
cancel: &AtomicBool,
on_event: &dyn Fn(&Event),
) -> Result<BatchSummary, String> {
let config_json = json!({
"runtime": cfg.runtime,
"endpoint": cfg.endpoint_url,
"limits": { "memory": cfg.limits.memory, "cpus": cfg.limits.cpus },
"system_prompt": crate::agent::SYSTEM_PROMPT,
"tool_output_chars": crate::agent::MAX_TOOL_OUTPUT_CHARS,
"loop_repeats": crate::agent::LOOP_REPEATS,
})
.to_string();
let batch_id = match batch_id {
Some(id) => {
if !store.batch_exists(id)? {
return Err(format!("Batch {id} existiert nicht"));
}
id
}
None => store.create_batch(note, repeats, &config_json)?,
};
let finished = store.finished_keys(batch_id)?;
let total = jobs.len();
let mut summary = BatchSummary { batch_id, completed: 0, skipped: 0, cancelled: false };
let mut done = 0usize;
// Modelle in der Reihenfolge des Plans, jedes Modell nur einmal aufwärmen.
let mut models: Vec<String> = Vec::new();
for j in jobs {
if !models.contains(&j.model) {
models.push(j.model.clone());
}
}
'models: for model in &models {
let client = OllamaClient::new(&cfg.endpoint_url, model)?;
let warm = client.chat(
&[Message::new("user", "ping")],
&json!([]),
WARMUP_TIMEOUT,
);
let unavailable = match warm {
Ok(_) => None,
Err(ModelError::Timeout) => Some("Aufwärmen hat das Zeitlimit überschritten".to_string()),
Err(ModelError::Endpoint(e)) => Some(e),
};
if let Some(reason) = &unavailable {
on_event(&Event::ModelUnavailable { model: model.clone(), reason: reason.clone() });
}
for (i, job) in jobs.iter().enumerate().filter(|(_, j)| &j.model == model) {
if cancel.load(Ordering::SeqCst) {
summary.cancelled = true;
break 'models;
}
let key = (job.model.clone(), job.task.meta.id.clone(), job.repeat_idx);
if finished.contains(&key) {
summary.skipped += 1;
done += 1;
on_event(&Event::RunSkipped {
model: job.model.clone(),
task: job.task.meta.id.clone(),
repeat: job.repeat_idx,
});
on_event(&Event::Progress { done, total });
continue;
}
on_event(&Event::RunStarted {
model: job.model.clone(),
task: job.task.meta.id.clone(),
repeat: job.repeat_idx,
});
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(),
},
transcript: vec![],
},
None => match execute_job(cfg, batch_id, i, job, &client, cancel)? {
JobResult::Cancelled => {
summary.cancelled = true;
break 'models;
}
JobResult::Finished(f) => f,
},
};
on_event(&Event::RunFinished {
model: job.model.clone(),
task: job.task.meta.id.clone(),
repeat: job.repeat_idx,
class: fin.record.error_class,
score: fin.record.score,
});
store.insert_run(&fin.record, &fin.transcript)?;
summary.completed += 1;
done += 1;
on_event(&Event::Progress { done, total });
}
}
if summary.cancelled {
on_event(&Event::Progress { done, total });
}
Ok(summary)
}
struct Finished {
record: RunRecord,
transcript: Vec<Message>,
}
enum JobResult {
Finished(Finished),
Cancelled,
}
fn execute_job(
cfg: &RunConfig,
batch_id: i64,
seq: usize,
job: &Job,
client: &OllamaClient,
cancel: &AtomicBool,
) -> Result<JobResult, String> {
let meta = &job.task.meta;
let name = container_name(&format!("{batch_id}-{seq}"));
remove_by_name(&cfg.runtime, &name);
let start_dir = job.task.dir.join(START_DIR);
let start_arg = if start_dir.is_dir() { Some(start_dir.as_path()) } else { None };
let sb = Sandbox::start(&cfg.runtime, &name, &meta.image, &cfg.limits, start_arg)?;
let ws = SandboxWorkspace { sandbox: &sb };
let limits = AgentLimits {
max_steps: meta.max_steps,
timeout: Duration::from_secs(meta.timeout_s),
};
let prompt = std::fs::read_to_string(job.task.dir.join("prompt.md"))
.map_err(|e| format!("prompt.md nicht lesbar: {e}"))?;
let outcome = run_agent_cancellable(client, &ws, &prompt, &limits, cancel);
if outcome.cancelled {
sb.remove()?;
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}")),
};
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 class = final_class(outcome.class, &check);
let secs = outcome.duration_ms as f64 / 1000.0;
let tps = if outcome.completion_tokens > 0 && secs > 0.0 {
Some(outcome.completion_tokens as f64 / secs)
} else {
None
};
let record = RunRecord {
batch_id,
model: job.model.clone(),
task_id: meta.id.clone(),
repeat_idx: job.repeat_idx,
error_class: class,
score: check.score,
steps: outcome.steps,
prompt_tokens: outcome.prompt_tokens,
completion_tokens: outcome.completion_tokens,
duration_ms: outcome.duration_ms,
tps,
ttft_tool_ms: outcome.time_to_first_tool_ms,
artifact_path,
summary: outcome.summary.clone(),
check_output: check_text,
};
Ok(JobResult::Finished(Finished {
record,
transcript: outcome.transcript,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tasks::TaskToml;
fn task(id: &str) -> Task {
Task {
meta: TaskToml {
id: id.into(),
title: id.into(),
group: "A".into(),
weight: 1.0,
image: "cb-python:latest".into(),
max_steps: 5,
timeout_s: 60,
check_timeout_s: 30,
},
dir: PathBuf::from("/x"),
}
}
#[test]
fn plan_reihenfolge_modell_aufgabe_wiederholung() {
let jobs = plan(
&["m1".into(), "m2".into()],
&[task("a-01"), task("b-04")],
2,
);
assert_eq!(jobs.len(), 8);
let keys: Vec<(String, String, u32)> = jobs
.iter()
.map(|j| (j.model.clone(), j.task.meta.id.clone(), j.repeat_idx))
.collect();
assert_eq!(keys[0], ("m1".into(), "a-01".into(), 1));
assert_eq!(keys[1], ("m1".into(), "a-01".into(), 2));
assert_eq!(keys[2], ("m1".into(), "b-04".into(), 1));
assert_eq!(keys[4], ("m2".into(), "a-01".into(), 1));
}
#[test]
fn check_json_score_gewinnt() {
let r = evaluate_check(Some(0), "viel text\n{\"score\": 0.5, \"notes\": \"halb\"}\n");
assert_eq!(r, CheckResult { score: 0.5, passed: false });
}
#[test]
fn check_ohne_json_zaehlt_exit_code() {
assert_eq!(evaluate_check(Some(0), "ok"), CheckResult { score: 1.0, passed: true });
assert_eq!(evaluate_check(Some(1), "fehler"), CheckResult { score: 0.0, passed: false });
assert_eq!(evaluate_check(None, ""), CheckResult { score: 0.0, passed: false });
}
#[test]
fn check_score_wird_begrenzt() {
let r = evaluate_check(Some(0), "{\"score\": 3.0}");
assert_eq!(r.score, 1.0);
assert!(r.passed);
}
/// Kleiner Batch end-to-end: echtes Modell, echte Sandbox, Fortsetzen über die Datenbank.
/// `CB_OLLAMA_URL=… CB_OLLAMA_MODEL=… CB_TEST_IMAGE=cb-python:latest cargo test batch_end_zu_end -- --ignored --nocapture`
#[test]
#[ignore]
fn batch_end_zu_end() {
let url = std::env::var("CB_OLLAMA_URL").expect("CB_OLLAMA_URL setzen");
let model = std::env::var("CB_OLLAMA_MODEL").expect("CB_OLLAMA_MODEL setzen");
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
let base = std::env::temp_dir().join(format!("cb-batch-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let task_dir = base.join("tasks").join("A").join("a-test");
std::fs::create_dir_all(task_dir.join("start")).unwrap();
std::fs::write(
task_dir.join("task.toml"),
format!("id = \"a-test\"\ntitle = \"Datei schreiben\"\ngroup = \"A\"\nimage = \"{image}\"\nmax_steps = 6\ntimeout_s = 300\ncheck_timeout_s = 60\n"),
)
.unwrap();
std::fs::write(task_dir.join("prompt.md"), "Erstelle die Datei out.txt mit dem Inhalt hallo (ohne Zeilenumbruch). Rufe danach done auf.").unwrap();
std::fs::write(task_dir.join("check.sh"), "#!/bin/sh\n[ \"$(cat /work/out.txt)\" = \"hallo\" ]\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(task_dir.join("check.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
}
let (tasks, errs) = {
let r = crate::tasks::load_all(&base.join("tasks"));
(r.tasks, r.errors)
};
assert!(errs.is_empty(), "{errs:?}");
let jobs = plan(&[model.clone()], &tasks, 2);
let cfg = RunConfig {
runtime: "podman".into(),
endpoint_url: url,
data_dir: base.join("data"),
limits: Limits::default(),
};
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, "e2e", 2, &jobs, &cancel, &on).unwrap();
eprintln!("erster Lauf: {first:?}");
assert_eq!(first.completed, 2);
assert_eq!(first.skipped, 0);
// Fortsetzen mit demselben Batch: nichts läuft erneut.
let second = run_batch(&mut store, &cfg, Some(first.batch_id), "", 2, &jobs, &cancel, &on).unwrap();
eprintln!("zweiter Lauf: {second:?}");
assert_eq!(second.completed, 0);
assert_eq!(second.skipped, 2);
assert_eq!(store.run_count(first.batch_id).unwrap(), 2);
for e in events.borrow().iter() {
eprintln!("{}", serde_json::to_string(e).unwrap());
}
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn klasse_agent_vor_pruefung() {
let ok = CheckResult { score: 1.0, passed: true };
let bad = CheckResult { score: 0.0, passed: false };
assert_eq!(final_class(ErrorClass::MaxSteps, &ok), ErrorClass::MaxSteps);
assert_eq!(final_class(ErrorClass::Ok, &bad), ErrorClass::CheckFailed);
assert_eq!(final_class(ErrorClass::Ok, &ok), ErrorClass::Ok);
}
}

319
src-tauri/src/sandbox.rs Normal file
View File

@ -0,0 +1,319 @@
//! Sandbox pro Lauf (F-04, SPEC Abschnitt 6).
//!
//! Jeder Lauf bekommt einen frischen Podman-Container ohne Netzwerk. Die Aufgabe
//! wird nach `/work` kopiert, Befehle laufen per `podman exec`, und am Ende wird
//! `/work` herausgeholt und der Container entfernt. Podman wird über die CLI
//! angesprochen (rootless, Docker-kompatible Befehle).
use std::io::Read;
use std::path::Path;
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
pub const WORK_DIR: &str = "/work";
/// Ressourcenlimits eines Containers.
#[derive(Debug, Clone, PartialEq)]
pub struct Limits {
/// Speicherlimit, Podman-Schreibweise, z. B. `2g`.
pub memory: String,
/// CPU-Anteil, z. B. `2`.
pub cpus: String,
}
impl Default for Limits {
fn default() -> Self {
Limits {
memory: "2g".into(),
cpus: "2".into(),
}
}
}
/// Ergebnis eines Befehls im Container.
#[derive(Debug, Clone, PartialEq)]
pub struct ExecOutput {
pub exit_code: Option<i32>,
pub stdout: String,
pub stderr: String,
pub timed_out: bool,
}
/// Argumente für `podman run`. Reine Funktion, damit sie testbar ist.
pub fn run_args(name: &str, image: &str, limits: &Limits) -> Vec<String> {
vec![
"run".into(),
"-d".into(),
"--name".into(),
name.into(),
"--network".into(),
"none".into(),
"--memory".into(),
limits.memory.clone(),
"--cpus".into(),
limits.cpus.clone(),
"--pids-limit".into(),
"512".into(),
"--label".into(),
"coding-bench=lauf".into(),
image.into(),
"sleep".into(),
"infinity".into(),
]
}
/// Eindeutiger Containername pro Lauf.
pub fn container_name(run_id: &str) -> String {
format!("cb-{run_id}")
}
/// Ein laufender Sandbox-Container. Wird beim Verwerfen entfernt.
pub struct Sandbox {
runtime: String,
name: String,
removed: bool,
}
impl Sandbox {
/// Startet den Container und kopiert optional das Startverzeichnis nach `/work`.
pub fn start(
runtime: &str,
name: &str,
image: &str,
limits: &Limits,
start_dir: Option<&Path>,
) -> Result<Sandbox, String> {
let sb = Sandbox {
runtime: runtime.into(),
name: name.into(),
removed: false,
};
let out = Command::new(runtime)
.args(run_args(name, image, limits))
.output()
.map_err(|e| format!("{runtime} nicht startbar: {e}"))?;
if !out.status.success() {
return Err(format!(
"Container konnte nicht gestartet werden: {}",
String::from_utf8_lossy(&out.stderr).trim()
));
}
// Ab hier räumt Drop den Container auf, auch wenn der Rest fehlschlägt.
let mut sb = sb;
// Ohne `-w`, weil /work noch nicht existiert.
let mkdir = sb.exec_in(None, &format!("mkdir -p {WORK_DIR}"), Duration::from_secs(30))?;
if mkdir.exit_code != Some(0) {
return Err(format!("{WORK_DIR} nicht anlegbar: {}", mkdir.stderr.trim()));
}
if let Some(src) = start_dir {
let src_spec = format!("{}/.", src.display());
let dst_spec = format!("{}:{WORK_DIR}/", sb.name);
let cp = Command::new(runtime)
.args(["cp", &src_spec, &dst_spec])
.output()
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
if !cp.status.success() {
return Err(format!(
"Startdateien nicht kopierbar: {}",
String::from_utf8_lossy(&cp.stderr).trim()
));
}
}
Ok(sb)
}
pub fn name(&self) -> &str {
&self.name
}
/// Führt `command` per `sh -c` in `/work` aus. Nach `timeout` wird der
/// Client-Prozess beendet und `timed_out` gesetzt.
pub fn exec(&self, command: &str, timeout: Duration) -> Result<ExecOutput, String> {
self.exec_in(Some(WORK_DIR), command, timeout)
}
fn exec_in(&self, workdir: Option<&str>, command: &str, timeout: Duration) -> Result<ExecOutput, String> {
let mut args: Vec<&str> = vec!["exec"];
if let Some(w) = workdir {
args.extend(["-w", w]);
}
args.extend([self.name.as_str(), "sh", "-c", command]);
let mut child = Command::new(&self.runtime)
.args(&args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("podman exec fehlgeschlagen: {e}"))?;
// 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 start = Instant::now();
let (status, timed_out) = loop {
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
break (Some(status), false);
}
if start.elapsed() >= timeout {
let _ = child.kill();
let status = child.wait().ok();
break (status, true);
}
thread::sleep(Duration::from_millis(50));
};
Ok(ExecOutput {
exit_code: status.and_then(|s| s.code()),
stdout: t_out.join().unwrap_or_default(),
stderr: t_err.join().unwrap_or_default(),
timed_out,
})
}
/// Kopiert `/work` in den Zielordner (Artefakt).
pub fn export_work(&self, dest: &Path) -> Result<(), String> {
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)
.args(["cp", &src_spec, &dst_spec])
.output()
.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()
));
}
Ok(())
}
/// Kopiert eine einzelne Datei in den Container (z. B. `check.sh`, nicht in `/work`).
pub fn copy_in(&self, src: &Path, dst: &str) -> Result<(), String> {
let dst_spec = format!("{}:{dst}", self.name);
let out = Command::new(&self.runtime)
.args(["cp", &src.display().to_string(), &dst_spec])
.output()
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
if out.status.success() {
Ok(())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
/// Entfernt den Container. Fehler werden zurückgegeben, nicht verschluckt.
pub fn remove(mut self) -> Result<(), String> {
self.remove_inner()
}
fn remove_inner(&mut self) -> Result<(), String> {
if self.removed {
return Ok(());
}
self.removed = true;
let out = Command::new(&self.runtime)
.args(["rm", "-f", &self.name])
.output()
.map_err(|e| format!("podman rm fehlgeschlagen: {e}"))?;
if out.status.success() {
Ok(())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
}
/// 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();
}
impl Drop for Sandbox {
fn drop(&mut self) {
let _ = self.remove_inner();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_args_enthalten_netzwerk_aus_und_limits() {
let args = run_args("cb-x", "img:1", &Limits::default());
let s = args.join(" ");
assert!(s.contains("--network none"));
assert!(s.contains("--memory 2g"));
assert!(s.contains("--cpus 2"));
assert!(s.ends_with("img:1 sleep infinity"));
}
#[test]
fn containername_ist_praefixiert() {
assert_eq!(container_name("42"), "cb-42");
}
/// Echter Lauf gegen Podman. Braucht ein lokales Image mit `sleep` und `sh`
/// und ist deshalb ignoriert. Ausführen mit:
/// `CB_TEST_IMAGE=docker.io/library/python:3.12-slim cargo test -- --ignored`
#[test]
#[ignore]
fn echter_lauf_ohne_netz_und_aufraeumen() {
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
let base = std::env::temp_dir().join(format!("cb-sandbox-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let start_dir = base.join("start");
std::fs::create_dir_all(&start_dir).unwrap();
std::fs::write(start_dir.join("eingabe.txt"), "hallo").unwrap();
let name = container_name(&format!("test-{}", std::process::id()));
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), Some(&start_dir))
.expect("Start");
// Startdatei liegt in /work.
let r = sb.exec("cat eingabe.txt", Duration::from_secs(30)).unwrap();
assert_eq!(r.stdout, "hallo");
// Kein Netz: Verbindung muss scheitern.
let r = sb
.exec(
"python3 -c 'import socket; socket.create_connection((\"1.1.1.1\", 80), timeout=3)'",
Duration::from_secs(30),
)
.unwrap();
assert_ne!(r.exit_code, Some(0), "Netz sollte aus sein: {}", r.stderr);
// Timeout wird erkannt.
let r = sb.exec("sleep 10", Duration::from_secs(1)).unwrap();
assert!(r.timed_out);
// Artefakt herausholen.
let art = base.join("artefakt");
sb.export_work(&art).unwrap();
assert_eq!(std::fs::read_to_string(art.join("eingabe.txt")).unwrap(), "hallo");
sb.remove().unwrap();
let ps = Command::new("podman")
.args(["ps", "-a", "--filter", &format!("name={name}"), "--format", "{{.Names}}"])
.output()
.unwrap();
assert!(String::from_utf8_lossy(&ps.stdout).trim().is_empty(), "Container nicht entfernt");
let _ = std::fs::remove_dir_all(&base);
}
}

257
src-tauri/src/store.rs Normal file
View File

@ -0,0 +1,257 @@
//! SQLite-Speicher für Batches, Läufe und Schritte (F-06, SPEC Abschnitt 8).
use crate::agent::{ErrorClass, Message};
use rusqlite::{params, Connection, OptionalExtension};
use serde::Serialize;
use std::collections::HashSet;
use std::path::Path;
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS batch (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
note TEXT NOT NULL DEFAULT '',
repeats INTEGER NOT NULL,
config_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS run (
id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_id INTEGER NOT NULL REFERENCES batch(id),
model TEXT NOT NULL,
task_id TEXT NOT NULL,
repeat_idx INTEGER NOT NULL,
status TEXT NOT NULL,
error_class TEXT NOT NULL,
score REAL NOT NULL,
steps INTEGER NOT NULL,
prompt_tokens INTEGER NOT NULL,
completion_tokens INTEGER NOT NULL,
duration_ms INTEGER NOT NULL,
tps REAL,
ttft_tool_ms INTEGER,
started_at TEXT NOT NULL DEFAULT (datetime('now')),
artifact_path TEXT,
summary TEXT,
check_output TEXT
);
CREATE INDEX IF NOT EXISTS run_batch ON run(batch_id, model, task_id, repeat_idx);
CREATE TABLE IF NOT EXISTS step (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id INTEGER NOT NULL REFERENCES run(id),
idx INTEGER NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
tool_name TEXT,
tool_args_json TEXT,
tool_result TEXT,
tokens INTEGER,
duration_ms INTEGER
);
";
/// Ein abgeschlossener Lauf, so wie er gespeichert wird.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RunRecord {
pub batch_id: i64,
pub model: String,
pub task_id: String,
pub repeat_idx: u32,
pub error_class: ErrorClass,
pub score: f64,
pub steps: u32,
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub duration_ms: u128,
pub tps: Option<f64>,
pub ttft_tool_ms: Option<u128>,
pub artifact_path: Option<String>,
pub summary: Option<String>,
pub check_output: String,
}
pub struct Store {
conn: Connection,
}
impl Store {
pub fn open(path: &Path) -> Result<Store, String> {
let conn = Connection::open(path).map_err(|e| format!("Datenbank nicht öffenbar: {e}"))?;
Self::init(conn)
}
pub fn open_in_memory() -> Result<Store, String> {
let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
Self::init(conn)
}
fn init(conn: Connection) -> Result<Store, String> {
conn.execute_batch("PRAGMA foreign_keys = ON;")
.and_then(|_| conn.execute_batch(SCHEMA))
.map_err(|e| format!("Schema nicht anlegbar: {e}"))?;
Ok(Store { conn })
}
pub fn create_batch(&self, note: &str, repeats: u32, config_json: &str) -> Result<i64, String> {
self.conn
.execute(
"INSERT INTO batch (note, repeats, config_json) VALUES (?1, ?2, ?3)",
params![note, repeats, config_json],
)
.map_err(|e| e.to_string())?;
Ok(self.conn.last_insert_rowid())
}
pub fn batch_exists(&self, batch_id: i64) -> Result<bool, String> {
self.conn
.query_row("SELECT 1 FROM batch WHERE id = ?1", params![batch_id], |_| Ok(()))
.optional()
.map(|r| r.is_some())
.map_err(|e| e.to_string())
}
/// Schlüssel (Modell, Aufgabe, Wiederholung) aller bereits gespeicherten Läufe eines Batches.
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")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![batch_id], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, u32>(2)?))
})
.map_err(|e| e.to_string())?;
rows.collect::<Result<HashSet<_>, _>>().map_err(|e| e.to_string())
}
/// Speichert einen Lauf mit seinen Schritten in einer Transaktion.
pub fn insert_run(&mut self, rec: &RunRecord, transcript: &[Message]) -> Result<i64, String> {
let tx = self.conn.transaction().map_err(|e| e.to_string())?;
let class = serde_json::to_value(rec.error_class)
.ok()
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_default();
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)",
params![
rec.batch_id,
rec.model,
rec.task_id,
rec.repeat_idx,
class,
rec.score,
rec.steps,
rec.prompt_tokens,
rec.completion_tokens,
rec.duration_ms as i64,
rec.tps,
rec.ttft_tool_ms.map(|v| v as i64),
rec.artifact_path,
rec.summary,
rec.check_output,
],
)
.map_err(|e| e.to_string())?;
let run_id = tx.last_insert_rowid();
for (idx, m) in transcript.iter().enumerate() {
let (args, tool_name) = match m.tool_calls.first() {
Some(c) => (Some(c.function.arguments.to_string()), Some(c.function.name.clone())),
None => (None, m.tool_name.clone()),
};
tx.execute(
"INSERT INTO step (run_id, idx, role, content, tool_name, tool_args_json, tool_result)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
run_id,
idx as i64,
m.role,
m.content,
tool_name,
args,
if m.role == "tool" { Some(m.content.clone()) } else { None },
],
)
.map_err(|e| e.to_string())?;
}
tx.commit().map_err(|e| e.to_string())?;
Ok(run_id)
}
pub fn run_count(&self, batch_id: i64) -> Result<i64, String> {
self.conn
.query_row("SELECT COUNT(*) FROM run WHERE batch_id = ?1", params![batch_id], |r| r.get(0))
.map_err(|e| e.to_string())
}
pub fn step_count(&self, run_id: i64) -> Result<i64, String> {
self.conn
.query_row("SELECT COUNT(*) FROM step WHERE run_id = ?1", params![run_id], |r| r.get(0))
.map_err(|e| e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agent::{FunctionCall, ToolCall};
use serde_json::json;
fn rec(batch: i64, model: &str, task: &str, rep: u32) -> RunRecord {
RunRecord {
batch_id: batch,
model: model.into(),
task_id: task.into(),
repeat_idx: rep,
error_class: ErrorClass::Ok,
score: 1.0,
steps: 2,
prompt_tokens: 10,
completion_tokens: 5,
duration_ms: 1234,
tps: Some(4.0),
ttft_tool_ms: Some(300),
artifact_path: None,
summary: Some("fertig".into()),
check_output: "ok".into(),
}
}
#[test]
fn batch_und_lauf_werden_gespeichert() {
let mut s = Store::open_in_memory().unwrap();
let b = s.create_batch("test", 3, "{}").unwrap();
assert!(s.batch_exists(b).unwrap());
let transcript = vec![
Message::new("user", "Aufgabe"),
Message {
role: "assistant".into(),
content: String::new(),
tool_calls: vec![ToolCall {
function: FunctionCall { name: "done".into(), arguments: json!({"summary": "x"}) },
}],
tool_name: None,
},
];
let run_id = s.insert_run(&rec(b, "m1", "a-01", 1), &transcript).unwrap();
assert_eq!(s.run_count(b).unwrap(), 1);
assert_eq!(s.step_count(run_id).unwrap(), 2);
}
#[test]
fn fertige_schluessel_werden_gelesen() {
let mut s = Store::open_in_memory().unwrap();
let b = s.create_batch("", 2, "{}").unwrap();
s.insert_run(&rec(b, "m1", "a-01", 1), &[]).unwrap();
let keys = s.finished_keys(b).unwrap();
assert!(keys.contains(&("m1".to_string(), "a-01".to_string(), 1)));
assert!(!keys.contains(&("m1".to_string(), "a-01".to_string(), 2)));
}
#[test]
fn unbekannter_batch_existiert_nicht() {
let s = Store::open_in_memory().unwrap();
assert!(!s.batch_exists(99).unwrap());
}
}

302
src-tauri/src/tasks.rs Normal file
View File

@ -0,0 +1,302 @@
//! Aufgaben laden und validieren (F-02, SPEC Abschnitt 4).
//!
//! Eine Aufgabe ist ein Ordner `tasks/<gruppe>/<name>/` mit `task.toml`,
//! `prompt.md`, `check.sh` und `start/`. Fehlerhafte Aufgaben werden nicht
//! geladen, sondern mit Pfad und Grund gemeldet.
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
pub const TASK_FILE: &str = "task.toml";
pub const PROMPT_FILE: &str = "prompt.md";
pub const CHECK_FILE: &str = "check.sh";
pub const START_DIR: &str = "start";
const GROUPS: [&str; 4] = ["A", "B", "C", "D"];
/// Metadaten aus `task.toml`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskToml {
pub id: String,
pub title: String,
pub group: String,
#[serde(default = "default_weight")]
pub weight: f64,
pub image: String,
pub max_steps: u32,
pub timeout_s: u64,
#[serde(default = "default_check_timeout")]
pub check_timeout_s: u64,
}
fn default_weight() -> f64 {
1.0
}
fn default_check_timeout() -> u64 {
120
}
/// Eine geladene, gültige Aufgabe.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Task {
#[serde(flatten)]
pub meta: TaskToml,
pub dir: PathBuf,
}
/// Ein Fehler bei einer Aufgabe, mit Ordner und Grund.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TaskError {
pub dir: PathBuf,
pub message: String,
}
/// Ergebnis eines Ladelaufs.
#[derive(Debug, Default, Clone, PartialEq, Serialize)]
pub struct LoadReport {
pub tasks: Vec<Task>,
pub errors: Vec<TaskError>,
}
/// Validiert die Metadaten. Gibt eine Liste aller Verstöße zurück.
pub fn validate_meta(meta: &TaskToml) -> Vec<String> {
let mut errs = Vec::new();
if meta.id.trim().is_empty() {
errs.push("id ist leer".into());
}
if meta.title.trim().is_empty() {
errs.push("title ist leer".into());
}
if !GROUPS.contains(&meta.group.as_str()) {
errs.push(format!("group muss A, B, C oder D sein, ist {:?}", meta.group));
}
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 meta.max_steps == 0 {
errs.push("max_steps muss größer als 0 sein".into());
}
if meta.timeout_s == 0 {
errs.push("timeout_s muss größer als 0 sein".into());
}
if meta.check_timeout_s == 0 {
errs.push("check_timeout_s muss größer als 0 sein".into());
}
errs
}
/// Prüft die Pflichtdateien und Rechte eines Aufgabenordners.
pub fn validate_files(dir: &Path) -> Vec<String> {
let mut errs = Vec::new();
for name in [TASK_FILE, PROMPT_FILE, CHECK_FILE] {
if !dir.join(name).is_file() {
errs.push(format!("Pflichtdatei fehlt: {name}"));
}
}
if !dir.join(START_DIR).is_dir() {
errs.push(format!("Ordner fehlt: {START_DIR}/ (darf leer sein)"));
}
if dir.join(CHECK_FILE).is_file() && !is_executable(&dir.join(CHECK_FILE)) {
errs.push(format!("{CHECK_FILE} ist nicht ausführbar"));
}
errs
}
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
fs::metadata(path)
.map(|m| m.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
#[cfg(not(unix))]
fn is_executable(_path: &Path) -> bool {
true
}
/// Lädt eine einzelne Aufgabe aus ihrem Ordner.
pub fn load_one(dir: &Path) -> Result<Task, Vec<String>> {
let mut errs = validate_files(dir);
let meta = match fs::read_to_string(dir.join(TASK_FILE)) {
Ok(text) => match toml::from_str::<TaskToml>(&text) {
Ok(meta) => {
errs.extend(validate_meta(&meta));
Some(meta)
}
Err(e) => {
errs.push(format!("{TASK_FILE} ist kein gültiges TOML: {e}"));
None
}
},
Err(_) => None, // Fehlende Datei ist oben schon gemeldet.
};
match (meta, errs.is_empty()) {
(Some(meta), true) => Ok(Task {
meta,
dir: dir.to_path_buf(),
}),
_ => Err(errs),
}
}
/// Lädt alle Aufgaben unterhalb von `tasks_dir` (Ebene `<gruppe>/<name>`).
/// Ein fehlender Aufgabenordner ist kein Fehler: es gibt dann keine Aufgaben.
pub fn load_all(tasks_dir: &Path) -> LoadReport {
let mut report = LoadReport::default();
if !tasks_dir.is_dir() {
return report;
}
let groups = match sorted_subdirs(tasks_dir) {
Ok(v) => v,
Err(e) => {
report.errors.push(TaskError {
dir: tasks_dir.to_path_buf(),
message: format!("Aufgabenordner nicht lesbar: {e}"),
});
return report;
}
};
for group_dir in groups {
match sorted_subdirs(&group_dir) {
Ok(tasks) => {
for task_dir in tasks {
match load_one(&task_dir) {
Ok(task) => report.tasks.push(task),
Err(messages) => report.errors.push(TaskError {
dir: task_dir,
message: messages.join("; "),
}),
}
}
}
Err(e) => report.errors.push(TaskError {
dir: group_dir,
message: format!("Gruppenordner nicht lesbar: {e}"),
}),
}
}
report
}
fn sorted_subdirs(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
let mut out: Vec<PathBuf> = fs::read_dir(dir)?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.is_dir())
.collect();
out.sort();
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
const GUT: &str = r#"
id = "b-05-bugfix-parser"
title = "Bug im Parser finden und fixen"
group = "B"
image = "cb-python:latest"
max_steps = 25
timeout_s = 600
"#;
fn tmp(name: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!("cb-tasks-{}-{}", name, std::process::id()));
let _ = fs::remove_dir_all(&p);
fs::create_dir_all(&p).unwrap();
p
}
fn make_task(dir: &Path, toml: &str, check_exec: bool) {
fs::create_dir_all(dir.join(START_DIR)).unwrap();
fs::write(dir.join(TASK_FILE), toml).unwrap();
fs::write(dir.join(PROMPT_FILE), "Aufgabe").unwrap();
fs::write(dir.join(CHECK_FILE), "#!/bin/sh\nexit 0\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = if check_exec { 0o755 } else { 0o644 };
fs::set_permissions(dir.join(CHECK_FILE), fs::Permissions::from_mode(mode)).unwrap();
}
}
#[test]
fn gueltige_aufgabe_wird_geladen() {
let base = tmp("gut");
let dir = base.join("B").join("b-05");
make_task(&dir, GUT, true);
let task = load_one(&dir).unwrap();
assert_eq!(task.meta.id, "b-05-bugfix-parser");
assert_eq!(task.meta.weight, 1.0);
assert_eq!(task.meta.check_timeout_s, 120);
let _ = fs::remove_dir_all(&base);
}
#[test]
fn fehlende_pflichtdatei_wird_gemeldet() {
let base = tmp("fehlt");
let dir = base.join("A").join("a-01");
make_task(&dir, GUT, true);
fs::remove_file(dir.join(CHECK_FILE)).unwrap();
let errs = load_one(&dir).unwrap_err();
assert!(errs.iter().any(|e| e.contains("check.sh")));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn check_sh_ohne_ausfuehrungsrecht_wird_gemeldet() {
let base = tmp("exec");
let dir = base.join("A").join("a-01");
make_task(&dir, GUT, false);
let errs = load_one(&dir).unwrap_err();
assert!(errs.iter().any(|e| e.contains("nicht ausführbar")));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn ungueltige_gruppe_und_unbekannter_schluessel() {
let base = tmp("toml");
let dir = base.join("X").join("x-01");
let toml = GUT.replace("group = \"B\"", "group = \"Z\"") + "unbekannt = 1\n";
make_task(&dir, &toml, true);
let errs = load_one(&dir).unwrap_err();
assert!(errs.iter().any(|e| e.contains("unbekannt") || e.contains("kein gültiges TOML")));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn ungueltige_zahlen_werden_gemeldet() {
let meta: TaskToml = toml::from_str(&GUT.replace("max_steps = 25", "max_steps = 0")).unwrap();
assert!(validate_meta(&meta).iter().any(|e| e.contains("max_steps")));
}
#[test]
fn load_all_trennt_gute_und_schlechte_aufgaben() {
let base = tmp("all");
make_task(&base.join("B").join("b-05"), GUT, true);
fs::create_dir_all(base.join("A").join("a-01")).unwrap(); // leer, also kaputt
let report = load_all(&base);
assert_eq!(report.tasks.len(), 1);
assert_eq!(report.errors.len(), 1);
assert!(report.errors[0].dir.ends_with("a-01"));
let _ = fs::remove_dir_all(&base);
}
#[test]
fn fehlender_aufgabenordner_ist_leer_nicht_fehler() {
let report = load_all(Path::new("/gibt/es/nicht/cb-test"));
assert!(report.tasks.is_empty() && report.errors.is_empty());
}
}

35
src-tauri/tauri.conf.json Normal file
View File

@ -0,0 +1,35 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "coding-bench",
"version": "0.1.0",
"identifier": "org.wlkns.codingbench",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run build",
"frontendDist": "../build"
},
"app": {
"windows": [
{
"title": "coding-bench",
"width": 800,
"height": 600
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

13
src/app.html Normal file
View File

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

5
src/routes/+layout.ts Normal file
View File

@ -0,0 +1,5 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we use adapter-static with a fallback to index.html to put the site in SPA mode
// See: https://svelte.dev/docs/kit/single-page-apps
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
export const ssr = false;

121
src/routes/+page.svelte Normal file
View File

@ -0,0 +1,121 @@
<script lang="ts">
import { onMount } from "svelte";
import { invoke } from "@tauri-apps/api/core";
type Paths = {
config_file: string;
data_dir: string;
tasks_dir: string;
};
type TaskInfo = { id: string; title: string; group: string; dir: string };
type TaskError = { dir: string; message: string };
type LoadReport = { tasks: TaskInfo[]; errors: TaskError[] };
let paths = $state<Paths | null>(null);
let error = $state("");
let report = $state<LoadReport | null>(null);
let taskError = $state("");
onMount(async () => {
try {
paths = await invoke<Paths>("get_paths");
} catch (e) {
error = String(e);
}
try {
report = await invoke<LoadReport>("load_tasks");
} catch (e) {
taskError = String(e);
}
});
</script>
<main class="container">
<h1>coding-bench</h1>
<section>
<h2>Setup: Pfade</h2>
{#if error}
<p class="fehler">Fehler: {error}</p>
{:else if paths}
<dl>
<dt>Konfiguration</dt>
<dd><code>{paths.config_file}</code></dd>
<dt>Datenordner</dt>
<dd><code>{paths.data_dir}</code></dd>
<dt>Aufgabenordner</dt>
<dd><code>{paths.tasks_dir}</code></dd>
</dl>
{:else}
<p>Lade Pfade …</p>
{/if}
</section>
<section>
<h2>Aufgaben</h2>
{#if taskError}
<p class="fehler">Fehler: {taskError}</p>
{:else if report}
<p>{report.tasks.length} gültig, {report.errors.length} mit Fehlern.</p>
<ul>
{#each report.tasks as t (t.dir)}
<li><strong>{t.id}</strong> · {t.title} <span class="gruppe">Gruppe {t.group}</span></li>
{/each}
</ul>
{#if report.errors.length > 0}
<h3>Fehler</h3>
<ul class="fehler">
{#each report.errors as e (e.dir)}
<li><code>{e.dir}</code>: {e.message}</li>
{/each}
</ul>
{/if}
{:else}
<p>Lade Aufgaben …</p>
{/if}
</section>
</main>
<style>
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
color: #0f0f0f;
background-color: #f6f6f6;
-webkit-text-size-adjust: 100%;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
}
.container {
margin: 0 auto;
padding: 2rem 1rem;
max-width: 48rem;
}
dl {
display: grid;
grid-template-columns: max-content 1fr;
gap: 0.4rem 1rem;
}
dt {
font-weight: 600;
}
dd {
margin: 0;
overflow-wrap: anywhere;
}
.fehler {
color: #c62828;
}
</style>

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

1
static/svelte.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

6
static/tauri.svg Normal file
View File

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

1
static/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

18
svelte.config.js Normal file
View File

@ -0,0 +1,18 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we use adapter-static with a fallback to index.html to put the site in SPA mode
// See: https://svelte.dev/docs/kit/single-page-apps
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
import adapter from "@sveltejs/adapter-static";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter({
fallback: "index.html",
}),
},
};
export default config;

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

32
vite.config.js Normal file
View File

@ -0,0 +1,32 @@
import { defineConfig } from "vite";
import { sveltekit } from "@sveltejs/kit/vite";
// @ts-expect-error type error without @types/node package
import process from "node:process";
const host = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/
export default defineConfig(() => ({
plugins: [sveltekit()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent Vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || "127.0.0.1",
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell Vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));