Files
coding-bench/src/lib/BenchPanel.svelte
2026-11-07 19:25:25 +01:00

604 lines
19 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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