import { tr } from '../lib/i18n'; import { useCallback, useEffect, useState } from 'react'; import { Btn, Dialog, Select } from './ui'; import { TuneRunView, TuneOutcomeCard } from './TuneRunView'; import { failureDetails, readOutcome } from '../lib/tune-outcome'; import { go } from '../lib/store'; import { nativeAction, useNative, type NativeJob } from '../lib/native'; import { TUNE_BLOCK_TEXT, answerNotice, tunePresetAction, tuneStartBlock, tuneStatus, tuneUndo, type TuneProgress, type TunePreset, type TuneResult, type TuneStatus } from '../lib/native-tune'; type Phase = 'idle' | 'running' | 'result'; /** * Tune model: find the fastest settings for this PC and keep them. The tuner is Strata Control's (the same one the Terminal runs, * with the same saved tunings); this dialog only starts it, shows its progress and result in plain words, and lists, switches, * renames, deletes and undoes the saved tunings. It reuses the Auto-tune dialog's look. */ export function NativeTune({ open, onClose, model, resourceProfile, vision, visionUnavailable = false }: { open: boolean; onClose: () => void; model: string; resourceProfile: 'work' | 'performance'; vision: string; /** The engine has no picture reader: the run goes without pictures and the model's own setting is left as it is. */ visionUnavailable?: boolean; }) { const native = useNative(); const [status, setStatus] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false); const [mode, setMode] = useState<'quick' | 'thorough'>('quick'), [use, setUse] = useState<'chat' | 'coding'>('chat'), [allowSmall, setAllowSmall] = useState(false); const [jobId, setJobId] = useState(''), [renaming, setRenaming] = useState(null), [name, setName] = useState(''); const running = native?.jobs.find(j => (j.kind === 'autotune' || j.kind === 'recheck') && j.state === 'running'); const job: NativeJob | undefined = native?.jobs.find(j => j.id === jobId) ?? running; const phase: Phase = job?.state === 'running' ? 'running' : job && job.id === jobId ? 'result' : 'idle'; const other = native?.jobs.find(j => j.state === 'running' && j.kind !== 'autotune' && j.kind !== 'recheck'); const reload = useCallback(async () => { try { setStatus(await tuneStatus(model, resourceProfile, vision)); setError(''); } catch (e) { setStatus(null); setError(e instanceof Error ? e.message : String(e)); } }, [model, resourceProfile, vision]); useEffect(() => { if (open && phase !== 'running') void reload(); }, [open, phase, reload, job?.state]); useEffect(() => { if (open && running && !jobId) setJobId(running.id); }, [open, running?.id]); async function start(kind: 'autotune' | 'recheck') { setBusy(true); setError(''); try { const started = await nativeAction('operations', { kind, args: { model, resourceProfile, vision, ...(visionUnavailable ? { visionUnavailable: true } : {}), mode, use, allowSmallDifferences: allowSmall, presetId: status?.active?.id } }); setJobId(started.id); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } } async function act(fn: () => Promise) { setBusy(true); setError(''); try { await fn(); await reload(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } } function close() { if (phase !== 'running') setJobId(''); onClose(); } const progress = job?.progress as TuneProgress | undefined; const result = job?.state === 'done' ? (job.result as TuneResult | null) : null; const ratio = progress && progress.runsPlanned ? Math.min(0.96, progress.runsDone / progress.runsPlanned) : 0; const active = status?.active ?? null; const block = tuneStartBlock({ busy, otherRunning: !!other, status, error }); // 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). const why = block === 'other' || block === 'loading' || block === 'unreadable' ?

{tr(TUNE_BLOCK_TEXT[block])}

: null; const notice = (cls?: string, steady?: boolean) => cls ?

{tr(answerNotice(cls, steady))}

: null; let body; let actions; if (phase === 'running') { body = ; actions = <> void act(() => nativeAction(`operations/${job!.id}/cancel`))} disabled={busy}>{tr("Stop")}; } else if (phase === 'result') { const outcome = readOutcome(result, job?.state); const ok = outcome.tone === 'ok'; body =
{outcome.code === 'faster' ? notice(result?.answers?.class, result?.answers?.default_repeatable) : null}
; const again = void start('autotune')}>{tr(outcome.code === 'faster' || outcome.code === 'already_fastest' || outcome.code === 'still_fast' ? 'Tune again' : 'Try again')}; actions = <> {status?.can_undo && outcome.code === 'faster' ? void act(async () => { await tuneUndo(model, resourceProfile, vision); setJobId(''); })}>{tr("Undo")} : null} {why} {ok ? <>{again} { close(); go('chat'); }}>{tr(outcome.code === 'faster' ? 'Start chatting' : 'Close')} : <>{tr("Close")}{again}} ; } else { const stale = active && status?.state && status.state !== 'fresh'; body =
{error ?

{error}

: null} {block === 'loading' ?

{tr("Checking for saved tunings\u2026")}

: active ?

{tr("Saved tuning in use: {0}", [active.name])}

{active.gain_pct ?

{tr("+{0}% faster answers", [Math.round(active.gain_pct)])}

: null} {notice(active.answers?.class, active.answers?.default_repeatable)} {stale ?

{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.")}

: null}
: status ?

{tr("No saved tuning for these choices yet.")}

: null}

{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.")}

{status && status.presets.length ?

{tr("Saved tunings")}

{status.presets.map(p =>
{p.name}{p.active ? {'ยท'} {tr("In use")} : null} {!p.active ? void act(() => tunePresetAction(p.id, 'apply'))}>{tr("Use")} : null} { setRenaming(p); setName(p.name); }}>{tr("Rename")} void act(() => tunePresetAction(p.id, 'delete'))}>{tr("Delete")}
)}
: null} {renaming ?
setName(e.target.value)}/> void act(async () => { await tunePresetAction(renaming.id, 'rename', { name: name.trim() }); setRenaming(null); })}>{tr("Save")} setRenaming(null)}>{tr("Cancel")}
: null}
; actions = <> {why} {status?.can_undo ? void act(async () => { await tuneUndo(model, resourceProfile, vision); })}>{tr("Undo")} : null} {active && status?.state === 'soft' ? void start('recheck')}>{tr("Check again")} : null} void start('autotune')}>{tr(active ? "Tune again" : "Start tuning")}; } return {body}; }