mod agent; mod config; mod discover; mod external; mod images; mod ranking; mod runner; mod sandbox; mod secrets; mod store; mod tasks; use config::{Config, ModelEntry, Paths}; use runner::{BatchSummary, Event, ModelConn, RunConfig}; use serde::Serialize; use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use store::{BatchInfo, RunRecord, Store}; use tauri::{Emitter, Manager, State}; pub const DB_FILE: &str = "coding-bench.sqlite"; pub const EVENT_NAME: &str = "batch-event"; pub const IMAGE_EVENT: &str = "image-build"; /// Aufgelöste Pfade, einmal beim Start ermittelt. pub struct AppPaths(pub Paths); /// Die laufende Konfiguration. Die Oberfläche ändert die Modell-Liste, die Datei wird mitgeschrieben. pub struct ConfigState { pub config: Mutex, pub file: PathBuf, /// In der App eingegebene Schlüssel, getrennt von der Konfiguration. pub secrets: Mutex, } /// Steuerung für den laufenden Batch. Es läuft immer nur einer. pub struct RunState { /// Gesetzt, wenn der laufende Batch abbrechen soll. pub cancel: Arc, /// Gesetzt, solange ein Batch läuft. pub running: Arc, /// Gesetzt, solange ein Image gebaut wird. pub building: Arc, } /// Setzt ein Flag beim Verlassen des Gültigkeitsbereichs zurück, auch nach einem Fehler oder Panic. /// Ohne diesen Wächter bliebe `running` nach einem abgestürzten Batch-Thread dauerhaft gesetzt. struct FlagGuard(Arc); impl Drop for FlagGuard { fn drop(&mut self) { self.0.store(false, Ordering::SeqCst); } } /// Ein Modell für die Oberfläche. Der Schlüssel selbst geht nie nach draußen, nur ob es einen gibt. #[derive(Serialize)] pub struct ModelInfo { #[serde(flatten)] pub entry: ModelEntry, /// Ein Schlüssel ist verfügbar (Umgebungsvariable gesetzt oder in der App gespeichert). pub api_key_set: bool, /// In der App gespeichert. pub api_key_stored: bool, } fn env_key(entry: &ModelEntry) -> Option { if entry.api_key_env.is_empty() { None } else { std::env::var(&entry.api_key_env).ok().filter(|k| !k.is_empty()) } } fn model_info(entry: &ModelEntry, secrets: &secrets::Secrets) -> ModelInfo { let api_key_stored = secrets.has(&entry.name); ModelInfo { entry: entry.clone(), api_key_set: api_key_stored || env_key(entry).is_some(), api_key_stored } } /// Löst einen Eintrag in eine Verbindung auf: Modell-ID und Schlüssel aus der Umgebung. fn conn_of(entry: &ModelEntry, secrets: &secrets::Secrets) -> ModelConn { // Die Umgebungsvariable gilt zuerst (bewusste Vorgabe), sonst der in der App gespeicherte Schlüssel. let api_key = env_key(entry).or_else(|| secrets.get(&entry.name).map(String::from)); ModelConn { name: entry.name.clone(), adapter: entry.adapter.clone(), url: entry.url.clone(), model_id: if entry.model.trim().is_empty() { entry.name.clone() } else { entry.model.clone() }, api_key, } } #[tauri::command] fn get_paths(paths: State<'_, AppPaths>) -> Paths { paths.0.clone() } #[tauri::command] fn load_tasks(paths: State<'_, AppPaths>) -> tasks::LoadReport { tasks::load_all(&paths.0.tasks_dir) } /// Angebundene Modelle. #[tauri::command] fn list_models(cfg: State<'_, ConfigState>) -> Result, String> { let c = cfg.config.lock().map_err(|e| e.to_string())?; let sec = cfg.secrets.lock().map_err(|e| e.to_string())?; Ok(c.models.iter().map(|m| model_info(m, &sec)).collect()) } /// Ein Modell von der Oberfläche. Der Schlüssel (`api_key`) wird nur hier entgegengenommen und /// nie in `config.toml` geschrieben. #[derive(serde::Deserialize)] pub struct ModelInput { pub name: String, pub adapter: String, pub url: String, pub model: String, pub api_key_env: String, /// Bisheriger Name, damit ein gespeicherter Schlüssel bei einer Umbenennung mitwandert. pub previous_name: Option, /// Neuer Schlüssel. Leer oder fehlend: gespeicherten Schlüssel nicht ändern. pub api_key: Option, /// Gespeicherten Schlüssel entfernen. pub clear_key: bool, } /// Wendet die Schlüsseländerungen der Oberfläche auf eine Kopie an: umbenennen, entfernen, setzen, /// und Schlüssel gelöschter Modelle verwerfen. fn apply_secret_changes(current: &secrets::Secrets, inputs: &[ModelInput], cleaned: &[ModelEntry]) -> secrets::Secrets { let mut next = current.clone(); for (input, entry) in inputs.iter().zip(cleaned) { if let Some(prev) = input.previous_name.as_deref() { next.rename(prev.trim(), &entry.name); } if input.clear_key { next.remove(&entry.name); } if let Some(key) = input.api_key.as_deref().map(str::trim).filter(|k| !k.is_empty()) { next.set(&entry.name, key); } } let names: Vec = cleaned.iter().map(|m| m.name.clone()).collect(); next.retain_names(&names); next } /// Ersetzt die Modell-Liste, prüft sie und schreibt `config.toml`. Schlüssel landen in `secrets.toml`. #[tauri::command] fn save_models(cfg: State<'_, ConfigState>, models: Vec) -> Result, String> { let cleaned: Vec = models .iter() .map(|m| ModelEntry { name: m.name.trim().to_string(), adapter: m.adapter.clone(), url: m.url.trim().to_string(), model: m.model.trim().to_string(), api_key_env: m.api_key_env.trim().to_string(), }) .collect(); config::validate_models(&cleaned)?; let mut c = cfg.config.lock().map_err(|e| e.to_string())?; let mut sec = cfg.secrets.lock().map_err(|e| e.to_string())?; // Schlüssel zuerst auf einer Kopie ändern und schreiben, dann die Konfiguration. So bleibt bei // einem Fehler der alte Stand im Speicher. let next_sec = apply_secret_changes(&sec, &models, &cleaned); next_sec.save()?; let mut next = c.clone(); next.models = cleaned; config::save(&cfg.file, &next)?; *c = next; *sec = next_sec; Ok(c.models.iter().map(|m| model_info(m, &sec)).collect()) } #[derive(Serialize)] pub struct ModelTest { pub ok: bool, pub duration_ms: u128, pub message: String, } /// Prüft die Verbindung zu einem Modell mit einer kurzen Anfrage. #[tauri::command] async fn test_model(cfg: State<'_, ConfigState>, name: String) -> Result { let entry = { let c = cfg.config.lock().map_err(|e| e.to_string())?; c.models .iter() .find(|m| m.name == name) .cloned() .ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))? }; let conn = { let sec = cfg.secrets.lock().map_err(|e| e.to_string())?; conn_of(&entry, &sec) }; tauri::async_runtime::spawn_blocking(move || { let started = Instant::now(); let result = runner::client_for(&conn).and_then(|client| { client .chat( &[agent::Message::new("user", "Antworte nur mit: ok")], &serde_json::json!([]), Duration::from_secs(90), ) .map_err(|e| match e { agent::ModelError::Timeout => "Zeitlimit überschritten (90 s)".to_string(), agent::ModelError::Endpoint(m) => m, }) }); let duration_ms = started.elapsed().as_millis(); match result { Ok(r) => ModelTest { ok: true, duration_ms, message: format!( "Antwort erhalten ({} Prompt-, {} Completion-Tokens).", r.prompt_tokens, r.completion_tokens ), }, Err(message) => ModelTest { ok: false, duration_ms, message }, } }) .await .map_err(|e| format!("Test abgebrochen: {e}")) } /// Fragt einen Server nach seinen Modellen. Schlüssel in dieser Reihenfolge: gerade eingegeben /// (`api_key`, noch nicht gespeichert), Umgebungsvariable `api_key_env`, gespeichert unter `name`. #[tauri::command] async fn discover_models( cfg: State<'_, ConfigState>, adapter: String, url: String, api_key_env: String, name: Option, api_key: Option, ) -> Result, String> { let stored = match name.as_deref() { Some(n) => cfg.secrets.lock().map_err(|e| e.to_string())?.get(n).map(String::from), None => None, }; tauri::async_runtime::spawn_blocking(move || { let typed = api_key.map(|k| k.trim().to_string()).filter(|k| !k.is_empty()); let env = if api_key_env.trim().is_empty() { None } else { std::env::var(api_key_env.trim()).ok().filter(|k| !k.is_empty()) }; let key = typed.or(env).or(stored); discover::list(&adapter, &url, key.as_deref()) }) .await .map_err(|e| format!("Abfrage abgebrochen: {e}"))? } /// Startet einen Batch mit den angegebenen Modellen (Anzeigenamen) und Aufgaben-IDs. /// Mit `batch_id` wird ein bestehender Batch fortgesetzt: fertige Läufe werden übersprungen. /// Fortschritt kommt als Ereignis `batch-event`. Das Ergebnis ist die Zusammenfassung. #[tauri::command] async fn start_batch( app: tauri::AppHandle, paths: State<'_, AppPaths>, cfg: State<'_, ConfigState>, run: State<'_, RunState>, models: Vec, task_ids: Vec, repeats: u32, note: String, batch_id: Option, ) -> Result { if models.is_empty() || task_ids.is_empty() { return Err("Mindestens ein Modell und eine Aufgabe wählen.".into()); } if repeats == 0 { return Err("Wiederholungen müssen mindestens 1 sein.".into()); } let (conns, runtime, limits) = { let c = cfg.config.lock().map_err(|e| e.to_string())?; let sec = cfg.secrets.lock().map_err(|e| e.to_string())?; let mut conns = Vec::new(); for name in &models { let entry = c .models .iter() .find(|m| &m.name == name) .ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?; conns.push(conn_of(entry, &sec)); } (conns, c.container_runtime.clone(), c.sandbox_limits()) }; let report = tasks::load_all(&paths.0.tasks_dir); let selected: Vec = report .tasks .into_iter() .filter(|t| task_ids.contains(&t.meta.id)) .collect(); if selected.len() != task_ids.len() { return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into()); } // Fehlt ein Image, scheitert sonst jeder Lauf einzeln. Besser sofort und mit klarer Anleitung. let mut missing: Vec = Vec::new(); for image in selected.iter().map(|t| t.meta.image.clone()).collect::>() { if !images::exists(&runtime, &image)? { missing.push(image); } } if !missing.is_empty() { return Err(format!( "Container-Image fehlt: {}. Baue es in den Einstellungen unter „Container-Images“.", missing.join(", ") )); } if run.running.swap(true, Ordering::SeqCst) { return Err("Ein Batch läuft bereits.".into()); } let _running_guard = FlagGuard(run.running.clone()); run.cancel.store(false, Ordering::SeqCst); let jobs = runner::plan(&models, &selected, repeats); let run_cfg = RunConfig { runtime, models: conns, data_dir: paths.0.data_dir.clone(), limits, }; let db_path = paths.0.data_dir.join(DB_FILE); let cancel = run.cancel.clone(); let emitter = app.clone(); let result = tauri::async_runtime::spawn_blocking(move || { let mut store = Store::open(&db_path)?; let on_event = |e: &Event| { let _ = emitter.emit(EVENT_NAME, e); }; runner::run_batch(&mut store, &run_cfg, batch_id, ¬e, repeats, &jobs, &cancel, &on_event) }) .await .map_err(|e| format!("Batch-Thread abgebrochen: {e}"))?; result } /// Legt einen Exportordner für Referenz-Läufe an (von Hand zu lösen, z. B. mit Claude Code). #[tauri::command] fn export_external(paths: State<'_, AppPaths>, task_ids: Vec, repeats: u32) -> Result { let selected: Vec = tasks::load_all(&paths.0.tasks_dir).tasks.into_iter().filter(|t| task_ids.contains(&t.meta.id)).collect(); if selected.len() != task_ids.len() { return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into()); } let stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); let out = paths.0.data_dir.join("exports").join(format!("referenz-{stamp}")); external::export(&selected, repeats, &out) } /// Prüft Ergebnisordner von Hand gelöster Aufgaben und speichert sie als externe Läufe. #[tauri::command] async fn import_external( paths: State<'_, AppPaths>, cfg: State<'_, ConfigState>, run: State<'_, RunState>, dir: String, model: String, batch_id: i64, ) -> Result { let model = model.trim().to_string(); if model.is_empty() || model.chars().count() > 80 { return Err("Der Modellname muss 1 bis 80 Zeichen lang sein.".into()); } let (runtime, limits) = { let c = cfg.config.lock().map_err(|e| e.to_string())?; if c.models.iter().any(|m| m.name == model) { return Err(format!( "{model:?} ist ein angebundenes Modell. Wähle für die Referenz einen eigenen Namen, z. B. „{model} (extern)“." )); } (c.container_runtime.clone(), c.sandbox_limits()) }; let loaded = tasks::load_all(&paths.0.tasks_dir).tasks; if run.running.swap(true, Ordering::SeqCst) { return Err("Ein Batch oder Import läuft bereits.".into()); } let _running_guard = FlagGuard(run.running.clone()); let run_cfg = RunConfig { runtime, models: Vec::new(), data_dir: paths.0.data_dir.clone(), limits }; let db_path = paths.0.data_dir.join(DB_FILE); tauri::async_runtime::spawn_blocking(move || { let mut store = Store::open(&db_path)?; external::import(&mut store, &run_cfg, &loaded, std::path::Path::new(&dir), &model, batch_id) }) .await .map_err(|e| format!("Import abgebrochen: {e}"))? } /// Zustand eines Container-Images für die Einstellungen. #[derive(Serialize)] pub struct ImageStatus { pub image: String, pub available: bool, /// Die App kann es selbst bauen. pub buildable: bool, /// Fehlertext, falls die Prüfung selbst scheiterte (z. B. Podman fehlt). pub error: Option, } /// Images, die die Aufgaben brauchen, und ihr Zustand. #[tauri::command] fn image_status(paths: State<'_, AppPaths>, cfg: State<'_, ConfigState>) -> Result, String> { let runtime = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone(); let mut names: std::collections::BTreeSet = tasks::load_all(&paths.0.tasks_dir) .tasks .into_iter() .map(|t| t.meta.image) .collect(); // Das eingebaute Standard-Image zeigen wir auch ohne Aufgaben. names.insert("cb-python:latest".to_string()); Ok(names .into_iter() .map(|image| { let buildable = images::embedded_containerfile(&image).is_some(); match images::exists(&runtime, &image) { Ok(available) => ImageStatus { image, available, buildable, error: None }, Err(e) => ImageStatus { image, available: false, buildable, error: Some(e) }, } }) .collect()) } /// Baut ein eingebettetes Image. Die Ausgabe kommt zeilenweise als Ereignis `image-build`. #[tauri::command] async fn build_image( app: tauri::AppHandle, cfg: State<'_, ConfigState>, run: State<'_, RunState>, image: String, ) -> Result<(), String> { tasks::validate_image(&image)?; if images::embedded_containerfile(&image).is_none() { return Err(format!("Für {image} gibt es kein eingebautes Containerfile.")); } let runtime = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone(); if run.building.swap(true, Ordering::SeqCst) { return Err("Es wird bereits ein Image gebaut.".into()); } let _guard = FlagGuard(run.building.clone()); let emitter = app.clone(); tauri::async_runtime::spawn_blocking(move || { let name = image.clone(); images::build(&runtime, &image, &mut |line| { let _ = emitter.emit(IMAGE_EVENT, serde_json::json!({ "image": name, "line": line })); }) }) .await .map_err(|e| format!("Build-Thread abgebrochen: {e}"))? } /// Bricht den laufenden Batch ab. Der aktuelle Lauf wird verworfen. /// Gibt `false` zurück, wenn gerade kein Batch läuft. #[tauri::command] fn cancel_batch(run: State<'_, RunState>) -> bool { let running = run.running.load(Ordering::SeqCst); if running { run.cancel.store(true, Ordering::SeqCst); } running } /// Alle bisherigen Batches, neueste zuerst. #[tauri::command] fn list_batches(paths: State<'_, AppPaths>) -> Result, String> { Store::open(&paths.0.data_dir.join(DB_FILE))?.list_batches() } /// Alle gespeicherten Läufe eines Batches. #[tauri::command] fn batch_results(paths: State<'_, AppPaths>, batch_id: i64) -> Result, String> { let store = Store::open(&paths.0.data_dir.join(DB_FILE))?; store.runs_for_batch(batch_id) } /// Schritte eines einzelnen Laufs für die Detailansicht. #[tauri::command] fn run_steps( paths: State<'_, AppPaths>, batch_id: i64, model: String, task_id: String, repeat_idx: u32, ) -> Result, String> { let store = Store::open(&paths.0.data_dir.join(DB_FILE))?; store.steps_for_run(batch_id, &model, &task_id, repeat_idx) } /// Zustand der Container-Laufzeit (Podman) für das Setup. #[derive(Serialize)] pub struct RuntimeStatus { pub program: String, pub available: bool, pub detail: String, } #[tauri::command] fn runtime_status(cfg: State<'_, ConfigState>) -> Result { let program = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone(); Ok( match std::process::Command::new(&program) .args(["version", "--format", "{{.Client.Version}}"]) .output() { Ok(out) if out.status.success() => RuntimeStatus { program, available: true, detail: format!("Version {}", String::from_utf8_lossy(&out.stdout).trim()), }, Ok(out) => RuntimeStatus { program, available: false, detail: String::from_utf8_lossy(&out.stderr).trim().to_string(), }, Err(e) => RuntimeStatus { program, available: false, detail: format!("nicht startbar: {e}"), }, }, ) } /// Bewertung je Modell und Bereich für einen Batch. Gruppe und Gewicht kommen aus den Aufgaben. #[tauri::command] fn batch_ranking(paths: State<'_, AppPaths>, batch_id: i64) -> Result { let store = Store::open(&paths.0.data_dir.join(DB_FILE))?; let runs = store.runs_for_batch(batch_id)?; let infos: BTreeMap = tasks::load_all(&paths.0.tasks_dir) .tasks .into_iter() .map(|t| { ( t.meta.id.clone(), ranking::TaskInfo { group: t.meta.group.clone(), weight: t.meta.weight }, ) }) .collect(); Ok(ranking::compute(batch_id, &runs, &infos)) } #[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)?; // Datenbank einmal anlegen, damit Fehler früh sichtbar werden. Store::open(&paths.data_dir.join(DB_FILE))?; let file = paths.config_file.clone(); app.manage(AppPaths(paths)); let secrets = secrets::Secrets::load(&file.with_file_name(secrets::SECRETS_FILE_NAME))?; app.manage(ConfigState { config: Mutex::new(cfg), file, secrets: Mutex::new(secrets) }); app.manage(RunState { cancel: Arc::new(AtomicBool::new(false)), running: Arc::new(AtomicBool::new(false)), building: Arc::new(AtomicBool::new(false)), }); Ok(()) }) .invoke_handler(tauri::generate_handler![ get_paths, load_tasks, list_models, save_models, test_model, discover_models, export_external, import_external, start_batch, cancel_batch, list_batches, batch_results, batch_ranking, run_steps, runtime_status, image_status, build_image ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } #[cfg(test)] mod tests { use super::*; fn input(name: &str, prev: Option<&str>, key: Option<&str>, clear: bool) -> ModelInput { ModelInput { name: name.into(), adapter: "ollama".into(), url: "http://h".into(), model: String::new(), api_key_env: String::new(), previous_name: prev.map(String::from), api_key: key.map(String::from), clear_key: clear, } } fn entries(inputs: &[ModelInput]) -> Vec { inputs .iter() .map(|m| ModelEntry { name: m.name.clone(), adapter: m.adapter.clone(), url: m.url.clone(), model: m.model.clone(), api_key_env: m.api_key_env.clone() }) .collect() } fn start() -> secrets::Secrets { let mut s = secrets::Secrets::default(); s.set("A", "key-a"); s.set("B", "key-b"); s } #[test] fn schluessel_wandert_bei_umbenennung_und_bleibt_sonst() { let ins = vec![input("A neu", Some("A"), None, false), input("B", Some("B"), None, false)]; let r = apply_secret_changes(&start(), &ins, &entries(&ins)); assert_eq!(r.get("A neu"), Some("key-a")); assert_eq!(r.get("B"), Some("key-b")); assert!(!r.has("A")); } #[test] fn neuer_schluessel_ersetzt_leerer_aendert_nichts_entfernen_loescht() { let ins = vec![input("A", Some("A"), Some(" neu "), false), input("B", Some("B"), Some(" "), false)]; let r = apply_secret_changes(&start(), &ins, &entries(&ins)); assert_eq!(r.get("A"), Some("neu")); assert_eq!(r.get("B"), Some("key-b")); let ins = vec![input("A", Some("A"), None, true), input("B", Some("B"), None, false)]; let r = apply_secret_changes(&start(), &ins, &entries(&ins)); assert!(!r.has("A")); assert!(r.has("B")); } #[test] fn schluessel_geloeschter_modelle_werden_verworfen() { let ins = vec![input("B", Some("B"), None, false)]; let r = apply_secret_changes(&start(), &ins, &entries(&ins)); assert!(!r.has("A")); assert!(r.has("B")); } #[test] fn umgebungsvariable_hat_vorrang_vor_dem_gespeicherten_schluessel() { let mut sec = secrets::Secrets::default(); sec.set("M", "gespeichert"); let mut e = ModelEntry { name: "M".into(), adapter: "ollama".into(), url: "http://h".into(), model: String::new(), api_key_env: String::new() }; assert_eq!(conn_of(&e, &sec).api_key.as_deref(), Some("gespeichert")); // `PATH` ist in jeder Umgebung gesetzt und dient hier als vorhandene Variable. e.api_key_env = "PATH".into(); assert_eq!(conn_of(&e, &sec).api_key, std::env::var("PATH").ok()); e.api_key_env = "CB_GIBT_ES_NICHT_12345".into(); assert_eq!(conn_of(&e, &sec).api_key.as_deref(), Some("gespeichert")); } }