Merge f-0243-guifix into f-0243-rel

This commit is contained in:
Niko1221 committed 2026-10-24 15:44:30 +02:00
commit 9caf39495c
52 files changed
+1523 -63

No files matched your search

+385
View File
@@ -0,0 +1,385 @@
"""Writes src/locales/fix-<lang>.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")
+5
View File
@@ -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`)) {
+4 -1
View File
@@ -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 })); });
});
}
+7 -5
View File
@@ -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;});
+3 -3
View File
@@ -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;
}
+38 -7
View File
@@ -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};
};
+90
View File
@@ -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<high>_0x<low> 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 <luid> <load percent> <dedicated bytes in use>". */
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);
}
+45
View File
@@ -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;
}
+4 -2
View File
@@ -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() {
<button ref={trigger} className="chat-model-badge chat-model-picker" aria-label={tr("Choose model: {0}", [apiModel?.name ?? (running?.local ? running.name : running?.family) ?? 'No model loaded'])} title={tr(apiModel ? `${connection?.name} · ${apiModel.id}` : 'View and switch models')} disabled={!library && !providers} aria-haspopup="menu" aria-expanded={open} onClick={() => setOpen(v => !v)}><Icon name={apiModel ? 'link' : modelFamilyIcon(running?.family ?? groups[0]?.family)} size={16}/><span>{tr(apiModel?.name ?? (running?.local ? running.name : running?.family) ?? groups[0]?.family ?? 'No model loaded')}</span><Icon name="chevron" size={12}/></button>
{tr(open ? <FloatingMenu anchor={trigger.current} title={tr("Models")} width={380} onClose={() => setOpen(false)}>
{tr(native?.instances.filter(i => i.status !== 'error').map(i => <button key={i.id} className="menu__item" role="menuitem" disabled={streaming || i.status !== 'ready'} onClick={() => void nativeAction(`instances/${i.id}/default`).then(() => { selectRemoteModel(null); setOpen(false); }).catch(e => setError(e.message))}><Icon name="models"/><span>{tr(i.label)}<small>{tr(i.gpus.map(g => `GPU ${g + 1}`).join(" + ") || "Automatic GPU")}</small></span></button>))}<p className="model-picker-heading">{tr("Local models")}</p>
{tr(!groups.length ? <p className="model-picker-empty">{tr("No local models downloaded yet.")}</p> : null)}
{tr(installedNative.map(m => <button key={m.config || m.model} className="menu__item" role="menuitem" disabled={streaming} onClick={() => { setOpen(false); go('models'); }}><Icon name="models"/><span>{tr(m.model_name || m.model)}<small>{tr("Downloaded, not loaded. Open Models to load it.")}</small></span></button>))}
{tr(!groups.length && !installedNative.length ? <p className="model-picker-empty">{tr("No local models downloaded yet.")}</p> : 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}`;
@@ -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 ? <button className="composer-choice" aria-label={tr("Use connected MCP tools")} aria-pressed={session?.preferences?.useTools === true} onClick={() => session?.preferences?.useTools ? setChatPreferences(session.id, { useTools: false }) : setToolsOpen(true)}><Icon name="skills" size={16}/>{tr("Tools")}{tr(session?.preferences?.useTools ? ' on' : '')}</button> : null)}
<Dialog open={toolsOpen} compact title={tr("Enable connected tools?")} onClose={() => setToolsOpen(false)} actions={<><Btn onClick={() => setToolsOpen(false)}>{tr("Keep tools off")}</Btn><Btn variant="primary" onClick={() => { setChatPreferences(session?.id, { useTools: true, mode: 'bypass' }); setToolsOpen(false); }}>{tr("Enable tools")}</Btn></>}><p>{tr("Connected servers can act on the resources you configured. Calls run automatically when the model chooses them, and their results appear in chat.")}</p><p className="small muted">{tr("This switches this conversation to Bypass permissions. Servers: ")}{tr((nativeModel?.metrics?.mcp?.servers ?? []).map((s: any) => s.name).join(', '))}.</p></Dialog>
<input ref={files} type="file" multiple hidden accept="image/*,.pdf,.txt,.md,.markdown,.csv,.ts,.tsx,.js,.jsx,.py,.json,.css,.rs,.go,.sh,.html,.htm,.yaml,.yml,.toml,.xml,.log" onChange={e => { void addFiles(Array.from(e.target.files ?? [])); e.target.value = ''; }}/>
<input ref={files} type="file" multiple hidden accept={FILE_ACCEPT} onChange={e => { void addFiles(Array.from(e.target.files ?? [])); e.target.value = ''; }}/>
<input ref={folder} type="file" multiple hidden onChange={e => { void addFiles(Array.from(e.target.files ?? []), true); e.target.value = ''; }}/>
<input ref={previewFile} type="file" hidden onChange={e => { void openFile(e.target.files?.[0]); e.target.value = ''; }}/>
<button ref={trigger} className="composer-add" aria-label={tr("Add or open")} title={tr("Add or open")} disabled={reading || streaming} aria-haspopup="menu" aria-expanded={menu} onClick={() => { setPreferences(null); setMenu(v => !v); }}><Icon name="plus" size={22}/></button>
+28
View File
@@ -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 <input className={className} aria-label={ariaLabel} inputMode="decimal" disabled={disabled} placeholder={placeholder} value={text}
onChange={e => {
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)); }}/>;
}
+1 -10
View File
@@ -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). */
+21 -1
View File
@@ -47,6 +47,15 @@ function inline(text: string, onOpenLink?: (url: string) => void, imageSession?:
: <Fragment key={p}>{inlineMarks(part.text, onOpenLink, imageSession)}</Fragment>)}</Fragment>;
});
}
/** 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(<p key={i}>{tr(inline(line, onOpenLink, imageSession))}</p>);
// 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(<Fragment key={parts.length}>{tr(inline(current.replace(/( {2,}|\\)$/, ''), onOpenLink, imageSession))}</Fragment>);
if (i >= lines.length || !continuesParagraph(lines, i))
break;
parts.push(hard ? <br key={`b${parts.length}`}/> : ' ');
current = lines[i++].trimStart();
}
nodes.push(<p key={key}>{tr(parts)}</p>);
}
return <>{tr(nodes)}</>;
}
+1 -1
View File
@@ -204,7 +204,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
{tr(expert && IMAGE_GENERATION_VISIBLE ? <><details className="native-generation"><summary>{tr("Image generation ")}<span className="muted">{tr("Optional")}</span></summary><RunImageModel library={imageLibrary} disabled={pending || !!active} onChange={() => { }}/></details></> : null)}
{tr(expert ? <section id="native-expert-settings" ref={expertSection} className="st-card native-execution"><h2 className="h4">{tr("Expert settings")}</h2>{tr(tunedNow ? <p className="small muted native-tuned-note">{tr("Showing the values of your tuning '{0}'.", [tunedNow.name])}</p> : null)}<label className="native-toggle"><span><strong>{tr("Run multiple models")}</strong><small>{tr("Loading another model keeps the others loaded.")}</small></span><button className="st-toggle" role="switch" aria-label={tr("Run multiple models")} aria-checked={multiple} onClick={() => setMultiple(v => !v)}/></label>{tr(cardsGpus.length > 1 ? <label className="input-field"><span>{tr("Layer split")}</span><input className="st-input" value={split} placeholder={tr("auto or 16,32")} onChange={e => setSplit(e.target.value)}/></label> : null)}<div className="native-field-grid"><label className="input-field"><span>{tr("Context memory")}</span><Select ariaLabel={tr("Native KV format")} value={kv} options={[{ value: 'int8', label: 'INT8' }, { value: 'q4_0', label: 'Q4' }, { value: 'k8v4', label: 'K8 / V4' }]} onChange={setKv}/></label><label className="input-field"><span>{tr("Low-RAM mode")}</span><Select ariaLabel={tr("Native low RAM mode")} value={lowRam} options={['auto', 'resident', 'mmap'].map(v => ({ value: v, label: v === 'auto' ? 'Automatic' : v === 'resident' ? 'Keep experts in RAM' : 'Read experts from disk' }))} onChange={setLowRam}/></label></div>{tr(installed ? <><NativeSettingsFile model={installed.model}/><NativeSettings model={installed.model}/></> : <p className="small muted">{tr("More engine parameters become available after preparing this version.")}</p>)}</section> : null)}
</div>
<aside className="stack stack--lg"><PcFitCard gpuName={pcGpu?.name} ramGb={pcRam} vramGb={pcVram} inUse={keptModels.length ? { ramGb: Math.round(keptRam), vramGb: Math.round(keptVramOn(chosenCards)) } : null} fit={selectedSize ? fitOn(selectedSize, fitHardware) : null}/><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>
<aside className="stack stack--lg"><PcFitCard gpuName={pcGpu?.name} ramGb={pcRam} vramGb={pcVram} inUse={keptModels.length ? { ramGb: Math.round(keptRam), vramGb: Math.round(keptVramOn(chosenCards)) } : null} fit={selectedSize ? fitOn(selectedSize, fitHardware, true, { context, kv }) : null}/><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(installed?.ready ? "Apply settings and load" : "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(installed?.ready ? "Apply & load" : "Download & load")}</Btn></>}><p><strong>{tr(plan?.plan?.title ?? selectedFamily?.title)}</strong>{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}</>)}</p>{tr(plan?.drafting?.needed ? <p className="small muted">{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])}</p> : null)}{tr(installed?.ready ? <p className="small muted">{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}</p> : null)}{tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)}{tr(installed?.ready ? <p className="small muted">{tr("Any currently loaded native models will be unloaded first.")}</p> : <><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>
+5 -9
View File
@@ -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 }: {
</details>;
const rows = (native?.fields ?? []).filter(f => `${tr(f.label)} ${f.id} ${tr(f.group)}`.toLowerCase().includes(query.toLowerCase()));
return <details className="native-settings"><summary>{tr("Native engine settings")}</summary>{tr(tuned?.changed?.length ? <div className="native-tuned"><p className="small"><strong>{tr("Your tuning '{0}' sets", [tuned.preset?.name ?? ''])}</strong></p><ul>{tuned.changed.map(c => { const d = describeChange(c); return <li key={c.flag}><span>{d.name}</span><b>{d.now || tr('off')}</b>{d.was !== null ? <small className="muted">{tr("was {0}", [d.was])}</small> : null}</li>; })}</ul></div> : null)}<p className="small muted">{tr(!original ? 'Reading saved settings… ' : '')}{tr("Settings for this model. Blank values use Strata\u2019s defaults.")}</p><div className="editor-tabs" role="tablist" aria-label={tr("Native settings editor")}>{tr(['fields', 'json', 'tools'].map(t => <button key={t} role="tab" aria-selected={tab === t} onClick={() => chooseTab(t)}>{tr(t === 'fields' ? 'Parameters' : t === 'json' ? 'JSON' : 'MCP tools')}</button>))}</div>
{tr(tab === 'fields' ? <><input className="st-input" type="search" aria-label={tr("Search native parameters")} placeholder={tr("Search parameters…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(['Responses', 'GPU & memory', 'Serving', 'Image reading', 'Tools', 'Recovery'].map(group => rows.some(f => f.group === group) ? <section className="native-settings-group" key={group}><h3 className="h4">{tr(group)}</h3>{tr(rows.filter(f => f.group === group).map(f => <label className="native-setting-row" key={f.id}><span><strong>{tr(f.label)}</strong>{tr(f.supported === false ? <small>{tr("Requires a newer Strata installation.")}</small> : f.hint ? <small>{tr(f.hint)}</small> : null)}</span><NativeFieldInput field={f} value={values[f.id]} onChange={v => change(f.id, v)}/></label>))}</section> : null))}<section className="native-settings-group"><h3 className="h4">{tr("Sampling")}</h3>{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]) => <label className="native-setting-row" key={id}><span><strong>{tr(label)}</strong></span><input className="st-input" aria-label={tr("Native {0}", [label])} inputMode="decimal" value={values.sampling?.[id] ?? ''} onChange={e => {
const sampling = { ...values.sampling };
if (e.target.value === '')
delete sampling[id];
else
sampling[id] = Number(e.target.value);
change('sampling', sampling);
}}/></label>))}</section></> : tab === 'json' ? <><p className="small muted">{tr("Engine arguments and STRATA environment flags are editable here. Program paths and network access remain managed by the host.")}</p><textarea className="st-input native-json" aria-label={tr("Native configuration JSON")} spellCheck={false} value={text} onChange={e => { setText(e.target.value); setNotice(''); }}/></> : <><p className="small muted">{tr("Add local programs or HTTP MCP servers. Connected tools can read or change the resources you give them access to. Enable tools in chat when you want the model to use them.")}</p><NativeMcpEditor text={mcp} onChange={value => { setMcp(value); setNotice(''); }}/><details><summary className="small">{tr("Configuration example")}</summary><pre className="native-example">{'{\n "files": {\n "command": "npx",\n "args": ["-y", "@modelcontextprotocol/server-filesystem", "/your/folder"],\n "disabled": false\n }\n}'}</pre><p className="xs muted">{tr("Saved credentials are masked. Keep the mask to preserve an existing value; type a new value to replace it.")}</p></details></>)}
{tr(tab === 'fields' ? <><input className="st-input" type="search" aria-label={tr("Search native parameters")} placeholder={tr("Search parameters…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(['Responses', 'GPU & memory', 'Serving', 'Image reading', 'Tools', 'Recovery'].map(group => rows.some(f => f.group === group) ? <section className="native-settings-group" key={group}><h3 className="h4">{tr(group)}</h3>{tr(rows.filter(f => f.group === group).map(f => <label className="native-setting-row" key={f.id}><span><strong>{tr(f.label)}</strong>{tr(f.supported === false ? <small>{tr("Requires a newer Strata installation.")}</small> : f.hint ? <small>{tr(f.hint)}</small> : null)}</span><NativeFieldInput field={f} value={values[f.id]} onChange={v => change(f.id, v)}/></label>))}</section> : null))}<section className="native-settings-group"><h3 className="h4">{tr("Sampling")}</h3>{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]) => <label className="native-setting-row" key={id}><span><strong>{tr(label)}</strong></span><DecimalInput ariaLabel={tr("Native {0}", [label])} value={values.sampling?.[id] ?? null} onChange={n => { const sampling = { ...values.sampling }; if (n === null) delete sampling[id]; else sampling[id] = n; change('sampling', sampling); }}/></label>))}</section></> : tab === 'json' ? <><p className="small muted">{tr("Engine arguments and STRATA environment flags are editable here. Program paths and network access remain managed by the host.")}</p><textarea className="st-input native-json" aria-label={tr("Native configuration JSON")} spellCheck={false} value={text} onChange={e => { setText(e.target.value); setNotice(''); }}/></> : <><p className="small muted">{tr("Add local programs or HTTP MCP servers. Connected tools can read or change the resources you give them access to. Enable tools in chat when you want the model to use them.")}</p><NativeMcpEditor text={mcp} onChange={value => { setMcp(value); setNotice(''); }}/><details><summary className="small">{tr("Configuration example")}</summary><pre className="native-example">{'{\n "files": {\n "command": "npx",\n "args": ["-y", "@modelcontextprotocol/server-filesystem", "/your/folder"],\n "disabled": false\n }\n}'}</pre><p className="xs muted">{tr("Saved credentials are masked. Keep the mask to preserve an existing value; type a new value to replace it.")}</p></details></>)}
<div className="native-settings-actions"><Btn disabled={pending || !original || !dirty} variant="primary" onClick={() => void save()}>{tr(pending ? 'Saving…' : 'Save settings')}</Btn><Btn disabled={pending} onClick={() => { const saved = JSON.parse(original || '{"values":{},"mcp":{}}'); setValues(saved.values); setText(JSON.stringify(saved.values, null, 2)); setMcp(JSON.stringify(saved.mcp, null, 2)); setError(''); }}>{tr("Restore saved")}</Btn></div>{tr(notice ? <p role="status" className="small">{tr(notice)}</p> : null)}{tr(error ? <ErrorNotice message={error} onRetry={() => setRevision(value => value + 1)}/> : null)}
</details>;
}
@@ -114,7 +108,9 @@ function NativeFieldInput({ field, value, onChange }: {
return <Select disabled={field.supported === false} ariaLabel={tr(field.label)} value={value === null || value === undefined ? '' : String(value)} options={[{ value: '', label: 'Default' }, { value: 'true', label: 'On' }, { value: 'false', label: 'Off' }]} onChange={v => onChange(v === '' ? null : v === 'true')}/>;
if (field.type === 'enum')
return <Select disabled={field.supported === false} ariaLabel={tr(field.label)} value={value ?? ''} options={[{ value: '', label: 'Default' }, ...(field.choices ?? []).map(v => ({ value: v, label: v }))]} onChange={v => onChange(v || null)}/>;
return <input disabled={field.supported === false} className="st-input" aria-label={tr(field.label)} inputMode={field.type === 'number' ? 'numeric' : undefined} placeholder={tr("Default")} value={Array.isArray(value) ? value.join(', ') : value ?? ''} onChange={e => onChange(e.target.value === '' ? null : field.type === 'array' ? e.target.value.split(',').map(s => s.trim()).filter(Boolean) : field.type === 'number' ? Number(e.target.value) : e.target.value)}/>;
if (field.type === 'number')
return <DecimalInput disabled={field.supported === false} ariaLabel={tr(field.label)} placeholder={tr("Default")} value={value === null || value === undefined || value === '' || !Number.isFinite(Number(value)) ? null : Number(value)} onChange={onChange}/>;
return <input disabled={field.supported === false} className="st-input" aria-label={tr(field.label)} placeholder={tr("Default")} value={Array.isArray(value) ? value.join(', ') : value ?? ''} onChange={e => onChange(e.target.value === '' ? null : field.type === 'array' ? e.target.value.split(',').map(s => s.trim()).filter(Boolean) : field.type === 'number' ? Number(e.target.value) : e.target.value)}/>;
}
function NativeAliases({ field, value, onChange }: {
field: NativeField;
+13 -2
View File
@@ -8,9 +8,20 @@ export function OnboardingMemory({ hardware, native }: {
hardware: Hardware | null;
native: NativeState['hardware'] | undefined;
}) {
const gpus = hardware ? hardware.gpus.filter(gpu => gpu.backend !== 'cpu').map(gpu => ({ id: gpu.id ?? String(gpu.index), name: gpu.name, memory: gpu.vramGb, shared: gpu.unified })) : native?.gpus.map(gpu => ({ id: String(gpu.index), name: gpu.name, memory: gpu.vram_gb, shared: false })) ?? [];
// The Windows host probe (Win32_VideoController) cannot read the VRAM of AMD cards and reports 0 for them; the engine's own list has
// the real size. For a dedicated card the host reports as 0, take the engine's figure for the card of the same name, or for the
// card in the same position when both lists have the same length. A card the engine does not list stays at 0.
const nativeGpus = native?.gpus ?? [];
const hostGpus = hardware ? hardware.gpus.filter(gpu => gpu.backend !== 'cpu') : [];
const engineVram = (name: string, position: number) => {
const norm = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
const byName = nativeGpus.find(g => norm(g.name).includes(norm(name)) || norm(name).includes(norm(g.name)));
return (byName ?? (nativeGpus.length === hostGpus.length ? nativeGpus[position] : undefined))?.vram_gb || 0;
};
const gpus = hardware ? hostGpus.map((gpu, position) => ({ id: gpu.id ?? String(gpu.index), name: gpu.name, memory: gpu.unified || gpu.vramGb > 0 ? gpu.vramGb : engineVram(gpu.name, position), shared: gpu.unified })) : nativeGpus.map(gpu => ({ id: String(gpu.index), name: gpu.name, memory: gpu.vram_gb, shared: false }));
const dedicatedCount = gpus.filter(gpu => !gpu.shared).length;
const memory = hardware ? memoryInventory(hardware) : native ? { ram: native.ram_gb, vram: native.gpus.reduce((sum, gpu) => sum + Math.max(0, gpu.vram_gb || 0), 0), total: 0, shared: false } : null;
const base = hardware ? memoryInventory(hardware) : null;
const memory = base ? (base.shared ? base : { ...base, vram: gpus.reduce((sum, gpu) => sum + (gpu.shared ? 0 : Math.max(0, gpu.memory || 0)), 0) }) : native ? { ram: native.ram_gb, vram: native.gpus.reduce((sum, gpu) => sum + Math.max(0, gpu.vram_gb || 0), 0), total: 0, shared: false } : null;
if (!memory)
return <div className="onboard-hardware" role="group" aria-label={tr("Computer memory")}><div className="onboard-memory-intro"><Icon name="memory" size={18}/><span>{tr("Reading memory\u2026")}</span></div></div>;
const total = memory.ram + memory.vram;
+11
View File
@@ -0,0 +1,11 @@
/** A file that is not a picture or plain text (a PDF) is saved by the host in the chat's folder and named in the next message, so the assistant can open it (#3838). */
export async function uploadChatFile(file: File, sessionId: string, fetchFn: typeof fetch = fetch): Promise<{ name: string }> {
const host = (globalThis as { __STRATA_HOST__?: string }).__STRATA_HOST__ ?? '';
const res = await fetchFn(`${host}/api/chat/upload?sessionId=${encodeURIComponent(sessionId)}&name=${encodeURIComponent(file.name)}`, { method: 'POST', headers: { 'content-type': file.type || 'application/octet-stream' }, body: file });
const data = await res.json().catch(() => ({})) as { files?: { name: string; attached?: boolean }[]; error?: string };
if (!res.ok) throw new Error(data.error || 'The file could not be added. Try again.');
return { name: data.files?.find(f => f.attached)?.name ?? file.name };
}
/** Types the Linux file dialog needs next to the extensions (WebKitGTK reads only the type part of `accept`). */
export const FILE_ACCEPT = 'image/*,application/pdf,text/*,application/json,application/xml,.pdf,.txt,.md,.markdown,.csv,.ts,.tsx,.js,.jsx,.py,.json,.css,.rs,.go,.sh,.html,.htm,.yaml,.yml,.toml,.xml,.log';
+35
View File
@@ -0,0 +1,35 @@
/**
* Copy text for the person. The browser clipboard call can be refused (the desktop web view asks for permission, or has no clipboard
* object); the older copy command through a hidden field still works there. The answer is always a toast: "Copied", or one plain
* sentence and what to do next (#3731).
*/
export interface ClipboardDeps {
clipboard?: { writeText(text: string): Promise<void> } | null;
legacyCopy?: (text: string) => boolean;
toast: (tone: 'success' | 'warn', title: string, body?: string) => void;
}
function legacyCopy(text: string): boolean {
if (typeof document === 'undefined') return false;
const field = document.createElement('textarea');
field.value = text;
field.setAttribute('readonly', '');
field.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
document.body.appendChild(field);
const active = document.activeElement as HTMLElement | null;
try {
field.select();
return document.execCommand('copy');
} catch { return false; }
finally { field.remove(); active?.focus?.(); }
}
export async function copyText(text: string, label: string, deps: ClipboardDeps): Promise<boolean> {
const clipboard = deps.clipboard === undefined ? (typeof navigator === 'undefined' ? null : navigator.clipboard) : deps.clipboard;
let done = false;
try { if (clipboard) { await clipboard.writeText(text); done = true; } } catch { /* the fallback is next */ }
if (!done) { try { done = (deps.legacyCopy ?? legacyCopy)(text); } catch { done = false; } }
if (done) deps.toast('success', 'Copied', label);
else deps.toast('warn', 'Couldn’t copy', 'Select the text and copy it with Ctrl+C.');
return done;
}
+9
View File
@@ -0,0 +1,9 @@
/** A number typed by a person: "0.95", ".95", "0,95" (a comma is a decimal point in many languages). null while it is not a whole number yet ("", ".", "0.", "-"). */
export function parseDecimal(text: string): number | null {
const t = String(text ?? '').trim().replace(',', '.');
if (!/^-?(\d+\.?\d*|\.\d+)$/.test(t) || t.endsWith('.')) return null;
const n = Number(t);
return Number.isFinite(n) ? n : null;
}
/** Whether what is typed could still become a number: the field keeps it while the person is in the middle of "0." */
export const partialDecimal = (text: string) => /^-?\d*[.,]?\d*$/.test(String(text ?? '').trim());
+12 -3
View File
@@ -15,6 +15,14 @@ import tools_es from '../locales/tools-es.json';
import tools_ru from '../locales/tools-ru.json';
import tools_pt from '../locales/tools-pt.json';
import tools_ko from '../locales/tools-ko.json';
import fix_en from '../locales/fix-en.json';
import fix_zh from '../locales/fix-zh.json';
import fix_ja from '../locales/fix-ja.json';
import fix_de from '../locales/fix-de.json';
import fix_es from '../locales/fix-es.json';
import fix_ru from '../locales/fix-ru.json';
import fix_pt from '../locales/fix-pt.json';
import fix_ko from '../locales/fix-ko.json';
import base_zh from '../locales/zh.json';
import base_ja from '../locales/ja.json';
import base_de from '../locales/de.json';
@@ -27,8 +35,9 @@ export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文
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. */
/* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-<lang>.json for the same reason. */
const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en};
const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh,...tools_zh},{...base_ja,...tune_ja,...tools_ja},{...base_de,...tune_de,...tools_de},{...base_es,...tune_es,...tools_es},{...base_ru,...tune_ru,...tools_ru},{...base_pt,...tune_pt,...tools_pt},{...base_ko,...tune_ko,...tools_ko}] as Record<string,string>[];
/* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-<lang>.json (scripts/make-fix-locales.py). */
const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en};
const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja},{...base_de,...tune_de,...tools_de,...fix_de},{...base_es,...tune_es,...tools_es,...fix_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt},{...base_ko,...tune_ko,...tools_ko,...fix_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);
@@ -45,7 +54,7 @@ const patterns=Object.entries(english).filter(([,value])=>/\{\d+\}/.test(value))
expression+=escape(value.slice(at));
return{id,slots,pattern:new RegExp('^'+expression+'$'),specificity:value.replace(/\{\d+\}/g,'').length};
}).sort((a,b)=>b.specificity-a.specificity);
const localizedTemplateSlots:Record<string,number[]>={s2473:[1,2],s0825:[0,1],s2455:[0],s2456:[0],s7400:[1]};
const localizedTemplateSlots:Record<string,number[]>={s1242:[0],s2473:[1,2],s0825:[0,1],s2455:[0],s2456:[0],s7400:[1]};
/** Translate interface copy only. Non-string React children pass through unchanged. */
export function tr<T>(value:T,values?:readonly unknown[]):T{
+6
View File
@@ -22,3 +22,9 @@ export function pickerGroups(library: ModelLibrary) {
}
return Array.from(groups, ([family, versions]) => ({ family, versions }));
}
/** Optimized models that are on this PC but not loaded yet: the chat picker must list them, or it says "none downloaded" while Storage shows them (#3814). */
export function pickerNativeModels<M extends { model: string; model_name?: string; ready?: boolean }>(installed: M[] | undefined | null, instances: { label: string }[] | undefined | null): M[] {
const loaded = new Set((instances ?? []).map(i => i.label));
return (installed ?? []).filter(m => m.ready !== false && !loaded.has(m.model_name ?? m.model));
}
+14 -3
View File
@@ -30,16 +30,27 @@ export function memoryNeeded(v: FitInput): number {
return round1((v.experts_gb ?? v.ram_needed_gb ?? 0) + DENSE_EXTRA_GB);
}
export function fitOn(v: FitInput, hw: FitHardware | null | undefined, mtp = true): Fit {
/** The conversation cache of Flash-Next: 13 attention layers, bytes per token per layer by cache format, 5.4% over the bare cache
* (strata_control/vram_fit.py KV_BYTES, KV_MEASURED_FACTOR; setup.py UD_FIT_KV_BYTES). */
const KV_BYTES: Record<string, number> = { fp16: 2112, int8: 1056, q4_0: 576, k8v4: 816 };
const KV_LAYERS = 13, KV_FACTOR = 1.054, BASE_CONTEXT = 32768;
export function cacheGb(context: number, kv = 'int8'): number {
return (121 + context * KV_LAYERS * (KV_BYTES[String(kv).toLowerCase()] ?? KV_BYTES.int8) * KV_FACTOR / 2 ** 20) / 1024; // 121 MiB fixed per session
}
export interface CacheChoice { context: number; kv?: string }
export function fitOn(v: FitInput, hw: FitHardware | null | undefined, mtp = true, cache?: CacheChoice | null): Fit {
const memoryGb = memoryNeeded(v);
// DENSE_GB already holds a 32K cache in the default format; the person's context and format replace it (#3832).
const denseGb = cache && cache.context > 0 ? Math.max(DENSE_GB - cacheGb(BASE_CONTEXT), 0) + cacheGb(cache.context, cache.kv) : DENSE_GB;
const ram = Number(hw?.ram_gb), vram = Number(hw?.vram_gb) || 0;
if (!Number.isFinite(ram) || ram <= 0) return { memoryGb, vramUseGb: 0, ramUseGb: 0, spillGb: 0, known: false };
const experts = Math.max(0, memoryNeeded(v) - DENSE_EXTRA_GB);
const onGpu = Math.max(0, Math.min(experts, vram - DENSE_GB - (mtp && vram > 0 ? MTP_VRAM_GB : 0)));
const onGpu = Math.max(0, Math.min(experts, vram - denseGb - (mtp && vram > 0 ? MTP_VRAM_GB : 0)));
const ramRoom = Math.max(0, ram - SYSTEM_ROOM_GB);
const spillGb = Math.max(0, experts - onGpu - ramRoom);
const inRam = Math.max(0, experts - onGpu - spillGb);
const vramUseGb = vram > 0 ? Math.min(vram, DENSE_GB + (mtp ? MTP_VRAM_GB : 0) + onGpu) : 0;
const vramUseGb = vram > 0 ? Math.min(vram, denseGb + (mtp ? MTP_VRAM_GB : 0) + onGpu) : 0;
return { memoryGb, vramUseGb: round1(vramUseGb), ramUseGb: round1(inRam + DENSE_EXTRA_GB * (vram > 0 ? 0 : 1)), spillGb: round1(spillGb), known: true };
}
+5 -1
View File
@@ -15,6 +15,10 @@ export interface NativeState {
visionReader?: boolean;available:boolean;repo:string;downloadDirectory?:string;/** Free bytes on the drive that holds the models folder. */downloadFreeBytes?:number|null;downloadTotalBytes?:number|null;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;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';/** The Drafting choice saved with the model: auto | mtp | dflash2 | off. */drafting?:string;dataFolder?:string;diskGb?:number;diskBytes?:number;/** Files this model shares with another (the picture reader, the draft layer): counted once, in `usage`. */sharedBytes?:number;/** What Delete frees: files in Strata's own folders that no other model uses. */removableGb?:number;missing_files?:string[]}[];/** What all models take on disk, from their real files, shared files counted once. */usage?:{total_bytes:number;total_gb:number;shared_bytes:number;shared_gb:number;models:Record<string,{bytes:number;gb:number}>}|null;data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;engine_vendor?:string;gpus:{index:number;name:string;vram_gb:number;usable:boolean;/** SMs x clock: only the order between cards matters (strata_control/gpu_roles.py). */speed?:number;vendor?:string;uma?:boolean;integrated?:boolean;unified_gb?:number;problem?:string|null}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{/** The engine serves DFlash2 (Control says): the Drafting choice then offers it. */dflash2?:boolean;responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}}
let state:NativeState|null=null;
const listeners=new Set<()=>void>();
/** True once the first read of the native state has ended, whatever its answer: until then the Models page must not pick a model of its own (#3740). */
let settled=false;
export const nativeSettled=()=>settled;
export function subscribeNative(fn:()=>void){listeners.add(fn);return()=>{listeners.delete(fn);};}
function put(value:NativeState){if(state&&JSON.stringify(state)===JSON.stringify(value))return;state=value;listeners.forEach(fn=>fn());}
/** The host pushes its whole native state (jobs included) at every progress step: the page shows it at once, without waiting for the next poll. */
export function applyNativeEvent(value:unknown){if(value&&typeof value==='object'&&'available' in value&&'jobs' in value)put(value as NativeState);}
@@ -24,7 +28,7 @@ function read(force:boolean):Promise<void>{
// A read that never answers must not freeze the page: after the limit the next poll starts a fresh one.
let stop:ReturnType<typeof setTimeout>|undefined;
const limit=new Promise<never>((_,reject)=>{stop=setTimeout(()=>reject(new Error('The host did not answer in time.')),READ_LIMIT_MS);});
return Promise.race([request,limit]).then(put).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>clearTimeout(stop));
return Promise.race([request,limit]).then(put).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>{clearTimeout(stop);if(!settled){settled=true;listeners.forEach(fn=>fn());}});
}
/* Two kinds of read that never wait for each other: the light poll (the host answers at once with the jobs it holds) and the forced read after an action (the host
re-reads the installation, which can take many seconds while a download is writing). A slow forced read used to hold every later poll, so a running download looked stuck. */
+19
View File
@@ -0,0 +1,19 @@
/** 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[] = [];
const found: File[] = Array.from(data?.files ?? []);
// A screenshot from the clipboard (Win+Shift+S) often comes as an item and not in `files` (#3748).
if (!found.some(f => f.type.startsWith('image/'))) {
for (const item of Array.from(data?.items ?? [])) {
if (item.kind !== 'file' || !item.type.startsWith('image/')) continue;
const file = item.getAsFile();
if (file) found.push(file);
}
}
for (const file of found) {
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;
}
+8
View File
@@ -0,0 +1,8 @@
import type { Session, Workspace } from './types';
/** The workspace a chat was made in: the sidebar groups chats by this same rule (the saved path, or an earlier folder of the workspace). */
export function workspaceIdForSession(workspaces: Workspace[], session: Pick<Session, 'workspace'> | null | undefined): string | null {
const path = session?.workspace;
if (!path) return null;
return workspaces.find(w => w.path === path || !!w.aliases?.includes(path))?.id ?? null;
}
+8 -3
View File
@@ -1,3 +1,4 @@
import { workspaceIdForSession } from './session-workspace';
import { plainFailure, plainFailureText } from './plain-errors';
import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase';
import { updateAgent } from './agents';
@@ -721,7 +722,7 @@ export async function bootstrap() {
skills,
workspacePath: workspaceState.workspaces[0]?.path ?? '',
workspaces: workspaceState.workspaces,
activeWorkspace: workspaceState.workspaces.some(w => w.id === state.activeWorkspace) ? state.activeWorkspace : workspaceState.workspaces[0]?.id ?? null,
activeWorkspace: workspaceState.workspaces.some(w => w.id === state.activeWorkspace) ? state.activeWorkspace : workspaceIdForSession(workspaceState.workspaces, state.sessions.find(s => s.id === state.activeSession)) ?? workspaceState.workspaces[0]?.id ?? null,
connection: 'live',
});
applyProviders(providers);
@@ -1104,7 +1105,11 @@ export function continueTaskInNewChat(task: Task) {
}
export function selectSession(id: string) {
set({ activeSession: id });
// A chat comes back in the workspace it was made in, so its next turn runs in the same folder (#3754).
const workspace = workspaceIdForSession(state.workspaces, state.sessions.find(s => s.id === id));
const change = workspace && workspace !== state.activeWorkspace;
set(change ? { activeSession: id, activeWorkspace: workspace } : { activeSession: id });
if (change) void loadWorkspaceFiles();
markRead(id);
}
@@ -1728,7 +1733,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g
// The Mode menu's choice for this chat, read when the turn starts; the host applies it to the agent.
mode:state.sessions.find(s=>s.id===sessionId)?.preferences?.mode??'manual',
// So a skill narrowed to another workspace does not fire here.
workspaceId: state.activeWorkspace,
workspaceId: workspaceIdForSession(state.workspaces, state.sessions.find(s => s.id === sessionId)) ?? state.activeWorkspace,
},
(frame) => {
// A line from the app itself carries `key` (the English sentence): shown in the person's language.
+45
View File
@@ -0,0 +1,45 @@
{
"fx01": "wird nicht mehr ausgeführt und entfernt.",
"fx02": "Heruntergeladen, aber nicht geladen. Öffne „Modelle“, um es zu laden.",
"fx03": "{0} Zeilen hinzugefügt, {1} entfernt",
"fx04": "{0} Dateien bearbeitet",
"fx05": "Dateien hier ablegen, um sie hinzuzufügen",
"fx06": "Bilder und Textdateien",
"fx07": "Ziel behalten",
"fx08": "Ziel entfernen",
"fx09": "Der Assistent arbeitet nicht mehr darauf hin. Dein Chat und deine Dateien bleiben unverändert.",
"fx10": "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.",
"fx11": "Zeigt die Werte deiner Abstimmung „{0}“.",
"fx12": "Deine Abstimmung „{0}“ setzt",
"fx13": "war {0}",
"fx14": "· {0} RAM",
"fx15": "Die Nachricht wurde nicht abgebrochen",
"fx16": "Zusätzliche Einstellungen für das Programm",
"fx17": "Mit KI entwerfen",
"fx18": "Denkzeit",
"fx19": "Schreibzeit",
"fx20": "Token/s",
"fx21": "% des Kontexts",
"fx22": "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.",
"fx23": "A behalten",
"fx24": "B behalten",
"fx25": "Dauer",
"fx26": "Schwankung",
"fx27": "Geändert",
"fx28": "Nichts",
"fx29": "Beide Versionen sind fertig. Vergleiche A und B und behalte eine.",
"fx30": "Der Assistent antwortet noch",
"fx31": "Sende deine Nachricht, wenn er fertig ist.",
"fx32": "Die Nachricht wurde nicht eingereiht",
"fx33": "Zur neuesten Nachricht scrollen",
"fx34": "Aufgabe entfernen",
"fx35": "Neue Unterhaltung beginnen; diese bleibt erhalten",
"fx36": "Der Assistent schreibt zuerst einen Plan; nichts läuft, bis du ihn freigibst",
"fx37": "Im Web suchen, die Seiten lesen und mit Quellen antworten",
"fx38": "Kopiert",
"fx39": "Antwort",
"fx40": "Nachricht",
"fx41": "PDF hinzugefügt",
"fx42": "Markiere den Text und kopiere ihn mit Strg+C.",
"fx43": "{0} ist in diesem Chat. Frag in deiner nächsten Nachricht danach."
}
+45
View File
@@ -0,0 +1,45 @@
{
"fx01": "will stop running and be removed.",
"fx02": "Downloaded, not loaded. Open Models to load it.",
"fx03": "{0} lines added, {1} removed",
"fx04": "Edited {0} files",
"fx05": "Drop files to add them",
"fx06": "Pictures and text files",
"fx07": "Keep goal",
"fx08": "Remove goal",
"fx09": "The assistant stops working towards it. Your chat and files stay as they are.",
"fx10": "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.",
"fx11": "Showing the values of your tuning '{0}'.",
"fx12": "Your tuning '{0}' sets",
"fx13": "was {0}",
"fx14": "· {0} RAM",
"fx15": "The message was not cancelled",
"fx16": "Extra settings for the program",
"fx17": "Draft it with AI",
"fx18": "Thinking time",
"fx19": "Writing time",
"fx20": "tokens/s",
"fx21": "% of context",
"fx22": "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.",
"fx23": "Keep A",
"fx24": "Keep B",
"fx25": "Took",
"fx26": "Variation",
"fx27": "Changed",
"fx28": "Nothing",
"fx29": "Both versions are ready. Compare A and B, then keep one.",
"fx30": "The assistant is still answering",
"fx31": "Send your message when it has finished.",
"fx32": "The message was not queued",
"fx33": "Scroll to the latest message",
"fx34": "Remove task",
"fx35": "Start a new conversation; keep this one",
"fx36": "Have the assistant write a plan first; nothing runs until you approve it",
"fx37": "Search the web, read the pages and answer with sources",
"fx38": "Copied",
"fx39": "Response",
"fx40": "Message",
"fx41": "PDF added",
"fx42": "Select the text and copy it with Ctrl+C.",
"fx43": "{0} is in this chat. Ask about it in your next message."
}
+45
View File
@@ -0,0 +1,45 @@
{
"fx01": "dejará de ejecutarse y se eliminará.",
"fx02": "Descargado, pero no cargado. Abre Modelos para cargarlo.",
"fx03": "{0} líneas añadidas, {1} eliminadas",
"fx04": "{0} archivos editados",
"fx05": "Suelta los archivos para añadirlos",
"fx06": "Imágenes y archivos de texto",
"fx07": "Mantener el objetivo",
"fx08": "Quitar el objetivo",
"fx09": "El asistente deja de trabajar en ello. Tu chat y tus archivos se quedan como están.",
"fx10": "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.",
"fx11": "Se muestran los valores de tu ajuste «{0}».",
"fx12": "Tu ajuste «{0}» establece",
"fx13": "antes {0}",
"fx14": "· {0} de RAM",
"fx15": "El mensaje no se canceló",
"fx16": "Ajustes adicionales del programa",
"fx17": "Redactar con IA",
"fx18": "Tiempo de pensar",
"fx19": "Tiempo de escribir",
"fx20": "tokens/s",
"fx21": "% del contexto",
"fx22": "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ó.",
"fx23": "Mantener A",
"fx24": "Mantener B",
"fx25": "Tardó",
"fx26": "Variación",
"fx27": "Cambiado",
"fx28": "Nada",
"fx29": "Las dos versiones están listas. Compara A y B y quédate con una.",
"fx30": "El asistente sigue respondiendo",
"fx31": "Envía tu mensaje cuando termine.",
"fx32": "El mensaje no se puso en cola",
"fx33": "Ir al último mensaje",
"fx34": "Quitar tarea",
"fx35": "Empieza una conversación nueva; esta se conserva",
"fx36": "El asistente escribe primero un plan; no se ejecuta nada hasta que lo apruebes",
"fx37": "Busca en la web, lee las páginas y responde con fuentes",
"fx38": "Copiado",
"fx39": "Respuesta",
"fx40": "Mensaje",
"fx41": "PDF añadido",
"fx42": "Selecciona el texto y cópialo con Ctrl+C.",
"fx43": "{0} está en este chat. Pregunta por él en tu próximo mensaje."
}
+45
View File
@@ -0,0 +1,45 @@
{
"fx01": "は停止され、削除されます。",
"fx02": "ダウンロード済みですが、読み込まれていません。「モデル」を開いて読み込んでください。",
"fx03": "{0} 行追加、{1} 行削除",
"fx04": "{0} 個のファイルを編集しました",
"fx05": "ファイルをドロップして追加",
"fx06": "画像とテキストファイル",
"fx07": "目標を残す",
"fx08": "目標を削除",
"fx09": "アシスタントはこの目標に向けた作業をやめます。チャットとファイルはそのまま残ります。",
"fx10": "このモデルは画像を読めますが、ここにインストールされているエンジンにはまだ画像リーダーが含まれていないため、「画像を読む」はオフです。設定 → 情報 でエンジンを更新するとオンにできます。",
"fx11": "チューニング「{0}」の値を表示しています。",
"fx12": "チューニング「{0}」が設定する項目",
"fx13": "変更前: {0}",
"fx14": "· {0} RAM",
"fx15": "メッセージはキャンセルされませんでした",
"fx16": "プログラムの追加設定",
"fx17": "AI で下書きを作成",
"fx18": "思考時間",
"fx19": "執筆時間",
"fx20": "トークン/秒",
"fx21": "% のコンテキスト",
"fx22": "このページはインターネット上のファイルを必要としますが、プレビューでは読み込まれないため、表示が不完全になることがあります。「コードを表示」で書かれた内容をそのまま確認できます。",
"fx23": "A を残す",
"fx24": "B を残す",
"fx25": "所要時間",
"fx26": "ばらつき",
"fx27": "変更点",
"fx28": "なし",
"fx29": "両方のバージョンの準備ができました。A と B を比べて、どちらかを残してください。",
"fx30": "アシスタントはまだ回答中です",
"fx31": "回答が終わってからメッセージを送ってください。",
"fx32": "メッセージは待機列に入りませんでした",
"fx33": "最新のメッセージへスクロール",
"fx34": "タスクを削除",
"fx35": "新しい会話を始めます。今の会話は残ります",
"fx36": "アシスタントにまず計画を書かせます。承認するまで何も実行されません",
"fx37": "ウェブを検索し、ページを読み、出典付きで回答します",
"fx38": "コピーしました",
"fx39": "返信",
"fx40": "メッセージ",
"fx41": "PDF を追加しました",
"fx42": "テキストを選択して Ctrl+C でコピーしてください。",
"fx43": "{0} をこのチャットに追加しました。次のメッセージで質問してください。"
}
+45
View File
@@ -0,0 +1,45 @@
{
"fx01": "실행이 중지되고 제거됩니다.",
"fx02": "다운로드했지만 아직 불러오지 않았습니다. 모델 화면을 열어 불러오세요.",
"fx03": "{0}줄 추가, {1}줄 삭제",
"fx04": "파일 {0}개 편집함",
"fx05": "파일을 놓아서 추가하세요",
"fx06": "그림과 텍스트 파일",
"fx07": "목표 유지",
"fx08": "목표 제거",
"fx09": "어시스턴트가 이 목표를 향한 작업을 멈춥니다. 대화와 파일은 그대로 남습니다.",
"fx10": "이 모델은 그림을 읽을 수 있지만, 여기에 설치된 엔진에는 아직 그림 읽기 기능이 없어서 '그림 읽기'가 꺼져 있습니다. 설정 → 정보에서 엔진을 업데이트하면 켤 수 있습니다.",
"fx11": "튜닝 '{0}'의 값을 보여 줍니다.",
"fx12": "튜닝 '{0}'이(가) 설정하는 항목",
"fx13": "이전 값 {0}",
"fx14": "· RAM {0}",
"fx15": "메시지가 취소되지 않았습니다",
"fx16": "프로그램 추가 설정",
"fx17": "AI로 초안 작성",
"fx18": "생각한 시간",
"fx19": "작성한 시간",
"fx20": "토큰/초",
"fx21": "컨텍스트 %",
"fx22": "이 페이지는 인터넷의 파일을 불러와야 하는데 미리보기는 이를 불러오지 않으므로 불완전하게 보일 수 있습니다. '코드 보기'에서 작성된 내용을 그대로 볼 수 있습니다.",
"fx23": "A 유지",
"fx24": "B 유지",
"fx25": "걸린 시간",
"fx26": "편차",
"fx27": "변경됨",
"fx28": "없음",
"fx29": "두 버전이 모두 준비되었습니다. A와 B를 비교한 뒤 하나를 유지하세요.",
"fx30": "어시스턴트가 아직 답하는 중입니다",
"fx31": "답이 끝나면 메시지를 보내세요.",
"fx32": "메시지가 대기열에 들어가지 않았습니다",
"fx33": "최신 메시지로 이동",
"fx34": "작업 제거",
"fx35": "새 대화를 시작합니다. 이 대화는 그대로 둡니다",
"fx36": "어시스턴트가 먼저 계획을 작성합니다. 승인하기 전에는 아무것도 실행되지 않습니다",
"fx37": "웹을 검색하고 페이지를 읽어 출처와 함께 답합니다",
"fx38": "복사했습니다",
"fx39": "답변",
"fx40": "메시지",
"fx41": "PDF를 추가했습니다",
"fx42": "텍스트를 선택한 뒤 Ctrl+C로 복사하세요.",
"fx43": "{0}이(가) 이 채팅에 있습니다. 다음 메시지에서 물어보세요."
}
+45
View File
@@ -0,0 +1,45 @@
{
"fx01": "vai parar de funcionar e será removido.",
"fx02": "Baixado, mas não carregado. Abra Modelos para carregá-lo.",
"fx03": "{0} linhas adicionadas, {1} removidas",
"fx04": "{0} arquivos editados",
"fx05": "Solte os arquivos para adicioná-los",
"fx06": "Imagens e arquivos de texto",
"fx07": "Manter a meta",
"fx08": "Remover a meta",
"fx09": "O assistente deixa de trabalhar nela. Seu chat e seus arquivos continuam como estão.",
"fx10": "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.",
"fx11": "Mostrando os valores do seu ajuste \"{0}\".",
"fx12": "Seu ajuste \"{0}\" define",
"fx13": "era {0}",
"fx14": "· {0} de RAM",
"fx15": "A mensagem não foi cancelada",
"fx16": "Configurações extras do programa",
"fx17": "Rascunhar com IA",
"fx18": "Tempo de raciocínio",
"fx19": "Tempo de escrita",
"fx20": "tokens/s",
"fx21": "% do contexto",
"fx22": "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.",
"fx23": "Manter A",
"fx24": "Manter B",
"fx25": "Levou",
"fx26": "Variação",
"fx27": "Alterado",
"fx28": "Nada",
"fx29": "As duas versões estão prontas. Compare A e B e mantenha uma.",
"fx30": "O assistente ainda está respondendo",
"fx31": "Envie sua mensagem quando ele terminar.",
"fx32": "A mensagem não entrou na fila",
"fx33": "Ir para a última mensagem",
"fx34": "Remover tarefa",
"fx35": "Começar uma nova conversa; esta continua salva",
"fx36": "O assistente escreve um plano primeiro; nada roda até você aprovar",
"fx37": "Pesquisar na web, ler as páginas e responder com fontes",
"fx38": "Copiado",
"fx39": "Resposta",
"fx40": "Mensagem",
"fx41": "PDF adicionado",
"fx42": "Selecione o texto e copie com Ctrl+C.",
"fx43": "{0} está neste chat. Pergunte sobre ele na próxima mensagem."
}
+45
View File
@@ -0,0 +1,45 @@
{
"fx01": "перестанет работать и будет удалена.",
"fx02": "Скачана, но не загружена. Откройте «Модели», чтобы загрузить её.",
"fx03": "Добавлено строк: {0}, удалено: {1}",
"fx04": "Изменено файлов: {0}",
"fx05": "Перетащите файлы сюда, чтобы добавить",
"fx06": "Картинки и текстовые файлы",
"fx07": "Оставить цель",
"fx08": "Удалить цель",
"fx09": "Ассистент перестанет работать над ней. Ваш чат и файлы останутся как есть.",
"fx10": "Эта модель умеет читать картинки, но установленный здесь движок пока не содержит модуль чтения картинок, поэтому «Читать картинки» выключено. Обновите движок в разделе «Настройки → О программе», чтобы включить.",
"fx11": "Показаны значения вашей настройки «{0}».",
"fx12": "Ваша настройка «{0}» задаёт",
"fx13": "было {0}",
"fx14": "· {0} ОЗУ",
"fx15": "Сообщение не было отменено",
"fx16": "Дополнительные настройки программы",
"fx17": "Набросать с помощью ИИ",
"fx18": "Время размышления",
"fx19": "Время написания",
"fx20": "токенов/с",
"fx21": "% контекста",
"fx22": "Эта страница запрашивает файлы из интернета, а предпросмотр их не загружает, поэтому она может выглядеть неполной. «Показать код» показывает, что именно было написано.",
"fx23": "Оставить A",
"fx24": "Оставить B",
"fx25": "Заняло",
"fx26": "Разброс",
"fx27": "Изменено",
"fx28": "Ничего",
"fx29": "Обе версии готовы. Сравните A и B и оставьте одну.",
"fx30": "Ассистент ещё отвечает",
"fx31": "Отправьте сообщение, когда он закончит.",
"fx32": "Сообщение не поставлено в очередь",
"fx33": "К последнему сообщению",
"fx34": "Удалить задачу",
"fx35": "Начать новый разговор; этот сохраняется",
"fx36": "Ассистент сначала напишет план; ничего не запустится, пока вы его не одобрите",
"fx37": "Искать в интернете, читать страницы и отвечать со ссылками на источники",
"fx38": "Скопировано",
"fx39": "Ответ",
"fx40": "Сообщение",
"fx41": "PDF добавлен",
"fx42": "Выделите текст и скопируйте его клавишами Ctrl+C.",
"fx43": "{0} добавлен в этот чат. Спросите о нём в следующем сообщении."
}
+45
View File
@@ -0,0 +1,45 @@
{
"fx01": "将停止运行并被移除。",
"fx02": "已下载,尚未加载。打开“模型”页面来加载它。",
"fx03": "新增 {0} 行,删除 {1} 行",
"fx04": "已编辑 {0} 个文件",
"fx05": "拖放文件即可添加",
"fx06": "图片和文本文件",
"fx07": "保留目标",
"fx08": "移除目标",
"fx09": "助手将不再朝这个目标工作。你的对话和文件保持不变。",
"fx10": "此模型可以读取图片,但这里安装的引擎还不包含图片读取器,所以“读取图片”已关闭。请在“设置 → 关于”中更新引擎后再开启。",
"fx11": "显示你的调优“{0}”的取值。",
"fx12": "你的调优“{0}”设置了",
"fx13": "原为 {0}",
"fx14": "· {0} 内存",
"fx15": "消息没有被取消",
"fx16": "程序的额外设置",
"fx17": "用 AI 起草",
"fx18": "思考时间",
"fx19": "写作时间",
"fx20": "词元/秒",
"fx21": "% 的上下文",
"fx22": "此页面需要从互联网加载文件,预览不会加载这些文件,所以看起来可能不完整。“查看代码”会显示实际写入的内容。",
"fx23": "保留 A",
"fx24": "保留 B",
"fx25": "用时",
"fx26": "波动",
"fx27": "已更改",
"fx28": "无",
"fx29": "两个版本都已就绪。比较 A 和 B,然后保留其中一个。",
"fx30": "助手仍在回答",
"fx31": "等它回答完再发送你的消息。",
"fx32": "消息没有进入队列",
"fx33": "滚动到最新消息",
"fx34": "移除任务",
"fx35": "开始新对话;保留当前这个",
"fx36": "让助手先写一份计划;在你批准之前不会运行任何内容",
"fx37": "搜索网络、阅读网页,并附上来源作答",
"fx38": "已复制",
"fx39": "回复",
"fx40": "消息",
"fx41": "已添加 PDF",
"fx42": "请选中文字,然后按 Ctrl+C 复制。",
"fx43": "{0} 已在此对话中。请在下一条消息里询问它。"
}
+5 -4
View File
@@ -39,6 +39,7 @@ import { Btn, Icon, IconBtn, ErrorNotice, type IconName } from '../components/ui
import { composerCap, scrollBehavior } from '../lib/responsive';
import { relTime, cx, duration, tokens, tps } from '../lib/format';
import { createSubagentExample, pushToast, setPreviewTabClosed, branchFrom, continueLast, markRead, resolveTool, retryLast, selectSession, rewindTo, sendMessage, stopStreaming, useStore, } from '../lib/store';
import { copyText } from '../lib/clipboard';
import { getSlashCommands } from '../lib/commands';
import { useLocation } from '../lib/router';
import { composerSends } from '../lib/shortcut-bindings';
@@ -616,11 +617,11 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp
const [sentTime, setSentTime] = useState(() => relTime(m.at));
if (m.role === 'user') {
return (<div className="st-msg st-msg--user" onMouseEnter={() => setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}>
<div className="st-bubble">{tr(m.photos?.length ? <ChatPhotos photos={m.photos}/> : null)}{m.markdown ? <Markdown text={m.content} onOpenLink={onOpenLink} imageSession={activeSession}/> : m.content}</div>
<div className="st-bubble">{tr(m.photos?.length ? <ChatPhotos photos={m.photos}/> : null)}{m.markdown ? <Markdown text={m.content} onOpenLink={onOpenLink} imageSession={activeSession}/> : <span className="st-bubble__text">{m.content}</span>}</div>
<div className="st-msg__meta">
<time dateTime={m.at} title={tr(new Date(m.at).toLocaleString(localeTag()))}>{tr(sentTime)}</time>
<span className="st-msg__actions">
<IconBtn name="copy" title={tr("Copy message")} onClick={() => void navigator.clipboard.writeText(m.content)}/>
<IconBtn name="copy" title={tr("Copy message")} onClick={() => void copyText(m.content, 'Message', { toast: pushToast })}/>
<IconBtn name="refresh" title={tr("Rewind to here")} disabled={streaming} onClick={() => {
const prompt = rewindTo(m.id);
if (prompt !== null)
@@ -659,11 +660,11 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp
{tr(!m.streaming && !m.timeSkipId && (m.content || m.error) ? (<div className="st-msg__meta">
<span className="st-msg__actions">
{tr(isLast ? <>
<IconBtn name="copy" title={tr("Copy response")} onClick={() => void navigator.clipboard.writeText(m.content)}/>
<IconBtn name="copy" title={tr("Copy response")} onClick={() => void copyText(m.content, 'Response', { toast: pushToast })}/>
<IconBtn name="refresh" title={tr("Ask again")} onClick={() => void retryLast(m.id)}/>
</> : null)}
<MessageMenu label={tr("More response actions")}>
{tr(!isLast ? <><button role="menuitem" className="menu__item" onClick={() => void navigator.clipboard.writeText(m.content)}>{tr("Copy response")}</button><button role="menuitem" className="menu__item" onClick={() => void retryLast(m.id)}>{tr("Ask again")}</button></> : null)}
{tr(!isLast ? <><button role="menuitem" className="menu__item" onClick={() => void copyText(m.content, 'Response', { toast: pushToast })}>{tr("Copy response")}</button><button role="menuitem" className="menu__item" onClick={() => void retryLast(m.id)}>{tr("Ask again")}</button></> : null)}
{tr(isLast ? <button role="menuitem" className="menu__item" onClick={() => void continueLast()}>{tr("Continue")}</button> : null)}
<button role="menuitem" className="menu__item" onClick={() => branchFrom(m.id)}>{tr("Branch from here")}</button>
{tr(m.tokens || m.tps || m.durationMs ? <p className="xs muted response-stats">{tr(m.tokens ? `${tokens(m.tokens)} tokens` : '')}{tr(m.tps ? ` · ${tps(m.tps)} tok/s` : '')}{tr(m.durationMs ? ` · ${duration(m.durationMs)}` : '')}{tr(m.demo ? ' · Example' : '')}</p> : null)}
+6 -2
View File
@@ -1,5 +1,5 @@
import { tr } from '../lib/i18n';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { ActionError, Btn, Dialog, ErrorNotice, Icon, Select } from '../components/ui';
import { Screen } from '../components/layout';
import { DemoTest } from '../components/EngineExperience';
@@ -24,7 +24,7 @@ import { familyVersion, modelFamilies } from '../lib/model-versions';
import { sizeGb } from '../lib/format';
import { applyImageModel, getState, useLifecycle, loadRuntimeModel, loadVariant, pushToast, restartEngine, saveEngine, selectImageModel, setConfigDraft, useStore, validateEngine } from '../lib/store';
import type { ImageModelChoice, RuntimeModels, RuntimeModel } from '../lib/types';
import { useNative } from '../lib/native';
import { useNative, nativeSettled, subscribeNative } from '../lib/native';
import { NativeModels } from '../components/NativeModels';
import { NativeLocalModel } from '../components/NativeLocalModel';
import { parseLocation } from '../lib/router';
@@ -35,8 +35,12 @@ type Issue = {
type RunStage = 'idle' | 'checking' | 'loading' | 'ready';
export function ModelRunScreen() {
const native = useNative();
const settled = useSyncExternalStore(subscribeNative, nativeSettled);
const location = parseLocation(window.location.hash), entry = location.param;
const [other, setOther] = useState(entry === 'local' || entry === 'local-import'), [importFirst, setImportFirst] = useState(entry === 'local-import');
// Before the engine's answer arrives the page would show the bundled Starter and then jump to the installed model (#3740): show a neutral placeholder instead.
if (!native && !settled)
return <div className="main__body"><div className="wrap stack" role="status" aria-label={tr("Loading…")}><div className="skel" style={{ height: 20, width: '60%' }}/><div className="skel" style={{ height: 20, width: '80%' }}/><div className="skel" style={{ height: 20, width: '70%' }}/></div></div>;
if (native && other)
return <NativeLocalModel onBack={() => { setOther(false); setImportFirst(false); }}/>;
if (native && !other)
+3
View File
@@ -7517,3 +7517,6 @@ textarea {
.md-math-block .md-math--display { margin: 0; }
.md-math .katex { font-size: 1.08em; }
.md-math .katex-display { margin: 0; }
/* A message the person typed keeps its line breaks (#3720). */
.st-bubble__text { white-space: pre-wrap; overflow-wrap: anywhere; }
+22
View File
@@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { transform } from 'esbuild';
const { code } = await transform(await readFile(new URL('../src/lib/chat-attach-file.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' });
const { uploadChatFile, FILE_ACCEPT } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
test('the file dialog lists PDFs and text on Linux: the types sit next to the extensions (#3838)', () => {
for (const t of ['image/*', 'application/pdf', 'text/*', '.pdf', '.md']) assert.ok(FILE_ACCEPT.split(',').includes(t), t);
});
test('a PDF is sent to the chat folder through the upload route and named back', async () => {
let seen;
const fake = async (url, init) => { seen = { url, init }; return { ok: true, json: async () => ({ files: [{ name: 'report-2.pdf', attached: true }] }) }; };
const out = await uploadChatFile(new File(['%PDF-1.4'], 'report.pdf', { type: 'application/pdf' }), 's 1', fake);
assert.equal(out.name, 'report-2.pdf');
assert.match(seen.url, /\/api\/chat\/upload\?sessionId=s%201&name=report\.pdf$/);
assert.equal(seen.init.method, 'POST'); assert.equal(seen.init.headers['content-type'], 'application/pdf');
});
test('a refused upload says why', async () => {
await assert.rejects(uploadChatFile(new File(['x'], 'a.pdf'), 's', async () => ({ ok: false, json: async () => ({ error: '"a.pdf" is bigger than 12 MB.' }) })), /bigger than 12 MB/);
});
+30
View File
@@ -0,0 +1,30 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { transform } from 'esbuild';
const { code } = await transform(await readFile(new URL('../src/lib/clipboard.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' });
const { copyText } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const toasts = () => { const list = []; return { list, toast: (...a) => list.push(a) }; };
test('Copy says Copied when the clipboard takes the text (#3731)', async () => {
const t = toasts(); let got = '';
assert.equal(await copyText('hello', 'Response', { clipboard: { writeText: async v => { got = v; } }, toast: t.toast }), true);
assert.equal(got, 'hello'); assert.equal(t.list[0][0], 'success');
});
test('a refused clipboard falls back to the older copy command', async () => {
const t = toasts(); let got = '';
assert.equal(await copyText('x', 'Response', { clipboard: { writeText: async () => { throw new Error('denied'); } }, legacyCopy: v => { got = v; return true; }, toast: t.toast }), true);
assert.equal(got, 'x'); assert.equal(t.list[0][0], 'success');
});
test('when nothing works the person is told, never left with a silent click', async () => {
const t = toasts();
assert.equal(await copyText('x', 'Response', { clipboard: null, legacyCopy: () => false, toast: t.toast }), false);
assert.equal(t.list.length, 1); assert.equal(t.list[0][0], 'warn'); assert.match(t.list[0][2], /Ctrl\+C/);
});
test('the typed message keeps its line breaks (#3720) and the chat uses the shared copy', async () => {
const css = await readFile(new URL('../src/styles/app.css', import.meta.url), 'utf8');
assert.match(css, /\.st-bubble__text\s*\{[^}]*white-space:\s*pre-wrap/);
const chat = await readFile(new URL('../src/screens/Chat.tsx', import.meta.url), 'utf8');
assert.doesNotMatch(chat, /void navigator\.clipboard\.writeText/);
});
+5 -1
View File
@@ -170,5 +170,9 @@ test('Windows: a PowerShell that is missing or fails is reported as before', asy
f.child.emit('error', Object.assign(new Error('x'), { code: 'ENOENT' }));
await assert.rejects(missing, e => e.code === 'ENOENT');
const g = fakeShell(); const failed = watchedWindowsDialog('powershell.exe', [], { spawnProcess: g.spawnProcess });
g.child.emit('close', 1); await assert.rejects(failed, e => e.code === 1);
g.child.emit('close', 1);
// Ended by security software before any window opened (#3831): the app asks for the path instead of an error.
assert.deepEqual(await failed, { noDialog: true });
const h = fakeShell(); const late = watchedWindowsDialog('powershell.exe', [], { spawnProcess: h.spawnProcess });
h.child.stdout.emit('data', 'READY\n'); h.child.emit('close', 1); await assert.rejects(late, e => e.code === 1);
});
+65
View File
@@ -0,0 +1,65 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import ts from 'typescript';
import { readdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { build } from 'esbuild';
const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];
const read = async name => JSON.parse(await readFile(`src/locales/${name}.json`, 'utf8'));
const built = 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(built.outputFiles[0].text).toString('base64')}`);
test('every tr("...") literal and every command hint has a key in the English catalog, so no language is stuck in English (#3479)', async () => {
const known = new Set();
for (const name of ['en', 'tune-en', 'tools-en', 'fix-en']) for (const v of Object.values(await read(name))) known.add(String(v));
const missing = [];
const scan = async dir => {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) { if (entry.name !== 'locales') await scan(path); continue; }
if (!/\.tsx?$/.test(path)) continue;
const source = await readFile(path, 'utf8'), sf = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
const visit = node => {
if (ts.isCallExpression(node) && node.expression.getText(sf) === 'tr' && node.arguments[0] && (ts.isStringLiteral(node.arguments[0]) || ts.isNoSubstitutionTemplateLiteral(node.arguments[0]))) {
const text = node.arguments[0].text.trim();
if (text && /[a-zA-Z]{2}/.test(text) && !known.has(text)) missing.push(`${path}: ${text}`);
}
if (ts.isPropertyAssignment(node) && node.name.getText(sf) === 'hint' && ts.isStringLiteral(node.initializer) && !path.endsWith('chat-showcase.ts')) {
const text = node.initializer.text.trim();
if (text && !known.has(text)) missing.push(`${path}: hint ${text}`);
}
ts.forEachChild(node, visit);
};
visit(sf);
}
};
await scan('src');
assert.deepEqual(missing, []);
});
test('the fix catalogs have the same keys and placeholders in all eight languages', async () => {
const en = await read('fix-en');
for (const language of languages) {
const catalog = await read(`fix-${language}`);
assert.deepEqual(Object.keys(catalog), Object.keys(en), language);
for (const [id, text] of Object.entries(catalog)) assert.deepEqual((text.match(/\{\d+\}/g) ?? []).sort(), (en[id].match(/\{\d+\}/g) ?? []).sort(), `${language} ${id}`);
}
});
test('the /plan, /research and /new hints and the four "Open ..." hints are translated (#3479, #3825)', () => {
for (const language of ['zh', 'ru']) {
setTranslationLanguage(language);
for (const hint of ['Have the assistant write a plan first; nothing runs until you approve it', 'Search the web, read the pages and answer with sources', 'Start a new conversation; keep this one'])
assert.notEqual(tr(hint), hint, `${language}: ${hint}`);
for (const label of ['Model settings', 'Serving', 'Models', 'Skills']) {
const hint = tr(`Open ${label}`);
assert.notEqual(hint, `Open ${label}`, `${language}: ${label} template`);
assert.ok(!hint.includes(label), `${language}: the label is translated too: ${hint}`);
}
}
setTranslationLanguage('zh');
assert.equal(tr('Open Skills'), '打开 技能');
setTranslationLanguage('en');
assert.equal(tr('Open Skills'), 'Open Skills');
});
@@ -0,0 +1,34 @@
// #3818: a single newline inside a paragraph is a space; a blank line starts a new paragraph; two trailing spaces or a backslash is a line break.
import assert from 'node:assert/strict';
import test from 'node:test';
import { resolve } from 'node:path';
import { createRequire } from 'node:module';
import { build } from 'esbuild';
const root = resolve(import.meta.dirname, '..');
const bundle = await build({
stdin: { contents: `import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { Markdown } from './src/components/Markdown.tsx'; export const html = text => renderToStaticMarkup(React.createElement(Markdown, { text }));`, resolveDir: root, loader: 'ts' },
bundle: true, write: false, platform: 'node', format: 'cjs', jsx: 'automatic', external: ['katex', 'katex/dist/katex.min.css'],
plugins: [{ name: 'stub', setup(b) {
b.onResolve({ filter: /^\.\/ui$/ }, () => ({ path: 'ui', namespace: 'test-stub' }));
b.onLoad({ filter: /.*/, namespace: 'test-stub' }, () => ({ contents: 'export const IconBtn = () => null; export const Btn = () => null;' }));
} }],
});
const mod = { exports: {} };
new Function('require', 'module', 'exports', bundle.outputFiles[0].text)(createRequire(import.meta.url), mod, mod.exports);
const { html } = mod.exports;
const paragraphs = out => (out.match(/<p>/g) ?? []).length;
test('a single newline is a soft break, a blank line a new paragraph', () => {
const soft = html('Line one\nLine two');
assert.equal(paragraphs(soft), 1); assert.match(soft, /Line one Line two/);
assert.equal(paragraphs(html('One\n\nTwo')), 2);
});
test('two trailing spaces or a backslash keep a line break', () => {
assert.match(html('One \nTwo'), /One<br\/>Two/);
assert.match(html('One' + String.fromCharCode(92) + String.fromCharCode(10) + 'Two'), /One<br\/>Two/);
});
test('a list, heading or code block right after a line still starts its own block', () => {
const out = html('Intro\n- a\n- b\n## Head\ntext\n```\ncode\n```');
assert.match(out, /<p>Intro<\/p><ul>/); assert.match(out, /<h2>Head<\/h2><p>text<\/p>/);
});
+8 -1
View File
@@ -4,7 +4,7 @@ import { readFile } from 'node:fs/promises';
import { transform } from 'esbuild';
const { code } = await transform(await readFile(new URL('../src/lib/model-picker.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' });
const { pickerGroups } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const { pickerGroups, pickerNativeModels } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const version = (id, family, state, diskGb, extra = {}) => ({ id, family, state, diskGb, ...extra });
test('chat picker groups every downloaded family and puts its running version first', () => {
@@ -35,3 +35,10 @@ test('downloaded files stay visible during load transitions and recoverable fail
assert.deepEqual(pickerGroups(library)[0].versions.map(v => v.id), ['loading', 'unloading', 'failed-load']);
assert.deepEqual(pickerGroups({ loaded: null, variants: [library.variants[0]] }), []);
});
test('downloaded optimized models that are not loaded still appear in the chat picker (#3814)', () => {
const installed = [{ model: 'swift', model_name: 'Swift IQ3_XXS', ready: true }, { model: 'half', model_name: 'Half', ready: false }, { model: 'run', model_name: 'Running one', ready: true }];
const out = pickerNativeModels(installed, [{ label: 'Running one' }]);
assert.deepEqual(out.map(m => m.model), ['swift']);
assert.deepEqual(pickerNativeModels(undefined, null), []);
});
+13 -1
View File
@@ -5,7 +5,7 @@ import { readFile } from 'node:fs/promises';
import { transform } from 'esbuild';
const { code } = await transform(await readFile(new URL('../src/lib/native-fit.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' });
const { fitOn, memoryNeeded, RECOMMENDED, VERSION_GROUPS, groupOpen, recommendedVersions, PICK_NOTE, OTHER_NOTE, MTP_VRAM_GB } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const { fitOn, cacheGb, memoryNeeded, RECOMMENDED, VERSION_GROUPS, groupOpen, recommendedVersions, PICK_NOTE, OTHER_NOTE, MTP_VRAM_GB } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const swift = { ram_needed_gb: 48, experts_gb: 35.5 };
const gyroS = { ram_needed_gb: 27.6, experts_gb: 25.8, mem_total: true };
@@ -83,3 +83,15 @@ test('the tiers of the engine are 40 GB Swift IQ2_XS, 48 GB IQ3_XXS, 64 GB IQ3_S
assert.deepEqual([...m[1].matchAll(/\(([\d.]+),\s*"(\w+)",\s*"(\w+)"\)/g)].map(x => [Number(x[1]), x[2], x[3]]), [[62, 'qwen', 'IQ3_S'], [46, 'qwen', 'IQ3_XXS'], [38, 'swift', 'IQ2_XS']], file);
}
});
test('the conversation context and cache format move the estimate (#3832)', () => {
const pc = { ram_gb: 64, vram_gb: 16 };
const base = fitOn(swift, pc);
assert.deepEqual(fitOn(swift, pc, true, { context: 32768, kv: 'int8' }), base, 'the default context is what the fixed figure already held');
const big = fitOn(swift, pc, true, { context: 524288, kv: 'int8' });
assert.ok(big.vramUseGb >= base.vramUseGb && big.ramUseGb > base.ramUseGb, 'a bigger cache takes graphics memory from the experts, which then sit in RAM');
assert.ok(fitOn(swift, pc, true, { context: 524288, kv: 'q4_0' }).ramUseGb < big.ramUseGb, 'a smaller cache format leaves more room');
assert.ok(Math.abs(cacheGb(524288, 'int8') * 1024 - 7361) < 25, 'the 512K Int8 cache is the 7361 MiB the engine reports');
const tight = fitOn(q4, pc, true, { context: 524288, kv: 'int8' });
assert.ok(tight.spillGb > fitOn(q4, pc).spillGb, 'what no longer fits is read from the SSD and the card says so');
});
+21
View File
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { build } from 'esbuild';
const compiled = await build({ stdin: { contents: "export * from './src/lib/native';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' });
const lib = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);
test('the Models page waits for the first native answer before it picks a model (#3740)', async () => {
let release;
globalThis.fetch = () => new Promise(resolve => { release = () => resolve({ ok: true, status: 200, statusText: 'OK', text: async () => JSON.stringify({ available: true, jobs: [], instances: [] }) }); });
let heard = 0;
const off = lib.subscribeNative(() => { heard++; });
assert.equal(lib.nativeSettled(), false, 'nothing read yet: show a placeholder, not the Starter');
const reading = lib.refreshNative();
assert.equal(lib.nativeSettled(), false);
release();
await reading;
assert.equal(lib.nativeSettled(), true);
assert.ok(heard >= 1, 'the page is told');
off();
});
+5
View File
@@ -102,3 +102,8 @@ test('missing model files are named, in every language, with a next step (#3478)
setTranslationLanguage('en');
assert.equal(plainFailure(missingFilesError('m', []).message).kind, 'plain', 'with no names the old sentence is left as it was');
});
test('the engine component is named in words, once (#3900)', async () => {
const { missingNames } = await import('../server/missing-files.mjs');
assert.deepEqual(missingNames([{ part: 'engine', file: 'component:strata-engine' }], ['component:strata-engine']), ['the engine program']);
});
@@ -0,0 +1,17 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { transform } from 'esbuild';
const { code } = await transform(await readFile(new URL('../src/lib/session-workspace.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' });
const { workspaceIdForSession } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const workspaces = [{ id: 'a', name: 'A', path: 'C:\A', aliases: ['C:\old'] }, { id: 'b', name: 'B', path: 'D:\Project' }];
test('a chat finds the workspace it was made in, by path or by an earlier folder (#3754)', () => {
assert.equal(workspaceIdForSession(workspaces, { workspace: 'D:\Project' }), 'b');
assert.equal(workspaceIdForSession(workspaces, { workspace: 'C:\old' }), 'a');
});
test('a chat with an unknown or no workspace changes nothing', () => {
assert.equal(workspaceIdForSession(workspaces, { workspace: 'E:\gone' }), null);
assert.equal(workspaceIdForSession(workspaces, undefined), null);
});
+24
View File
@@ -0,0 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { transform } from 'esbuild';
const load = async name => import(`data:text/javascript;base64,${Buffer.from((await transform(await readFile(new URL(`../src/lib/${name}.ts`, import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' })).code).toString('base64')}`);
const { parseDecimal, partialDecimal } = await load('decimal');
const { pastedFiles } = await load('pasted-files');
test('a decimal point can be typed step by step (#3736)', () => {
for (const step of ['', '.', '0', '0.', '0.9', '0.95']) assert.equal(partialDecimal(step), true, step);
assert.equal(parseDecimal('.'), null); assert.equal(parseDecimal('0.'), null);
assert.equal(parseDecimal('0.95'), 0.95); assert.equal(parseDecimal('.95'), 0.95); assert.equal(parseDecimal('0,95'), 0.95); assert.equal(parseDecimal('20'), 20);
assert.equal(partialDecimal('0.9x'), false); assert.equal(parseDecimal('1e3'), null);
});
test('a screenshot that is only in clipboard items is attached (#3748)', () => {
const png = new File(['x'], 'image.png', { type: 'image/png' });
const data = { files: [], items: [{ kind: 'file', type: 'image/png', getAsFile: () => png }, { kind: 'string', type: 'text/plain', getAsFile: () => null }] };
const out = pastedFiles(data);
assert.equal(out.length, 1); assert.equal(out[0].type, 'image/png'); assert.match(out[0].name, /^Pasted picture .*\.png$/);
assert.equal(pastedFiles({ files: [png], items: [{ kind: 'file', type: 'image/png', getAsFile: () => png }] }).length, 1, 'never twice');
assert.deepEqual(pastedFiles({ files: [], items: [{ kind: 'string', type: 'text/plain', getAsFile: () => null }] }), []);
});
@@ -0,0 +1,43 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { parseWindowsDiskLine, createWindowsDiskReader, diskRate } from '../server/system-telemetry.mjs';
function fakeSpawn(log) {
return (cmd, args) => {
const proc = new EventEmitter();
proc.stdout = new EventEmitter();
proc.stdout.unref = () => {};
proc.unref = () => {};
proc.kill = () => { proc.killed = true; };
log.push({ cmd, args, proc });
return proc;
};
}
test('one PowerShell is started and reused for every sample (#3939)', () => {
const log = [];
const reader = createWindowsDiskReader({ spawnFn: fakeSpawn(log), now: () => 1000 });
assert.equal(reader.read(), null, 'nothing before the first line');
reader.read(); reader.read();
assert.equal(log.length, 1);
log[0].proc.stdout.emit('data', '1000 2');
log[0].proc.stdout.emit('data', '000\n');
assert.deepEqual(reader.read(), { read: 1000, write: 2000, at: 1000 });
assert.equal(log.length, 1);
});
test('after repeated early exits it stops starting processes', () => {
const log = [];
const reader = createWindowsDiskReader({ spawnFn: fakeSpawn(log), maxStarts: 3 });
for (let i = 0; i < 6; i++) { reader.read(); log.at(-1).proc.emit('exit'); }
assert.equal(log.length, 3);
assert.equal(reader.read(), null);
});
test('garbage lines are ignored and a repeated reading gives no new rate', () => {
assert.equal(parseWindowsDiskLine('Name : x'), null);
assert.deepEqual(parseWindowsDiskLine('12 34\r'), { read: 12, write: 34 });
const prev = { time: 0, counters: { read: 0, write: 0, at: 1000 } };
assert.deepEqual(diskRate(prev, { read: 1048576, write: 0, at: 2000 }, 5000), { readMbs: 1, writeMbs: 0 });
});
+47
View File
@@ -0,0 +1,47 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { luidName, parseDxAdapters, windowsOtherGpus, parseGpuCounterLine, createWindowsGpuReader } from '../server/windows-gpu.mjs';
const dxRaw = JSON.stringify([
{ Description: 'AMD Radeon RX 9070 XT', VendorId: '4098', Luid: '90370', Dedicated: '17094934528', Software: '0' },
{ Description: 'Microsoft Basic Render Driver', VendorId: '5140', Luid: '1', Dedicated: '0', Software: '1' },
]);
test('the LUID is spelled as the performance counters spell it', () => {
assert.equal(luidName('90370'), 'luid_0x00000000_0x00016102');
assert.equal(luidName(String(0x12n * 2n ** 32n + 5n)), 'luid_0x00000012_0x00000005');
assert.equal(luidName('nope'), null);
});
test('an AMD card on Windows gets its real memory size and a LUID, virtual monitors are not cards (#3727, #3836)', () => {
const dx = parseDxAdapters(dxRaw);
const cards = windowsOtherGpus([
{ Name: 'AMD Radeon RX 9070 XT', PNPDeviceID: 'PCI-A' },
{ Name: 'Meta Virtual Monitor', PNPDeviceID: 'ROOT-1' },
{ Name: 'Virtual Desktop Monitor', PNPDeviceID: 'ROOT-2' },
], dx);
assert.equal(cards.length, 1);
assert.equal(cards[0].vendor, 'amd');
assert.equal(cards[0].vramGb, 15.9);
assert.equal(cards[0].luid, 'luid_0x00000000_0x00016102');
});
test('without the registry list an AMD card is still listed, with no size', () => {
const cards = windowsOtherGpus([{ Name: 'AMD Radeon RX 7900 XT', PNPDeviceID: 'PCI-B' }], parseDxAdapters('garbage'));
assert.deepEqual(cards.map(c => [c.vendor, c.vramGb, c.luid]), [['amd', 0, null]]);
});
test('counter lines are read, and the load and VRAM in use reach the card by its LUID', () => {
assert.equal(parseGpuCounterLine('nonsense'), null);
const line = parseGpuCounterLine('G luid_0x00000000_0x00016102 37 4294967296');
assert.equal(line.utilizationPct, 37);
assert.equal(line.memoryUsedGb, 4);
const procs = [];
const reader = createWindowsGpuReader({ spawnFn: () => { const p = new EventEmitter(); p.stdout = new EventEmitter(); p.kill = () => {}; procs.push(p); return p; }, now: () => 5 });
assert.equal(reader.read('luid_0x00000000_0x00016102'), null, 'nothing before the first line');
procs[0].stdout.emit('data', 'G luid_0x00000000_0x00016102 37 4294967296\nG luid_0x00000000_0x00000001 0 0\n');
assert.equal(reader.read('LUID_0x00000000_0x00016102').utilizationPct, 37);
assert.equal(reader.read('luid_0x00000000_0x00099999'), null);
assert.equal(procs.length, 1, 'one process for every read');
});
+17
View File
@@ -451,6 +451,23 @@ class DeleteModelTests(unittest.TestCase):
described = self.s.describe_config(self.root / "strata-iq3_s.json")
self.assertGreater(described["disk_bytes"], 10000)
def test_files_strata_downloaded_into_another_models_folder_are_deleted_too(self):
# The app installs into its own Models folder while settings.json names another data folder (#3716).
other = Path(self.tmp.name) / "Documents" / "Strata"
shard = self.make(other / "Models" / "IQ3" / "m-00001.gguf", 5000)
self.make(shard.with_name(shard.name + ".done"), 1)
pack = other / "packs" / "iq3"
self.make(pack / "dense.bin", 300)
self.make(pack / "conversions.json", 2)
mine = self.make(Path(self.tmp.name) / "mine" / "own.gguf", 99)
(self.root / "strata-iq3x.json").write_text(json.dumps({"exe": "component:strata-engine", "args": [
"--pack", str(pack), "--native", str(shard), "--ple-gguf", str(mine)]}), encoding="utf-8")
result = self.tools.strata_remove(model="iq3x", confirm=True)
self.assertEqual(result["failed"], [])
self.assertFalse(shard.exists())
self.assertFalse(pack.exists())
self.assertTrue(mine.is_file(), "a file the person brought stays")
class LocalGgufInstallTests(unittest.TestCase):
def test_a_plan_from_a_local_folder_adopts_the_files_and_needs_no_download_space(self):
+12 -1
View File
@@ -766,6 +766,17 @@ class Strata:
return {"models": models, "shared_bytes": shared_bytes, "shared_gb": round(shared_bytes / 1e9, 2),
"total_bytes": total, "total_gb": round(total / 1e9, 2)}
@staticmethod
def made_by_strata(p: Path, is_dir: bool) -> bool:
"""A download or pack Strata wrote itself, even in a models folder the person picked or the app chose: a finished GGUF has its
.done mark beside it, a prepared pack has its conversion record. The person's own GGUF files have neither (#3716)."""
try:
if is_dir:
return any((p / n).is_file() for n in ("conversions.json", "experts.bin.src.json"))
return p.with_name(p.name + ".done").is_file()
except OSError:
return False
def removal_plan(self, config: Path) -> dict:
"""What deleting this model removes and what it keeps. A file or folder another installed model's config still names
(the shared MTP draft, a shared PLE shard) is kept; so is anything outside Strata's own folders."""
@@ -789,7 +800,7 @@ class Strata:
for p, is_dir in [(x, False) for x in files] + [(x, True) for x in dirs]:
if not p.exists():
continue
if not self.allowed(p):
if not self.allowed(p) and not self.made_by_strata(p, is_dir):
keep.append({"path": str(p), "reason": "outside Strata's folders"})
elif shared(p, is_dir):
keep.append({"path": str(p), "reason": "another installed model still uses it"})