okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
6.2 KiB94 linesraw
1import {localeTag} from '../lib/i18n';
2import { tr } from '../lib/i18n';
3import { useEffect, useState } from 'react';
4import { api } from '../lib/client';
5import { nativeAction, useNative, type NativeJob } from '../lib/native';
6import { Btn, Dialog, ErrorNotice, Select } from './ui';
7import { NativeProgress } from './NativeModels';
8import { jobErrorText } from '../lib/native-job-diagnostics';
9import { SettingsEngine } from './SettingsEngine';
10export function NativeBenchmark({ open, onClose }: {
11    open: boolean;
12    onClose: () => void;
13}) {
14    const native = useNative();
15    const [selected, setSelected] = useState(''), [error, setError] = useState(''), [jobId, setJobId] = useState(''), [report, setReport] = useState<Record<string, any> | null>(null);
16    const instance = native?.instances.find(i => i.id === selected) ?? native?.instances.find(i => i.id === native.defaultId) ?? native?.instances[0];
17    const job = native?.jobs.find(j => j.id === jobId), active = native?.jobs.some(j => j.state === 'running');
18    useEffect(() => {
19        if (open)
20            void api.get<Record<string, any> | null>('/api/native/benchmark').then(setReport).catch(() => { });
21    }, [open]);
22    useEffect(() => {
23        if (job?.state === 'done' && job.result)
24            setReport(job.result);
25        if (job?.state === 'error')
26            setError(job.error ?? job.summary);
27    }, [job?.state]);
28    async function run() {
29        setError('');
30        try {
31            const job = await nativeAction<NativeJob>('operations', { kind: 'benchmark', args: { instanceId: instance?.id } });
32            setJobId(job.id);
33        }
34        catch (e) {
35            setError(e instanceof Error ? e.message : String(e));
36        }
37    }
38    function download() {
39        if (!report)
40            return;
41        const url = URL.createObjectURL(new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' }));
42        const a = document.createElement('a');
43        a.href = url;
44        a.download = 'strata-benchmark.json';
45        a.click();
46        URL.revokeObjectURL(url);
47    }
48    return <Dialog open={open} title={tr("Measure performance")} onClose={onClose} actions={<><Btn onClick={onClose}>{tr("Close")}</Btn>{tr(job?.state === 'running' ? <Btn onClick={() => void nativeAction(`operations/${job.id}/cancel`).catch(e => setError(e.message))}>{tr("Stop benchmark")}</Btn> : null)}{tr(report ? <Btn icon="download" onClick={download}>{tr("Save report")}</Btn> : null)}<Btn variant="primary" disabled={!instance || instance.status !== 'ready' || active} onClick={() => void run()}>{tr(active ? 'Measuring…' : 'Run short benchmark')}</Btn></>}><div className="stack"><p className="small muted">{tr("A fixed prompt with thinking off and up to 200 output tokens. Usually takes 10\u201360 seconds. Results are measured by your engine.")}</p>{tr((native?.instances.length ?? 0) > 1 ? <Select ariaLabel={tr("Benchmark model")} value={instance?.id ?? ''} options={(native?.instances ?? []).map(i => ({ value: i.id, label: i.label }))} onChange={setSelected}/> : null)}{tr(!instance ? <p>{tr("Load a native model first.")}</p> : null)}{tr(job?.state === 'running' ? <p role="status">{tr(job.summary)}</p> : null)}{tr(report ? <div className="native-benchmark"><div><span>{tr("Generating")}</span><strong>{tr(report.outputTps == null ? '—' : Number(report.outputTps).toFixed(1))} <small>{tr("tok/s")}</small></strong></div><div><span>{tr("Reading")}</span><strong>{tr(report.promptTps == null ? '—' : Number(report.promptTps).toFixed(0))} <small>{tr("tok/s")}</small></strong></div><p className="xs muted">{tr(report.model)} · {tr(new Date(report.at).toLocaleString(localeTag()))} · {tr(report.settings)}</p></div> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}</div></Dialog>;
49}
50export function NativeOperations() {
51    const native = useNative();
52    const [error, setError] = useState(''), [saved, setSaved] = useState(''), [saving, setSaving] = useState(false);
53    const [logs, setLogs] = useState<{
54        at: string;
55        instanceId: string;
56        line: string;
57    }[]>([]), [showLogs, setShowLogs] = useState(false);
58    const active = native?.jobs.find(j => j.state === 'running');
59    useEffect(() => {
60        if (!showLogs)
61            return;
62        const read = () => void api.get<{
63            logs: typeof logs;
64        }>('/api/native/logs').then(value => { setLogs(value.logs); }).catch(() => { });
65        read();
66        const timer = setInterval(read, 2000);
67        return () => clearInterval(timer);
68    }, [showLogs]);
69    // The window cannot save a download, so the host writes the file to Downloads and says where.
70    async function saveLogs() {
71        setSaving(true);
72        setSaved('');
73        setError('');
74        try {
75            const result = await api.post<{ path: string }>('/api/native/logs/save', {});
76            setSaved(result.path);
77        }
78        catch (e) {
79            setError(e instanceof Error ? e.message : String(e));
80        }
81        finally {
82            setSaving(false);
83        }
84    }
85    return <div className="stack stack--lg native-engine-settings">
86 <SettingsEngine />
87 <section className="st-card"><div className="section-toolbar"><h2 className="h3">{tr("Diagnostics")}</h2><Btn size="sm" onClick={() => setShowLogs(true)}>{tr("View logs")}</Btn></div><p className="small muted">{tr("Downloads, preparation and engine failures include their original messages here.")}</p>{tr(native?.jobs.filter(j => j.state === 'error').slice(-3).map(j => <ErrorNotice key={j.id} message={jobErrorText(j, native.jobs)} detail={j.details}/>))}</section>
88 <Dialog open={showLogs} wide compact title={tr("Engine logs")} onClose={() => setShowLogs(false)} actions={<><Btn icon="download" disabled={saving} onClick={() => void saveLogs()}>{tr(saving ? 'Working…' : 'Save logs')}</Btn><Btn variant="primary" onClick={() => setShowLogs(false)}>{tr("Close")}</Btn></>}>
89  <pre className="native-log" aria-label={tr("Engine log")}>{logs.length ? logs.map(l => `${l.at} · ${l.line}`).join(String.fromCharCode(10)) : tr('No engine messages yet.')}</pre>
90  {tr(saved ? <p className="small" role="status">{tr("Saved to {0}", [saved])}</p> : null)}
91 </Dialog>
92 {tr(active ? <NativeProgress job={active}/> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}
93 </div>;
94}