okami.mom/strata

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

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
10.0 KiB112 linesraw
1import { tr } from '../lib/i18n';
2import { useCallback, useEffect, useState } from 'react';
3import { Btn, Dialog, Select } from './ui';
4import { TuneRunView, TuneOutcomeCard } from './TuneRunView';
5import { failureDetails, readOutcome } from '../lib/tune-outcome';
6import { go } from '../lib/store';
7import { nativeAction, useNative, type NativeJob } from '../lib/native';
8import { TUNE_BLOCK_TEXT, answerNotice, tunePresetAction, tuneStartBlock, tuneStatus, tuneUndo, type TuneProgress, type TunePreset, type TuneResult, type TuneStatus } from '../lib/native-tune';
9
10type Phase = 'idle' | 'running' | 'result';
11
12/**
13 * Tune model: find the fastest settings for this PC and keep them. The tuner is Strata Control's (the same one the Terminal runs,
14 * with the same saved tunings); this dialog only starts it, shows its progress and result in plain words, and lists, switches,
15 * renames, deletes and undoes the saved tunings. It reuses the Auto-tune dialog's look.
16 */
17export function NativeTune({ open, onClose, model, resourceProfile, vision, visionUnavailable = false }: {
18    open: boolean;
19    onClose: () => void;
20    model: string;
21    resourceProfile: 'work' | 'performance';
22    vision: string;
23    /** The engine has no picture reader: the run goes without pictures and the model's own setting is left as it is. */
24    visionUnavailable?: boolean;
25}) {
26    const native = useNative();
27    const [status, setStatus] = useState<TuneStatus | null>(null), [error, setError] = useState(''), [busy, setBusy] = useState(false);
28    const [mode, setMode] = useState<'quick' | 'thorough'>('quick'), [use, setUse] = useState<'chat' | 'coding'>('chat'), [allowSmall, setAllowSmall] = useState(false);
29    const [jobId, setJobId] = useState(''), [renaming, setRenaming] = useState<TunePreset | null>(null), [name, setName] = useState('');
30    const running = native?.jobs.find(j => (j.kind === 'autotune' || j.kind === 'recheck') && j.state === 'running');
31    const job: NativeJob | undefined = native?.jobs.find(j => j.id === jobId) ?? running;
32    const phase: Phase = job?.state === 'running' ? 'running' : job && job.id === jobId ? 'result' : 'idle';
33    const other = native?.jobs.find(j => j.state === 'running' && j.kind !== 'autotune' && j.kind !== 'recheck');
34
35    const reload = useCallback(async () => {
36        try { setStatus(await tuneStatus(model, resourceProfile, vision)); setError(''); }
37        catch (e) { setStatus(null); setError(e instanceof Error ? e.message : String(e)); }
38    }, [model, resourceProfile, vision]);
39    useEffect(() => { if (open && phase !== 'running') void reload(); }, [open, phase, reload, job?.state]);
40    useEffect(() => { if (open && running && !jobId) setJobId(running.id); }, [open, running?.id]);
41
42    async function start(kind: 'autotune' | 'recheck') {
43        setBusy(true); setError('');
44        try {
45            const started = await nativeAction<NativeJob>('operations', { kind, args: { model, resourceProfile, vision, ...(visionUnavailable ? { visionUnavailable: true } : {}), mode, use, allowSmallDifferences: allowSmall, presetId: status?.active?.id } });
46            setJobId(started.id);
47        } catch (e) { setError(e instanceof Error ? e.message : String(e)); }
48        finally { setBusy(false); }
49    }
50    async function act(fn: () => Promise<unknown>) {
51        setBusy(true); setError('');
52        try { await fn(); await reload(); }
53        catch (e) { setError(e instanceof Error ? e.message : String(e)); }
54        finally { setBusy(false); }
55    }
56    function close() { if (phase !== 'running') setJobId(''); onClose(); }
57
58    const progress = job?.progress as TuneProgress | undefined;
59    const result = job?.state === 'done' ? (job.result as TuneResult | null) : null;
60    const ratio = progress && progress.runsPlanned ? Math.min(0.96, progress.runsDone / progress.runsPlanned) : 0;
61    const active = status?.active ?? null;
62    const block = tuneStartBlock({ busy, otherRunning: !!other, status, error });
63    // The one sentence beside a greyed-out Start tuning, in the footer so it is never below the fold of a scrolling body (the same line serves Tune again and Check again).
64    const why = block === 'other' || block === 'loading' || block === 'unreadable' ? <p className="small muted tune-why" role="status">{tr(TUNE_BLOCK_TEXT[block])}</p> : null;
65
66    const notice = (cls?: string, steady?: boolean) => cls ? <p className="small muted">{tr(answerNotice(cls, steady))}</p> : null;
67    let body;
68    let actions;
69    if (phase === 'running') {
70        body = <TuneRunView progress={progress} ratio={ratio} saving={false}/>;
71        actions = <><Btn onClick={() => void act(() => nativeAction(`operations/${job!.id}/cancel`))} disabled={busy}>{tr("Stop")}</Btn></>;
72    } else if (phase === 'result') {
73        const outcome = readOutcome(result, job?.state);
74        const ok = outcome.tone === 'ok';
75        body = <div className="stack"><TuneOutcomeCard outcome={outcome} details={job?.state === 'error' ? (job.details || job.error) : outcome.code === 'failed' || outcome.code === 'busy_pc' ? failureDetails(job?.result as TuneResult | null, native?.hardware) : null}/>{outcome.code === 'faster' ? notice(result?.answers?.class, result?.answers?.default_repeatable) : null}</div>;
76        const again = <Btn variant={ok ? undefined : 'primary'} disabled={busy || !!other} onClick={() => void start('autotune')}>{tr(outcome.code === 'faster' || outcome.code === 'already_fastest' || outcome.code === 'still_fast' ? 'Tune again' : 'Try again')}</Btn>;
77        actions = <>
78            {status?.can_undo && outcome.code === 'faster' ? <Btn disabled={busy} onClick={() => void act(async () => { await tuneUndo(model, resourceProfile, vision); setJobId(''); })}>{tr("Undo")}</Btn> : null}
79            {why}
80            <span className="tune-actions-gap"/>
81            {ok ? <>{again}<Btn variant="primary" onClick={() => { close(); go('chat'); }}>{tr(outcome.code === 'faster' ? 'Start chatting' : 'Close')}</Btn></> : <><Btn onClick={close}>{tr("Close")}</Btn>{again}</>}
82        </>;
83    } else {
84        const stale = active && status?.state && status.state !== 'fresh';
85        body = <div className="stack">
86            {error ? <p className="small inline-error" role="alert">{error}</p> : null}
87            {block === 'loading' ? <p className="small muted">{tr("Checking for saved tunings\u2026")}</p> : active ? <div><p className="strong">{tr("Saved tuning in use: {0}", [active.name])}</p>
88                {active.gain_pct ? <p className="small muted">{tr("+{0}% faster answers", [Math.round(active.gain_pct)])}</p> : null}
89                {notice(active.answers?.class, active.answers?.default_repeatable)}
90                {stale ? <p className="small">{status?.state === 'hard' ? tr("This PC changed since it was tuned, so these settings are not used until you tune again.") : tr("This PC or the engine changed since it was tuned. A short check takes about 2 minutes.")}</p> : null}</div>
91                : status ? <p className="small muted">{tr("No saved tuning for these choices yet.")}</p> : null}
92            <p className="small muted">{tr("Strata tries different settings on this PC and keeps the ones that make answers faster. Your model is unloaded while this runs, and the computer will be busy.")}</p>
93            <label className="input-field"><span>{tr("How long to spend")}</span><Select value={mode} ariaLabel={tr("How long to spend")} options={[{ value: 'quick', label: 'Quick (about 20 minutes)' }, { value: 'thorough', label: 'Thorough (up to 2 hours)' }]} onChange={v => setMode(v as 'quick' | 'thorough')}/></label>
94            <label className="input-field"><span>{tr("What you mostly do")}</span><Select value={use} ariaLabel={tr("What you mostly do")} options={[{ value: 'chat', label: 'Chat' }, { value: 'coding', label: 'Coding with long prompts' }]} onChange={v => setUse(v as 'chat' | 'coding')}/></label>
95            <label className="check-label"><input type="checkbox" checked={allowSmall} onChange={e => setAllowSmall(e.target.checked)}/>{tr("Allow settings that change answers very slightly (same quality)")}</label>
96            {status && status.presets.length ? <section className="stack"><h2 className="h4">{tr("Saved tunings")}</h2>
97                {status.presets.map(p => <div className="row row--between" key={p.id}>
98                    <span>{p.name}{p.active ? <small> {'·'} {tr("In use")}</small> : null}</span>
99                    <span className="row">{!p.active ? <Btn size="sm" variant="ghost" disabled={busy} onClick={() => void act(() => tunePresetAction(p.id, 'apply'))}>{tr("Use")}</Btn> : null}
100                        <Btn size="sm" variant="ghost" disabled={busy} onClick={() => { setRenaming(p); setName(p.name); }}>{tr("Rename")}</Btn>
101                        <Btn size="sm" variant="ghost" disabled={busy} onClick={() => void act(() => tunePresetAction(p.id, 'delete'))}>{tr("Delete")}</Btn></span></div>)}
102            </section> : null}
103            {renaming ? <div className="row"><input className="st-input" aria-label={tr("Name")} value={name} maxLength={80} onChange={e => setName(e.target.value)}/><Btn size="sm" variant="primary" disabled={!name.trim() || busy} onClick={() => void act(async () => { await tunePresetAction(renaming.id, 'rename', { name: name.trim() }); setRenaming(null); })}>{tr("Save")}</Btn><Btn size="sm" onClick={() => setRenaming(null)}>{tr("Cancel")}</Btn></div> : null}
104        </div>;
105        actions = <>
106            {why}
107            {status?.can_undo ? <Btn disabled={busy || !!other} onClick={() => void act(async () => { await tuneUndo(model, resourceProfile, vision); })}>{tr("Undo")}</Btn> : null}
108            {active && status?.state === 'soft' ? <Btn disabled={busy || !!other} onClick={() => void start('recheck')}>{tr("Check again")}</Btn> : null}
109            <Btn variant="primary" icon="gauge" disabled={block !== null} onClick={() => void start('autotune')}>{tr(active ? "Tune again" : "Start tuning")}</Btn></>;
110    }
111    return <Dialog open={open} wide={phase !== 'idle'} title={phase === 'result' && readOutcome(result, job?.state).code === 'faster' ? tr("Tuned and saved") : tr("Tune this model")} onClose={close} actions={actions}>{body}</Dialog>;
112}