SevdanurGenc's picture
Upload 300 files
9438a57 verified
Raw History Blame Contribute Delete
32 kB
import { useEffect, useMemo, useRef, useState } from 'react';
import { api } from '../api';
import { useI18n, type MsgKey } from '../i18n';
import { isNum, usePref } from '../settings';
import type { AutoItem, AutoRun, Device, Health, Lang, Language, LibItem, LibItemIn, ModelOption, ProbeResult, Sample, TestKind } from '../types';
import { ACCEPT, MAX_TOTAL, baseName, helpersFor, isTestFile, langOf, readInputs, type InFile } from '../projectFiles';
import ModelSelect, { allModels, modelName, providerOf } from './ModelSelect';
const LANG_NAME: Record<string, string> = { python: 'Python', javascript: 'JavaScript', typescript: 'TypeScript', java: 'Java' };
const KINDS = ['unit', 'interface', 'ui'] as const;
/** Sunucudaki ranking.weights ile aynı: en zayıf 1, en güçlü r = 4…16 (havuz büyüdükçe artar), üstel. */
function shareMap(models: ModelOption[], weighted: boolean): Record<string, number> {
if (!models.length) return {};
const sc = models.map((m) => m.score ?? 0);
const lo = Math.min(...sc), hi = Math.max(...sc);
const r = Math.min(16, Math.max(4, models.length / 3));
const w = models.map((m) => (!weighted || models.length === 1 ? 1 : r ** (hi > lo ? ((m.score ?? 0) - lo) / (hi - lo) : 1)));
const tot = w.reduce((a, b) => a + b, 0);
return Object.fromEntries(models.map((m, i) => [m.id, w[i] / tot]));
}
interface Entry { id: string; title: string; title_en?: string; language: Language; kind: TestKind; description: string; lib?: LibItem }
/** Seçilen dosyalardan kitaplık öğeleri: her kaynak dosya bir örnek; aynı yüklemedeki diğerleri yardımcı. */
function toLibraryItems(files: InFile[], group: string | null): LibItemIn[] {
const pages = files.filter((f) => langOf(f.path) === 'html');
const scripts = files.filter((f) => langOf(f.path) === 'javascript');
const sources = files.filter((f) => { const l = langOf(f.path); return l && l !== 'html'; });
if (pages.length === 1 && scripts.length <= 1 && sources.length === scripts.length) { // Web UI: sayfa (+ betik)
const js = scripts[0];
return [{ name: baseName(js ? js.path : pages[0].path), language: 'javascript', kind: 'ui',
code: js ? js.text : pages[0].text, html: js ? pages[0].text : null, group }];
}
const targets = sources.filter((f) => !isTestFile(f.path));
const multi = files.length > 1 && files.reduce((a, f) => a + f.text.length, 0) <= MAX_TOTAL;
return (targets.length ? targets : sources).map((f) => ({
name: f.path, language: langOf(f.path) as Language, kind: 'unit' as TestKind, code: f.text,
extra_files: multi ? helpersFor(files, f.path).extra : {}, source_name: baseName(f.path), group,
}));
}
function useDuration() {
const { t } = useI18n();
return (s: number) => {
if (!s || s < 60) return t('exp.dur.min', { m: s ? 1 : 0 });
const h = Math.floor(s / 3600), m = Math.round((s % 3600) / 60);
return h ? t('exp.dur.hm', { h, m }) : t('exp.dur.min', { m });
};
}
function ReportLinks({ run, it }: { run: AutoRun; it: AutoItem }) {
const { t } = useI18n();
const keys = ['tr.html', 'tr.pdf', 'en.html', 'en.pdf'].filter((k) => it.reports[k]);
if (!keys.length) return <span className="muted">—</span>;
return (
<span className="rep-links">
{keys.map((k) => {
const [lg, ext] = k.split('.');
return (
<a key={k} className={`rep-link ${ext}`} target="_blank" rel="noreferrer"
href={`/api/automation/runs/${run.id}/files/${it.reports[k]}`}>{lg.toUpperCase()}{ext === 'pdf' ? ' PDF' : ''}</a>
);
})}
{it.pdf_error && run.settings.pdf && <span className="muted small" title={it.pdf_error}> · {t('auto.pdfMissing')}</span>}
</span>
);
}
export default function AutomationPage({ health }: { health: Health | null }) {
const { t, pct, date, lang } = useI18n();
const dur = useDuration();
const itemDur = (s: number) => (s < 120 ? `${Math.round(s)} ${lang === 'tr' ? 'sn' : 's'}` : dur(s));
const [samples, setSamples] = useState<Sample[]>([]);
const [libItems, setLibItems] = useState<LibItem[]>([]);
const [libMsg, setLibMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [dragging, setDragging] = useState(false);
const fileInput = useRef<HTMLInputElement>(null);
const [mode, setMode] = usePref<'single' | 'random'>('auto.modelMode', 'single', (v) => v === 'single' || v === 'random');
const [poolPref, setPool] = usePref<string[] | null>('auto.pool', null, (v) => Array.isArray(v));
const [weighted, setWeighted] = usePref('auto.weighted', true);
const [probes, setProbes] = useState<Record<string, ProbeResult>>({});
const [probing, setProbing] = useState(false);
const [selected, setSelected] = usePref<string[]>('auto.samples', [], (v) => Array.isArray(v));
const [query, setQuery] = useState('');
const [fLang, setFLang] = useState('');
const [fKind, setFKind] = useState('');
// Ayarlar: varsayılanlar Çalışma alanındakilerdir
const [wsModel] = usePref<string>('ws.model', '');
const [model, setModel] = usePref<string>('auto.model', '');
const [device, setDevice] = usePref<Device | null>('auto.device', null, (v) => v === 'auto' || v === 'gpu' || v === 'cpu');
const [wsIter] = usePref('ws.maxIter', 4, isNum);
const [maxIter, setMaxIter] = usePref('auto.maxIter', wsIter, isNum);
const [wsTarget] = usePref('ws.target', 85, isNum);
const [target, setTarget] = usePref('auto.target', wsTarget, isNum);
const [mutation, setMutation] = usePref('auto.mutation', true);
const [maxMutants, setMaxMutants] = usePref('auto.maxMutants', 25, isNum);
const [mutRound, setMutRound] = usePref('auto.mutRound', true);
const [repLangs, setRepLangs] = usePref<Lang[]>('auto.reportLangs', ['tr', 'en'], (v) => Array.isArray(v) && v.length > 0);
const [pdf, setPdf] = usePref('auto.pdf', true);
const [notify, setNotify] = usePref('auto.notify', true);
const [runs, setRuns] = useState<AutoRun[]>([]);
const [sel, setSel] = useState<string | null>(null);
const [err, setErr] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [expBusy, setExpBusy] = useState(false);
useEffect(() => { api.samples().then(setSamples).catch((e) => setErr(String(e.message || e))); }, []);
const loadLib = () => api.library().then(setLibItems).catch(() => {});
useEffect(() => { loadLib(); }, []);
const addFiles = async (list: FileList | File[]) => {
setLibMsg(null);
try {
const arr = [...list];
const { files } = await readInputs(arr);
const group = arr.length === 1 ? arr[0].name : null;
const items = toLibraryItems(files, group);
if (!items.length) { setLibMsg({ ok: false, text: t('auto.addNone') }); return; }
const { ids } = await api.addLibrary(items);
await loadLib();
setSelected(Array.from(new Set([...selected, ...ids])));
setLibMsg({ ok: true, text: t('auto.added', { n: ids.length }) });
} catch (e: any) { setLibMsg({ ok: false, text: String(e.message || e) }); }
};
const removeLib = async (it: LibItem) => {
if (!window.confirm(t('auto.removeLibConfirm', { n: it.title }))) return;
try { await api.deleteLibrary(it.id); } catch { /* yoksay */ }
setSelected(selected.filter((x) => x !== it.id));
loadLib();
};
const load = () => api.autoRuns().then((l) => {
setRuns(l);
setSel((s) => (s && l.some((r) => r.id === s) ? s : l[0]?.id || null));
}).catch(() => {});
const active = runs.find((r) => r.status === 'running' || r.status === 'queued');
const rebuilding = runs.some((r) => r.rebuild?.state === 'running');
useEffect(() => {
load();
api.experiments().then((l) => setExpBusy(l.some((e) => e.status === 'running'))).catch(() => {});
const h = setInterval(load, active || rebuilding ? 3000 : 10000);
return () => clearInterval(h);
}, [!!active, rebuilding]); // eslint-disable-line react-hooks/exhaustive-deps
const known = allModels(health);
const effModel = model && known.some((m) => m.id === model) ? model
: wsModel && known.some((m) => m.id === wsModel) ? wsModel : (health?.default_model || model);
const cloud = providerOf(effModel) !== 'ollama';
const effDevice: Device = device || health?.providers?.device || 'auto';
const probeOf = (id: string): ProbeResult | null | undefined => probes[id] ?? known.find((m) => m.id === id)?.probe;
const failed = (id: string) => probeOf(id)?.ok === false;
// Sınamada hata veren modeller havuza girmez
const pool = (poolPref ?? known.map((m) => m.id)).filter((id) => known.some((m) => m.id === id) && !failed(id));
const togglePool = (id: string) => setPool(pool.includes(id) ? pool.filter((x) => x !== id) : [...pool, id]);
const poolShares = shareMap(known.filter((m) => pool.includes(m.id)), weighted);
const runProbe = async () => {
setProbing(true); setErr(null);
try {
const ids = known.map((m) => m.id);
const res = await api.probeModels(ids, true);
setProbes((p) => ({ ...p, ...res }));
setPool(pool.filter((id) => res[id]?.ok !== false));
} catch (e: any) { setErr(String(e.message || e)); }
setProbing(false);
};
const randomCloud = mode === 'random' && pool.some((m) => providerOf(m) !== 'ollama');
const title = (s: { title: string; title_en?: string }) => (lang === 'en' && s.title_en ? s.title_en : s.title);
const entries: Entry[] = useMemo(() => [
...libItems.map((l) => ({ id: l.id, title: l.title, language: l.language, kind: l.kind, description: l.group || '', lib: l })),
...samples.map((s) => ({ id: s.id, title: s.title, title_en: s.title_en, language: s.language, kind: s.kind,
description: lang === 'en' && s.description_en ? s.description_en : s.description })),
], [libItems, samples, lang]);
const visible = useMemo(() => entries.filter((s) =>
(!fLang || s.language === fLang) && (!fKind || s.kind === fKind)
&& (!query || `${title(s)} ${s.id} ${s.description}`.toLowerCase().includes(query.toLowerCase()))),
[entries, fLang, fKind, query, lang]); // eslint-disable-line react-hooks/exhaustive-deps
const chosen = entries.filter((s) => selected.includes(s.id)).map((s) => s.id); // liste sırası korunur
const toggle = (id: string) => setSelected(selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id]);
const selectVisible = () => setSelected(Array.from(new Set([...selected, ...visible.map((s) => s.id)])));
const clearVisible = () => setSelected(selected.filter((id) => !visible.some((s) => s.id === id)));
const groups = [
{ l: 'mine', label: t('auto.mine'), items: visible.filter((s) => s.lib) },
...Object.keys(LANG_NAME).map((l) => ({ l, label: LANG_NAME[l], items: visible.filter((s) => !s.lib && s.language === l) })),
].filter((g) => g.items.length);
const lastAvg = runs.find((r) => r.counts?.done > 0)?.avg_item_s || 180;
const cur = runs.find((r) => r.id === sel) || null;
const start = async () => {
setErr(null); setBusy(true);
try {
if (notify && 'Notification' in window && Notification.permission === 'default') {
try { await Notification.requestPermission(); } catch { /* yoksay */ }
}
const { id } = await api.startAuto(chosen, {
model: mode === 'random' ? null : effModel || null, model_mode: mode, model_pool: mode === 'random' ? pool : [], weighted,
device: mode === 'single' && cloud ? null : device, max_iterations: maxIter, coverage_target: target,
run_mutation: mutation, max_mutants: maxMutants, mutation_rounds: mutation && mutRound ? 1 : 0,
lang, report_langs: repLangs, pdf,
});
setSel(id); await load();
} catch (e: any) { setErr(String(e.message) === 'busy' ? t('auto.err.busy') : String(e.message || e)); }
setBusy(false);
};
const act = async (fn: () => Promise<unknown>) => {
setErr(null);
try { await fn(); await load(); } catch (e: any) { setErr(String(e.message) === 'busy' ? t('auto.err.busy') : String(e.message || e)); }
};
useEffect(() => { // bitmiş otomasyonu bu sayfada açmak "görüldü" sayılır
if (cur && !cur.seen && ['done', 'cancelled', 'failed'].includes(cur.status)) api.seenAuto(cur.id).catch(() => {});
}, [cur?.id, cur?.status]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className="page">
<h1>{t('auto.title')}</h1>
<p className="lead">{t('auto.lead')}</p>
<div className="grid-2 auto-grid">
<div className="panel">
<div className="panel-head"><h2>{t('auto.new')}</h2></div>
<div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div>
<div className="row" style={{ justifyContent: 'space-between' }}>
<strong className="small">{t('auto.samples')}</strong>
<span className="row" style={{ gap: 6 }}>
<span className="small muted">{t('auto.selected', { n: chosen.length, t: entries.length })}</span>
<button className="btn btn-sm" onClick={selectVisible}>{t('auto.all')}</button>
<button className="btn btn-sm" onClick={clearVisible}>{t('auto.none')}</button>
</span>
</div>
<div className="row auto-filters">
<input type="search" placeholder={t('auto.filter')} value={query} onChange={(e) => setQuery(e.target.value)} />
<select value={fLang} onChange={(e) => setFLang(e.target.value)} aria-label={t('auto.allLangs')}>
<option value="">{t('auto.allLangs')}</option>
{Object.entries(LANG_NAME).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
</select>
<select value={fKind} onChange={(e) => setFKind(e.target.value)} aria-label={t('auto.allKinds')}>
<option value="">{t('auto.allKinds')}</option>
{KINDS.map((k) => <option key={k} value={k}>{t(`kind.${k}` as MsgKey)}</option>)}
</select>
</div>
<div className={`check-list auto-samples${dragging ? ' dragging' : ''}`}
onDragOver={(e) => { e.preventDefault(); setDragging(true); }} onDragLeave={() => setDragging(false)}
onDrop={(e) => { e.preventDefault(); setDragging(false); if (e.dataTransfer.files.length) addFiles(e.dataTransfer.files); }}>
{dragging && <div className="auto-drop">{t('auto.drop')}</div>}
{groups.map((g) => (
<div key={g.l}>
<div className="small muted auto-group">{g.label} · {g.items.length}</div>
{g.items.map((s) => (
<label key={s.id} title={s.description}>
<input type="checkbox" checked={selected.includes(s.id)} onChange={() => toggle(s.id)} />
<span className="auto-title">{title(s)}</span>
{s.kind !== 'unit' && <span className="tag queued">{t(`kind.${s.kind}` as MsgKey)}</span>}
{s.lib ? (<>
<span className="muted small nowrap">{LANG_NAME[s.language]}{s.lib.helpers ? ` · ${t('auto.helpers', { n: s.lib.helpers })}` : ''}</span>
<button className="icon-btn auto-x" title={t('auto.removeLib')} aria-label={t('auto.removeLib')}
onClick={(e) => { e.preventDefault(); removeLib(s.lib!); }}>✕</button>
</>) : <code className="muted small auto-id">{s.id}</code>}
</label>
))}
</div>
))}
</div>
<div className="row" style={{ marginTop: 6, gap: 8 }}>
<button className="btn btn-sm" onClick={() => fileInput.current?.click()}>{t('auto.addFiles')}</button>
<input ref={fileInput} type="file" multiple accept={ACCEPT} hidden
onChange={(e) => { if (e.target.files?.length) addFiles(e.target.files); e.target.value = ''; }} />
</div>
<div className="small muted" style={{ marginTop: 4 }}>{t('auto.addHint')}</div>
{libMsg && <div className={`${libMsg.ok ? 'ok-box' : 'error-box'} small`} style={{ marginTop: 6 }}>{libMsg.text}</div>}
</div>
<div>
<strong className="small">{t('auto.settings')}</strong>
<div className="row auto-settings">
<div className="field">{t('auto.modelMode')}
<div className="seg" role="radiogroup" aria-label={t('auto.modelMode')}>
{(['single', 'random'] as const).map((m) => (
<button key={m} role="radio" aria-checked={mode === m} aria-pressed={mode === m} onClick={() => setMode(m)}>
{t(`auto.mode.${m}` as MsgKey)}</button>))}
</div>
</div>
{mode === 'single' && (
<label className="field">{t('ws.model')}
<ModelSelect health={health} value={effModel} onChange={setModel} style={{ maxWidth: 220 }} />
</label>
)}
<div className="field">{t('ws.device')}
<div className="seg" role="radiogroup" aria-label={t('ws.device')}>
{mode === 'single' && cloud ? <button disabled aria-pressed>{t('ws.device.cloud')}</button>
: (['auto', 'gpu', 'cpu'] as const).map((d) => (
<button key={d} role="radio" aria-checked={effDevice === d} aria-pressed={effDevice === d}
onClick={() => setDevice(d)}>{t(`conn.device.${d}`)}</button>))}
</div>
</div>
<label className="field">{t('ws.maxIter')}
<input type="number" min={1} max={10} value={maxIter} onChange={(e) => setMaxIter(+e.target.value)} style={{ width: 64 }} />
</label>
<label className="field">{t('ws.target')}
<input type="number" min={0} max={100} value={target} onChange={(e) => setTarget(+e.target.value)} style={{ width: 72 }} />
</label>
<label className="field">{t('ws.mutants')}
<span className="row" style={{ gap: 6 }}>
<input type="checkbox" checked={mutation} onChange={(e) => setMutation(e.target.checked)} aria-label={t('ws.mutants.aria')} />
<input type="number" min={0} max={200} value={maxMutants} disabled={!mutation}
onChange={(e) => setMaxMutants(+e.target.value)} style={{ width: 64 }} aria-label={t('ws.maxMutants.aria')} />
</span>
</label>
<label className="field" title={t('ws.mutRound.hint')}>{t('ws.mutRound')}
<span className="row" style={{ minHeight: 34 }}>
<input type="checkbox" checked={mutation && mutRound} disabled={!mutation} onChange={(e) => setMutRound(e.target.checked)} />
</span>
</label>
</div>
{mode === 'random' && (
<div className="auto-pool">
<div className="row" style={{ justifyContent: 'space-between' }}>
<strong className="small">{t('auto.pool', { n: pool.length })}</strong>
<span className="row" style={{ gap: 6 }}>
<button className="btn btn-sm" onClick={() => setPool(known.map((m) => m.id))}>{t('auto.all')}</button>
<button className="btn btn-sm" onClick={() => setPool([])}>{t('auto.none')}</button>
</span>
</div>
<div className="check-list" style={{ maxHeight: 260 }}>
{(['ollama', 'openai', 'anthropic'] as const).map((pv) => {
const items = known.filter((m) => m.provider === pv);
return items.length ? (
<div key={pv}>
<div className="small muted auto-group">{t(`model.group.${pv}` as MsgKey)}</div>
{items.map((m) => {
const pr = probeOf(m.id);
return (
<label key={m.id} className={`pool-row${pr?.ok === false ? ' bad' : ''}`} title={pr?.error || ''}>
<input type="checkbox" checked={pool.includes(m.id)} disabled={pr?.ok === false} onChange={() => togglePool(m.id)} />
<code>{m.name}</code>
<span className={`probe-badge ${pr ? (pr.ok ? 'ok' : 'bad') : ''}`}>
{pr ? (pr.ok ? `✓ ${t('auto.probe.ok', { s: pr.seconds ?? 0 })}` : `✕ ${t('auto.probe.bad')}`) : t('auto.probe.none')}</span>
{pool.includes(m.id) && poolShares[m.id] != null &&
<span className="pool-share">{t('auto.share', { p: Math.round(poolShares[m.id] * 100) })}</span>}
</label>
);
})}
</div>) : null;
})}
</div>
<label className="small"><input type="checkbox" checked={weighted} onChange={(e) => setWeighted(e.target.checked)} /> {t('auto.weighted')}</label>
<div className="small muted">{weighted ? t('auto.weighted.hint') : t('auto.random.hint')}</div>
<div className="row" style={{ gap: 8 }}>
<button className="btn btn-sm" onClick={runProbe} disabled={probing}>{probing ? t('auto.probing') : t('auto.probe')}</button>
<span className="small muted" style={{ flex: 1 }}>{t('auto.probe.hint')}</span>
</div>
{!pool.length && <div className="warn-box small">{t('auto.poolEmpty')}</div>}
</div>
)}
<div className="row auto-settings">
<span className="small"><strong>{t('auto.reports')}:</strong></span>
{(['tr', 'en'] as const).map((l) => (
<label key={l} className="small"><input type="checkbox" checked={repLangs.includes(l)}
onChange={() => setRepLangs(repLangs.includes(l) ? repLangs.filter((x) => x !== l) : [...repLangs, l].sort() as Lang[])} /> {l.toUpperCase()}</label>
))}
<label className="small"><input type="checkbox" checked={pdf} onChange={(e) => setPdf(e.target.checked)} /> {t('auto.pdf')}</label>
<label className="small"><input type="checkbox" checked={notify} onChange={(e) => setNotify(e.target.checked)} /> {t('auto.notify')}</label>
</div>
<div className="small muted">{t('auto.runLang', { l: lang.toUpperCase() })}</div>
</div>
{chosen.length > 0 && (
<div className="plan-box small">
<strong>{t('auto.estimate', { d: dur(chosen.length * lastAvg) })}</strong>
<span className="muted"> · {t('auto.estimateHint')}</span>
</div>
)}
{((mode === 'single' && cloud) || randomCloud) && chosen.length > 0 && <div className="warn-box small">{t('ev.cloudCost')}</div>}
{expBusy && <div className="warn-box small">{t('auto.busyExp')}</div>}
<button className="btn primary" onClick={start} disabled={busy || !chosen.length || !repLangs.length || !!active || (mode === 'random' && !pool.length)}>
{active ? t('auto.running') : t('auto.start', { n: chosen.length })}
</button>
{err && <div className="error-box">{err}</div>}
{runs.length > 0 && (
<div>
<strong className="small">{t('auto.previous')}</strong>
<table className="data-table"><tbody>
{runs.map((r) => (
<tr key={r.id} className={`clickable${r.id === sel ? ' selected' : ''}`} onClick={() => setSel(r.id)}>
<td>{t('auto.runLabel', { n: r.total })} · {r.settings.model_mode === 'random'
? t('auto.randomRun', { n: (r.settings.model_pool || []).length }) : <code>{r.settings.model || health?.default_model}</code>}
<div className="small muted">{date(r.created_at)}</div></td>
<td className="num"><span className={`tag ${r.status}`}>{t(`exp.status.${r.status === 'queued' ? 'running' : r.status}` as MsgKey)}</span>
<div className="small muted">{r.done_n}/{r.total}</div></td>
</tr>
))}
</tbody></table>
</div>
)}
</div>
</div>
<div className="panel">
<div className="panel-head">
<h2>{cur ? <>{t('auto.progress')} · {cur.settings.model_mode === 'random'
? t('auto.randomRun', { n: (cur.settings.model_pool || []).length }) : <code>{cur.settings.model || health?.default_model}</code>}</> : t('auto.progress')}</h2>
<div className="spacer" />
{cur && ['running', 'queued'].includes(cur.status) && <button className="btn" onClick={() => act(() => api.pauseAuto(cur.id))}>{t('exp.pause')}</button>}
{cur && ['running', 'queued', 'paused', 'failed'].includes(cur.status) &&
<button className="btn danger" onClick={() => { if (window.confirm(t('auto.stopConfirm'))) act(() => api.cancelAuto(cur.id)); }}>{t('exp.stop')}</button>}
{cur && ['paused', 'failed', 'cancelled'].includes(cur.status) && cur.counts.queued + cur.counts.cancelled > 0 &&
<button className="btn primary" onClick={() => act(() => api.resumeAuto(cur.id))}>{t('exp.resume')}</button>}
{cur && (<>
<a className="btn" target="_blank" rel="noreferrer" href={`/api/automation/runs/${cur.id}/summary.html?lang=${lang}`}>{t('auto.summary')}</a>
<a className="btn" href={`/api/automation/runs/${cur.id}/results.zip`}>{t('auto.zip')}</a>
{!['running', 'queued'].includes(cur.status) && (cur.rebuild?.state === 'running'
? <button className="btn" disabled>{t('auto.rebuilding', { d: cur.rebuild.done || 0, n: cur.rebuild.total || 0 })}</button>
: <button className="btn" title={t('auto.rebuildHint')} onClick={() => act(() => api.rebuildAuto(cur.id))}>
{cur.rebuild?.state === 'done' ? t('auto.rebuildDone') : cur.rebuild?.state === 'partial' || cur.rebuild?.state === 'failed' ? t('auto.rebuildPartial') : t('auto.rebuild')}</button>)}
{!['running', 'queued'].includes(cur.status) &&
<button className="btn danger" onClick={() => { if (window.confirm(t('auto.deleteConfirm'))) act(() => api.deleteAuto(cur.id)); }}>{t('auto.delete')}</button>}
</>)}
</div>
<div className="panel-body">
{!cur ? (
<div className="empty"><div><h3>{t('auto.emptyTitle')}</h3><p>{t('auto.emptyText')}</p></div></div>
) : (<>
<div className="exp-progress">
<div className="row" style={{ justifyContent: 'space-between' }}>
<span><span className={`tag ${cur.status}`}>{t(`exp.status.${cur.status === 'queued' ? 'running' : cur.status}` as MsgKey)}</span>{' '}
<strong>{pct(cur.percent, 0)}</strong> · {cur.done_n}/{cur.total}
{cur.counts.green > 0 && <> · <span className="ok">✓ {cur.counts.green}</span></>}
{cur.counts.failed > 0 && <> · <span className="bad">✕ {cur.counts.failed}</span></>}
{(cur.counts.empty || 0) > 0 && <> · <span className="warn" title={t('auto.empty')}>∅ {cur.counts.empty}</span></>}</span>
{['running', 'queued', 'paused'].includes(cur.status) && <span className="small muted">{t('exp.eta', { d: dur(cur.eta_s), a: cur.avg_item_s })}</span>}
</div>
<div className="meter neutral" style={{ marginTop: 8, height: 10 }}><span style={{ width: `${cur.percent}%` }} /></div>
{cur.status === 'running' && !cur.worker && <div className="small muted" style={{ marginTop: 6 }}>{t('auto.pausing')}</div>}
{cur.phase === 'probing' && <div className="info-box small" style={{ marginTop: 8 }}>{t('auto.phase.probing')}</div>}
{cur.settings.model_mode === 'random' && cur.shares && Object.keys(cur.shares).length > 0 && (
<div className="small" style={{ marginTop: 8 }}><strong>{t('auto.shares')}:</strong>{' '}
{Object.entries(cur.shares).sort((a, b) => b[1] - a[1]).map(([m, v]) => (
<span key={m} className="share-chip"><code>{modelName(m, health)}</code> {t('auto.share', { p: Math.round(v * 100) })}</span>))}
</div>
)}
{cur.excluded && Object.keys(cur.excluded).length > 0 && (
<div className="warn-box small" style={{ marginTop: 8 }}><strong>{t('auto.excluded')}:</strong>
{Object.entries(cur.excluded).map(([m, e]) => (
<div key={m}><code>{modelName(m, health)}</code> — <span className="muted">{e.slice(0, 160)}</span></div>))}
</div>
)}
{cur.error && <div className="error-box small" style={{ marginTop: 10 }}>{cur.error}</div>}
</div>
<div style={{ overflowX: 'auto' }} className="section-gap">
<table className="data-table">
<thead><tr><th className="num">#</th><th>{t('auto.col.sample')}</th><th>{t('auto.col.status')}</th>
<th className="num">{t('auto.col.tests')}</th><th className="num">{t('ev.col.cov')}</th><th className="num">{t('ev.col.mut')}</th>
<th className="num">{t('auto.col.time')}</th><th>{t('auto.col.reports')}</th></tr></thead>
<tbody>
{cur.items.map((it, i) => (
<tr key={i} className={it.status === 'running' ? 'selected' : ''}>
<td className="num">{i + 1}</td>
<td>{title(it)}<div className="small muted">{LANG_NAME[it.language]} · {t(`kind.${it.kind}` as MsgKey)}
{cur.settings.model_mode === 'random' && it.model && <> · <code>{modelName(it.model, health)}</code></>}
{it.retried_from && <div className="small muted">{t('auto.retried', { m: modelName(it.retried_from, health) })}</div>}
{it.job_id && <> · <a href={`#/job/${it.job_id}`}>{t('auto.open')}</a></>}</div>
{it.error && <div className="small" style={{ color: 'var(--miss)' }}>{it.error.slice(0, 160)}</div>}</td>
<td><span className={`tag ${it.status === 'done' && (!it.total || it.passed !== it.total) ? 'paused' : it.status}`}>
{t(`auto.item.${it.status}` as MsgKey)}</span></td>
<td className="num">{it.total != null ? `${it.passed}/${it.total}` : '—'}</td>
<td className="num">{pct(it.coverage)}</td>
<td className="num">{pct(it.mutation)}</td>
<td className="num nowrap">{it.started_at && it.finished_at ? itemDur(it.finished_at - it.started_at) : it.status === 'running' ? '…' : '—'}</td>
<td><ReportLinks run={cur} it={it} /></td>
</tr>
))}
</tbody>
</table>
</div>
</>)}
</div>
</div>
</div>
</div>
);
}