Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
app: Tune model dialog (real tuner, saved tunings, undo) reusing the Auto-tune look; its strings in separate catalogs
Niko1221bd773bbd77a9
diff --git a/apps/host/scripts/make-tune-locales.py b/apps/host/scripts/make-tune-locales.pynew file mode 100644index 000000000..f7a186f03--- /dev/null+++ b/apps/host/scripts/make-tune-locales.py@@ -0,0 +1,171 @@+"""Writes src/locales/tune-<lang>.json: the interface strings of the Tune model dialog (auto-tuner), kept apart from the main+catalogs so that other work on the interface text does not collide with them. i18n.ts merges them. Run: python scripts/make-tune-locales.py"""+import json+from pathlib import Path++KEYS = [+ "Tune this model",+ "Finding the fastest settings for your PC…",+ "about {0} min left",+ "This takes about 20 minutes.",+ "Stopped. Your settings were not changed.",+ "The tune did not finish. Your settings were not changed.",+ "Still as fast as when it was saved.",+ "It is slower than before. You can tune again.",+ "Could not tell right now. Your tuning was kept.",+ "+{0}% faster answers, saved as '{1}'",+ "Your current settings are already the fastest we found.",+ "Nothing was changed.",+ "Saved as '{0}', so it is not tuned again when you reopen the app.",+ "Speed: {0} → {1} tok/s",+ "Answers are identical to the standard setup.",+ "Answers may differ slightly from the standard setup.",+ "Answers are not repeatable run to run.",+ "Includes a quality setting that changes the numbers.",+ "Saved tuning in use: {0}",+ "+{0}% faster answers",+ "This PC changed since it was tuned, so these settings are not used until you tune again.",+ "This PC or the engine changed since it was tuned. A short check takes about 2 minutes.",+ "No saved tuning for these choices yet.",+ "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.",+ "Finish the current operation first.",+ "How long to spend",+ "Quick (about 20 minutes)",+ "Thorough (up to 2 hours)",+ "What you mostly do",+ "Coding with long prompts",+ "Allow settings that can change answers slightly",+ "Saved tunings",+ "In use",+ "Use",+ "Check again (about 2 minutes)",+ "Tune again",+ "Start tuning",+ "Tuning your model",+]++T = {+ "zh": [+ "调优此模型", "正在为你的电脑寻找最快的设置…", "还剩约 {0} 分钟",+ "这大约需要 20 分钟。", "已停止。你的设置没有改变。", "调优未完成。你的设置没有改变。",+ "仍然和保存时一样快。", "比以前慢了。你可以再次调优。", "目前无法判断。已保留你的调优结果。",+ "回答快了 {0}%,已保存为“{1}”", "你当前的设置已经是我们找到的最快设置。", "没有做任何改动。",+ "已保存为“{0}”,重新打开应用时不会再次调优。", "速度:{0} → {1} tok/s",+ "回答与标准设置完全相同。", "回答可能与标准设置略有不同。", "每次运行的回答不一定相同。",+ "包含会改变数值的质量设置。", "正在使用的已保存调优:{0}", "回答快了 {0}%",+ "自调优以来这台电脑发生了变化,因此在你再次调优之前不会使用这些设置。",+ "自调优以来这台电脑或引擎发生了变化。快速检查大约需要 2 分钟。",+ "这些选择还没有已保存的调优。",+ "Strata 会在这台电脑上尝试不同的设置,并保留能让回答更快的设置。运行期间模型会被卸载,电脑会比较忙。",+ "请先完成当前操作。", "花多长时间", "快速(约 20 分钟)", "彻底(最多 2 小时)", "你主要做什么",+ "长提示的编程", "允许可能略微改变回答的设置", "已保存的调优", "使用中", "使用",+ "再次检查(约 2 分钟)", "再次调优", "开始调优", "正在调优你的模型",+ ],+ "ja": [+ "このモデルをチューニング", "あなたの PC で最も速い設定を探しています…", "残り約 {0} 分",+ "約 20 分かかります。", "停止しました。設定は変更されていません。", "チューニングが完了しませんでした。設定は変更されていません。",+ "保存したときと同じ速さを保っています。", "以前より遅くなっています。もう一度チューニングできます。", "今は判断できませんでした。チューニング結果はそのまま保持しています。",+ "回答が {0}% 速くなりました。「{1}」として保存しました", "現在の設定が、見つかった中で最も速い設定です。", "何も変更されませんでした。",+ "「{0}」として保存しました。アプリを開き直しても再チューニングはしません。", "速度:{0} → {1} tok/s",+ "回答は標準設定と完全に同じです。", "回答が標準設定とわずかに異なることがあります。", "回答は実行ごとに同じになるとは限りません。",+ "数値を変える品質設定が含まれています。", "使用中の保存済みチューニング:{0}", "回答が {0}% 速くなりました",+ "チューニング後にこの PC が変わったため、もう一度チューニングするまでこの設定は使われません。",+ "チューニング後にこの PC またはエンジンが変わりました。簡易チェックは約 2 分です。",+ "この選択に対する保存済みチューニングはまだありません。",+ "Strata はこの PC でさまざまな設定を試し、回答が速くなるものを残します。実行中はモデルがアンロードされ、コンピューターは負荷が高くなります。",+ "先に現在の操作を終えてください。", "かける時間", "クイック(約 20 分)", "じっくり(最大 2 時間)", "主な用途",+ "長いプロンプトでのコーディング", "回答がわずかに変わる可能性のある設定も許可する", "保存済みチューニング", "使用中", "使用する",+ "もう一度チェック(約 2 分)", "もう一度チューニング", "チューニングを開始", "モデルをチューニング中",+ ],+ "de": [+ "Dieses Modell abstimmen", "Die schnellsten Einstellungen für deinen PC werden gesucht…", "noch etwa {0} Min.",+ "Das dauert etwa 20 Minuten.", "Gestoppt. Deine Einstellungen wurden nicht geändert.", "Die Abstimmung wurde nicht abgeschlossen. Deine Einstellungen wurden nicht geändert.",+ "Noch genauso schnell wie beim Speichern.", "Langsamer als vorher. Du kannst erneut abstimmen.", "Im Moment nicht feststellbar. Deine Abstimmung wurde beibehalten.",+ "+{0} % schnellere Antworten, gespeichert als „{1}“", "Deine aktuellen Einstellungen sind bereits die schnellsten, die wir gefunden haben.", "Es wurde nichts geändert.",+ "Gespeichert als „{0}“, deshalb wird beim nächsten Öffnen der App nicht erneut abgestimmt.", "Tempo: {0} → {1} tok/s",+ "Die Antworten sind mit der Standardeinstellung identisch.", "Die Antworten können leicht von der Standardeinstellung abweichen.", "Die Antworten sind von Lauf zu Lauf nicht wiederholbar.",+ "Enthält eine Qualitätseinstellung, die die Zahlen verändert.", "Gespeicherte Abstimmung in Gebrauch: {0}", "+{0} % schnellere Antworten",+ "Dieser PC hat sich seit der Abstimmung verändert, daher werden diese Einstellungen erst nach einer neuen Abstimmung verwendet.",+ "Dieser PC oder die Engine hat sich seit der Abstimmung verändert. Eine kurze Prüfung dauert etwa 2 Minuten.",+ "Für diese Auswahl gibt es noch keine gespeicherte Abstimmung.",+ "Strata probiert auf diesem PC verschiedene Einstellungen aus und behält die, die Antworten schneller machen. Dein Modell wird dabei entladen, und der Computer ist ausgelastet.",+ "Beende zuerst den aktuellen Vorgang.", "Wie lange soll es dauern?", "Schnell (etwa 20 Minuten)", "Gründlich (bis zu 2 Stunden)", "Was du hauptsächlich machst",+ "Programmieren mit langen Prompts", "Einstellungen erlauben, die Antworten leicht verändern können", "Gespeicherte Abstimmungen", "In Gebrauch", "Verwenden",+ "Erneut prüfen (etwa 2 Minuten)", "Erneut abstimmen", "Abstimmung starten", "Dein Modell wird abgestimmt",+ ],+ "es": [+ "Ajustar este modelo", "Buscando los ajustes más rápidos para tu PC…", "faltan unos {0} min",+ "Esto tarda unos 20 minutos.", "Detenido. Tus ajustes no se han cambiado.", "El ajuste no terminó. Tus ajustes no se han cambiado.",+ "Sigue tan rápido como cuando se guardó.", "Es más lento que antes. Puedes volver a ajustar.", "Ahora no se puede saber. Se ha conservado tu ajuste.",+ "Respuestas un {0} % más rápidas, guardado como «{1}»", "Tus ajustes actuales ya son los más rápidos que hemos encontrado.", "No se ha cambiado nada.",+ "Guardado como «{0}», así que no se vuelve a ajustar al reabrir la aplicación.", "Velocidad: {0} → {1} tok/s",+ "Las respuestas son idénticas a las del ajuste estándar.", "Las respuestas pueden diferir ligeramente del ajuste estándar.", "Las respuestas no se repiten de una ejecución a otra.",+ "Incluye un ajuste de calidad que cambia los números.", "Ajuste guardado en uso: {0}", "Respuestas un {0} % más rápidas",+ "Este PC ha cambiado desde el ajuste, así que estos ajustes no se usan hasta que vuelvas a ajustar.",+ "Este PC o el motor han cambiado desde el ajuste. Una comprobación breve tarda unos 2 minutos.",+ "Todavía no hay un ajuste guardado para estas opciones.",+ "Strata prueba distintos ajustes en este PC y conserva los que hacen las respuestas más rápidas. Tu modelo se descarga mientras tanto y el ordenador estará ocupado.",+ "Termina primero la operación actual.", "Cuánto tiempo dedicar", "Rápido (unos 20 minutos)", "A fondo (hasta 2 horas)", "Qué haces sobre todo",+ "Programar con prompts largos", "Permitir ajustes que pueden cambiar ligeramente las respuestas", "Ajustes guardados", "En uso", "Usar",+ "Comprobar de nuevo (unos 2 minutos)", "Ajustar de nuevo", "Empezar a ajustar", "Ajustando tu modelo",+ ],+ "ru": [+ "Настроить эту модель", "Ищем самые быстрые настройки для вашего ПК…", "осталось примерно {0} мин.",+ "Это займёт около 20 минут.", "Остановлено. Ваши настройки не изменились.", "Настройка не завершилась. Ваши настройки не изменились.",+ "Всё так же быстро, как при сохранении.", "Сейчас медленнее, чем раньше. Можно настроить заново.", "Сейчас не удалось определить. Ваша настройка сохранена.",+ "Ответы быстрее на {0}%, сохранено как «{1}»", "Ваши текущие настройки уже самые быстрые из найденных.", "Ничего не изменено.",+ "Сохранено как «{0}», поэтому при повторном открытии приложения настройка не будет повторяться.", "Скорость: {0} → {1} tok/s",+ "Ответы такие же, как при стандартных настройках.", "Ответы могут немного отличаться от стандартных настроек.", "Ответы не повторяются от запуска к запуску.",+ "Включает настройку качества, которая меняет числа.", "Используется сохранённая настройка: {0}", "Ответы быстрее на {0}%",+ "С момента настройки этот ПК изменился, поэтому эти настройки не используются, пока вы не настроите заново.",+ "С момента настройки этот ПК или движок изменились. Короткая проверка займёт около 2 минут.",+ "Для этих параметров пока нет сохранённой настройки.",+ "Strata пробует на этом ПК разные настройки и оставляет те, что ускоряют ответы. Пока это идёт, модель выгружена, а компьютер занят.",+ "Сначала завершите текущую операцию.", "Сколько времени потратить", "Быстро (около 20 минут)", "Тщательно (до 2 часов)", "Чем вы в основном занимаетесь",+ "Программирование с длинными промптами", "Разрешить настройки, которые могут немного изменить ответы", "Сохранённые настройки", "Используется", "Использовать",+ "Проверить снова (около 2 минут)", "Настроить снова", "Начать настройку", "Настройка вашей модели",+ ],+ "pt": [+ "Ajustar este modelo", "Procurando as configurações mais rápidas para o seu PC…", "faltam cerca de {0} min",+ "Isso leva cerca de 20 minutos.", "Interrompido. Suas configurações não foram alteradas.", "O ajuste não terminou. Suas configurações não foram alteradas.",+ "Continua tão rápido quanto quando foi salvo.", "Está mais lento do que antes. Você pode ajustar de novo.", "Não foi possível saber agora. Seu ajuste foi mantido.",+ "Respostas {0} % mais rápidas, salvo como “{1}”", "Suas configurações atuais já são as mais rápidas que encontramos.", "Nada foi alterado.",+ "Salvo como “{0}”, então não é ajustado de novo quando você reabre o app.", "Velocidade: {0} → {1} tok/s",+ "As respostas são idênticas às da configuração padrão.", "As respostas podem diferir um pouco da configuração padrão.", "As respostas não se repetem de uma execução para outra.",+ "Inclui uma configuração de qualidade que muda os números.", "Ajuste salvo em uso: {0}", "Respostas {0} % mais rápidas",+ "Este PC mudou desde o ajuste, então estas configurações não são usadas até você ajustar de novo.",+ "Este PC ou o motor mudou desde o ajuste. Uma verificação rápida leva cerca de 2 minutos.",+ "Ainda não há ajuste salvo para estas escolhas.",+ "O Strata testa configurações diferentes neste PC e mantém as que deixam as respostas mais rápidas. Seu modelo é descarregado enquanto isso e o computador fica ocupado.",+ "Termine primeiro a operação atual.", "Quanto tempo dedicar", "Rápido (cerca de 20 minutos)", "Completo (até 2 horas)", "O que você mais faz",+ "Programação com prompts longos", "Permitir configurações que podem mudar um pouco as respostas", "Ajustes salvos", "Em uso", "Usar",+ "Verificar de novo (cerca de 2 minutos)", "Ajustar de novo", "Iniciar ajuste", "Ajustando o seu modelo",+ ],+ "ko": [+ "이 모델 최적화", "내 PC에서 가장 빠른 설정을 찾는 중…", "약 {0}분 남음",+ "약 20분 걸립니다.", "중지되었습니다. 설정이 변경되지 않았습니다.", "최적화가 완료되지 않았습니다. 설정이 변경되지 않았습니다.",+ "저장할 때와 같은 속도를 유지하고 있습니다.", "이전보다 느려졌습니다. 다시 최적화할 수 있습니다.", "지금은 판단할 수 없습니다. 최적화 결과는 유지되었습니다.",+ "답변이 {0}% 빨라졌습니다. ‘{1}’(으)로 저장됨", "현재 설정이 찾은 것 중 이미 가장 빠른 설정입니다.", "아무것도 변경되지 않았습니다.",+ "‘{0}’(으)로 저장되었으므로 앱을 다시 열어도 다시 최적화하지 않습니다.", "속도: {0} → {1} tok/s",+ "답변은 표준 설정과 동일합니다.", "답변이 표준 설정과 조금 다를 수 있습니다.", "답변이 실행마다 동일하지 않습니다.",+ "숫자를 바꾸는 품질 설정이 포함되어 있습니다.", "사용 중인 저장된 최적화: {0}", "답변이 {0}% 빨라졌습니다",+ "최적화 이후 이 PC가 변경되어 다시 최적화할 때까지 이 설정은 사용되지 않습니다.",+ "최적화 이후 이 PC 또는 엔진이 변경되었습니다. 간단 점검은 약 2분 걸립니다.",+ "이 선택에 대해 저장된 최적화가 아직 없습니다.",+ "Strata는 이 PC에서 여러 설정을 시험하고 답변을 더 빠르게 하는 설정만 남깁니다. 실행하는 동안 모델이 언로드되고 컴퓨터가 바쁝니다.",+ "먼저 현재 작업을 끝내세요.", "얼마나 오래 할까요", "빠름 (약 20분)", "꼼꼼히 (최대 2시간)", "주로 하는 일",+ "긴 프롬프트로 코딩", "답변을 조금 바꿀 수 있는 설정 허용", "저장된 최적화", "사용 중", "사용",+ "다시 점검 (약 2분)", "다시 최적화", "최적화 시작", "모델을 최적화하는 중",+ ],+}++out = Path(__file__).resolve().parent.parent / "src" / "locales"+ids = [f"tune{i + 1:02d}" for i in range(len(KEYS))]+for lang, values in T.items():+ assert len(values) == len(KEYS), (lang, len(values), len(KEYS))+ for k, v in zip(KEYS, values):+ import re+ assert sorted(re.findall(r"\{\d+\}", k)) == sorted(re.findall(r"\{\d+\}", v)), (lang, k, v)+ (out / f"tune-{lang}.json").write_text(json.dumps(dict(zip(ids, values)), ensure_ascii=False, indent=1) + "\n", encoding="utf-8")+(out / "tune-en.json").write_text(json.dumps(dict(zip(ids, KEYS)), ensure_ascii=False, indent=1) + "\n", encoding="utf-8")+print("wrote", len(KEYS), "strings x", len(T) + 1, "languages")diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsxindex fdc6a9530..80d244cb2 100644--- a/apps/host/src/components/NativeModels.tsx+++ b/apps/host/src/components/NativeModels.tsx@@ -10,6 +10,7 @@ import { RunImageModel } from './RunImageModel';import { useStore } from '../lib/store';import { NativePresets } from './NativePresets';import { NativeBenchmark } from './NativeOperations';+import { NativeTune } from './NativeTune';import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog';export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }: {onOtherModels: () => void;@@ -22,7 +23,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngineconst manual = useStore(s => s.setup?.choices?.onboarding?.manual ?? false);const [expert, setExpert] = useState(manual), [multiple, setMultiple] = useState(false), [gpus, setGpus] = useState<number[]>([]), [kv, setKv] = useState('int8'), [lowRam, setLowRam] = useState('auto'), [split, setSplit] = useState('auto'), [deviceChoice, setDeviceChoice] = useState('auto');const [resourceProfile, setResourceProfile] = useState<'work' | 'performance'>('work');- const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState<Record<string, any> | null>(null), [benchmark, setBenchmark] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false);+ const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState<Record<string, any> | null>(null), [benchmark, setBenchmark] = useState(false), [tuneOpen, setTuneOpen] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false);const presetPending = useRef(false);const families = nativeCatalogModels(native?.catalog?.families ?? []);const expertSection = useRef<HTMLElement>(null);@@ -91,13 +92,14 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine{tr(active ? <NativeProgress job={active}/> : null)}{tr(job?.state === 'error' ? <ErrorNotice message={job.error ?? job.summary} action={tr("Retry")} onRetry={() => void load()}/> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}- <div className="native-model-actions">{tr(onReady && native?.instances.some(i => i.status === 'ready') ? <Btn variant="primary" onClick={onReady}>{tr("Start chatting")}</Btn> : <><Btn icon="gauge" disabled={!native?.instances.some(i => i.status === 'ready') || !!active} onClick={() => setBenchmark(true)}>{tr("Tune model")}</Btn><Btn variant="primary" icon="models" disabled={pending || !native?.available || !!active || !selectedSize || expert && deviceChoice === 'split' && gpus.length < 2} onClick={() => void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')}</Btn></>)}</div>+ <div className="native-model-actions">{tr(onReady && native?.instances.some(i => i.status === 'ready') ? <Btn variant="primary" onClick={onReady}>{tr("Start chatting")}</Btn> : <><Btn icon="gauge" disabled={!installed?.ready || !native?.available || !!active || !selectedSize} onClick={() => setTuneOpen(true)}>{tr("Tune model")}</Btn><Btn variant="primary" icon="models" disabled={pending || !native?.available || !!active || !selectedSize || expert && deviceChoice === 'split' && gpus.length < 2} onClick={() => void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')}</Btn></>)}</div></div><aside className="stack stack--lg"><section className="st-card"><h2 className="h4">{tr("This computer")}</h2><p>{tr(native?.hardware?.ram_gb || hardware?.memory.totalGb || '—')}{tr(" GB RAM")}</p>{tr(native?.hardware?.gpus.length ? native.hardware.gpus.map(g => <p className="small" key={g.index}>{tr(g.name)} · {tr(g.vram_gb)}{tr(" GB")}</p>) : <p className="small muted">{tr("No supported GPU reported by this installation.")}</p>)}<p className="small muted">{tr("Compatibility and sizes come from your installed Strata version.")}</p></section><section className="st-card"><h2 className="h4">{tr("Model files")}</h2><p className="small muted">{tr("Strata prepares all shards, the draft layer and shared files. Completed downloads are reused.")}</p><code className="native-path">{installed?.dataFolder ?? native?.downloadDirectory ?? native?.installed?.data_folder ?? 'Choose an installation'}</code><Btn size="sm" variant="ghost" onClick={() => { setSettingsSection('Storage'); go('settings'); }}>{tr("Storage settings")}</Btn></section><Btn size="sm" variant="ghost" onClick={onOtherModels}>{tr("Other local models\u2026")}</Btn></aside></div><Dialog open={!!plan} title={tr("Download and prepare")} compact onClose={() => !pending && setPlan(null)} actions={<><Btn disabled={pending} onClick={() => setPlan(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={pending || !!plan?.plan?.disk_short} onClick={() => void download()}>{tr("Download & load")}</Btn></>}><p><strong>{tr(plan?.plan?.title ?? selectedFamily?.title)}</strong>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}</p>{tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)}<p className="small muted">{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}</p><p className="small muted">{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}</p>{tr(selectedSize?.images ? <p className="small muted">{tr("Vision encoder files are included. Picture reading loads only when enabled.")}</p> : null)}</Dialog><Dialog open={manage} title={tr("Manage models")} onClose={() => setManage(false)} actions={<Btn onClick={() => setManage(false)}>{tr("Done")}</Btn>}><div className="stack"><p className="strong">{tr(selectedFamily?.title)}</p><div className="st-tablewrap"><table className="st-table"><thead><tr><th>{tr("Version")}</th><th>{tr("Download")}</th><th>{tr("Status")}</th><th></th></tr></thead><tbody>{tr(selectedFamily?.sizes.map(v => <tr key={v.id}><td><strong>{tr(catalogVersionLabel(v))}</strong><small>{tr(v.model)} · {tr(v.about)}</small></td><td>{tr(v.download_gb.toFixed(1))}{tr(" GB")}</td><td>{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')}</td><td><Btn size="sm" disabled={!!active} onClick={() => { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}</Btn></td></tr>))}</tbody></table></div><Btn variant="ghost" icon="folder" onClick={() => { setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}</Btn><p className="xs muted">{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}</p></div></Dialog><NativeBenchmark open={benchmark} onClose={() => setBenchmark(false)}/>+ {selectedSize ? <NativeTune open={tuneOpen} onClose={() => setTuneOpen(false)} model={selectedSize.id} resourceProfile={resourceProfile} vision={selectedSize.images ? vision : 'no'}/> : null}</Screen>;}export function NativeProgress({ job }: {@@ -110,4 +112,4 @@ catch (e) {}finally {setStopping(false);-} } return <section className="st-card native-progress" aria-live="polite"><div className="section-toolbar"><h2 className="h4">{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}</h2>{tr(job.kind === 'install' || job.kind === 'load' ? <Btn size="sm" disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}</Btn> : null)}</div><p className="small">{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}</p>{tr(download ? <><progress max={100} value={download.percent ?? 0}/><p className="xs muted">{tr(download.file)} · {tr(download.percent ?? 0)}%</p></> : null)}<details><summary className="small">{tr("Details")}</summary><p className="small muted">{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}</p></details>{tr(error ? <ErrorNotice message={error}/> : null)}</section>; }+} } return <section className="st-card native-progress" aria-live="polite"><div className="section-toolbar"><h2 className="h4">{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : job.kind === 'autotune' || job.kind === 'recheck' ? 'Tuning your model' : 'Engine operation')}</h2>{tr(job.kind === 'install' || job.kind === 'load' || job.kind === 'autotune' || job.kind === 'recheck' ? <Btn size="sm" disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}</Btn> : null)}</div><p className="small">{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}</p>{tr(download ? <><progress max={100} value={download.percent ?? 0}/><p className="xs muted">{tr(download.file)} · {tr(download.percent ?? 0)}%</p></> : null)}<details><summary className="small">{tr("Details")}</summary><p className="small muted">{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}</p></details>{tr(error ? <ErrorNotice message={error}/> : null)}</section>; }diff --git a/apps/host/src/components/NativeTune.tsx b/apps/host/src/components/NativeTune.tsxnew file mode 100644index 000000000..94fb95ee6--- /dev/null+++ b/apps/host/src/components/NativeTune.tsx@@ -0,0 +1,108 @@+import { tr } from '../lib/i18n';+import { useCallback, useEffect, useState } from 'react';+import { Btn, Dialog, Icon, Select } from './ui';+import { nativeAction, useNative, type NativeJob } from '../lib/native';+import { ANSWER_NOTICE, tunePresetAction, 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 }: {+ open: boolean;+ onClose: () => void;+ model: string;+ resourceProfile: 'work' | 'performance';+ vision: string;+}) {+ const native = useNative();+ const [status, setStatus] = useState<TuneStatus | null>(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<TunePreset | null>(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<NativeJob>('operations', { kind, args: { model, resourceProfile, vision, 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<unknown>) {+ 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 stopped = job?.state === 'cancelled';+ const ratio = progress && progress.runsPlanned ? Math.min(0.96, progress.runsDone / progress.runsPlanned) : 0;+ const left = progress?.minutesLeft ?? null;+ const active = status?.active ?? null;++ const orbit = (complete: boolean) => <div className="tune-orbit" data-complete={complete}><svg viewBox="0 0 120 120" aria-hidden="true"><circle cx="60" cy="60" r="50"/><circle cx="60" cy="60" r="50" pathLength="100" strokeDasharray={`${complete ? 100 : Math.max(4, Math.round(ratio * 100))} 100`}/></svg><Icon name={complete ? 'check' : 'gauge'} size={42}/></div>;+ const notice = (cls?: string) => cls ? <p className="small muted">{tr(ANSWER_NOTICE[cls] ?? '')}</p> : null;++ let body;+ let actions;+ if (phase === 'running') {+ body = <div className="tune-progress">{orbit(false)}<h3 role="status">{tr("Finding the fastest settings for your PC…")}</h3>+ <p className="small muted">{left != null ? tr("about {0} min left", [left]) : tr("This takes about 20 minutes.")}</p>+ {progress?.step ? <p className="xs muted">{progress.step}</p> : null}+ <div className="tune-steps">{[0, 1, 2, 3].map(i => <span key={i} data-done={ratio >= i / 4 && ratio > 0}/>)}</div></div>;+ actions = <><Btn onClick={() => void act(() => nativeAction(`operations/${job!.id}/cancel`))} disabled={busy}>{tr("Stop")}</Btn></>;+ } else if (phase === 'result') {+ const improved = result?.outcome === 'improved' || result?.verdict === 'keep';+ const text = stopped ? tr("Stopped. Your settings were not changed.") : job?.state === 'error' ? tr("The tune did not finish. Your settings were not changed.") : result?.verdict ? (result.verdict === 'keep' ? tr("Still as fast as when it was saved.") : result.verdict === 'retune' ? tr("It is slower than before. You can tune again.") : tr("Could not tell right now. Your tuning was kept.")) : result?.outcome === 'improved' ? tr("+{0}% faster answers, saved as '{1}'", [Math.max(0, Math.round(result.gain_pct ?? 0)), result.preset?.name ?? '']) : result?.outcome === 'default_confirmed' ? tr("Your current settings are already the fastest we found.") : (result?.message ?? tr("Nothing was changed."));+ body = <div className="tune-progress">{orbit(improved || result?.outcome === 'default_confirmed')}<h3 role="status">{text}</h3>+ {result?.outcome === 'default_confirmed' && result.preset ? <p className="small muted">{tr("Saved as '{0}', so it is not tuned again when you reopen the app.", [result.preset.name])}</p> : null}+ {result?.outcome === 'improved' ? <><p className="small muted">{tr("Speed: {0} → {1} tok/s", [Math.round((result.base?.decode_tok_s ?? 0) * 10) / 10, Math.round((result.chosen?.decode_tok_s ?? 0) * 10) / 10])}</p>{notice(result.answers?.class)}</> : null}+ {job?.state === 'error' ? <p className="small inline-error" role="alert">{job.error}</p> : null}</div>;+ actions = <>{status?.can_undo && result?.outcome === 'improved' ? <Btn disabled={busy} onClick={() => void act(async () => { await tuneUndo(model, resourceProfile, vision); setJobId(''); })}>{tr("Undo")}</Btn> : null}<Btn variant="primary" onClick={close}>{tr("Close")}</Btn></>;+ } else {+ const stale = active && status?.state && status.state !== 'fresh';+ body = <div className="stack">+ {error ? <p className="small inline-error" role="alert">{error}</p> : null}+ {active ? <div className="stack"><p className="strong">{tr("Saved tuning in use: {0}", [active.name])}</p>+ {active.gain_pct ? <p className="small muted">{tr("+{0}% faster answers", [Math.round(active.gain_pct)])}</p> : null}+ {notice(active.answers?.class)}+ {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>+ : <p className="small muted">{tr("No saved tuning for these choices yet.")}</p>}+ <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>+ {other ? <p className="small inline-error" role="alert">{tr("Finish the current operation first.")}</p> : null}+ <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>+ <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>+ <label className="check-label"><input type="checkbox" checked={allowSmall} onChange={e => setAllowSmall(e.target.checked)}/>{tr("Allow settings that can change answers slightly")}</label>+ {status && status.presets.length ? <section className="stack"><h2 className="h4">{tr("Saved tunings")}</h2>+ {status.presets.map(p => <div className="row row--between" key={p.id}>+ <span>{p.name}{p.active ? <small> {'·'} {tr("In use")}</small> : null}</span>+ <span className="row">{!p.active ? <Btn size="sm" variant="ghost" disabled={busy} onClick={() => void act(() => tunePresetAction(p.id, 'apply'))}>{tr("Use")}</Btn> : null}+ <Btn size="sm" variant="ghost" disabled={busy} onClick={() => { setRenaming(p); setName(p.name); }}>{tr("Rename")}</Btn>+ <Btn size="sm" variant="ghost" disabled={busy} onClick={() => void act(() => tunePresetAction(p.id, 'delete'))}>{tr("Delete")}</Btn></span></div>)}+ </section> : null}+ {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}+ </div>;+ actions = <><Btn onClick={close}>{tr("Close")}</Btn>+ {status?.can_undo ? <Btn disabled={busy || !!other} onClick={() => void act(async () => { await tuneUndo(model, resourceProfile, vision); })}>{tr("Undo")}</Btn> : null}+ {active && status?.state === 'soft' ? <Btn disabled={busy || !!other} onClick={() => void start('recheck')}>{tr("Check again (about 2 minutes)")}</Btn> : null}+ <Btn variant="primary" icon="gauge" disabled={busy || !!other || !status} onClick={() => void start('autotune')}>{tr(active ? "Tune again" : "Start tuning")}</Btn></>;+ }+ return <Dialog open={open} title={tr("Tune this model")} onClose={close} actions={actions}>{body}</Dialog>;+}diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.tsindex ffbe6add9..53c9196f4 100644--- a/apps/host/src/lib/i18n.ts+++ b/apps/host/src/lib/i18n.ts@@ -1,14 +1,25 @@-import english from '../locales/en.json';-import zh from '../locales/zh.json';-import ja from '../locales/ja.json';-import de from '../locales/de.json';-import es from '../locales/es.json';-import ru from '../locales/ru.json';-import pt from '../locales/pt.json';-import ko from '../locales/ko.json';+import baseEnglish from '../locales/en.json';+import tune_en from '../locales/tune-en.json';+import tune_zh from '../locales/tune-zh.json';+import tune_ja from '../locales/tune-ja.json';+import tune_de from '../locales/tune-de.json';+import tune_es from '../locales/tune-es.json';+import tune_ru from '../locales/tune-ru.json';+import tune_pt from '../locales/tune-pt.json';+import tune_ko from '../locales/tune-ko.json';+import base_zh from '../locales/zh.json';+import base_ja from '../locales/ja.json';+import base_de from '../locales/de.json';+import base_es from '../locales/es.json';+import base_ru from '../locales/ru.json';+import base_pt from '../locales/pt.json';+import base_ko from '../locales/ko.json';export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文(简体)'},{value:'ja',label:'日本語'},{value:'de',label:'Deutsch'},{value:'es',label:'Español'},{value:'ru',label:'Русский'},{value:'pt',label:'Português'},{value:'ko',label:'한국어'}] as const;export type Language=typeof LANGUAGES[number]['value'];+/* The Tune model dialog's strings live in tune-<lang>.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */+const english:Record<string,string>={...baseEnglish,...tune_en};+const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh},{...base_ja,...tune_ja},{...base_de,...tune_de},{...base_es,...tune_es},{...base_ru,...tune_ru},{...base_pt,...tune_pt},{...base_ko,...tune_ko}] as Record<string,string>[];const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,es,ru,pt,ko};const entities:Record<string,string>={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'};const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole);diff --git a/apps/host/src/lib/native-tune.ts b/apps/host/src/lib/native-tune.tsnew file mode 100644index 000000000..fc4e2b893--- /dev/null+++ b/apps/host/src/lib/native-tune.ts@@ -0,0 +1,64 @@+import { api } from './client';++/** A saved tuning, as Strata Control reports it (the same store the Terminal uses). */+export interface TunePreset {+ id: string;+ name: string;+ active: boolean;+ created?: string;+ answers?: { class: 'exact' | 'placement' | 'nonrepeatable' | 'quality'; fields: string[] };+ settings?: { args: Record<string, unknown>; env: Record<string, unknown>; per_request: Record<string, unknown> };+ gain_pct?: number | null;+ decode_tok_s?: number | null;+ baseline_decode_tok_s?: number | null;+ recheck?: { last_ok?: string | null; last_result?: { verdict?: string; reason?: string } | null } | null;+ slot?: string;+}++export interface TuneStatus {+ ok: boolean;+ slot: string;+ suggested_name: string;+ active: TunePreset | null;+ /** fresh, soft (a short check is offered) or hard (the settings are not applied; tune again). */+ state: 'fresh' | 'soft' | 'hard' | null;+ reasons: string[];+ presets: TunePreset[];+ can_undo: boolean;+}++export interface TuneProgress { stage: string; text: string | null; minutesLeft: number | null; runsDone: number; runsPlanned: number; elapsedS: number; step: string }++export interface TuneResult {+ summary: string;+ outcome?: 'improved' | 'default_confirmed' | 'inconclusive' | 'base_failed' | 'cancelled';+ message?: string;+ gain_pct?: number;+ seconds?: number;+ pairs?: number;+ faster_pairs?: number;+ base?: { decode_tok_s?: number | null };+ chosen?: { decode_tok_s?: number | null };+ answers?: { class: TunePreset['answers'] extends infer A ? (A extends { class: infer C } ? C : never) : never; fields: string[] };+ preset?: { id: string; name: string } | null;+ notes?: string[];+ verdict?: 'keep' | 'retune' | 'inconclusive';+ reason?: string;+}++const q = (o: Record<string, string | undefined>) => Object.entries(o).filter(([, v]) => v).map(([k, v]) => `${k}=${encodeURIComponent(v as string)}`).join('&');++export const tuneStatus = (model: string, resourceProfile: string, vision: string) =>+ api.get<TuneStatus>(`/api/native/tune/status?${q({ model, resourceProfile, vision })}`);+export const tunePresetAction = (id: string, action: 'apply' | 'rename' | 'delete' | 'undo', body: Record<string, unknown> = {}) =>+ api.post(`/api/native/tune/presets/${id}/${action}`, body);+export const tuneUndo = (model: string, resourceProfile: string, vision: string) =>+ api.post('/api/native/tune/undo', { model, resourceProfile, vision });++/** The four answer classes, in the words the app uses (the Terminal prints the same sentences). */+export const ANSWER_NOTICE: Record<string, string> = {+ exact: 'Answers are identical to the standard setup.',+ placement: 'Answers may differ slightly from the standard setup.',+ nonrepeatable: 'Answers are not repeatable run to run.',+ quality: 'Includes a quality setting that changes the numbers.',+};diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.tsindex b4fb4df8a..6029e6116 100644--- a/apps/host/src/lib/native.ts+++ b/apps/host/src/lib/native.ts@@ -4,7 +4,7 @@ import type { Hardware, RuntimeModels } from './types';export interface NativeSize {id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean}export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[]}export interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean}-export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;result:Record<string,any>|null}+export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;result:Record<string,any>|null;progress?:Record<string,any>|null}export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record<string,any>|null}export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean}}let state:NativeState|null=null,timer:ReturnType<typeof setInterval>|null=null,reading:Promise<void>|null=null;diff --git a/apps/host/src/locales/tune-de.json b/apps/host/src/locales/tune-de.jsonnew file mode 100644index 000000000..9d3ded556--- /dev/null+++ b/apps/host/src/locales/tune-de.json@@ -0,0 +1,40 @@+{+ "tune01": "Dieses Modell abstimmen",+ "tune02": "Die schnellsten Einstellungen für deinen PC werden gesucht…",+ "tune03": "noch etwa {0} Min.",+ "tune04": "Das dauert etwa 20 Minuten.",+ "tune05": "Gestoppt. Deine Einstellungen wurden nicht geändert.",+ "tune06": "Die Abstimmung wurde nicht abgeschlossen. Deine Einstellungen wurden nicht geändert.",+ "tune07": "Noch genauso schnell wie beim Speichern.",+ "tune08": "Langsamer als vorher. Du kannst erneut abstimmen.",+ "tune09": "Im Moment nicht feststellbar. Deine Abstimmung wurde beibehalten.",+ "tune10": "+{0} % schnellere Antworten, gespeichert als „{1}“",+ "tune11": "Deine aktuellen Einstellungen sind bereits die schnellsten, die wir gefunden haben.",+ "tune12": "Es wurde nichts geändert.",+ "tune13": "Gespeichert als „{0}“, deshalb wird beim nächsten Öffnen der App nicht erneut abgestimmt.",+ "tune14": "Tempo: {0} → {1} tok/s",+ "tune15": "Die Antworten sind mit der Standardeinstellung identisch.",+ "tune16": "Die Antworten können leicht von der Standardeinstellung abweichen.",+ "tune17": "Die Antworten sind von Lauf zu Lauf nicht wiederholbar.",+ "tune18": "Enthält eine Qualitätseinstellung, die die Zahlen verändert.",+ "tune19": "Gespeicherte Abstimmung in Gebrauch: {0}",+ "tune20": "+{0} % schnellere Antworten",+ "tune21": "Dieser PC hat sich seit der Abstimmung verändert, daher werden diese Einstellungen erst nach einer neuen Abstimmung verwendet.",+ "tune22": "Dieser PC oder die Engine hat sich seit der Abstimmung verändert. Eine kurze Prüfung dauert etwa 2 Minuten.",+ "tune23": "Für diese Auswahl gibt es noch keine gespeicherte Abstimmung.",+ "tune24": "Strata probiert auf diesem PC verschiedene Einstellungen aus und behält die, die Antworten schneller machen. Dein Modell wird dabei entladen, und der Computer ist ausgelastet.",+ "tune25": "Beende zuerst den aktuellen Vorgang.",+ "tune26": "Wie lange soll es dauern?",+ "tune27": "Schnell (etwa 20 Minuten)",+ "tune28": "Gründlich (bis zu 2 Stunden)",+ "tune29": "Was du hauptsächlich machst",+ "tune30": "Programmieren mit langen Prompts",+ "tune31": "Einstellungen erlauben, die Antworten leicht verändern können",+ "tune32": "Gespeicherte Abstimmungen",+ "tune33": "In Gebrauch",+ "tune34": "Verwenden",+ "tune35": "Erneut prüfen (etwa 2 Minuten)",+ "tune36": "Erneut abstimmen",+ "tune37": "Abstimmung starten",+ "tune38": "Dein Modell wird abgestimmt"+}diff --git a/apps/host/src/locales/tune-en.json b/apps/host/src/locales/tune-en.jsonnew file mode 100644index 000000000..5761db290--- /dev/null+++ b/apps/host/src/locales/tune-en.json@@ -0,0 +1,40 @@+{+ "tune01": "Tune this model",+ "tune02": "Finding the fastest settings for your PC…",+ "tune03": "about {0} min left",+ "tune04": "This takes about 20 minutes.",+ "tune05": "Stopped. Your settings were not changed.",+ "tune06": "The tune did not finish. Your settings were not changed.",+ "tune07": "Still as fast as when it was saved.",+ "tune08": "It is slower than before. You can tune again.",+ "tune09": "Could not tell right now. Your tuning was kept.",+ "tune10": "+{0}% faster answers, saved as '{1}'",+ "tune11": "Your current settings are already the fastest we found.",+ "tune12": "Nothing was changed.",+ "tune13": "Saved as '{0}', so it is not tuned again when you reopen the app.",+ "tune14": "Speed: {0} → {1} tok/s",+ "tune15": "Answers are identical to the standard setup.",+ "tune16": "Answers may differ slightly from the standard setup.",+ "tune17": "Answers are not repeatable run to run.",+ "tune18": "Includes a quality setting that changes the numbers.",+ "tune19": "Saved tuning in use: {0}",+ "tune20": "+{0}% faster answers",+ "tune21": "This PC changed since it was tuned, so these settings are not used until you tune again.",+ "tune22": "This PC or the engine changed since it was tuned. A short check takes about 2 minutes.",+ "tune23": "No saved tuning for these choices yet.",+ "tune24": "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.",+ "tune25": "Finish the current operation first.",+ "tune26": "How long to spend",+ "tune27": "Quick (about 20 minutes)",+ "tune28": "Thorough (up to 2 hours)",+ "tune29": "What you mostly do",+ "tune30": "Coding with long prompts",+ "tune31": "Allow settings that can change answers slightly",+ "tune32": "Saved tunings",+ "tune33": "In use",+ "tune34": "Use",+ "tune35": "Check again (about 2 minutes)",+ "tune36": "Tune again",+ "tune37": "Start tuning",+ "tune38": "Tuning your model"+}diff --git a/apps/host/src/locales/tune-es.json b/apps/host/src/locales/tune-es.jsonnew file mode 100644index 000000000..2466e9311--- /dev/null+++ b/apps/host/src/locales/tune-es.json@@ -0,0 +1,40 @@+{+ "tune01": "Ajustar este modelo",+ "tune02": "Buscando los ajustes más rápidos para tu PC…",+ "tune03": "faltan unos {0} min",+ "tune04": "Esto tarda unos 20 minutos.",+ "tune05": "Detenido. Tus ajustes no se han cambiado.",+ "tune06": "El ajuste no terminó. Tus ajustes no se han cambiado.",+ "tune07": "Sigue tan rápido como cuando se guardó.",+ "tune08": "Es más lento que antes. Puedes volver a ajustar.",+ "tune09": "Ahora no se puede saber. Se ha conservado tu ajuste.",+ "tune10": "Respuestas un {0} % más rápidas, guardado como «{1}»",+ "tune11": "Tus ajustes actuales ya son los más rápidos que hemos encontrado.",+ "tune12": "No se ha cambiado nada.",+ "tune13": "Guardado como «{0}», así que no se vuelve a ajustar al reabrir la aplicación.",+ "tune14": "Velocidad: {0} → {1} tok/s",+ "tune15": "Las respuestas son idénticas a las del ajuste estándar.",+ "tune16": "Las respuestas pueden diferir ligeramente del ajuste estándar.",+ "tune17": "Las respuestas no se repiten de una ejecución a otra.",+ "tune18": "Incluye un ajuste de calidad que cambia los números.",+ "tune19": "Ajuste guardado en uso: {0}",+ "tune20": "Respuestas un {0} % más rápidas",+ "tune21": "Este PC ha cambiado desde el ajuste, así que estos ajustes no se usan hasta que vuelvas a ajustar.",+ "tune22": "Este PC o el motor han cambiado desde el ajuste. Una comprobación breve tarda unos 2 minutos.",+ "tune23": "Todavía no hay un ajuste guardado para estas opciones.",+ "tune24": "Strata prueba distintos ajustes en este PC y conserva los que hacen las respuestas más rápidas. Tu modelo se descarga mientras tanto y el ordenador estará ocupado.",+ "tune25": "Termina primero la operación actual.",+ "tune26": "Cuánto tiempo dedicar",+ "tune27": "Rápido (unos 20 minutos)",+ "tune28": "A fondo (hasta 2 horas)",+ "tune29": "Qué haces sobre todo",+ "tune30": "Programar con prompts largos",+ "tune31": "Permitir ajustes que pueden cambiar ligeramente las respuestas",+ "tune32": "Ajustes guardados",+ "tune33": "En uso",+ "tune34": "Usar",+ "tune35": "Comprobar de nuevo (unos 2 minutos)",+ "tune36": "Ajustar de nuevo",+ "tune37": "Empezar a ajustar",+ "tune38": "Ajustando tu modelo"+}diff --git a/apps/host/src/locales/tune-ja.json b/apps/host/src/locales/tune-ja.jsonnew file mode 100644index 000000000..186a78501--- /dev/null+++ b/apps/host/src/locales/tune-ja.json@@ -0,0 +1,40 @@+{+ "tune01": "このモデルをチューニング",+ "tune02": "あなたの PC で最も速い設定を探しています…",+ "tune03": "残り約 {0} 分",+ "tune04": "約 20 分かかります。",+ "tune05": "停止しました。設定は変更されていません。",+ "tune06": "チューニングが完了しませんでした。設定は変更されていません。",+ "tune07": "保存したときと同じ速さを保っています。",+ "tune08": "以前より遅くなっています。もう一度チューニングできます。",+ "tune09": "今は判断できませんでした。チューニング結果はそのまま保持しています。",+ "tune10": "回答が {0}% 速くなりました。「{1}」として保存しました",+ "tune11": "現在の設定が、見つかった中で最も速い設定です。",+ "tune12": "何も変更されませんでした。",+ "tune13": "「{0}」として保存しました。アプリを開き直しても再チューニングはしません。",+ "tune14": "速度:{0} → {1} tok/s",+ "tune15": "回答は標準設定と完全に同じです。",+ "tune16": "回答が標準設定とわずかに異なることがあります。",+ "tune17": "回答は実行ごとに同じになるとは限りません。",+ "tune18": "数値を変える品質設定が含まれています。",+ "tune19": "使用中の保存済みチューニング:{0}",+ "tune20": "回答が {0}% 速くなりました",+ "tune21": "チューニング後にこの PC が変わったため、もう一度チューニングするまでこの設定は使われません。",+ "tune22": "チューニング後にこの PC またはエンジンが変わりました。簡易チェックは約 2 分です。",+ "tune23": "この選択に対する保存済みチューニングはまだありません。",+ "tune24": "Strata はこの PC でさまざまな設定を試し、回答が速くなるものを残します。実行中はモデルがアンロードされ、コンピューターは負荷が高くなります。",+ "tune25": "先に現在の操作を終えてください。",+ "tune26": "かける時間",+ "tune27": "クイック(約 20 分)",+ "tune28": "じっくり(最大 2 時間)",+ "tune29": "主な用途",+ "tune30": "長いプロンプトでのコーディング",+ "tune31": "回答がわずかに変わる可能性のある設定も許可する",+ "tune32": "保存済みチューニング",+ "tune33": "使用中",+ "tune34": "使用する",+ "tune35": "もう一度チェック(約 2 分)",+ "tune36": "もう一度チューニング",+ "tune37": "チューニングを開始",+ "tune38": "モデルをチューニング中"+}diff --git a/apps/host/src/locales/tune-ko.json b/apps/host/src/locales/tune-ko.jsonnew file mode 100644index 000000000..0dfccea96--- /dev/null+++ b/apps/host/src/locales/tune-ko.json@@ -0,0 +1,40 @@+{+ "tune01": "이 모델 최적화",+ "tune02": "내 PC에서 가장 빠른 설정을 찾는 중…",+ "tune03": "약 {0}분 남음",+ "tune04": "약 20분 걸립니다.",+ "tune05": "중지되었습니다. 설정이 변경되지 않았습니다.",+ "tune06": "최적화가 완료되지 않았습니다. 설정이 변경되지 않았습니다.",+ "tune07": "저장할 때와 같은 속도를 유지하고 있습니다.",+ "tune08": "이전보다 느려졌습니다. 다시 최적화할 수 있습니다.",+ "tune09": "지금은 판단할 수 없습니다. 최적화 결과는 유지되었습니다.",+ "tune10": "답변이 {0}% 빨라졌습니다. ‘{1}’(으)로 저장됨",+ "tune11": "현재 설정이 찾은 것 중 이미 가장 빠른 설정입니다.",+ "tune12": "아무것도 변경되지 않았습니다.",+ "tune13": "‘{0}’(으)로 저장되었으므로 앱을 다시 열어도 다시 최적화하지 않습니다.",+ "tune14": "속도: {0} → {1} tok/s",+ "tune15": "답변은 표준 설정과 동일합니다.",+ "tune16": "답변이 표준 설정과 조금 다를 수 있습니다.",+ "tune17": "답변이 실행마다 동일하지 않습니다.",+ "tune18": "숫자를 바꾸는 품질 설정이 포함되어 있습니다.",+ "tune19": "사용 중인 저장된 최적화: {0}",+ "tune20": "답변이 {0}% 빨라졌습니다",+ "tune21": "최적화 이후 이 PC가 변경되어 다시 최적화할 때까지 이 설정은 사용되지 않습니다.",+ "tune22": "최적화 이후 이 PC 또는 엔진이 변경되었습니다. 간단 점검은 약 2분 걸립니다.",+ "tune23": "이 선택에 대해 저장된 최적화가 아직 없습니다.",+ "tune24": "Strata는 이 PC에서 여러 설정을 시험하고 답변을 더 빠르게 하는 설정만 남깁니다. 실행하는 동안 모델이 언로드되고 컴퓨터가 바쁝니다.",+ "tune25": "먼저 현재 작업을 끝내세요.",+ "tune26": "얼마나 오래 할까요",+ "tune27": "빠름 (약 20분)",+ "tune28": "꼼꼼히 (최대 2시간)",+ "tune29": "주로 하는 일",+ "tune30": "긴 프롬프트로 코딩",+ "tune31": "답변을 조금 바꿀 수 있는 설정 허용",+ "tune32": "저장된 최적화",+ "tune33": "사용 중",+ "tune34": "사용",+ "tune35": "다시 점검 (약 2분)",+ "tune36": "다시 최적화",+ "tune37": "최적화 시작",+ "tune38": "모델을 최적화하는 중"+}diff --git a/apps/host/src/locales/tune-pt.json b/apps/host/src/locales/tune-pt.jsonnew file mode 100644index 000000000..a5a5ded54--- /dev/null+++ b/apps/host/src/locales/tune-pt.json@@ -0,0 +1,40 @@+{+ "tune01": "Ajustar este modelo",+ "tune02": "Procurando as configurações mais rápidas para o seu PC…",+ "tune03": "faltam cerca de {0} min",+ "tune04": "Isso leva cerca de 20 minutos.",+ "tune05": "Interrompido. Suas configurações não foram alteradas.",+ "tune06": "O ajuste não terminou. Suas configurações não foram alteradas.",+ "tune07": "Continua tão rápido quanto quando foi salvo.",+ "tune08": "Está mais lento do que antes. Você pode ajustar de novo.",+ "tune09": "Não foi possível saber agora. Seu ajuste foi mantido.",+ "tune10": "Respostas {0} % mais rápidas, salvo como “{1}”",+ "tune11": "Suas configurações atuais já são as mais rápidas que encontramos.",+ "tune12": "Nada foi alterado.",+ "tune13": "Salvo como “{0}”, então não é ajustado de novo quando você reabre o app.",+ "tune14": "Velocidade: {0} → {1} tok/s",+ "tune15": "As respostas são idênticas às da configuração padrão.",+ "tune16": "As respostas podem diferir um pouco da configuração padrão.",+ "tune17": "As respostas não se repetem de uma execução para outra.",+ "tune18": "Inclui uma configuração de qualidade que muda os números.",+ "tune19": "Ajuste salvo em uso: {0}",+ "tune20": "Respostas {0} % mais rápidas",+ "tune21": "Este PC mudou desde o ajuste, então estas configurações não são usadas até você ajustar de novo.",+ "tune22": "Este PC ou o motor mudou desde o ajuste. Uma verificação rápida leva cerca de 2 minutos.",+ "tune23": "Ainda não há ajuste salvo para estas escolhas.",+ "tune24": "O Strata testa configurações diferentes neste PC e mantém as que deixam as respostas mais rápidas. Seu modelo é descarregado enquanto isso e o computador fica ocupado.",+ "tune25": "Termine primeiro a operação atual.",+ "tune26": "Quanto tempo dedicar",+ "tune27": "Rápido (cerca de 20 minutos)",+ "tune28": "Completo (até 2 horas)",+ "tune29": "O que você mais faz",+ "tune30": "Programação com prompts longos",+ "tune31": "Permitir configurações que podem mudar um pouco as respostas",+ "tune32": "Ajustes salvos",+ "tune33": "Em uso",+ "tune34": "Usar",+ "tune35": "Verificar de novo (cerca de 2 minutos)",+ "tune36": "Ajustar de novo",+ "tune37": "Iniciar ajuste",+ "tune38": "Ajustando o seu modelo"+}diff --git a/apps/host/src/locales/tune-ru.json b/apps/host/src/locales/tune-ru.jsonnew file mode 100644index 000000000..07b12e500--- /dev/null+++ b/apps/host/src/locales/tune-ru.json@@ -0,0 +1,40 @@+{+ "tune01": "Настроить эту модель",+ "tune02": "Ищем самые быстрые настройки для вашего ПК…",+ "tune03": "осталось примерно {0} мин.",+ "tune04": "Это займёт около 20 минут.",+ "tune05": "Остановлено. Ваши настройки не изменились.",+ "tune06": "Настройка не завершилась. Ваши настройки не изменились.",+ "tune07": "Всё так же быстро, как при сохранении.",+ "tune08": "Сейчас медленнее, чем раньше. Можно настроить заново.",+ "tune09": "Сейчас не удалось определить. Ваша настройка сохранена.",+ "tune10": "Ответы быстрее на {0}%, сохранено как «{1}»",+ "tune11": "Ваши текущие настройки уже самые быстрые из найденных.",+ "tune12": "Ничего не изменено.",+ "tune13": "Сохранено как «{0}», поэтому при повторном открытии приложения настройка не будет повторяться.",+ "tune14": "Скорость: {0} → {1} tok/s",+ "tune15": "Ответы такие же, как при стандартных настройках.",+ "tune16": "Ответы могут немного отличаться от стандартных настроек.",+ "tune17": "Ответы не повторяются от запуска к запуску.",+ "tune18": "Включает настройку качества, которая меняет числа.",+ "tune19": "Используется сохранённая настройка: {0}",+ "tune20": "Ответы быстрее на {0}%",+ "tune21": "С момента настройки этот ПК изменился, поэтому эти настройки не используются, пока вы не настроите заново.",+ "tune22": "С момента настройки этот ПК или движок изменились. Короткая проверка займёт около 2 минут.",+ "tune23": "Для этих параметров пока нет сохранённой настройки.",+ "tune24": "Strata пробует на этом ПК разные настройки и оставляет те, что ускоряют ответы. Пока это идёт, модель выгружена, а компьютер занят.",+ "tune25": "Сначала завершите текущую операцию.",+ "tune26": "Сколько времени потратить",+ "tune27": "Быстро (около 20 минут)",+ "tune28": "Тщательно (до 2 часов)",+ "tune29": "Чем вы в основном занимаетесь",+ "tune30": "Программирование с длинными промптами",+ "tune31": "Разрешить настройки, которые могут немного изменить ответы",+ "tune32": "Сохранённые настройки",+ "tune33": "Используется",+ "tune34": "Использовать",+ "tune35": "Проверить снова (около 2 минут)",+ "tune36": "Настроить снова",+ "tune37": "Начать настройку",+ "tune38": "Настройка вашей модели"+}diff --git a/apps/host/src/locales/tune-zh.json b/apps/host/src/locales/tune-zh.jsonnew file mode 100644index 000000000..740e69bfa--- /dev/null+++ b/apps/host/src/locales/tune-zh.json@@ -0,0 +1,40 @@+{+ "tune01": "调优此模型",+ "tune02": "正在为你的电脑寻找最快的设置…",+ "tune03": "还剩约 {0} 分钟",+ "tune04": "这大约需要 20 分钟。",+ "tune05": "已停止。你的设置没有改变。",+ "tune06": "调优未完成。你的设置没有改变。",+ "tune07": "仍然和保存时一样快。",+ "tune08": "比以前慢了。你可以再次调优。",+ "tune09": "目前无法判断。已保留你的调优结果。",+ "tune10": "回答快了 {0}%,已保存为“{1}”",+ "tune11": "你当前的设置已经是我们找到的最快设置。",+ "tune12": "没有做任何改动。",+ "tune13": "已保存为“{0}”,重新打开应用时不会再次调优。",+ "tune14": "速度:{0} → {1} tok/s",+ "tune15": "回答与标准设置完全相同。",+ "tune16": "回答可能与标准设置略有不同。",+ "tune17": "每次运行的回答不一定相同。",+ "tune18": "包含会改变数值的质量设置。",+ "tune19": "正在使用的已保存调优:{0}",+ "tune20": "回答快了 {0}%",+ "tune21": "自调优以来这台电脑发生了变化,因此在你再次调优之前不会使用这些设置。",+ "tune22": "自调优以来这台电脑或引擎发生了变化。快速检查大约需要 2 分钟。",+ "tune23": "这些选择还没有已保存的调优。",+ "tune24": "Strata 会在这台电脑上尝试不同的设置,并保留能让回答更快的设置。运行期间模型会被卸载,电脑会比较忙。",+ "tune25": "请先完成当前操作。",+ "tune26": "花多长时间",+ "tune27": "快速(约 20 分钟)",+ "tune28": "彻底(最多 2 小时)",+ "tune29": "你主要做什么",+ "tune30": "长提示的编程",+ "tune31": "允许可能略微改变回答的设置",+ "tune32": "已保存的调优",+ "tune33": "使用中",+ "tune34": "使用",+ "tune35": "再次检查(约 2 分钟)",+ "tune36": "再次调优",+ "tune37": "开始调优",+ "tune38": "正在调优你的模型"+}diff --git a/apps/host/tests/tune-locales.test.mjs b/apps/host/tests/tune-locales.test.mjsnew file mode 100644index 000000000..a27bf2d14--- /dev/null+++ b/apps/host/tests/tune-locales.test.mjs@@ -0,0 +1,35 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { build } from 'esbuild';++const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];+const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/tune-${l}.json`, 'utf8'))])));+const main = JSON.parse(await readFile('src/locales/en.json', 'utf8'));+const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort();+const compiled = await build({ stdin: { contents: "export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });+const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);++test('the Tune dialog strings exist in every language with the same slots and no empty text', () => {+ for (const l of languages) {+ assert.deepEqual(Object.keys(catalogs[l]), Object.keys(catalogs.en), l);+ for (const [id, source] of Object.entries(catalogs.en)) {+ assert.ok(catalogs[l][id].trim(), `${l}:${id} is empty`);+ assert.deepEqual(slots(catalogs[l][id]), slots(source), `${l}:${id}`);+ }+ }+});++test('the Tune strings do not collide with the main catalog ids or texts, and translate through tr()', () => {+ const mainTexts = new Set(Object.values(main));+ for (const [id, text] of Object.entries(catalogs.en)) {+ assert.ok(!(id in main), id);+ assert.ok(!mainTexts.has(text), `already in the main catalog: ${text}`);+ }+ setTranslationLanguage('de');+ assert.equal(tr('Tune this model'), catalogs.de.tune01);+ assert.equal(tr('about {0} min left', [7]), catalogs.de.tune03.replace('{0}', '7'));+ assert.equal(tr("+{0}% faster answers, saved as '{1}'", [12, 'IQ3_S 128K']), catalogs.de.tune10.replace('{0}', '12').replace('{1}', 'IQ3_S 128K'));+ setTranslationLanguage('en');+ assert.equal(tr('Tune this model'), 'Tune this model');+});