diff --git a/apps/host/scripts/make-fix-locales.py b/apps/host/scripts/make-fix-locales.py new file mode 100644 index 00000000..19ce9635 --- /dev/null +++ b/apps/host/scripts/make-fix-locales.py @@ -0,0 +1,385 @@ +"""Writes src/locales/fix-.json: the interface strings that had no key in the locale files (#3479, #3825) and the strings of the 0.2.4.3 bug fixes. +Run from apps/host: python scripts/make-fix-locales.py +The keys are fx01.. in this order; fix-en.json is the English source. Placeholders ({0}, {1}) must be kept in every language.""" +import json +from pathlib import Path + +EN = [ + "will stop running and be removed.", + "Downloaded, not loaded. Open Models to load it.", + "{0} lines added, {1} removed", + "Edited {0} files", + "Drop files to add them", + "Pictures and text files", + "Keep goal", + "Remove goal", + "The assistant stops working towards it. Your chat and files stay as they are.", + "This model can read pictures, but the engine installed here does not include the picture reader yet, so Read pictures is off. Update the engine in Settings → About to turn it on.", + "Showing the values of your tuning '{0}'.", + "Your tuning '{0}' sets", + "was {0}", + "· {0} RAM", + "The message was not cancelled", + "Extra settings for the program", + "Draft it with AI", + "Thinking time", + "Writing time", + "tokens/s", + "% of context", + "This page asks for files from the internet, which the preview does not load, so it may look incomplete. View code shows exactly what was written.", + "Keep A", + "Keep B", + "Took", + "Variation", + "Changed", + "Nothing", + "Both versions are ready. Compare A and B, then keep one.", + "The assistant is still answering", + "Send your message when it has finished.", + "The message was not queued", + "Scroll to the latest message", + "Remove task", + "Start a new conversation; keep this one", + "Have the assistant write a plan first; nothing runs until you approve it", + "Search the web, read the pages and answer with sources", + "Copied", + "Response", + "Message", + "PDF added", + "Select the text and copy it with Ctrl+C.", + "{0} is in this chat. Ask about it in your next message.", +] + +T = { +"zh": [ + "将停止运行并被移除。", + "已下载,尚未加载。打开“模型”页面来加载它。", + "新增 {0} 行,删除 {1} 行", + "已编辑 {0} 个文件", + "拖放文件即可添加", + "图片和文本文件", + "保留目标", + "移除目标", + "助手将不再朝这个目标工作。你的对话和文件保持不变。", + "此模型可以读取图片,但这里安装的引擎还不包含图片读取器,所以“读取图片”已关闭。请在“设置 → 关于”中更新引擎后再开启。", + "显示你的调优“{0}”的取值。", + "你的调优“{0}”设置了", + "原为 {0}", + "· {0} 内存", + "消息没有被取消", + "程序的额外设置", + "用 AI 起草", + "思考时间", + "写作时间", + "词元/秒", + "% 的上下文", + "此页面需要从互联网加载文件,预览不会加载这些文件,所以看起来可能不完整。“查看代码”会显示实际写入的内容。", + "保留 A", + "保留 B", + "用时", + "波动", + "已更改", + "无", + "两个版本都已就绪。比较 A 和 B,然后保留其中一个。", + "助手仍在回答", + "等它回答完再发送你的消息。", + "消息没有进入队列", + "滚动到最新消息", + "移除任务", + "开始新对话;保留当前这个", + "让助手先写一份计划;在你批准之前不会运行任何内容", + "搜索网络、阅读网页,并附上来源作答", + "已复制", + "回复", + "消息", + "已添加 PDF", + "请选中文字,然后按 Ctrl+C 复制。", + "{0} 已在此对话中。请在下一条消息里询问它。", +], +"ja": [ + "は停止され、削除されます。", + "ダウンロード済みですが、読み込まれていません。「モデル」を開いて読み込んでください。", + "{0} 行追加、{1} 行削除", + "{0} 個のファイルを編集しました", + "ファイルをドロップして追加", + "画像とテキストファイル", + "目標を残す", + "目標を削除", + "アシスタントはこの目標に向けた作業をやめます。チャットとファイルはそのまま残ります。", + "このモデルは画像を読めますが、ここにインストールされているエンジンにはまだ画像リーダーが含まれていないため、「画像を読む」はオフです。設定 → 情報 でエンジンを更新するとオンにできます。", + "チューニング「{0}」の値を表示しています。", + "チューニング「{0}」が設定する項目", + "変更前: {0}", + "· {0} RAM", + "メッセージはキャンセルされませんでした", + "プログラムの追加設定", + "AI で下書きを作成", + "思考時間", + "執筆時間", + "トークン/秒", + "% のコンテキスト", + "このページはインターネット上のファイルを必要としますが、プレビューでは読み込まれないため、表示が不完全になることがあります。「コードを表示」で書かれた内容をそのまま確認できます。", + "A を残す", + "B を残す", + "所要時間", + "ばらつき", + "変更点", + "なし", + "両方のバージョンの準備ができました。A と B を比べて、どちらかを残してください。", + "アシスタントはまだ回答中です", + "回答が終わってからメッセージを送ってください。", + "メッセージは待機列に入りませんでした", + "最新のメッセージへスクロール", + "タスクを削除", + "新しい会話を始めます。今の会話は残ります", + "アシスタントにまず計画を書かせます。承認するまで何も実行されません", + "ウェブを検索し、ページを読み、出典付きで回答します", + "コピーしました", + "返信", + "メッセージ", + "PDF を追加しました", + "テキストを選択して Ctrl+C でコピーしてください。", + "{0} をこのチャットに追加しました。次のメッセージで質問してください。", +], +"de": [ + "wird nicht mehr ausgeführt und entfernt.", + "Heruntergeladen, aber nicht geladen. Öffne „Modelle“, um es zu laden.", + "{0} Zeilen hinzugefügt, {1} entfernt", + "{0} Dateien bearbeitet", + "Dateien hier ablegen, um sie hinzuzufügen", + "Bilder und Textdateien", + "Ziel behalten", + "Ziel entfernen", + "Der Assistent arbeitet nicht mehr darauf hin. Dein Chat und deine Dateien bleiben unverändert.", + "Dieses Modell kann Bilder lesen, aber die hier installierte Engine enthält den Bildleser noch nicht, deshalb ist „Bilder lesen“ aus. Aktualisiere die Engine unter Einstellungen → Info, um es einzuschalten.", + "Zeigt die Werte deiner Abstimmung „{0}“.", + "Deine Abstimmung „{0}“ setzt", + "war {0}", + "· {0} RAM", + "Die Nachricht wurde nicht abgebrochen", + "Zusätzliche Einstellungen für das Programm", + "Mit KI entwerfen", + "Denkzeit", + "Schreibzeit", + "Token/s", + "% des Kontexts", + "Diese Seite lädt Dateien aus dem Internet, was die Vorschau nicht tut. Sie kann deshalb unvollständig aussehen. „Code anzeigen“ zeigt genau, was geschrieben wurde.", + "A behalten", + "B behalten", + "Dauer", + "Schwankung", + "Geändert", + "Nichts", + "Beide Versionen sind fertig. Vergleiche A und B und behalte eine.", + "Der Assistent antwortet noch", + "Sende deine Nachricht, wenn er fertig ist.", + "Die Nachricht wurde nicht eingereiht", + "Zur neuesten Nachricht scrollen", + "Aufgabe entfernen", + "Neue Unterhaltung beginnen; diese bleibt erhalten", + "Der Assistent schreibt zuerst einen Plan; nichts läuft, bis du ihn freigibst", + "Im Web suchen, die Seiten lesen und mit Quellen antworten", + "Kopiert", + "Antwort", + "Nachricht", + "PDF hinzugefügt", + "Markiere den Text und kopiere ihn mit Strg+C.", + "{0} ist in diesem Chat. Frag in deiner nächsten Nachricht danach.", +], +"es": [ + "dejará de ejecutarse y se eliminará.", + "Descargado, pero no cargado. Abre Modelos para cargarlo.", + "{0} líneas añadidas, {1} eliminadas", + "{0} archivos editados", + "Suelta los archivos para añadirlos", + "Imágenes y archivos de texto", + "Mantener el objetivo", + "Quitar el objetivo", + "El asistente deja de trabajar en ello. Tu chat y tus archivos se quedan como están.", + "Este modelo puede leer imágenes, pero el motor instalado aquí aún no incluye el lector de imágenes, así que Leer imágenes está desactivado. Actualiza el motor en Ajustes → Acerca de para activarlo.", + "Se muestran los valores de tu ajuste «{0}».", + "Tu ajuste «{0}» establece", + "antes {0}", + "· {0} de RAM", + "El mensaje no se canceló", + "Ajustes adicionales del programa", + "Redactar con IA", + "Tiempo de pensar", + "Tiempo de escribir", + "tokens/s", + "% del contexto", + "Esta página pide archivos de internet, que la vista previa no carga, así que puede verse incompleta. Ver código muestra exactamente lo que se escribió.", + "Mantener A", + "Mantener B", + "Tardó", + "Variación", + "Cambiado", + "Nada", + "Las dos versiones están listas. Compara A y B y quédate con una.", + "El asistente sigue respondiendo", + "Envía tu mensaje cuando termine.", + "El mensaje no se puso en cola", + "Ir al último mensaje", + "Quitar tarea", + "Empieza una conversación nueva; esta se conserva", + "El asistente escribe primero un plan; no se ejecuta nada hasta que lo apruebes", + "Busca en la web, lee las páginas y responde con fuentes", + "Copiado", + "Respuesta", + "Mensaje", + "PDF añadido", + "Selecciona el texto y cópialo con Ctrl+C.", + "{0} está en este chat. Pregunta por él en tu próximo mensaje.", +], +"ru": [ + "перестанет работать и будет удалена.", + "Скачана, но не загружена. Откройте «Модели», чтобы загрузить её.", + "Добавлено строк: {0}, удалено: {1}", + "Изменено файлов: {0}", + "Перетащите файлы сюда, чтобы добавить", + "Картинки и текстовые файлы", + "Оставить цель", + "Удалить цель", + "Ассистент перестанет работать над ней. Ваш чат и файлы останутся как есть.", + "Эта модель умеет читать картинки, но установленный здесь движок пока не содержит модуль чтения картинок, поэтому «Читать картинки» выключено. Обновите движок в разделе «Настройки → О программе», чтобы включить.", + "Показаны значения вашей настройки «{0}».", + "Ваша настройка «{0}» задаёт", + "было {0}", + "· {0} ОЗУ", + "Сообщение не было отменено", + "Дополнительные настройки программы", + "Набросать с помощью ИИ", + "Время размышления", + "Время написания", + "токенов/с", + "% контекста", + "Эта страница запрашивает файлы из интернета, а предпросмотр их не загружает, поэтому она может выглядеть неполной. «Показать код» показывает, что именно было написано.", + "Оставить A", + "Оставить B", + "Заняло", + "Разброс", + "Изменено", + "Ничего", + "Обе версии готовы. Сравните A и B и оставьте одну.", + "Ассистент ещё отвечает", + "Отправьте сообщение, когда он закончит.", + "Сообщение не поставлено в очередь", + "К последнему сообщению", + "Удалить задачу", + "Начать новый разговор; этот сохраняется", + "Ассистент сначала напишет план; ничего не запустится, пока вы его не одобрите", + "Искать в интернете, читать страницы и отвечать со ссылками на источники", + "Скопировано", + "Ответ", + "Сообщение", + "PDF добавлен", + "Выделите текст и скопируйте его клавишами Ctrl+C.", + "{0} добавлен в этот чат. Спросите о нём в следующем сообщении.", +], +"pt": [ + "vai parar de funcionar e será removido.", + "Baixado, mas não carregado. Abra Modelos para carregá-lo.", + "{0} linhas adicionadas, {1} removidas", + "{0} arquivos editados", + "Solte os arquivos para adicioná-los", + "Imagens e arquivos de texto", + "Manter a meta", + "Remover a meta", + "O assistente deixa de trabalhar nela. Seu chat e seus arquivos continuam como estão.", + "Este modelo consegue ler imagens, mas o motor instalado aqui ainda não inclui o leitor de imagens, então Ler imagens está desligado. Atualize o motor em Configurações → Sobre para ligar.", + "Mostrando os valores do seu ajuste \"{0}\".", + "Seu ajuste \"{0}\" define", + "era {0}", + "· {0} de RAM", + "A mensagem não foi cancelada", + "Configurações extras do programa", + "Rascunhar com IA", + "Tempo de raciocínio", + "Tempo de escrita", + "tokens/s", + "% do contexto", + "Esta página pede arquivos da internet, que a visualização não carrega, então pode parecer incompleta. Ver código mostra exatamente o que foi escrito.", + "Manter A", + "Manter B", + "Levou", + "Variação", + "Alterado", + "Nada", + "As duas versões estão prontas. Compare A e B e mantenha uma.", + "O assistente ainda está respondendo", + "Envie sua mensagem quando ele terminar.", + "A mensagem não entrou na fila", + "Ir para a última mensagem", + "Remover tarefa", + "Começar uma nova conversa; esta continua salva", + "O assistente escreve um plano primeiro; nada roda até você aprovar", + "Pesquisar na web, ler as páginas e responder com fontes", + "Copiado", + "Resposta", + "Mensagem", + "PDF adicionado", + "Selecione o texto e copie com Ctrl+C.", + "{0} está neste chat. Pergunte sobre ele na próxima mensagem.", +], +"ko": [ + "실행이 중지되고 제거됩니다.", + "다운로드했지만 아직 불러오지 않았습니다. 모델 화면을 열어 불러오세요.", + "{0}줄 추가, {1}줄 삭제", + "파일 {0}개 편집함", + "파일을 놓아서 추가하세요", + "그림과 텍스트 파일", + "목표 유지", + "목표 제거", + "어시스턴트가 이 목표를 향한 작업을 멈춥니다. 대화와 파일은 그대로 남습니다.", + "이 모델은 그림을 읽을 수 있지만, 여기에 설치된 엔진에는 아직 그림 읽기 기능이 없어서 '그림 읽기'가 꺼져 있습니다. 설정 → 정보에서 엔진을 업데이트하면 켤 수 있습니다.", + "튜닝 '{0}'의 값을 보여 줍니다.", + "튜닝 '{0}'이(가) 설정하는 항목", + "이전 값 {0}", + "· RAM {0}", + "메시지가 취소되지 않았습니다", + "프로그램 추가 설정", + "AI로 초안 작성", + "생각한 시간", + "작성한 시간", + "토큰/초", + "컨텍스트 %", + "이 페이지는 인터넷의 파일을 불러와야 하는데 미리보기는 이를 불러오지 않으므로 불완전하게 보일 수 있습니다. '코드 보기'에서 작성된 내용을 그대로 볼 수 있습니다.", + "A 유지", + "B 유지", + "걸린 시간", + "편차", + "변경됨", + "없음", + "두 버전이 모두 준비되었습니다. A와 B를 비교한 뒤 하나를 유지하세요.", + "어시스턴트가 아직 답하는 중입니다", + "답이 끝나면 메시지를 보내세요.", + "메시지가 대기열에 들어가지 않았습니다", + "최신 메시지로 이동", + "작업 제거", + "새 대화를 시작합니다. 이 대화는 그대로 둡니다", + "어시스턴트가 먼저 계획을 작성합니다. 승인하기 전에는 아무것도 실행되지 않습니다", + "웹을 검색하고 페이지를 읽어 출처와 함께 답합니다", + "복사했습니다", + "답변", + "메시지", + "PDF를 추가했습니다", + "텍스트를 선택한 뒤 Ctrl+C로 복사하세요.", + "{0}이(가) 이 채팅에 있습니다. 다음 메시지에서 물어보세요.", +], +} + +here = Path(__file__).resolve().parent.parent / "locales" if False else Path(__file__).resolve().parent.parent / "src" / "locales" + + +def write(lang, values): + assert len(values) == len(EN), (lang, len(values), len(EN)) + for source, text in zip(EN, values): + assert sorted(__import__("re").findall(r"\{\d+\}", source)) == sorted(__import__("re").findall(r"\{\d+\}", text)), (lang, source, text) + data = {f"fx{i + 1:02d}": text for i, text in enumerate(values)} + (here / f"fix-{lang}.json").write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") + + +write("en", EN) +for lang, values in T.items(): + write(lang, values) +print("written", len(EN), "strings in", len(T) + 1, "languages") diff --git a/apps/host/server/device-probes.mjs b/apps/host/server/device-probes.mjs index 496c3aeb..f29bd666 100644 --- a/apps/host/server/device-probes.mjs +++ b/apps/host/server/device-probes.mjs @@ -1,6 +1,7 @@ /** Physical topology and GPU sensors; unavailable values stay null. */ import { readFile, readdir, realpath } from 'node:fs/promises'; import { probe, round } from './util.mjs'; +import { windowsGpuReading } from './windows-gpu.mjs'; /** Unified GPUs share one system memory pool; dedicated GPUs each have their own. */ export function gpuMemoryTotals(devices, readings) { @@ -83,6 +84,10 @@ export async function readGpuTelemetry(gpus) { return Promise.all(gpus.map(async gpu=>{ let reading=nvidia.get(gpu.id)??{id:gpu.id??`${gpu.vendor}:${gpu.index}`,temperatureC:null,utilizationPct:null,memoryUsedGb:null,powerW:null,powerLimitW:null,pcieGen:null,pcieGenMax:null,pcieWidth:null,pcieRxMbs:null}; if(gpu.vendor==='nvidia')reading={...reading,pcieRxMbs:transfer.get(gpu.sensorIndex??gpu.index)??null}; + if(gpu.luid&&!nvidia.has(gpu.id)) { + const counters=windowsGpuReading(gpu.luid); + if(counters)reading={...reading,utilizationPct:counters.utilizationPct,memoryUsedGb:round(counters.memoryUsedGb,2)}; + } if(gpu.sensorPath&&!nvidia.has(gpu.id)) { let temperature=null,power=null,powerLimit=null; for(const hwmon of await list(`${gpu.sensorPath}/hwmon`)) { diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjs index 1785d86b..ef90a663 100644 --- a/apps/host/server/folder-dialog.mjs +++ b/apps/host/server/folder-dialog.mjs @@ -62,7 +62,10 @@ export function watchedWindowsDialog(shell, args, { readyMs = 30_000, openMs = 2 const later = () => { clearTimeout(timer); ready = true; setTimeout(() => end(resolve, { stdout: '' }), openMs).unref?.(); }; child.stdout?.on('data', chunk => { stdout += chunk; if (!ready && /^READY\s*$/m.test(stdout)) { clearTimeout(timer); later(); } }); child.on('error', error => end(reject, error)); - child.on('close', code => { if (settled) return; settled = true; clearTimeout(timer); code === 0 ? resolve({ stdout }) : reject(Object.assign(new Error('exit ' + code), { code })); }); + child.on('close', code => { if (settled) return; settled = true; clearTimeout(timer); + // PowerShell ended before its window opened (security software ended it, #3831): the person types the path instead. + if (!ready) return resolve({ noDialog: true }); + code === 0 ? resolve({ stdout }) : reject(Object.assign(new Error('exit ' + code), { code })); }); }); } diff --git a/apps/host/server/hardware.mjs b/apps/host/server/hardware.mjs index 0a42b729..d53889e9 100644 --- a/apps/host/server/hardware.mjs +++ b/apps/host/server/hardware.mjs @@ -12,6 +12,7 @@ import { CONTEXT_TOKENS, VARIANTS, footprint } from './catalog.mjs'; import { MODELS_DIR, diskFreeGb, diskTotalGb } from './store.mjs'; import { probe, round } from './util.mjs'; import { utf8Script } from './powershell-utf8.mjs'; +import { DX_ADAPTERS_SCRIPT, parseDxAdapters, windowsOtherGpus } from './windows-gpu.mjs'; let cached = null; let cachedAt = 0; @@ -187,11 +188,12 @@ async function detectGpus(platform, totalGb) { } if(platform==='win32') { const raw=await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',utf8Script('Get-CimInstance Win32_VideoController | Select-Object Name,PNPDeviceID | ConvertTo-Json -Compress')]); - try {const parsed=JSON.parse(raw);for(const row of Array.isArray(parsed)?parsed:[parsed]) { - if(!row?.Name||(/nvidia/i.test(row.Name)&&gpus.some(g=>g.vendor==='nvidia')))continue; - const vendor=/amd|radeon/i.test(row.Name)?'amd':/intel/i.test(row.Name)?'intel':'unknown'; - gpus.push({id:String(row.PNPDeviceID),index:gpus.length,vendor,name:row.Name,vramGb:0,unified:false,backend:'vulkan'}); - }}catch{} + try { + const parsed=JSON.parse(raw); + const rows=(Array.isArray(parsed)?parsed:[parsed]).filter(row=>row?.Name&&!(/nvidia/i.test(row.Name)&&gpus.some(g=>g.vendor==='nvidia'))); + const dx=rows.length?parseDxAdapters(await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',DX_ADAPTERS_SCRIPT],8000)):[]; + for(const card of windowsOtherGpus(rows,dx))gpus.push({...card,index:gpus.length,unified:false,backend:'vulkan'}); + }catch{} } gpus.forEach((g,i)=>{g.index=i;}); diff --git a/apps/host/server/missing-files.mjs b/apps/host/server/missing-files.mjs index f575571a..25133a7e 100644 --- a/apps/host/server/missing-files.mjs +++ b/apps/host/server/missing-files.mjs @@ -5,15 +5,15 @@ */ import { basename } from 'node:path'; -const PART_WORDS = { engine: 'the engine program', 'tokenizer/vocab.json': 'the tokenizer', 'tokenizer/merges.txt': 'the tokenizer', 'tokenizer/token_type.json': 'the tokenizer' }; +const PART_WORDS = { engine: 'the engine program', 'component:strata-engine': 'the engine program', 'tokenizer/vocab.json': 'the tokenizer', 'tokenizer/merges.txt': 'the tokenizer', 'tokenizer/token_type.json': 'the tokenizer' }; /** Short readable names, no duplicates, most useful first. */ export function missingNames(controlParts, installerFiles) { const names = []; const add = text => { const t = String(text ?? '').trim(); if (t && !names.includes(t)) names.push(t); }; - for (const file of Array.isArray(installerFiles) ? installerFiles : []) add(basename(String(file).split(String.fromCharCode(92)).join('/'))); + for (const file of Array.isArray(installerFiles) ? installerFiles : []) { const name = basename(String(file).split(String.fromCharCode(92)).join('/')); add(PART_WORDS[name] ?? name); } for (const item of Array.isArray(controlParts) ? controlParts : []) { - add(PART_WORDS[item?.part] ?? item?.file ?? item?.part); + add(PART_WORDS[item?.part] ?? PART_WORDS[item?.file] ?? item?.file ?? item?.part); } return names; } diff --git a/apps/host/server/system-telemetry.mjs b/apps/host/server/system-telemetry.mjs index 4d7c9c6d..4085cd54 100644 --- a/apps/host/server/system-telemetry.mjs +++ b/apps/host/server/system-telemetry.mjs @@ -1,5 +1,7 @@ /** Host counters. CPU sockets are measured only when their logical CPU IDs are known. */ import os from 'node:os'; +import { spawn } from 'node:child_process'; +import { createPowerShellLoop, endWithHost } from './windows-poll.mjs'; import { readFile, readdir } from 'node:fs/promises'; import { availableMemoryGb } from './hardware.mjs'; import { probe } from './util.mjs'; @@ -18,7 +20,7 @@ export function cpuUtilization(previous, current, ids) { } export function diskRate(previous, current, time) { - const elapsed=previous?(time-previous.time)/1000:0; + const elapsed=previous?((current?.at??time)-(previous.counters?.at??previous.time))/1000:0; if(elapsed<=0||!current||!previous?.counters)return {readMbs:null,writeMbs:null}; const read=current.read-previous.counters.read,write=current.write-previous.counters.write; return {readMbs:read>=0?read/1024**2/elapsed:null,writeMbs:write>=0?write/1024**2/elapsed:null}; @@ -41,6 +43,33 @@ export function parseMacDiskCounters(raw) { return reads.length&&writes.length?{read:reads.reduce((n,m)=>n+Number(m[1]),0),write:writes.reduce((n,m)=>n+Number(m[1]),0)}:null; } +export function parseWindowsDiskLine(line) { + const m=/^\s*(\d+)\s+(\d+)\s*$/.exec(String(line)); + return m?{read:Number(m[1]),write:Number(m[2])}:null; +} + +/** The disk counters, read by one long-lived PowerShell (windows-poll.mjs; #3939). */ +export function createWindowsDiskReader({ spawnFn=spawn, intervalSec=4, maxStarts=3, now=Date.now }={}) { + let latest=null; + const script=`while($true){$d=Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk -Filter "Name='_Total'";if($d){[Console]::Out.WriteLine(([string]$d.DiskReadBytesPersec)+' '+([string]$d.DiskWriteBytesPersec));[Console]::Out.Flush()};Start-Sleep -Seconds ${intervalSec}}`; + const loop=createPowerShellLoop({script,spawnFn,maxStarts,onLine:line=>{ + const parsed=parseWindowsDiskLine(line); + if(parsed)latest={...parsed,at:now()}; + return !!parsed; + }}); + return { + read() { loop.start(); return latest&&now()-latest.at<5*intervalSec*1000?latest:null; }, + stop() { loop.stop(); }, + get starts() { return loop.starts; }, + }; +} + +let windowsReader=null; +function windowsDisks() { + windowsReader??=endWithHost(createWindowsDiskReader()); + return windowsReader.read(); +} + async function disks() { try { if(process.platform==='linux') { @@ -49,24 +78,26 @@ async function disks() { } if(process.platform==='darwin')return parseMacDiskCounters(await probe('ioreg',['-r','-c','IOBlockStorageDriver','-l'],1500)); if(process.platform==='win32') { - const raw=await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',"Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk -Filter \"Name='_Total'\" | Select-Object DiskReadBytesPersec,DiskWriteBytesPersec | ConvertTo-Json -Compress"],2000); - const value=JSON.parse(raw); - if(value.DiskReadBytesPersec!=null&&value.DiskWriteBytesPersec!=null)return {read:Number(value.DiskReadBytesPersec),write:Number(value.DiskWriteBytesPersec)}; + return windowsDisks(); } } catch { /* An unsupported counter stays unavailable. */ } return null; } export function createSystemSampler() { - let previousCpu=null,previousDisk=null; + let previousCpu=null,previousDisk=null,lastRate={readMbs:null,writeMbs:null}; return async processors => { const current=os.cpus(),time=Date.now(); const cpuLoad=cpuUtilization(previousCpu,current,current.map((_,i)=>i)); const cpus=processors.map(p=>({id:p.id,utilizationPct:cpuUtilization(previousCpu,current,p.logicalIds??(processors.length===1?current.map((_,i)=>i):[]))})); previousCpu=current; const [available,counters]=await Promise.all([availableMemoryGb(process.platform),disks()]); - const rate=diskRate(previousDisk,counters,time); - previousDisk={time,counters}; + let rate=lastRate; + if(!(counters&&counters.at!==undefined&&previousDisk?.counters?.at===counters.at)) { + rate=diskRate(previousDisk,counters,time); + previousDisk={time,counters}; + lastRate=rate; + } const total=os.totalmem()/1024**3,free=available??os.freemem()/1024**3; return {cpuLoad,cpus,ramUsedGb:Math.max(0,Math.min(total,total-free)),ramTotalGb:total,diskReadGbs:rate.readMbs===null?null:rate.readMbs/1024,diskWriteMbs:rate.writeMbs}; }; diff --git a/apps/host/server/windows-gpu.mjs b/apps/host/server/windows-gpu.mjs new file mode 100644 index 00000000..8475f192 --- /dev/null +++ b/apps/host/server/windows-gpu.mjs @@ -0,0 +1,90 @@ +/** + * Windows graphics cards that nvidia-smi does not cover (AMD, Intel): their size and their load. + * - size: the DirectX adapter list in the registry (HKLM\SOFTWARE\Microsoft\DirectX) has a 64-bit DedicatedVideoMemory and the adapter + * LUID. Win32_VideoController.AdapterRAM is 32 bits and reads 0 or 4 GB for a 16 GB card (#3727, #3836). + * - load and memory in use: the Windows GPU performance counters (the ones Task Manager shows), read by one long-lived PowerShell and + * matched to the card by LUID. Temperature, power and the PCIe link need the vendor's own library, so they stay "not available". + */ +import { createPowerShellLoop, endWithHost } from './windows-poll.mjs'; +import { utf8Script } from './powershell-utf8.mjs'; + +export const DX_ADAPTERS_SCRIPT = utf8Script( + "Get-ChildItem HKLM:\\SOFTWARE\\Microsoft\\DirectX | ForEach-Object { $p = Get-ItemProperty $_.PSPath; " + + "if ($p.Description -and $null -ne $p.AdapterLuid) { [pscustomobject]@{ Description = [string]$p.Description; VendorId = [string]$p.VendorId; " + + "Luid = [string]$p.AdapterLuid; Dedicated = [string]$p.DedicatedVideoMemory; Software = [string]$p.SoftwareAdapter } } } | ConvertTo-Json -Compress"); + +/** luid_0x_0x in the spelling of the performance counters, from the registry's 64-bit number. */ +export function luidName(value) { + try { + const n = BigInt.asUintN(64, BigInt(String(value))); + const hex = v => '0x' + v.toString(16).padStart(8, '0'); + return `luid_${hex(n >> 32n)}_${hex(n & 0xffffffffn)}`; + } catch { return null; } +} + +/** The adapters the DirectX registry lists: [{ description, vendorId, luid, bytes, software }]. Never throws. */ +export function parseDxAdapters(raw) { + try { + const parsed = JSON.parse(raw), rows = Array.isArray(parsed) ? parsed : [parsed]; + return rows.filter(r => r?.Description).map(r => ({ + description: String(r.Description), vendorId: Number(r.VendorId) || 0, luid: luidName(r.Luid), + bytes: Number(r.Dedicated) || 0, software: String(r.Software) === '1' || String(r.Software).toLowerCase() === 'true', + })); + } catch { return []; } +} + +const norm = text => String(text ?? '').toLowerCase().replace(/[^a-z0-9]/g, ''); +const VIRTUAL = /virtual|remote|indirect|mirror|basic render|meta |parsec|displaylink|idd/i; + +/** + * Win32_VideoController rows + the DirectX adapter list -> the cards this app can show. A card keeps the size from the registry; + * a display driver for a virtual monitor (no size, no known maker) is not a graphics card and is dropped. + */ +export function windowsOtherGpus(videoRows, dx) { + const used = new Set(); + const out = []; + for (const row of videoRows) { + if (!row?.Name) continue; + const match = dx.find((a, i) => !used.has(i) && !a.software && norm(a.description) === norm(row.Name)); + if (match) used.add(dx.indexOf(match)); + const vendor = /amd|radeon/i.test(row.Name) ? 'amd' : /intel/i.test(row.Name) ? 'intel' : 'unknown'; + const vramGb = match?.bytes ? Math.round(match.bytes / 1024 ** 3 * 10) / 10 : 0; + if (vendor === 'unknown' && (!vramGb || VIRTUAL.test(row.Name))) continue; + out.push({ id: String(row.PNPDeviceID), vendor, name: row.Name, vramGb, luid: match?.luid ?? null }); + } + return out; +} + +/** One counter line: "G ". */ +export function parseGpuCounterLine(line) { + const m = /^G\s+(luid_0x[0-9a-f]+_0x[0-9a-f]+)\s+(\d+(?:\.\d+)?)\s+(\d+)\s*$/i.exec(String(line)); + return m ? { luid: m[1].toLowerCase(), utilizationPct: Math.max(0, Math.min(100, Number(m[2]))), memoryUsedGb: Number(m[3]) / 1024 ** 3 } : null; +} + +export function createWindowsGpuReader({ spawnFn, intervalSec = 4, maxStarts = 3, now = Date.now } = {}) { + const readings = new Map(); + const script = utf8Script( + `while($true){` + + `$e=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine);$m=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUAdapterMemory);` + + `$u=@{};foreach($r in $e){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)_phys_\\d+_eng_\\d+_engtype_(\\w+)'){$k=$matches[1].ToLower()+'|'+$matches[2];$u[$k]=[double]$u[$k]+[double]$r.UtilizationPercentage}};` + + `$b=@{};foreach($k in $u.Keys){$l=$k.Split('|')[0];if(-not $b.ContainsKey($l) -or $u[$k] -gt $b[$l]){$b[$l]=$u[$k]}};` + + `foreach($r in $m){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)'){$l=$matches[1].ToLower();[Console]::Out.WriteLine('G '+$l+' '+[math]::Round([double]$b[$l],0)+' '+$r.DedicatedUsage)}};` + + `[Console]::Out.Flush();Start-Sleep -Seconds ${intervalSec}}`); + const loop = createPowerShellLoop({ script, spawnFn, maxStarts, onLine: line => { + const parsed = parseGpuCounterLine(line); + if (parsed) readings.set(parsed.luid, { ...parsed, at: now() }); + return !!parsed; + } }); + return { + read(luid) { loop.start(); const r = readings.get(String(luid ?? '').toLowerCase()); return r && now() - r.at < 6 * intervalSec * 1000 ? r : null; }, + stop() { loop.stop(); }, + }; +} + +let shared = null; +/** The card's load and memory in use from the Windows counters; null when there is no reading. */ +export function windowsGpuReading(luid) { + if (process.platform !== 'win32' || !luid) return null; + shared ??= endWithHost(createWindowsGpuReader()); + return shared.read(luid); +} diff --git a/apps/host/server/windows-poll.mjs b/apps/host/server/windows-poll.mjs new file mode 100644 index 00000000..39e247b3 --- /dev/null +++ b/apps/host/server/windows-poll.mjs @@ -0,0 +1,45 @@ +/** + * One long-lived PowerShell that prints a line per reading, in a loop. The monitor used to start a cold PowerShell for every sample; + * its WMI start cost more than the probe timeout, so every query failed and WmiPrvSE burned a core (#3939). + * The loop gives up after `maxStarts` early exits in a row, so a counter that cannot be read stays quiet. + */ +import { spawn } from 'node:child_process'; + +export function createPowerShellLoop({ script, onLine, spawnFn = spawn, maxStarts = 3 }) { + let child = null, starts = 0, buffer = ''; + function start() { + if (child || starts >= maxStarts) return; + starts++; + let proc; + try { proc = spawnFn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); } + catch { return; } + child = proc; + buffer = ''; + proc.on?.('error', () => { if (child === proc) child = null; }); + proc.on?.('exit', () => { if (child === proc) child = null; }); + proc.stdout?.on('data', chunk => { + buffer += chunk; + let i; + while ((i = buffer.indexOf('\n')) >= 0) { + const line = buffer.slice(0, i); + buffer = buffer.slice(i + 1); + if (onLine(line)) starts = 0; + } + }); + proc.unref?.(); + proc.stdout?.unref?.(); + } + return { + start, + stop() { try { child?.kill(); } catch { /* gone */ } child = null; }, + get starts() { return starts; }, + }; +} + +let stoppers = null; +/** Every loop is ended with the host. */ +export function endWithHost(loop) { + if (!stoppers) { stoppers = new Set(); process.once('exit', () => stoppers.forEach(l => l.stop())); } + stoppers.add(loop); + return loop; +} diff --git a/apps/host/src/components/ChatModelPicker.tsx b/apps/host/src/components/ChatModelPicker.tsx index 7389b90c..5c267b2f 100644 --- a/apps/host/src/components/ChatModelPicker.tsx +++ b/apps/host/src/components/ChatModelPicker.tsx @@ -4,7 +4,7 @@ import { useId, useRef, useState } from 'react'; import { FloatingMenu } from './FloatingMenu'; import { Bar, Btn, Dialog, ErrorNotice, Icon } from './ui'; import { go, useLifecycle, loadVariant, selectRemoteModel, setSettingsSection, useStore } from '../lib/store'; -import { pickerGroups, pickerVersionState } from '../lib/model-picker'; +import { pickerGroups, pickerNativeModels, pickerVersionState } from '../lib/model-picker'; import { versionFit } from '../lib/model-versions'; import type { ModelVariant } from '../lib/types'; import { sizeGb } from '../lib/format'; @@ -37,6 +37,7 @@ function LegacyChatModelPicker() { const running = library?.variants.find(v => v.id === library.loaded); const version = library?.variants.find(v => v.id === selected); const groups = library ? pickerGroups(library) : []; + const installedNative = pickerNativeModels(native?.installed?.models, native?.instances); const status = version ? pickerVersionState(version, library?.loaded ?? null) : null; const tooBig = !!version && library?.mode === 'real' && versionFit(version, hardware, contextTokens(engine?.beginner.contextLength ?? '32K')).zone === 'too-big'; async function apply() { @@ -78,7 +79,8 @@ function LegacyChatModelPicker() { {tr(open ? setOpen(false)}> {tr(native?.instances.filter(i => i.status !== 'error').map(i => ))}

{tr("Local models")}

- {tr(!groups.length ?

{tr("No local models downloaded yet.")}

: null)} + {tr(installedNative.map(m => ))} + {tr(!groups.length && !installedNative.length ?

{tr("No local models downloaded yet.")}

: null)} {tr(groups.map(({ family, versions }, index) => { const main = versions[0], state = pickerVersionState(main, library!.loaded); const others = versions.slice(1), isExpanded = expanded.includes(family), id = `${groupsId}-${index}`; diff --git a/apps/host/src/components/ComposerControls.tsx b/apps/host/src/components/ComposerControls.tsx index 4dab2992..7156199b 100644 --- a/apps/host/src/components/ComposerControls.tsx +++ b/apps/host/src/components/ComposerControls.tsx @@ -5,10 +5,11 @@ import { FloatingMenu } from './FloatingMenu'; import { DictationControl } from './DictationControl'; import { Btn, Dialog, Icon, ErrorNotice } from './ui'; import { MOD } from '../lib/commands'; -import { setChatPreferences, useStore } from '../lib/store'; +import { pushToast, setChatPreferences, useStore } from '../lib/store'; import { artifactFromUrl, type PreviewArtifact } from '../lib/artifacts'; import type { ChatMode, Session } from '../lib/types'; import { attachChatPhoto } from '../lib/chat-photos'; +import { uploadChatFile, FILE_ACCEPT } from '../lib/chat-attach-file'; import { useNative } from '../lib/native'; import { pictureStatus } from '../lib/pictures'; const modes: { @@ -91,6 +92,12 @@ export function ComposerControls({ session, onPreview, onAttach, onError, onSlas await attachChatPhoto(file, session?.id); continue; } + if (!directory && session?.id && /\.pdf$/i.test(file.name) && file.size <= 12 * 1024 * 1024) { + // A PDF goes to the chat's folder and is named in the next message; "Open a file" still previews it. + const saved = await uploadChatFile(file, session.id); + pushToast('success', 'PDF added', `${saved.name} is in this chat. Ask about it in your next message.`); + continue; + } if (!directory && (photoTypes.test(file.name) || /\.pdf$/i.test(file.name))) { await openFile(file); if (photoTypes.test(file.name)) @@ -157,7 +164,7 @@ export function ComposerControls({ session, onPreview, onAttach, onError, onSlas return <> {tr(!remoteModel && nativeModel?.metrics?.mcp?.servers?.length ? : null)} setToolsOpen(false)} actions={<> setToolsOpen(false)}>{tr("Keep tools off")} { setChatPreferences(session?.id, { useTools: true, mode: 'bypass' }); setToolsOpen(false); }}>{tr("Enable tools")}}>

{tr("Connected servers can act on the resources you configured. Calls run automatically when the model chooses them, and their results appear in chat.")}

{tr("This switches this conversation to Bypass permissions. Servers: ")}{tr((nativeModel?.metrics?.mcp?.servers ?? []).map((s: any) => s.name).join(', '))}.

- { void addFiles(Array.from(e.target.files ?? [])); e.target.value = ''; }}/> + { void addFiles(Array.from(e.target.files ?? [])); e.target.value = ''; }}/> { void addFiles(Array.from(e.target.files ?? []), true); e.target.value = ''; }}/> { void openFile(e.target.files?.[0]); e.target.value = ''; }}/> diff --git a/apps/host/src/components/DecimalInput.tsx b/apps/host/src/components/DecimalInput.tsx new file mode 100644 index 00000000..e48f9689 --- /dev/null +++ b/apps/host/src/components/DecimalInput.tsx @@ -0,0 +1,28 @@ +import { useEffect, useState } from 'react'; +import { parseDecimal, partialDecimal } from '../lib/decimal'; + +/** A number field that lets the person type a decimal point: it keeps the text while it is typed and tells the page the number once it is one (#3736). */ +export function DecimalInput({ value, onChange, ariaLabel, className = 'st-input', placeholder, disabled }: { + value: number | null | undefined; + onChange: (value: number | null) => void; + ariaLabel: string; + className?: string; + placeholder?: string; + disabled?: boolean; +}) { + const [text, setText] = useState(value === null || value === undefined ? '' : String(value)); + // A change that came from elsewhere (Restore saved, another tab) replaces the text, but never while the typed text already means this number. + useEffect(() => { + const shown = text === '' ? null : parseDecimal(text); + if ((value ?? null) !== shown) setText(value === null || value === undefined ? '' : String(value)); + }, [value]); + return { + const next = e.target.value; + if (!partialDecimal(next)) return; + setText(next); + if (next.trim() === '') onChange(null); + else { const n = parseDecimal(next); if (n !== null) onChange(n); } + }} + onBlur={() => { const n = text.trim() === '' ? null : parseDecimal(text); setText(n === null ? '' : String(n)); }}/>; +} diff --git a/apps/host/src/components/DropZone.tsx b/apps/host/src/components/DropZone.tsx index c0b1f976..d9a3ed46 100644 --- a/apps/host/src/components/DropZone.tsx +++ b/apps/host/src/components/DropZone.tsx @@ -6,16 +6,7 @@ import { Icon } from './ui'; /** Files dropped on the chat go where the attach button would put them: the composer reads the 'strata:drop-files' event. */ export const DROP_EVENT = 'strata:drop-files'; -/** The pictures on the clipboard, named so each one is told apart in the composer (a pasted screenshot arrives as "image.png"). */ -export function pastedFiles(data: DataTransfer | null | undefined): File[] { - const out: File[] = []; - for (const file of Array.from(data?.files ?? [])) { - if (!file.type.startsWith('image/')) continue; - const extension = file.type.split('/')[1]?.replace('jpeg', 'jpg').replace(/[+].*/, '') || 'png'; - out.push(new File([file], `Pasted picture ${new Date().toLocaleTimeString().replace(/[^0-9]+/g, '-').replace(/-$/, '')}${out.length ? `-${out.length + 1}` : ''}.${extension}`, { type: file.type })); - } - return out; -} +export { pastedFiles } from '../lib/pasted-files'; const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files'); /** A file dropped outside the chat must not take the window to that file: the page ignores it (called once at start). */ diff --git a/apps/host/src/components/Markdown.tsx b/apps/host/src/components/Markdown.tsx index 996b191f..1750d40b 100644 --- a/apps/host/src/components/Markdown.tsx +++ b/apps/host/src/components/Markdown.tsx @@ -47,6 +47,15 @@ function inline(text: string, onOpenLink?: (url: string) => void, imageSession?: : {inlineMarks(part.text, onOpenLink, imageSession)})}; }); } +/** Does this line continue the paragraph above it, or does it start a block of its own? */ +export function continuesParagraph(lines: string[], at: number): boolean { + const line = lines[at]; + if (!line.trim() || /^\s*```/.test(line) || /^(#{1,6})\s+(.+)$/.test(line) || /^\s*[-*+]\s+\S/.test(line) || /^\s*\d+[.)]\s+\S/.test(line) || /^>\s?/.test(line)) + return false; + if (line.includes('|') && at + 1 < lines.length && /^\s*\|?\s*:?-{3,}/.test(lines[at + 1])) + return false; + return !displayBlock(lines, at); +} export function Markdown({ text, onOpenLink, onPreviewHtml, imageSession }: { text: string; onOpenLink?: (url: string) => void; @@ -113,8 +122,19 @@ export function Markdown({ text, onOpenLink, onPreviewHtml, imageSession }: { i++; continue; } - nodes.push(

{tr(inline(line, onOpenLink, imageSession))}

); + // One paragraph: a single newline inside it is a soft break (a space); two spaces or a backslash at the end of a line is a hard break (#3818). + const key = i, parts: ReactNode[] = []; + let current = line; i++; + while (true) { + const hard = /( {2,}|\\)$/.test(current); + parts.push({tr(inline(current.replace(/( {2,}|\\)$/, ''), onOpenLink, imageSession))}); + if (i >= lines.length || !continuesParagraph(lines, i)) + break; + parts.push(hard ?
: ' '); + current = lines[i++].trimStart(); + } + nodes.push(

{tr(parts)}

); } return <>{tr(nodes)}; } diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 9523827c..4bf16382 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -204,7 +204,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(expert && IMAGE_GENERATION_VISIBLE ? <>
{tr("Image generation ")}{tr("Optional")} { }}/>
: null)} {tr(expert ?

{tr("Expert settings")}

{tr(tunedNow ?

{tr("Showing the values of your tuning '{0}'.", [tunedNow.name])}

: null)}
: null)} - + !pending && setPlan(null)} actions={<> setPlan(null)}>{tr("Cancel")} void download()}>{tr(installed?.ready ? "Apply & load" : "Download & load")}}>

{tr(plan?.plan?.title ?? selectedFamily?.title)}{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")})}

{tr(plan?.drafting?.needed ?

{tr("Choosing DFlash2 also downloads its drafter: about {0} GB, once. If it does not fit in graphics memory, the model uses the MTP instead.", [plan.drafting.gb])}

: null)}{tr(installed?.ready ?

{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}

: null)}{tr(plan?.plan?.disk_short ? : null)}{tr(installed?.ready ?

{tr("Any currently loaded native models will be unloaded first.")}

: <>

{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}

{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}

)}{tr(selectedSize?.images ?

{tr("Vision encoder files are included. Picture reading loads only when enabled.")}

: null)}
diff --git a/apps/host/src/components/NativeSettings.tsx b/apps/host/src/components/NativeSettings.tsx index 8b1e39bb..53eac3e6 100644 --- a/apps/host/src/components/NativeSettings.tsx +++ b/apps/host/src/components/NativeSettings.tsx @@ -1,3 +1,4 @@ +import { DecimalInput } from './DecimalInput'; import { tr } from '../lib/i18n'; import {nativeSettingsResponse,nativeSettingsValues} from '../lib/native-settings-response'; import { describeChange, type TunedChange } from '../lib/tune-values'; @@ -92,14 +93,7 @@ export function NativeSettings({ model }: { ; const rows = (native?.fields ?? []).filter(f => `${tr(f.label)} ${f.id} ${tr(f.group)}`.toLowerCase().includes(query.toLowerCase())); return
{tr("Native engine settings")}{tr(tuned?.changed?.length ?

{tr("Your tuning '{0}' sets", [tuned.preset?.name ?? ''])}

    {tuned.changed.map(c => { const d = describeChange(c); return
  • {d.name}{d.now || tr('off')}{d.was !== null ? {tr("was {0}", [d.was])} : null}
  • ; })}
: null)}

{tr(!original ? 'Reading saved settings… ' : '')}{tr("Settings for this model. Blank values use Strata\u2019s defaults.")}

{tr(['fields', 'json', 'tools'].map(t => ))}
- {tr(tab === 'fields' ? <> setQuery(e.target.value)}/>{tr(['Responses', 'GPU & memory', 'Serving', 'Image reading', 'Tools', 'Recovery'].map(group => rows.some(f => f.group === group) ?

{tr(group)}

{tr(rows.filter(f => f.group === group).map(f => ))}
: null))}

{tr("Sampling")}

{tr([['temperature', 'Temperature'], ['top_p', 'Top-p'], ['top_k', 'Top-k'], ['min_p', 'Min-p'], ['repetition_penalty', 'Repetition penalty'], ['presence_penalty', 'Presence penalty'], ['frequency_penalty', 'Frequency penalty'], ['penalty_last_n', 'Penalty window'], ['seed', 'Seed']].map(([id, label]) => ))}
: tab === 'json' ? <>

{tr("Engine arguments and STRATA environment flags are editable here. Program paths and network access remain managed by the host.")}