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 = { 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 { 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 —; return ( {keys.map((k) => { const [lg, ext] = k.split('.'); return ( {lg.toUpperCase()}{ext === 'pdf' ? ' PDF' : ''} ); })} {it.pdf_error && run.settings.pdf && · {t('auto.pdfMissing')}} ); } 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([]); const [libItems, setLibItems] = useState([]); const [libMsg, setLibMsg] = useState<{ ok: boolean; text: string } | null>(null); const [dragging, setDragging] = useState(false); const fileInput = useRef(null); const [mode, setMode] = usePref<'single' | 'random'>('auto.modelMode', 'single', (v) => v === 'single' || v === 'random'); const [poolPref, setPool] = usePref('auto.pool', null, (v) => Array.isArray(v)); const [weighted, setWeighted] = usePref('auto.weighted', true); const [probes, setProbes] = useState>({}); const [probing, setProbing] = useState(false); const [selected, setSelected] = usePref('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('ws.model', ''); const [model, setModel] = usePref('auto.model', ''); const [device, setDevice] = usePref('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('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([]); const [sel, setSel] = useState(null); const [err, setErr] = useState(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) => { 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 (

{t('auto.title')}

{t('auto.lead')}

{t('auto.new')}

{t('auto.samples')} {t('auto.selected', { n: chosen.length, t: entries.length })}
setQuery(e.target.value)} />
{ e.preventDefault(); setDragging(true); }} onDragLeave={() => setDragging(false)} onDrop={(e) => { e.preventDefault(); setDragging(false); if (e.dataTransfer.files.length) addFiles(e.dataTransfer.files); }}> {dragging &&
{t('auto.drop')}
} {groups.map((g) => (
{g.label} · {g.items.length}
{g.items.map((s) => ( ))}
))}
{ if (e.target.files?.length) addFiles(e.target.files); e.target.value = ''; }} />
{t('auto.addHint')}
{libMsg &&
{libMsg.text}
}
{t('auto.settings')}
{t('auto.modelMode')}
{(['single', 'random'] as const).map((m) => ( ))}
{mode === 'single' && ( )}
{t('ws.device')}
{mode === 'single' && cloud ? : (['auto', 'gpu', 'cpu'] as const).map((d) => ( ))}
{mode === 'random' && (
{t('auto.pool', { n: pool.length })}
{(['ollama', 'openai', 'anthropic'] as const).map((pv) => { const items = known.filter((m) => m.provider === pv); return items.length ? (
{t(`model.group.${pv}` as MsgKey)}
{items.map((m) => { const pr = probeOf(m.id); return ( ); })}
) : null; })}
{weighted ? t('auto.weighted.hint') : t('auto.random.hint')}
{t('auto.probe.hint')}
{!pool.length &&
{t('auto.poolEmpty')}
}
)}
{t('auto.reports')}: {(['tr', 'en'] as const).map((l) => ( ))}
{t('auto.runLang', { l: lang.toUpperCase() })}
{chosen.length > 0 && (
{t('auto.estimate', { d: dur(chosen.length * lastAvg) })} · {t('auto.estimateHint')}
)} {((mode === 'single' && cloud) || randomCloud) && chosen.length > 0 &&
{t('ev.cloudCost')}
} {expBusy &&
{t('auto.busyExp')}
} {err &&
{err}
} {runs.length > 0 && (
{t('auto.previous')} {runs.map((r) => ( setSel(r.id)}> ))}
{t('auto.runLabel', { n: r.total })} · {r.settings.model_mode === 'random' ? t('auto.randomRun', { n: (r.settings.model_pool || []).length }) : {r.settings.model || health?.default_model}}
{date(r.created_at)}
{t(`exp.status.${r.status === 'queued' ? 'running' : r.status}` as MsgKey)}
{r.done_n}/{r.total}
)}

{cur ? <>{t('auto.progress')} · {cur.settings.model_mode === 'random' ? t('auto.randomRun', { n: (cur.settings.model_pool || []).length }) : {cur.settings.model || health?.default_model}} : t('auto.progress')}

{cur && ['running', 'queued'].includes(cur.status) && } {cur && ['running', 'queued', 'paused', 'failed'].includes(cur.status) && } {cur && ['paused', 'failed', 'cancelled'].includes(cur.status) && cur.counts.queued + cur.counts.cancelled > 0 && } {cur && (<> {t('auto.summary')} {t('auto.zip')} {!['running', 'queued'].includes(cur.status) && (cur.rebuild?.state === 'running' ? : )} {!['running', 'queued'].includes(cur.status) && } )}
{!cur ? (

{t('auto.emptyTitle')}

{t('auto.emptyText')}

) : (<>
{t(`exp.status.${cur.status === 'queued' ? 'running' : cur.status}` as MsgKey)}{' '} {pct(cur.percent, 0)} · {cur.done_n}/{cur.total} {cur.counts.green > 0 && <> · ✓ {cur.counts.green}} {cur.counts.failed > 0 && <> · ✕ {cur.counts.failed}} {(cur.counts.empty || 0) > 0 && <> · ∅ {cur.counts.empty}} {['running', 'queued', 'paused'].includes(cur.status) && {t('exp.eta', { d: dur(cur.eta_s), a: cur.avg_item_s })}}
{cur.status === 'running' && !cur.worker &&
{t('auto.pausing')}
} {cur.phase === 'probing' &&
{t('auto.phase.probing')}
} {cur.settings.model_mode === 'random' && cur.shares && Object.keys(cur.shares).length > 0 && (
{t('auto.shares')}:{' '} {Object.entries(cur.shares).sort((a, b) => b[1] - a[1]).map(([m, v]) => ( {modelName(m, health)} {t('auto.share', { p: Math.round(v * 100) })}))}
)} {cur.excluded && Object.keys(cur.excluded).length > 0 && (
{t('auto.excluded')}: {Object.entries(cur.excluded).map(([m, e]) => (
{modelName(m, health)} — {e.slice(0, 160)}
))}
)} {cur.error &&
{cur.error}
}
{cur.items.map((it, i) => ( ))}
#{t('auto.col.sample')}{t('auto.col.status')} {t('auto.col.tests')}{t('ev.col.cov')}{t('ev.col.mut')} {t('auto.col.time')}{t('auto.col.reports')}
{i + 1} {title(it)}
{LANG_NAME[it.language]} · {t(`kind.${it.kind}` as MsgKey)} {cur.settings.model_mode === 'random' && it.model && <> · {modelName(it.model, health)}} {it.retried_from &&
{t('auto.retried', { m: modelName(it.retried_from, health) })}
} {it.job_id && <> · {t('auto.open')}}
{it.error &&
{it.error.slice(0, 160)}
}
{t(`auto.item.${it.status}` as MsgKey)} {it.total != null ? `${it.passed}/${it.total}` : '—'} {pct(it.coverage)} {pct(it.mutation)} {it.started_at && it.finished_at ? itemDur(it.finished_at - it.started_at) : it.status === 'running' ? '…' : '—'}
)}
); }