532 lines
18 KiB
Rust
532 lines
18 KiB
Rust
mod agent;
|
|
mod config;
|
|
mod discover;
|
|
mod external;
|
|
mod images;
|
|
mod ranking;
|
|
mod runner;
|
|
mod sandbox;
|
|
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<Config>,
|
|
pub file: PathBuf,
|
|
}
|
|
|
|
/// Steuerung für den laufenden Batch. Es läuft immer nur einer.
|
|
pub struct RunState {
|
|
/// Gesetzt, wenn der laufende Batch abbrechen soll.
|
|
pub cancel: Arc<AtomicBool>,
|
|
/// Gesetzt, solange ein Batch läuft.
|
|
pub running: Arc<AtomicBool>,
|
|
/// Gesetzt, solange ein Image gebaut wird.
|
|
pub building: Arc<AtomicBool>,
|
|
}
|
|
|
|
/// Setzt ein Flag beim Verlassen des Gültigkeitsbereichs zurück, auch nach einem Fehler oder Panic.
|
|
/// Ohne diesen Wächter bliebe `running` nach einem abgestürzten Batch-Thread dauerhaft gesetzt.
|
|
struct FlagGuard(Arc<AtomicBool>);
|
|
|
|
impl Drop for FlagGuard {
|
|
fn drop(&mut self) {
|
|
self.0.store(false, Ordering::SeqCst);
|
|
}
|
|
}
|
|
|
|
/// Ein Modell für die Oberfläche, mit Hinweis, ob die Schlüssel-Variable gesetzt ist.
|
|
#[derive(Serialize)]
|
|
pub struct ModelInfo {
|
|
#[serde(flatten)]
|
|
pub entry: ModelEntry,
|
|
pub api_key_set: bool,
|
|
}
|
|
|
|
fn model_info(entry: &ModelEntry) -> ModelInfo {
|
|
let api_key_set = !entry.api_key_env.is_empty()
|
|
&& std::env::var(&entry.api_key_env).map_or(false, |v| !v.is_empty());
|
|
ModelInfo { entry: entry.clone(), api_key_set }
|
|
}
|
|
|
|
/// Löst einen Eintrag in eine Verbindung auf: Modell-ID und Schlüssel aus der Umgebung.
|
|
fn conn_of(entry: &ModelEntry) -> ModelConn {
|
|
let api_key = if entry.api_key_env.is_empty() {
|
|
None
|
|
} else {
|
|
std::env::var(&entry.api_key_env).ok().filter(|k| !k.is_empty())
|
|
};
|
|
ModelConn {
|
|
name: entry.name.clone(),
|
|
adapter: entry.adapter.clone(),
|
|
url: entry.url.clone(),
|
|
model_id: if entry.model.trim().is_empty() { entry.name.clone() } else { entry.model.clone() },
|
|
api_key,
|
|
}
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn get_paths(paths: State<'_, AppPaths>) -> Paths {
|
|
paths.0.clone()
|
|
}
|
|
|
|
#[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<Vec<ModelInfo>, String> {
|
|
let c = cfg.config.lock().map_err(|e| e.to_string())?;
|
|
Ok(c.models.iter().map(model_info).collect())
|
|
}
|
|
|
|
/// Ersetzt die Modell-Liste, prüft sie und schreibt `config.toml`.
|
|
#[tauri::command]
|
|
fn save_models(cfg: State<'_, ConfigState>, models: Vec<ModelEntry>) -> Result<Vec<ModelInfo>, String> {
|
|
let cleaned: Vec<ModelEntry> = models
|
|
.into_iter()
|
|
.map(|mut m| {
|
|
m.name = m.name.trim().to_string();
|
|
m.url = m.url.trim().to_string();
|
|
m.model = m.model.trim().to_string();
|
|
m.api_key_env = m.api_key_env.trim().to_string();
|
|
m
|
|
})
|
|
.collect();
|
|
config::validate_models(&cleaned)?;
|
|
let mut c = cfg.config.lock().map_err(|e| e.to_string())?;
|
|
let mut next = c.clone();
|
|
next.models = cleaned;
|
|
config::save(&cfg.file, &next)?;
|
|
*c = next;
|
|
Ok(c.models.iter().map(model_info).collect())
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
pub struct ModelTest {
|
|
pub ok: bool,
|
|
pub duration_ms: u128,
|
|
pub message: String,
|
|
}
|
|
|
|
/// Prüft die Verbindung zu einem Modell mit einer kurzen Anfrage.
|
|
#[tauri::command]
|
|
async fn test_model(cfg: State<'_, ConfigState>, name: String) -> Result<ModelTest, String> {
|
|
let entry = {
|
|
let c = cfg.config.lock().map_err(|e| e.to_string())?;
|
|
c.models
|
|
.iter()
|
|
.find(|m| m.name == name)
|
|
.cloned()
|
|
.ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?
|
|
};
|
|
let conn = conn_of(&entry);
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
let started = Instant::now();
|
|
let result = runner::client_for(&conn).and_then(|client| {
|
|
client
|
|
.chat(
|
|
&[agent::Message::new("user", "Antworte nur mit: ok")],
|
|
&serde_json::json!([]),
|
|
Duration::from_secs(90),
|
|
)
|
|
.map_err(|e| match e {
|
|
agent::ModelError::Timeout => "Zeitlimit überschritten (90 s)".to_string(),
|
|
agent::ModelError::Endpoint(m) => m,
|
|
})
|
|
});
|
|
let duration_ms = started.elapsed().as_millis();
|
|
match result {
|
|
Ok(r) => ModelTest {
|
|
ok: true,
|
|
duration_ms,
|
|
message: format!(
|
|
"Antwort erhalten ({} Prompt-, {} Completion-Tokens).",
|
|
r.prompt_tokens, r.completion_tokens
|
|
),
|
|
},
|
|
Err(message) => ModelTest { ok: false, duration_ms, message },
|
|
}
|
|
})
|
|
.await
|
|
.map_err(|e| format!("Test abgebrochen: {e}"))
|
|
}
|
|
|
|
/// Fragt einen Server nach seinen Modellen. Der Schlüssel kommt aus der Umgebungsvariable `api_key_env`.
|
|
#[tauri::command]
|
|
async fn discover_models(adapter: String, url: String, api_key_env: String) -> Result<Vec<String>, String> {
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
let key = if api_key_env.trim().is_empty() { None } else { std::env::var(api_key_env.trim()).ok() };
|
|
discover::list(&adapter, &url, key.as_deref())
|
|
})
|
|
.await
|
|
.map_err(|e| format!("Abfrage abgebrochen: {e}"))?
|
|
}
|
|
|
|
/// Startet einen Batch mit den angegebenen Modellen (Anzeigenamen) und Aufgaben-IDs.
|
|
/// Mit `batch_id` wird ein bestehender Batch fortgesetzt: fertige Läufe werden übersprungen.
|
|
/// Fortschritt kommt als Ereignis `batch-event`. Das Ergebnis ist die Zusammenfassung.
|
|
#[tauri::command]
|
|
async fn start_batch(
|
|
app: tauri::AppHandle,
|
|
paths: State<'_, AppPaths>,
|
|
cfg: State<'_, ConfigState>,
|
|
run: State<'_, RunState>,
|
|
models: Vec<String>,
|
|
task_ids: Vec<String>,
|
|
repeats: u32,
|
|
note: String,
|
|
batch_id: Option<i64>,
|
|
) -> Result<BatchSummary, String> {
|
|
if models.is_empty() || task_ids.is_empty() {
|
|
return Err("Mindestens ein Modell und eine Aufgabe wählen.".into());
|
|
}
|
|
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 mut conns = Vec::new();
|
|
for name in &models {
|
|
let entry = c
|
|
.models
|
|
.iter()
|
|
.find(|m| &m.name == name)
|
|
.ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?;
|
|
conns.push(conn_of(entry));
|
|
}
|
|
(conns, c.container_runtime.clone(), c.sandbox_limits())
|
|
};
|
|
|
|
let report = tasks::load_all(&paths.0.tasks_dir);
|
|
let selected: Vec<tasks::Task> = report
|
|
.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<String> = Vec::new();
|
|
for image in selected.iter().map(|t| t.meta.image.clone()).collect::<std::collections::BTreeSet<_>>() {
|
|
if !images::exists(&runtime, &image)? {
|
|
missing.push(image);
|
|
}
|
|
}
|
|
if !missing.is_empty() {
|
|
return Err(format!(
|
|
"Container-Image fehlt: {}. Baue es in den Einstellungen unter „Container-Images“.",
|
|
missing.join(", ")
|
|
));
|
|
}
|
|
|
|
if run.running.swap(true, Ordering::SeqCst) {
|
|
return Err("Ein Batch läuft bereits.".into());
|
|
}
|
|
let _running_guard = FlagGuard(run.running.clone());
|
|
run.cancel.store(false, Ordering::SeqCst);
|
|
|
|
let jobs = runner::plan(&models, &selected, repeats);
|
|
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<String>, repeats: u32) -> Result<external::ExportResult, String> {
|
|
let selected: Vec<tasks::Task> =
|
|
tasks::load_all(&paths.0.tasks_dir).tasks.into_iter().filter(|t| task_ids.contains(&t.meta.id)).collect();
|
|
if selected.len() != task_ids.len() {
|
|
return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into());
|
|
}
|
|
let stamp = std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.map(|d| d.as_secs())
|
|
.unwrap_or(0);
|
|
let out = paths.0.data_dir.join("exports").join(format!("referenz-{stamp}"));
|
|
external::export(&selected, repeats, &out)
|
|
}
|
|
|
|
/// Prüft Ergebnisordner von Hand gelöster Aufgaben und speichert sie als externe Läufe.
|
|
#[tauri::command]
|
|
async fn import_external(
|
|
paths: State<'_, AppPaths>,
|
|
cfg: State<'_, ConfigState>,
|
|
run: State<'_, RunState>,
|
|
dir: String,
|
|
model: String,
|
|
batch_id: i64,
|
|
) -> Result<external::ImportSummary, String> {
|
|
let model = model.trim().to_string();
|
|
if model.is_empty() || model.chars().count() > 80 {
|
|
return Err("Der Modellname muss 1 bis 80 Zeichen lang sein.".into());
|
|
}
|
|
let (runtime, limits) = {
|
|
let c = cfg.config.lock().map_err(|e| e.to_string())?;
|
|
if c.models.iter().any(|m| m.name == model) {
|
|
return Err(format!(
|
|
"{model:?} ist ein angebundenes Modell. Wähle für die Referenz einen eigenen Namen, z. B. „{model} (extern)“."
|
|
));
|
|
}
|
|
(c.container_runtime.clone(), c.sandbox_limits())
|
|
};
|
|
let loaded = tasks::load_all(&paths.0.tasks_dir).tasks;
|
|
|
|
if run.running.swap(true, Ordering::SeqCst) {
|
|
return Err("Ein Batch oder Import läuft bereits.".into());
|
|
}
|
|
let _running_guard = FlagGuard(run.running.clone());
|
|
|
|
let run_cfg = RunConfig { runtime, models: Vec::new(), data_dir: paths.0.data_dir.clone(), limits };
|
|
let db_path = paths.0.data_dir.join(DB_FILE);
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
let mut store = Store::open(&db_path)?;
|
|
external::import(&mut store, &run_cfg, &loaded, std::path::Path::new(&dir), &model, batch_id)
|
|
})
|
|
.await
|
|
.map_err(|e| format!("Import abgebrochen: {e}"))?
|
|
}
|
|
|
|
/// Zustand eines Container-Images für die Einstellungen.
|
|
#[derive(Serialize)]
|
|
pub struct ImageStatus {
|
|
pub image: String,
|
|
pub available: bool,
|
|
/// Die App kann es selbst bauen.
|
|
pub buildable: bool,
|
|
/// Fehlertext, falls die Prüfung selbst scheiterte (z. B. Podman fehlt).
|
|
pub error: Option<String>,
|
|
}
|
|
|
|
/// Images, die die Aufgaben brauchen, und ihr Zustand.
|
|
#[tauri::command]
|
|
fn image_status(paths: State<'_, AppPaths>, cfg: State<'_, ConfigState>) -> Result<Vec<ImageStatus>, String> {
|
|
let runtime = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
|
|
let mut names: std::collections::BTreeSet<String> = tasks::load_all(&paths.0.tasks_dir)
|
|
.tasks
|
|
.into_iter()
|
|
.map(|t| t.meta.image)
|
|
.collect();
|
|
// Das eingebaute Standard-Image zeigen wir auch ohne Aufgaben.
|
|
names.insert("cb-python:latest".to_string());
|
|
Ok(names
|
|
.into_iter()
|
|
.map(|image| {
|
|
let buildable = images::embedded_containerfile(&image).is_some();
|
|
match images::exists(&runtime, &image) {
|
|
Ok(available) => ImageStatus { image, available, buildable, error: None },
|
|
Err(e) => ImageStatus { image, available: false, buildable, error: Some(e) },
|
|
}
|
|
})
|
|
.collect())
|
|
}
|
|
|
|
/// Baut ein eingebettetes Image. Die Ausgabe kommt zeilenweise als Ereignis `image-build`.
|
|
#[tauri::command]
|
|
async fn build_image(
|
|
app: tauri::AppHandle,
|
|
cfg: State<'_, ConfigState>,
|
|
run: State<'_, RunState>,
|
|
image: String,
|
|
) -> Result<(), String> {
|
|
tasks::validate_image(&image)?;
|
|
if images::embedded_containerfile(&image).is_none() {
|
|
return Err(format!("Für {image} gibt es kein eingebautes Containerfile."));
|
|
}
|
|
let runtime = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
|
|
if run.building.swap(true, Ordering::SeqCst) {
|
|
return Err("Es wird bereits ein Image gebaut.".into());
|
|
}
|
|
let _guard = FlagGuard(run.building.clone());
|
|
let emitter = app.clone();
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
let name = image.clone();
|
|
images::build(&runtime, &image, &mut |line| {
|
|
let _ = emitter.emit(IMAGE_EVENT, serde_json::json!({ "image": name, "line": line }));
|
|
})
|
|
})
|
|
.await
|
|
.map_err(|e| format!("Build-Thread abgebrochen: {e}"))?
|
|
}
|
|
|
|
/// Bricht den laufenden Batch ab. Der aktuelle Lauf wird verworfen.
|
|
/// Gibt `false` zurück, wenn gerade kein Batch läuft.
|
|
#[tauri::command]
|
|
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<Vec<BatchInfo>, String> {
|
|
Store::open(&paths.0.data_dir.join(DB_FILE))?.list_batches()
|
|
}
|
|
|
|
/// Alle gespeicherten Läufe eines Batches.
|
|
#[tauri::command]
|
|
fn batch_results(paths: State<'_, AppPaths>, batch_id: i64) -> Result<Vec<RunRecord>, String> {
|
|
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<Vec<store::StepRow>, 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<RuntimeStatus, String> {
|
|
let program = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
|
|
Ok(
|
|
match std::process::Command::new(&program)
|
|
.args(["version", "--format", "{{.Client.Version}}"])
|
|
.output()
|
|
{
|
|
Ok(out) if out.status.success() => RuntimeStatus {
|
|
program,
|
|
available: true,
|
|
detail: format!("Version {}", String::from_utf8_lossy(&out.stdout).trim()),
|
|
},
|
|
Ok(out) => RuntimeStatus {
|
|
program,
|
|
available: false,
|
|
detail: String::from_utf8_lossy(&out.stderr).trim().to_string(),
|
|
},
|
|
Err(e) => RuntimeStatus {
|
|
program,
|
|
available: false,
|
|
detail: format!("nicht startbar: {e}"),
|
|
},
|
|
},
|
|
)
|
|
}
|
|
|
|
/// Bewertung je Modell und Bereich für einen Batch. Gruppe und Gewicht kommen aus den Aufgaben.
|
|
#[tauri::command]
|
|
fn batch_ranking(paths: State<'_, AppPaths>, batch_id: i64) -> Result<ranking::Ranking, String> {
|
|
let store = Store::open(&paths.0.data_dir.join(DB_FILE))?;
|
|
let runs = store.runs_for_batch(batch_id)?;
|
|
let infos: BTreeMap<String, ranking::TaskInfo> = 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));
|
|
app.manage(ConfigState { config: Mutex::new(cfg), file });
|
|
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");
|
|
}
|