Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

App: the Monitor's readings strip (energy since start, cost in the person's own currency, GPU fan and clock, CPU and SSD temperature) with the Electricity price setting (#3628, PR #3628 by hash13 as the starting idea); a sound when work finishes (#3586); desktop notification and tray, pinned port and interface size settings with their host routes (#3477, #3402, #3970); the gh-<lang> catalog in nine languages

Niko1221c17a6f4ce1cd
diff --git a/apps/host/public/strata-done-sound.wav b/apps/host/public/strata-done-sound.wav
new file mode 100644
index 000000000..ec3173e3a
Binary files /dev/null and b/apps/host/public/strata-done-sound.wav differ
diff --git a/apps/host/scripts/make-gh-locales.py b/apps/host/scripts/make-gh-locales.py
new file mode 100644
index 000000000..41898d252
--- /dev/null
+++ b/apps/host/scripts/make-gh-locales.py
@@ -0,0 +1,365 @@
+"""Writes src/locales/gh-<lang>.json: the interface strings of the 0.2.7 GitHub items done in f-027-gh-app (the Monitor's Power card #3628,
+approval notifications and the tray #3477, the finished-task sound #3586, the pinned port #3402, the interface size #3970).
+Run from apps/host: python scripts/make-gh-locales.py
+The keys are gh01.. in this order; gh-en.json is the English source. Placeholders ({0}, {1}) must be kept in every language.
+A separate file keeps this work from colliding with the other catalogs (the same reason tune-, tools- and fix- exist)."""
+import json
+import re
+from pathlib import Path
+
+EN = [
+ "Energy since start",
+ "Cost since start",
+ "GPU fan",
+ "GPU clock",
+ "CPU temperature",
+ "SSD temperature",
+ "Electricity price",
+ "Price of one kilowatt-hour. The Monitor then shows what your graphics card has cost since Strata started. Leave it empty to hide the cost.",
+ "Price per kWh",
+ "Sound when work finishes",
+ "Plays a short sound when an answer or task that took a while is finished, or when Strata is in the background.",
+ "Play sound",
+ "Notify me when Strata needs an answer",
+ "In Manual mode, shows a desktop notification when the assistant waits for your approval and Strata is in the background.",
+ "Strata needs your answer",
+ "The assistant wants to use {0}. Open Strata to approve or deny.",
+ "a tool",
+ "Minimise to tray",
+ "Closing the window keeps Strata running in the tray, next to the clock. Choose Quit in the tray menu to stop it. Applies the next time Strata starts.",
+ "App port",
+ "The port Strata’s window and local address use. Leave it empty to let Strata choose (47831 when it is free). Applies the next time Strata starts.",
+ "Port (empty = automatic)",
+ "Using port {0} now.",
+ "Strata could not use its port",
+ "Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.",
+ "Choose a port between 1024 and 65535, or leave it empty.",
+ "Makes all text, buttons and menus in Strata larger or smaller.",
+ "Energy and temperature readings",
+ "per kWh, in {0}",
+ "per kWh",
+ "Change currency",
+ "Automatic ({0})",
+ "Currency",
+ "less than {0}",
+]
+
+T = {
+"zh": [
+ "启动以来的能耗",
+ "启动以来的费用",
+ "GPU 风扇",
+ "GPU 频率",
+ "CPU 温度",
+ "SSD 温度",
+ "电价",
+ "每千瓦时的价格。监控页会据此显示 Strata 启动以来显卡用电的费用。留空则不显示费用。",
+ "每千瓦时价格",
+ "工作完成时的提示音",
+ "回答或耗时较长的任务完成时,或 Strata 在后台时,播放一段简短的提示音。",
+ "播放提示音",
+ "Strata 需要您答复时通知我",
+ "在手动模式下,当助手等待您批准而 Strata 在后台时,显示桌面通知。",
+ "Strata 需要您的答复",
+ "助手想使用 {0}。打开 Strata 以批准或拒绝。",
+ "一个工具",
+ "最小化到托盘",
+ "关闭窗口后,Strata 会继续在托盘(时钟旁边)运行。要停止它,请在托盘菜单中选择“退出”。下次启动 Strata 时生效。",
+ "应用端口",
+ "Strata 窗口和本地地址使用的端口。留空则由 Strata 自行选择(空闲时为 47831)。下次启动 Strata 时生效。",
+ "端口(留空 = 自动)",
+ "当前使用端口 {0}。",
+ "Strata 无法使用它的端口",
+ "端口 {0} 已被其他程序占用,因此 Strata 改用端口 {1} 启动。在端口 {0} 上保存的聊天和设置在 Strata 能再次使用该端口之前不会显示。请关闭其他程序并重新启动 Strata。",
+ "请选择 1024 到 65535 之间的端口,或留空。",
+ "让 Strata 中的所有文字、按钮和菜单变大或变小。",
+ "能耗和温度读数",
+ "每千瓦时,币种 {0}",
+ "每千瓦时",
+ "更改货币",
+ "自动({0})",
+ "货币",
+ "不足 {0}",
+],
+"ja": [
+ "起動後の消費電力量",
+ "起動後の電気代",
+ "GPU ファン",
+ "GPU クロック",
+ "CPU 温度",
+ "SSD 温度",
+ "電気料金",
+ "1キロワット時あたりの料金です。モニターに、Strata の起動後にグラフィックスカードが使った電気代が表示されます。空欄のままなら電気代は表示されません。",
+ "1 kWh あたりの料金",
+ "作業完了時の音",
+ "回答や時間のかかった作業が終わったとき、または Strata がバックグラウンドにあるときに、短い音を鳴らします。",
+ "音を鳴らす",
+ "Strata の返答が必要なときに通知する",
+ "手動モードで、アシスタントが承認を待っていて Strata がバックグラウンドにあるときに、デスクトップ通知を表示します。",
+ "Strata があなたの返答を待っています",
+ "アシスタントが {0} を使おうとしています。Strata を開いて承認または拒否してください。",
+ "ツール",
+ "トレイに最小化",
+ "ウィンドウを閉じても、Strata は時計の横のトレイで動き続けます。止めるには、トレイのメニューで「終了」を選びます。次に Strata を起動したときから有効になります。",
+ "アプリのポート",
+ "Strata のウィンドウとローカルアドレスが使うポートです。空欄なら Strata が選びます(空いていれば 47831)。次に Strata を起動したときから有効になります。",
+ "ポート(空欄 = 自動)",
+ "現在のポートは {0} です。",
+ "Strata は指定のポートを使えませんでした",
+ "ポート {0} は別のプログラムが使っているため、Strata はポート {1} で起動しました。ポート {0} に保存されたチャットと設定は、Strata が再びそのポートを使えるようになるまで表示されません。他のプログラムを閉じて Strata を再起動してください。",
+ "1024 から 65535 の間のポートを選ぶか、空欄にしてください。",
+ "Strata のすべての文字、ボタン、メニューを大きくしたり小さくしたりします。",
+ "消費電力量と温度の値",
+ "1 kWh あたり、通貨は {0}",
+ "1 kWh あたり",
+ "通貨を変更",
+ "自動({0})",
+ "通貨",
+ "{0} 未満",
+],
+"de": [
+ "Energie seit dem Start",
+ "Kosten seit dem Start",
+ "GPU-Lüfter",
+ "GPU-Takt",
+ "CPU-Temperatur",
+ "SSD-Temperatur",
+ "Strompreis",
+ "Preis einer Kilowattstunde. Der Monitor zeigt dann, was Ihre Grafikkarte seit dem Start von Strata gekostet hat. Leer lassen, um die Kosten auszublenden.",
+ "Preis pro kWh",
+ "Ton, wenn Arbeit fertig ist",
+ "Spielt einen kurzen Ton, wenn eine Antwort oder Aufgabe, die länger gedauert hat, fertig ist oder wenn Strata im Hintergrund läuft.",
+ "Ton abspielen",
+ "Benachrichtigen, wenn Strata eine Antwort braucht",
+ "Zeigt im manuellen Modus eine Desktop-Benachrichtigung, wenn der Assistent auf Ihre Freigabe wartet und Strata im Hintergrund läuft.",
+ "Strata braucht Ihre Antwort",
+ "Der Assistent möchte {0} verwenden. Öffnen Sie Strata, um zu erlauben oder abzulehnen.",
+ "ein Werkzeug",
+ "In den Infobereich minimieren",
+ "Beim Schließen des Fensters läuft Strata im Infobereich neben der Uhr weiter. Wählen Sie im Menü des Symbols „Beenden“, um es zu stoppen. Gilt ab dem nächsten Start von Strata.",
+ "App-Port",
+ "Der Port, den das Fenster und die lokale Adresse von Strata verwenden. Leer lassen, damit Strata ihn wählt (47831, wenn frei). Gilt ab dem nächsten Start von Strata.",
+ "Port (leer = automatisch)",
+ "Aktuell wird Port {0} verwendet.",
+ "Strata konnte seinen Port nicht verwenden",
+ "Port {0} wird von einem anderen Programm verwendet, daher wurde Strata auf Port {1} gestartet. Unter Port {0} gespeicherte Chats und Einstellungen werden nicht angezeigt, bis Strata ihn wieder verwenden kann. Schließen Sie das andere Programm und starten Sie Strata neu.",
+ "Wählen Sie einen Port zwischen 1024 und 65535 oder lassen Sie das Feld leer.",
+ "Macht alle Texte, Schaltflächen und Menüs in Strata größer oder kleiner.",
+ "Energie- und Temperaturwerte",
+ "pro kWh, in {0}",
+ "pro kWh",
+ "Währung ändern",
+ "Automatisch ({0})",
+ "Währung",
+ "weniger als {0}",
+],
+"es": [
+ "Energía desde el inicio",
+ "Coste desde el inicio",
+ "Ventilador de la GPU",
+ "Reloj de la GPU",
+ "Temperatura de la CPU",
+ "Temperatura del SSD",
+ "Precio de la electricidad",
+ "Precio de un kilovatio hora. El Monitor mostrará entonces lo que ha costado tu tarjeta gráfica desde que se inició Strata. Déjalo vacío para ocultar el coste.",
+ "Precio por kWh",
+ "Sonido al terminar el trabajo",
+ "Reproduce un sonido breve cuando termina una respuesta o tarea que tardó un rato, o cuando Strata está en segundo plano.",
+ "Reproducir sonido",
+ "Avisarme cuando Strata necesite una respuesta",
+ "En el modo manual, muestra una notificación de escritorio cuando el asistente espera tu aprobación y Strata está en segundo plano.",
+ "Strata necesita tu respuesta",
+ "El asistente quiere usar {0}. Abre Strata para aprobar o denegar.",
+ "una herramienta",
+ "Minimizar a la bandeja",
+ "Al cerrar la ventana, Strata sigue funcionando en la bandeja, junto al reloj. Elige Salir en el menú de la bandeja para detenerlo. Se aplica la próxima vez que se inicie Strata.",
+ "Puerto de la aplicación",
+ "El puerto que usan la ventana y la dirección local de Strata. Déjalo vacío para que Strata elija (47831 si está libre). Se aplica la próxima vez que se inicie Strata.",
+ "Puerto (vacío = automático)",
+ "Ahora se usa el puerto {0}.",
+ "Strata no pudo usar su puerto",
+ "El puerto {0} lo usa otro programa, así que Strata se inició en el puerto {1}. Los chats y ajustes guardados en el puerto {0} no se muestran hasta que Strata pueda volver a usarlo. Cierra el otro programa y reinicia Strata.",
+ "Elige un puerto entre 1024 y 65535, o déjalo vacío.",
+ "Hace más grandes o más pequeños todos los textos, botones y menús de Strata.",
+ "Lecturas de energía y temperatura",
+ "por kWh, en {0}",
+ "por kWh",
+ "Cambiar moneda",
+ "Automática ({0})",
+ "Moneda",
+ "menos de {0}",
+],
+"ru": [
+ "Энергия с запуска",
+ "Стоимость с запуска",
+ "Вентилятор GPU",
+ "Частота GPU",
+ "Температура CPU",
+ "Температура SSD",
+ "Цена электричества",
+ "Цена одного киловатт-часа. Тогда монитор покажет, во сколько видеокарта обошлась с запуска Strata. Оставьте поле пустым, чтобы скрыть стоимость.",
+ "Цена за кВт·ч",
+ "Звук по окончании работы",
+ "Проигрывает короткий звук, когда закончился долгий ответ или задача, а также когда Strata работает в фоне.",
+ "Проиграть звук",
+ "Уведомлять, когда Strata нужен ответ",
+ "В ручном режиме показывает уведомление на рабочем столе, когда помощник ждёт вашего подтверждения, а Strata работает в фоне.",
+ "Strata нужен ваш ответ",
+ "Помощник хочет использовать {0}. Откройте Strata, чтобы разрешить или отклонить.",
+ "инструмент",
+ "Сворачивать в трей",
+ "При закрытии окна Strata продолжает работать в трее рядом с часами. Чтобы остановить её, выберите «Выход» в меню значка. Действует со следующего запуска Strata.",
+ "Порт приложения",
+ "Порт, который используют окно и локальный адрес Strata. Оставьте поле пустым, чтобы Strata выбрала сама (47831, если свободен). Действует со следующего запуска Strata.",
+ "Порт (пусто = автоматически)",
+ "Сейчас используется порт {0}.",
+ "Strata не смогла использовать свой порт",
+ "Порт {0} занят другой программой, поэтому Strata запустилась на порту {1}. Чаты и настройки, сохранённые на порту {0}, не показываются, пока Strata не сможет снова его использовать. Закройте другую программу и перезапустите Strata.",
+ "Выберите порт от 1024 до 65535 или оставьте поле пустым.",
+ "Увеличивает или уменьшает весь текст, кнопки и меню в Strata.",
+ "Показания энергии и температуры",
+ "за кВт·ч, в валюте {0}",
+ "за кВт·ч",
+ "Сменить валюту",
+ "Автоматически ({0})",
+ "Валюта",
+ "меньше {0}",
+],
+"pt": [
+ "Energia desde o início",
+ "Custo desde o início",
+ "Ventoinha da GPU",
+ "Clock da GPU",
+ "Temperatura da CPU",
+ "Temperatura do SSD",
+ "Preço da eletricidade",
+ "Preço de um quilowatt-hora. O Monitor passa a mostrar quanto a sua placa de vídeo custou desde que o Strata iniciou. Deixe vazio para ocultar o custo.",
+ "Preço por kWh",
+ "Som ao terminar o trabalho",
+ "Toca um som curto quando uma resposta ou tarefa que demorou termina, ou quando o Strata está em segundo plano.",
+ "Tocar som",
+ "Avisar quando o Strata precisar de uma resposta",
+ "No modo manual, mostra uma notificação na área de trabalho quando o assistente espera sua aprovação e o Strata está em segundo plano.",
+ "O Strata precisa da sua resposta",
+ "O assistente quer usar {0}. Abra o Strata para aprovar ou negar.",
+ "uma ferramenta",
+ "Minimizar para a bandeja",
+ "Ao fechar a janela, o Strata continua em execução na bandeja, ao lado do relógio. Escolha Sair no menu da bandeja para encerrá-lo. Vale a partir da próxima vez que o Strata iniciar.",
+ "Porta do aplicativo",
+ "A porta usada pela janela e pelo endereço local do Strata. Deixe vazio para o Strata escolher (47831 quando estiver livre). Vale a partir da próxima vez que o Strata iniciar.",
+ "Porta (vazio = automático)",
+ "Usando a porta {0} agora.",
+ "O Strata não conseguiu usar a sua porta",
+ "A porta {0} está em uso por outro programa, então o Strata iniciou na porta {1}. Os chats e as configurações salvos na porta {0} não aparecem até o Strata poder usá-la de novo. Feche o outro programa e reinicie o Strata.",
+ "Escolha uma porta entre 1024 e 65535, ou deixe vazio.",
+ "Deixa todos os textos, botões e menus do Strata maiores ou menores.",
+ "Leituras de energia e temperatura",
+ "por kWh, em {0}",
+ "por kWh",
+ "Alterar moeda",
+ "Automática ({0})",
+ "Moeda",
+ "menos de {0}",
+],
+"ko": [
+ "시작 이후 에너지",
+ "시작 이후 비용",
+ "GPU 팬",
+ "GPU 클럭",
+ "CPU 온도",
+ "SSD 온도",
+ "전기 요금",
+ "1킬로와트시의 요금입니다. 모니터에 Strata를 시작한 뒤 그래픽 카드에 든 전기 요금이 표시됩니다. 비워 두면 비용을 표시하지 않습니다.",
+ "kWh당 요금",
+ "작업이 끝났을 때 소리",
+ "답변이나 오래 걸린 작업이 끝났을 때, 또는 Strata가 백그라운드에 있을 때 짧은 소리를 재생합니다.",
+ "소리 재생",
+ "Strata가 답을 필요로 할 때 알림",
+ "수동 모드에서 어시스턴트가 승인을 기다리고 Strata가 백그라운드에 있을 때 데스크톱 알림을 표시합니다.",
+ "Strata가 답을 기다리고 있습니다",
+ "어시스턴트가 {0}을(를) 사용하려고 합니다. Strata를 열어 승인하거나 거부하세요.",
+ "도구",
+ "트레이로 최소화",
+ "창을 닫아도 Strata는 시계 옆 트레이에서 계속 실행됩니다. 끝내려면 트레이 메뉴에서 '종료'를 선택하세요. 다음에 Strata를 시작할 때부터 적용됩니다.",
+ "앱 포트",
+ "Strata의 창과 로컬 주소가 사용하는 포트입니다. 비워 두면 Strata가 고릅니다(비어 있으면 47831). 다음에 Strata를 시작할 때부터 적용됩니다.",
+ "포트(비움 = 자동)",
+ "지금은 포트 {0}을(를) 사용 중입니다.",
+ "Strata가 지정한 포트를 사용할 수 없었습니다",
+ "포트 {0}을(를) 다른 프로그램이 사용 중이어서 Strata는 포트 {1}에서 시작했습니다. 포트 {0}에 저장된 채팅과 설정은 Strata가 다시 그 포트를 쓸 수 있을 때까지 표시되지 않습니다. 다른 프로그램을 닫고 Strata를 다시 시작하세요.",
+ "1024에서 65535 사이의 포트를 고르거나 비워 두세요.",
+ "Strata의 모든 글자, 버튼, 메뉴를 더 크게 또는 더 작게 만듭니다.",
+ "에너지 및 온도 측정값",
+ "kWh당, 통화 {0}",
+ "kWh당",
+ "통화 변경",
+ "자동({0})",
+ "통화",
+ "{0} 미만",
+],
+"fr": [
+ "Énergie depuis le démarrage",
+ "Coût depuis le démarrage",
+ "Ventilateur du GPU",
+ "Fréquence du GPU",
+ "Température du CPU",
+ "Température du SSD",
+ "Prix de l'électricité",
+ "Prix d'un kilowattheure. Le Moniteur affiche alors ce que votre carte graphique a coûté depuis le démarrage de Strata. Laissez vide pour masquer le coût.",
+ "Prix par kWh",
+ "Son à la fin du travail",
+ "Joue un court son quand une réponse ou une tâche qui a pris du temps est terminée, ou quand Strata est en arrière-plan.",
+ "Jouer le son",
+ "Me prévenir quand Strata a besoin d'une réponse",
+ "En mode manuel, affiche une notification sur le bureau quand l'assistant attend votre accord et que Strata est en arrière-plan.",
+ "Strata a besoin de votre réponse",
+ "L'assistant veut utiliser {0}. Ouvrez Strata pour accepter ou refuser.",
+ "un outil",
+ "Réduire dans la zone de notification",
+ "Fermer la fenêtre garde Strata actif dans la zone de notification, près de l'horloge. Choisissez Quitter dans le menu de l'icône pour l'arrêter. S'applique au prochain démarrage de Strata.",
+ "Port de l'application",
+ "Le port que la fenêtre et l'adresse locale de Strata utilisent. Laissez vide pour que Strata choisisse (47831 s'il est libre). S'applique au prochain démarrage de Strata.",
+ "Port (vide = automatique)",
+ "Port {0} utilisé en ce moment.",
+ "Strata n'a pas pu utiliser son port",
+ "Le port {0} est utilisé par un autre programme, donc Strata a démarré sur le port {1}. Les conversations et réglages enregistrés sur le port {0} ne s'affichent pas tant que Strata ne peut pas le réutiliser. Fermez l'autre programme et relancez Strata.",
+ "Choisissez un port entre 1024 et 65535, ou laissez vide.",
+ "Agrandit ou réduit tous les textes, boutons et menus de Strata.",
+ "Relevés d'énergie et de température",
+ "par kWh, en {0}",
+ "par kWh",
+ "Changer de devise",
+ "Automatique ({0})",
+ "Devise",
+ "moins de {0}",
+],
+}
+
+here = Path(__file__).resolve().parent.parent / "src" / "locales"
+
+
+NBSP = "\u00a0"
+
+
+def french(text):
+ """The same French spacing as scripts/fr_sync.py: a typographic apostrophe, a no-break space before : ; ? ! % and inside the guillemets."""
+ text = re.sub(r"(?<=[A-Za-z\u00c0-\u017f])'(?=[A-Za-z\u00c0-\u017f{])", "\u2019", text)
+ text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text)
+ text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text)
+ return text
+
+
+def write(lang, values):
+ assert len(values) == len(EN), (lang, len(values), len(EN))
+ for source, text in zip(EN, values):
+ assert sorted(re.findall(r"\{\d+\}", source)) == sorted(re.findall(r"\{\d+\}", text)), (lang, source, text)
+ if lang == "fr":
+ values = [french(v) for v in values]
+ data = {f"gh{i + 1:02d}": text for i, text in enumerate(values)}
+ (here / f"gh-{lang}.json").write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
+
+
+write("en", EN)
+for lang, values in T.items():
+ write(lang, values)
+print("written", len(EN), "strings in", len(T) + 1, "languages")
diff --git a/apps/host/server/device-probes.mjs b/apps/host/server/device-probes.mjs
index cee55a4b4..80a68d8c5 100644
--- a/apps/host/server/device-probes.mjs
+++ b/apps/host/server/device-probes.mjs
@@ -40,13 +40,15 @@ export function parseNvidiaDevices(raw) {
return [{id:uuid,index:Number(index),sensorIndex:Number(index),busId:bus?.toLowerCase(),vendor:'nvidia',name,vramGb:round((number(memory)??0)/1024,1),unified:false,backend:'cuda',driver}];
});
}
+/** A percentage reading; "[N/A]" and out-of-range values are no reading. */
+const percentOf = v => { const n=number(v); return n!==null&&n>=0&&n<=100?n:null; };
export function parseNvidiaReadings(raw) {
return raw.split('\n').flatMap(line=>{
- const [id,temp,load,memory,power,limit,gen,maxGen,width]=line.split(',').map(s=>s.trim());
+ const [id,temp,load,memory,power,limit,gen,maxGen,width,fan,clock]=line.split(',').map(s=>s.trim());
if (!id?.startsWith('GPU-')) return [];
const t=number(temp),u=number(load),m=number(memory);
const positive = v => { const n=number(v); return n!==null&&n>=0?n:null; };
- return [{id,temperatureC:t!==null&&t>=0&&t<=150?t:null,utilizationPct:u!==null&&u>=0&&u<=100?u:null,memoryUsedGb:m!==null&&m>=0?round(m/1024,2):null,powerW:positive(power),powerLimitW:positive(limit),pcieGen:positive(gen),pcieGenMax:positive(maxGen),pcieWidth:positive(width),pcieRxMbs:null}];
+ return [{id,temperatureC:t!==null&&t>=0&&t<=150?t:null,utilizationPct:u!==null&&u>=0&&u<=100?u:null,memoryUsedGb:m!==null&&m>=0?round(m/1024,2):null,powerW:positive(power),powerLimitW:positive(limit),pcieGen:positive(gen),pcieGenMax:positive(maxGen),pcieWidth:positive(width),pcieRxMbs:null,fanPct:percentOf(fan),clockMhz:positive(clock)}];
});
}
export function parsePcieThroughput(raw) {
@@ -77,7 +79,7 @@ export async function detectDrmGpus() {
export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, run = probe } = {}) {
const now=new Date().toISOString();
const hasNvidia=gpus.some(g=>g.vendor==='nvidia');
- let raw=hasNvidia?await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used,power.draw,power.limit,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current','--format=csv,noheader,nounits'],2000):'';
+ let raw=hasNvidia?await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used,power.draw,power.limit,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current,fan.speed,clocks.current.graphics','--format=csv,noheader,nounits'],2000):'';
// Older drivers can reject a field; retain their basic sensors in that case.
if(hasNvidia&&!raw)raw=await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used','--format=csv,noheader,nounits'],2000);
const nvidia=new Map(parseNvidiaReadings(raw).map(r=>[r.id,r]));
@@ -90,11 +92,13 @@ export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, ru
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;
+ let temperature=null,power=null,powerLimit=null,fanPwm=null,clockHz=null;
for(const hwmon of await list(`${gpu.sensorPath}/hwmon`)) {
const folder=`${gpu.sensorPath}/hwmon/${hwmon}`,inputs=(await list(folder)).filter(n=>/^temp\d+_input$/.test(n));
power ??= number(await read(`${folder}/power1_average`)) ?? number(await read(`${folder}/power1_input`));
powerLimit ??= number(await read(`${folder}/power1_cap`));
+ fanPwm ??= number(await read(`${folder}/pwm1`)); // 0-255, the fan's duty as the amdgpu driver reports it
+ clockHz ??= number(await read(`${folder}/freq1_input`)); // the graphics clock in Hz
for(const input of inputs) {
const label=await read(`${folder}/${input.replace('_input','_label')}`);
if(label&&!/edge|gpu/i.test(label))continue;
@@ -106,7 +110,7 @@ export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, ru
const utilization=number(await read(`${gpu.sensorPath}/gpu_busy_percent`)),bytes=number(await read(`${gpu.sensorPath}/mem_info_vram_used`));
const gen=path=>read(path).then(raw=>({2.5:1,5:2,8:3,16:4,32:5,64:6}[Number.parseFloat(raw)]??null));
const [pcieGen,pcieGenMax,width]=await Promise.all([gen(`${gpu.sensorPath}/current_link_speed`),gen(`${gpu.sensorPath}/max_link_speed`),read(`${gpu.sensorPath}/current_link_width`)]);
- reading={...reading,temperatureC:temperature,utilizationPct:utilization!==null&&utilization>=0&&utilization<=100?utilization:null,memoryUsedGb:bytes!==null&&bytes>=0?round(bytes/1024**3,2):null,powerW:power!==null&&power>=0?power/1e6:null,powerLimitW:powerLimit!==null&&powerLimit>=0?powerLimit/1e6:null,pcieGen,pcieGenMax,pcieWidth:number(width)};
+ reading={...reading,fanPct:fanPwm!==null&&fanPwm>=0&&fanPwm<=255?Math.round(fanPwm/255*100):null,clockMhz:clockHz!==null&&clockHz>0?Math.round(clockHz/1e6):null,temperatureC:temperature,utilizationPct:utilization!==null&&utilization>=0&&utilization<=100?utilization:null,memoryUsedGb:bytes!==null&&bytes>=0?round(bytes/1024**3,2):null,powerW:power!==null&&power>=0?power/1e6:null,powerLimitW:powerLimit!==null&&powerLimit>=0?powerLimit/1e6:null,pcieGen,pcieGenMax,pcieWidth:number(width)};
}
return {...reading,sampledAt:now,source:Object.entries(reading).some(([key,value])=>key!=='id'&&typeof value==='number')?'sensor':'none'};
}));
diff --git a/apps/host/server/energy-meter.mjs b/apps/host/server/energy-meter.mjs
new file mode 100644
index 000000000..9bed3eef4
--- /dev/null
+++ b/apps/host/server/energy-meter.mjs
@@ -0,0 +1,14 @@
+/**
+ * GPU energy since the host started, in Wh (#3628): the power reading held for the time since the last tick, added up.
+ * A long gap (the PC slept, the host was paused) counts for at most 5 s, so a sleep never adds a made-up hour of use.
+ */
+const meter = { wh: 0, at: 0 };
+
+export function addEnergy(powerW, at) {
+ const dt = meter.at ? Math.min((at - meter.at) / 1000, 5) : 0;
+ meter.at = at;
+ if (typeof powerW === 'number' && Number.isFinite(powerW) && powerW >= 0 && dt > 0) meter.wh += powerW * dt / 3600;
+ return meter.wh;
+}
+
+export const energyWh = () => meter.wh;
diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs
index d28418c8c..e059a6570 100644
--- a/apps/host/server/index.mjs
+++ b/apps/host/server/index.mjs
@@ -71,6 +71,8 @@ import { createRuntimeModels } from './runtime-models.mjs';
import { createNativeControl } from './native-control.mjs';
import { nativeUnloadPlan } from './storage-check.mjs';
import { installBundledEngine, cleanupAfterInstall } from './bundled-engine.mjs';
+import { systemLocale } from './region.mjs';
+import { createShellNotifier, DEFAULT_PORT, parsePortNotice, readShellPrefs, writeShellPrefs } from './shell-prefs.mjs';
import { findControl, createControl, componentsDirectory } from './control-runtime.mjs';
import { forbidden as acquisitionForbidden } from './acquisition.mjs';
import { randomBytes, timingSafeEqual } from 'node:crypto';
@@ -127,6 +129,19 @@ const appUi = createAppUi({ shutdown: () => shutdown() });
/* The app's version has one source: the desktop shell passes it (STRATA_APP_VERSION, from apps/desktop/src-tauri/Cargo.toml). Outside the app it is read from the same file in a checkout, else 'dev'. */
function appVersion() { return appVersionFrom({ env: process.env, here: HERE }); }
const appUpdater = appUi.updater;
+const shellNotifier = createShellNotifier();
+/** What the page needs for the desktop settings: whether this is the desktop app, the port in use, the saved choices and a busy-port notice. */
+function shellState() {
+ const saved = readShellPrefs();
+ const desktop = !!shellNotifier;
+ return {
+ desktop,
+ tray: desktop && process.platform !== 'linux',
+ port: PORT, defaultPort: DEFAULT_PORT,
+ pinnedPort: saved.port || null, minimizeToTray: saved.tray,
+ portNotice: parsePortNotice(process.env.STRATA_PORT_NOTICE),
+ };
+}
/* The engine that ships inside the installer is put in the components folder when this PC has none (or an older one); no network, hashes checked. The model list waits for it. */
const bundledEngine = control && !process.env.STRATA_NO_BUNDLED_ENGINE
? installBundledEngine({ bundleDir: process.env.STRATA_ENGINE_BUNDLE_DIR || resolve(HERE, '..', '..', 'engine-bundle'), components: componentsDirectory(), log: line => console.log(line) })
@@ -1932,6 +1947,19 @@ async function api(req, res, path, method, url) {
try { return json(res, 200, await agent.approve({ chatId: b.sessionId, callId: b.toolId, decision: b.decision })); }
catch (e) { return error(res, e.code === 'approval-gone' ? 409 : 400, e.message); }
}
+ /* The desktop shell's own choices (#3402, #3477): the port it asks for, the tray, and a desktop notification through the shell. */
+ if (path === '/api/locale' && method === 'GET') return json(res, 200, systemLocale());
+ if (path === '/api/shell' && method === 'GET') return json(res, 200, shellState());
+ if (path === '/api/shell/prefs' && method === 'POST') {
+ const b = await readBody(req);
+ try { writeShellPrefs(b); } catch (e) { return error(res, 400, e.message); }
+ return json(res, 200, shellState());
+ }
+ if (path === '/api/shell/notify' && method === 'POST') {
+ const b = await readBody(req);
+ if (!shellNotifier || typeof b.title !== 'string') return json(res, 200, { shown: false });
+ try { return json(res, 200, await shellNotifier.notify({ title: b.title, body: String(b.body ?? '') })); } catch { return json(res, 200, { shown: false }); }
+ }
/* The person changed the chat's mode while a turn runs: it applies to the next tool call, goal and helpers included. */
if (path === '/api/chat/mode' && method === 'POST') {
const b = await readBody(req);
diff --git a/apps/host/server/monitor.mjs b/apps/host/server/monitor.mjs
index e07e291fb..c861d9b97 100644
--- a/apps/host/server/monitor.mjs
+++ b/apps/host/server/monitor.mjs
@@ -4,6 +4,8 @@ import { detect, cachedHardware } from './hardware.mjs';
import { readGpuTelemetry, gpuMemoryTotals } from './device-probes.mjs';
import { createSystemSampler } from './system-telemetry.mjs';
import { sensorPace, WATCH_MS } from './sensor-pace.mjs';
+import { readTemperatures } from './temperature-telemetry.mjs';
+import { addEnergy, energyWh } from './energy-meter.mjs';
import { state as servingState } from './serving.mjs';
import { originalDashboard } from './monitor-dashboard.mjs';
import { get as getStore } from './store.mjs';
@@ -68,6 +70,8 @@ export function watch() {
}
export function setLiveProbe(probe) { liveProbe = typeof probe === 'function' ? probe : () => false; }
let systemReading=null;
+/* CPU and SSD temperatures (null where this PC cannot give one) and the GPU energy used since the host started (#3628). */
+let temperatures={cpuTempC:null,ssdTempC:null};
const sampleSystem=createSystemSampler();
const finite = value => typeof value==='number'&&Number.isFinite(value);
function aggregate(readings,key,mode='sum') {
@@ -80,7 +84,7 @@ function hardwareSnapshot() {
const demo=process.env.STRATA_REAL_ENGINE!=='1',hw=state.hardware;
const devices=cachedHardware()?.gpus??hwCache?.gpus??[];
const memoryPools=Math.max(1,devices.filter(g=>!g.unified).length+Number(devices.some(g=>g.unified)));
- const readings=demo?devices.map((gpu,i)=>({id:gpu.id??`${gpu.vendor}:${gpu.index}`,source:'demo',sampledAt:new Date().toISOString(),utilizationPct:Math.round(clamp(hw.gpuLoad+i*2,0,100)),temperatureC:Math.round(hw.gpuTempC+i),memoryUsedGb:round(Math.min(gpu.vramGb,hw.vramUsedGb/memoryPools),2),powerW:gpu.unified?null:round(35+hw.gpuLoad*2,0),powerLimitW:gpu.unified?null:300,pcieGen:gpu.unified?null:4,pcieGenMax:gpu.unified?null:4,pcieWidth:gpu.unified?null:16,pcieRxMbs:gpu.unified?null:round(hw.gpuLoad*1.2,1)})):hw.gpus.map(g=>({...g}));
+ const readings=demo?devices.map((gpu,i)=>({id:gpu.id??`${gpu.vendor}:${gpu.index}`,source:'demo',sampledAt:new Date().toISOString(),utilizationPct:Math.round(clamp(hw.gpuLoad+i*2,0,100)),temperatureC:Math.round(hw.gpuTempC+i),memoryUsedGb:round(Math.min(gpu.vramGb,hw.vramUsedGb/memoryPools),2),powerW:gpu.unified?null:round(35+hw.gpuLoad*2,0),powerLimitW:gpu.unified?null:300,pcieGen:gpu.unified?null:4,pcieGenMax:gpu.unified?null:4,pcieWidth:gpu.unified?null:16,pcieRxMbs:gpu.unified?null:round(hw.gpuLoad*1.2,1),fanPct:gpu.unified?null:Math.round(30+hw.gpuLoad*0.5),clockMhz:gpu.unified?null:Math.round(1400+hw.gpuLoad*14)})):hw.gpus.map(g=>({...g}));
const memory = gpuMemoryTotals(devices,readings);
return {
gpus:readings,cpus:systemReading?.cpus??[],cpuLoad:systemReading?.cpuLoad??null,
@@ -90,7 +94,9 @@ function hardwareSnapshot() {
ramUsedGb:systemReading?.ramUsedGb??null,ramTotalGb:systemReading?.ramTotalGb??hw.ramTotalGb,
gpuTempC:aggregate(readings,'temperatureC','max'),tempLimitC:hw.tempLimitC,
powerW:aggregate(readings,'powerW'),powerLimitW:aggregate(readings,'powerLimitW'),
- pcieRxMbs:aggregate(readings,'pcieRxMbs'),diskReadGbs:systemReading?.diskReadGbs??null,diskWriteMbs:systemReading?.diskWriteMbs??null,
+ pcieRxMbs:aggregate(readings,'pcieRxMbs'),
+ cpuTempC:demo?54:temperatures.cpuTempC,ssdTempC:demo?41:temperatures.ssdTempC,energyWh:round(energyWh(),3),
+ diskReadGbs:systemReading?.diskReadGbs??null,diskWriteMbs:systemReading?.diskWriteMbs??null,
};
}
@@ -121,11 +127,12 @@ function tick() {
if(!sensorsPending&&Date.now()-sensorsAt>=pace.intervalMs){
sensorsPending=true;sensorsAt=Date.now();
const hardware=cachedHardware()??hwCache;
- void Promise.all([readGpuTelemetry(hardware?.gpus??[],{transfer:pace.transfer}),sampleSystem(hardware?.processors??[])])
- .then(([readings,system])=>{state.hardware.gpus=readings;systemReading=system;})
+ void Promise.all([readGpuTelemetry(hardware?.gpus??[],{transfer:pace.transfer}),sampleSystem(hardware?.processors??[]),(process.env.STRATA_REAL_ENGINE==='1'?readTemperatures():Promise.resolve(temperatures)).catch(()=>({cpuTempC:null,ssdTempC:null}))])
+ .then(([readings,system,temps])=>{state.hardware.gpus=readings;systemReading=system;temperatures=temps;})
.catch(()=>{state.hardware.gpus=[];systemReading=null;})
.finally(()=>{sensorsPending=false;});
}
+ addEnergy(hardwareSnapshot().powerW,Date.now());
const hw = state.hardware;
const busy = state.phase === 'generating' || state.phase === 'reading' || state.phase === 'thinking';
diff --git a/apps/host/server/region.mjs b/apps/host/server/region.mjs
new file mode 100644
index 000000000..312b122cf
--- /dev/null
+++ b/apps/host/server/region.mjs
@@ -0,0 +1,66 @@
+/**
+ * The computer's regional format, for the Monitor's cost line (#3628): which region and, where the system names it, which currency the
+ * person uses. Read once, without PowerShell:
+ * Windows the regional format (Settings > Time & language > Region > Regional format) from the registry: LocaleName ("en-US"); when it
+ * names no region, the country or region setting (Geo\Name).
+ * macOS `defaults read -g AppleLocale` ("en_US", or "de_DE@currency=CHF" when the person set another currency).
+ * Linux LC_ALL, LC_MONETARY or LANG ("de_DE.UTF-8"), and the locale's own currency when `locale -k int_curr_symbol` answers.
+ * Nothing here is a guess: no region means no answer, and the page then falls back to its own language list.
+ */
+import { execFileSync } from 'node:child_process';
+
+const NONE = Object.freeze({ locale: null, region: null, currency: null, source: null });
+
+/** "en_US.UTF-8" / "de_DE@euro" / "zh-Hans-CN" -> { locale: "en-US", region: "US" } (null parts when the tag has none). */
+export function parseLocaleTag(text) {
+ const tag = String(text ?? '').trim().replace(/[.@].*$/, '').replace(/_/g, '-');
+ if (!tag || /^(c|posix)$/i.test(tag)) return { locale: null, region: null };
+ const parts = tag.split('-');
+ const region = parts.slice(1).find(p => /^[A-Za-z]{2}$/.test(p)) ?? null;
+ const language = /^[A-Za-z]{2,3}$/.test(parts[0]) ? parts[0].toLowerCase() : null;
+ if (!language) return { locale: null, region: null };
+ return { locale: region ? `${language}-${region.toUpperCase()}` : language, region: region ? region.toUpperCase() : null };
+}
+
+export function parseRegValue(out, name) {
+ const m = new RegExp(`^\\s*${name}\\s+REG_SZ\\s+(.*?)\\s*$`, 'mi').exec(String(out ?? ''));
+ return m ? m[1] : null;
+}
+
+const currencyCode = value => (/^[A-Z]{3}$/.test(String(value ?? '').trim().toUpperCase()) ? String(value).trim().toUpperCase() : null);
+
+export function detectRegion({ platform = process.platform, env = process.env, run = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', timeout: 4000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }) } = {}) {
+ try {
+ if (platform === 'win32') {
+ const intl = 'HKCU\\Control Panel\\International';
+ const named = parseLocaleTag(parseRegValue(run('reg', ['query', intl, '/v', 'LocaleName']), 'LocaleName'));
+ if (named.region) return { ...named, currency: null, source: 'windows' };
+ let geo = null;
+ try { geo = parseRegValue(run('reg', ['query', `${intl}\\Geo`, '/v', 'Name']), 'Name'); } catch { /* no country setting */ }
+ const region = /^[A-Za-z]{2}$/.test(geo ?? '') ? geo.toUpperCase() : null;
+ return region ? { locale: named.locale ? `${named.locale}-${region}` : null, region, currency: null, source: 'windows' } : { ...NONE };
+ }
+ if (platform === 'darwin') {
+ const raw = String(run('defaults', ['read', '-g', 'AppleLocale'])).trim();
+ const named = parseLocaleTag(raw);
+ const currency = currencyCode(/@currency=([A-Za-z]{3})/.exec(raw)?.[1]);
+ return named.region || currency ? { ...named, currency, source: 'macos' } : { ...NONE };
+ }
+ const named = parseLocaleTag(env.LC_ALL || env.LC_MONETARY || env.LANG);
+ let currency = null;
+ try { currency = currencyCode(/int_curr_symbol="?([A-Za-z]{3})/.exec(run('locale', ['-k', 'int_curr_symbol']))?.[1]); } catch { /* no locale command */ }
+ return named.region || currency ? { ...named, currency, source: 'linux' } : { ...NONE };
+ } catch {
+ return { ...NONE };
+ }
+}
+
+let cached = null;
+/** The answer is cached: the regional format does not change while the host runs. */
+export function systemLocale(options) {
+ if (options) return detectRegion(options);
+ // A test or a demo can name the regional format (the screenshots of the Monitor); a packaged app never reads it.
+ if (process.env.STRATA_TEST_LOCALE && process.env.STRATA_PACKAGED !== '1') { const named = parseLocaleTag(process.env.STRATA_TEST_LOCALE); return { ...named, currency: null, source: 'test' }; }
+ cached ??= detectRegion();
+ return cached;
+}
diff --git a/apps/host/server/shell-prefs.mjs b/apps/host/server/shell-prefs.mjs
new file mode 100644
index 000000000..a81237f8a
--- /dev/null
+++ b/apps/host/server/shell-prefs.mjs
@@ -0,0 +1,77 @@
+/**
+ * The desktop shell's own choices, kept in <Strata data folder>/shell-prefs.json (#3402, #3477): the shell reads the file when it starts
+ * (the port it asks for, whether closing the window keeps Strata in the tray, the language of the tray menu), before any page exists.
+ * The page changes them through the host (POST /api/shell/prefs); a change of the port or the tray applies the next time Strata starts.
+ *
+ * { "port": 0 | 1024..65535, "tray": false, "language": "en" }
+ *
+ * Port 0 is the default: the shell asks for 47831 and takes a free port when that one is busy.
+ */
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { componentsDirectory } from './control-runtime.mjs';
+
+export const DEFAULT_PORT = 47831;
+export const LANGUAGES = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];
+export const DEFAULTS = Object.freeze({ port: 0, tray: false, language: 'en' });
+
+export const validPort = value => Number.isInteger(value) && value >= 1024 && value <= 65535;
+
+export function shellPrefsFile({ env = process.env } = {}) {
+ return join(dirname(componentsDirectory({ env })), 'shell-prefs.json');
+}
+
+/** The file's content with every field checked; anything missing or wrong is the default. */
+export function cleanPrefs(raw) {
+ const value = raw && typeof raw === 'object' ? raw : {};
+ return {
+ port: validPort(value.port) ? value.port : 0,
+ tray: value.tray === true,
+ language: LANGUAGES.includes(value.language) ? value.language : 'en',
+ };
+}
+
+export function readShellPrefs(file = shellPrefsFile()) {
+ try { return cleanPrefs(JSON.parse(readFileSync(file, 'utf8').replace(/^/, ''))); } catch { return { ...DEFAULTS }; }
+}
+
+/** Merge a change into the file. Throws a plain sentence for a port that cannot be used. */
+export function writeShellPrefs(patch, file = shellPrefsFile()) {
+ const next = readShellPrefs(file);
+ if (patch && 'port' in patch) {
+ const wanted = patch.port === null || patch.port === '' || patch.port === 0 ? 0 : Number(patch.port);
+ if (wanted !== 0 && !validPort(wanted)) throw new Error('Choose a port between 1024 and 65535, or leave it empty to let Strata choose.');
+ next.port = wanted;
+ }
+ if (patch && 'tray' in patch) next.tray = patch.tray === true;
+ if (patch && 'language' in patch && LANGUAGES.includes(patch.language)) next.language = patch.language;
+ mkdirSync(dirname(file), { recursive: true });
+ const temporary = `${file}.${process.pid}.tmp`;
+ writeFileSync(temporary, JSON.stringify(next, null, 2) + '\n');
+ renameSync(temporary, file);
+ return next;
+}
+
+/**
+ * What the shell tells the host about this start: STRATA_PORT_NOTICE is "busy:<wanted>:<used>" when the port it wanted was taken
+ * (set by the shell, never by the person). The page turns it into a sentence in the person's language.
+ */
+export function parsePortNotice(value) {
+ const m = /^busy:(\d{1,5}):(\d{1,5})$/.exec(String(value ?? ''));
+ return m ? { wanted: Number(m[1]), used: Number(m[2]) } : null;
+}
+
+/** The notification route of the shell's bridge (loopback, token). Null outside the desktop app. */
+export function createShellNotifier({ env = process.env, fetcher = fetch } = {}) {
+ const base = env.STRATA_SHELL_BRIDGE, token = env.STRATA_SHELL_TOKEN;
+ if (!base || !token || !/^http:\/\/127\.0\.0\.1:\d+$/.test(base)) return null;
+ return {
+ async notify({ title, body }) {
+ const query = `title=${encodeURIComponent(String(title ?? '').slice(0, 120))}&body=${encodeURIComponent(String(body ?? '').slice(0, 300))}`;
+ const response = await fetcher(`${base}/shell/notify?${query}`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(5000) });
+ let reply = null;
+ try { reply = await response.json(); } catch { /* no body */ }
+ return { shown: response.ok && reply?.shown === true };
+ },
+ };
+}
diff --git a/apps/host/server/temperature-telemetry.mjs b/apps/host/server/temperature-telemetry.mjs
new file mode 100644
index 000000000..0417dc043
--- /dev/null
+++ b/apps/host/server/temperature-telemetry.mjs
@@ -0,0 +1,124 @@
+/**
+ * CPU and SSD temperatures for the Monitor's Power card (#3628). A value that this PC cannot give stays null and its line is left out,
+ * so the card never shows a made-up number.
+ *
+ * Linux: the kernel's hwmon sensors (coretemp, k10temp, zenpower for the processor; nvme and drivetemp for the drives).
+ * Windows: the drive reports its own temperature to a query that needs no administrator (IOCTL_STORAGE_QUERY_PROPERTY with the device
+ * temperature property). Get-StorageReliabilityCounter is tried first because it is the documented route; on a normal account it is
+ * refused, then the query is used. One long-lived PowerShell asks every 30 s (windows-poll.mjs).
+ * There is no unprivileged, trustworthy processor temperature on Windows, so none is shown there.
+ * macOS: none.
+ */
+import { readFile, readdir } from 'node:fs/promises';
+import { spawn } from 'node:child_process';
+import { createPowerShellLoop, endWithHost } from './windows-poll.mjs';
+
+const CPU_SENSORS = new Set(['coretemp', 'k10temp', 'zenpower', 'cpu_thermal', 'cpu-thermal']);
+const DISK_SENSORS = new Set(['nvme', 'drivetemp']);
+const plausible = c => Number.isFinite(c) && c > 0 && c < 150;
+
+/** hwmon entries [{name, temps: [milli-degrees…]}] -> the hottest processor and drive sensor. */
+export function pickTemperatures(entries) {
+ let cpu = null, ssd = null;
+ for (const { name, temps } of entries) {
+ const hottest = Math.max(...temps.map(t => t / 1000).filter(plausible), -Infinity);
+ if (!Number.isFinite(hottest)) continue;
+ if (CPU_SENSORS.has(name)) cpu = Math.max(cpu ?? -Infinity, hottest);
+ else if (DISK_SENSORS.has(name)) ssd = Math.max(ssd ?? -Infinity, hottest);
+ }
+ return { cpuTempC: cpu === null ? null : Math.round(cpu), ssdTempC: ssd === null ? null : Math.round(ssd) };
+}
+
+export async function readLinuxTemperatures({ base = '/sys/class/hwmon', read = readFile, list = readdir } = {}) {
+ const entries = [];
+ let folders = [];
+ try { folders = await list(base); } catch { return { cpuTempC: null, ssdTempC: null }; }
+ for (const folder of folders) {
+ try {
+ const name = String(await read(`${base}/${folder}/name`, 'utf8')).trim();
+ if (!CPU_SENSORS.has(name) && !DISK_SENSORS.has(name)) continue;
+ const files = (await list(`${base}/${folder}`)).filter(f => /^temp\d+_input$/.test(f));
+ const temps = [];
+ for (const file of files) temps.push(Number(String(await read(`${base}/${folder}/${file}`, 'utf8')).trim()));
+ entries.push({ name, temps });
+ } catch { /* a sensor that disappears is skipped */ }
+ }
+ return pickTemperatures(entries);
+}
+
+/** One line of the Windows loop: "ssd 53" or "ssd -". */
+export function parseSsdLine(line) {
+ const m = /^\s*ssd\s+(-?\d+|-)\s*$/.exec(String(line));
+ if (!m) return undefined;
+ const value = m[1] === '-' ? NaN : Number(m[1]);
+ return plausible(value) ? value : null;
+}
+
+const WINDOWS_SCRIPT = String.raw`
+$ErrorActionPreference='SilentlyContinue'
+$cs=@'
+using System;
+using System.Runtime.InteropServices;
+public static class StrataDiskTemp {
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateFile(string n, uint a, uint s, IntPtr p, uint d, uint f, IntPtr t);
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool DeviceIoControl(IntPtr h, uint c, byte[] i, uint il, byte[] o, uint ol, out uint r, IntPtr ov);
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
+ public static int Read(int n) {
+ IntPtr h = CreateFile("\\\\.\\PhysicalDrive" + n, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
+ if (h == (IntPtr)(-1)) return -1;
+ try {
+ byte[] q = new byte[12]; q[0] = 0x34; byte[] o = new byte[512]; uint r;
+ if (!DeviceIoControl(h, 0x002D1400, q, 12, o, 512, out r, IntPtr.Zero)) return -1;
+ if (BitConverter.ToUInt16(o, 12) < 1) return -1;
+ return BitConverter.ToInt16(o, 26);
+ } finally { CloseHandle(h); }
+ }
+}
+'@
+$compiled=$false
+while($true){
+ $max=-1
+ $c=@(Get-PhysicalDisk | Get-StorageReliabilityCounter | Where-Object { $_.Temperature -gt 0 })
+ if($c.Count -gt 0){ $max=($c | Measure-Object Temperature -Maximum).Maximum }
+ else {
+ if(-not $compiled){ Add-Type -TypeDefinition $cs; $compiled=$true }
+ foreach($n in 0..15){ $v=[StrataDiskTemp]::Read($n); if($v -gt $max){ $max=$v } }
+ }
+ if($max -gt 0){ [Console]::Out.WriteLine('ssd '+$max) } else { [Console]::Out.WriteLine('ssd -') }
+ [Console]::Out.Flush()
+ Start-Sleep -Seconds 30
+}`;
+
+export function createWindowsSsdReader({ spawnFn = spawn, maxStarts = 2, now = Date.now, intervalSec = 30 } = {}) {
+ let latest = null;
+ const loop = createPowerShellLoop({
+ script: WINDOWS_SCRIPT, spawnFn, maxStarts,
+ onLine: line => {
+ const parsed = parseSsdLine(line);
+ if (parsed === undefined) return false;
+ latest = { value: parsed, at: now() };
+ return true;
+ },
+ });
+ return {
+ read() { loop.start(); return latest && now() - latest.at < 4 * intervalSec * 1000 ? latest.value : null; },
+ stop() { loop.stop(); },
+ get starts() { return loop.starts; },
+ };
+}
+
+let windowsReader = null;
+let linuxCache = { at: 0, value: { cpuTempC: null, ssdTempC: null } };
+
+/** The temperatures this PC can give now: { cpuTempC, ssdTempC } (null where unreadable). Cheap to call every few seconds. */
+export async function readTemperatures({ platform = process.platform, now = Date.now } = {}) {
+ if (platform === 'linux') {
+ if (now() - linuxCache.at > 10_000) linuxCache = { at: now(), value: await readLinuxTemperatures() };
+ return linuxCache.value;
+ }
+ if (platform === 'win32') {
+ windowsReader ??= endWithHost(createWindowsSsdReader());
+ return { cpuTempC: null, ssdTempC: windowsReader.read() };
+ }
+ return { cpuTempC: null, ssdTempC: null };
+}
diff --git a/apps/host/src/components/ElectricityPrice.tsx b/apps/host/src/components/ElectricityPrice.tsx
new file mode 100644
index 000000000..168518773
--- /dev/null
+++ b/apps/host/src/components/ElectricityPrice.tsx
@@ -0,0 +1,29 @@
+import { useEffect, useMemo, useState } from 'react';
+import { currencyChoices, currencyLabel } from '../lib/currency';
+import { tr } from '../lib/i18n';
+import { useMoney } from '../lib/money';
+import { setElectricity, useStore } from '../lib/store';
+import { Btn, Select } from './ui';
+
+/**
+ * The price of one kWh for the Monitor's cost line (#3628). The person types only the number: the currency is the one of the computer's
+ * region, shown beside it. "Change currency" is a way to pick another one, never a step that has to be taken.
+ */
+export function ElectricityPrice() {
+ const price = useStore(s => s.electricityPrice), override = useStore(s => s.electricityCurrency);
+ const money = useMoney();
+ const [text, setText] = useState(price > 0 ? String(price) : ''), [picking, setPicking] = useState(false);
+ useEffect(() => { setText(price > 0 ? String(price) : ''); }, [price]);
+ const commit = () => setElectricity(Number(text.replace(',', '.')), override);
+ const choices = useMemo(() => currencyChoices(money.locale), [money.locale]);
+ return <span className="stack">
+ <span className="row">
+ <input className="st-input" inputMode="decimal" size={7} aria-label={tr("Price per kWh")} placeholder="0.30" value={text} onChange={e => setText(e.target.value)} onBlur={commit} onKeyDown={e => { if (e.key === 'Enter') commit(); }}/>
+ <span className="small muted">{money.currency ? tr("per kWh, in {0}", [currencyLabel(money.currency, money.locale)]) : tr("per kWh")}</span>
+ <Btn size="sm" onClick={() => setPicking(v => !v)}>{tr("Change currency")}</Btn>
+ </span>
+ {picking ? <Select ariaLabel={tr("Currency")} translateLabels={false} value={override}
+ options={[{ value: '', label: tr("Automatic ({0})", [money.detected ?? '—']) }, ...choices]}
+ onChange={value => { setElectricity(price, String(value)); setPicking(false); }}/> : null}
+ </span>;
+}
diff --git a/apps/host/src/components/ShellSettings.tsx b/apps/host/src/components/ShellSettings.tsx
new file mode 100644
index 000000000..32cf0839e
--- /dev/null
+++ b/apps/host/src/components/ShellSettings.tsx
@@ -0,0 +1,74 @@
+import { useEffect, useState } from 'react';
+import { api } from '../lib/client';
+import { tr } from '../lib/i18n';
+import { askNotificationPermission, playDoneSound } from '../lib/attention';
+import { setApprovalNotify, setDoneSound, useStore } from '../lib/store';
+import { Btn } from './ui';
+
+/** What the host says about the desktop shell (GET /api/shell): null in a browser or while it loads. */
+export interface ShellState {
+ desktop: boolean;
+ tray: boolean;
+ port: number;
+ defaultPort: number;
+ pinnedPort: number | null;
+ minimizeToTray: boolean;
+ portNotice: { wanted: number; used: number } | null;
+}
+
+export function useShellState(): [ShellState | null, (patch: { port?: number | null; tray?: boolean }) => Promise<string | null>] {
+ const [shell, setShell] = useState<ShellState | null>(null);
+ useEffect(() => {
+ let alive = true;
+ api.get<ShellState>('/api/shell').then(s => { if (alive) setShell(s); }).catch(() => undefined);
+ return () => { alive = false; };
+ }, []);
+ const save = async (patch: { port?: number | null; tray?: boolean }) => {
+ try { setShell(await api.post<ShellState>('/api/shell/prefs', patch)); return null; }
+ catch (error) { return error instanceof Error ? error.message : 'The choice was not saved.'; }
+ };
+ return [shell, save];
+}
+
+/** The sound for finished work (#3586): off until switched on, with a button to hear it. */
+export function DoneSoundSetting() {
+ const on = useStore(s => s.doneSound);
+ return <span className="row">
+ <Btn size="sm" onClick={() => playDoneSound()}>{tr("Play sound")}</Btn>
+ <button className="st-toggle" role="switch" aria-checked={on} aria-label={tr("Sound when work finishes")} onClick={() => setDoneSound(!on)}/>
+ </span>;
+}
+
+/** A desktop notification when Manual mode waits for an approval (#3477). */
+export function ApprovalNotifySetting() {
+ const on = useStore(s => s.approvalNotify);
+ return <button className="st-toggle" role="switch" aria-checked={on} aria-label={tr("Notify me when Strata needs an answer")}
+ onClick={() => { if (!on) void askNotificationPermission(); setApprovalNotify(!on); }}/>;
+}
+
+/** Keep the app running in the tray when its window is closed (#3477). Desktop app on Windows and macOS only. */
+export function TraySetting({ shell, save }: { shell: ShellState; save: (patch: { tray: boolean }) => Promise<string | null> }) {
+ return <button className="st-toggle" role="switch" aria-checked={shell.minimizeToTray} aria-label={tr("Minimise to tray")} onClick={() => void save({ tray: !shell.minimizeToTray })}/>;
+}
+
+/** The port the app's window and local address use (#3402). Empty lets Strata choose; the choice applies the next time Strata starts. */
+export function PortSetting({ shell, save }: { shell: ShellState; save: (patch: { port: number | null }) => Promise<string | null> }) {
+ const [text, setText] = useState(shell.pinnedPort ? String(shell.pinnedPort) : ''), [problem, setProblem] = useState('');
+ useEffect(() => { setText(shell.pinnedPort ? String(shell.pinnedPort) : ''); }, [shell.pinnedPort]);
+ const commit = async () => {
+ const trimmed = text.trim();
+ if (trimmed === (shell.pinnedPort ? String(shell.pinnedPort) : '')) { setProblem(''); return; }
+ if (trimmed === '') { setProblem((await save({ port: null })) ?? ''); return; }
+ const value = Number(trimmed);
+ if (!Number.isInteger(value) || value < 1024 || value > 65535) { setProblem(tr("Choose a port between 1024 and 65535, or leave it empty.")); return; }
+ setProblem((await save({ port: value })) ?? '');
+ };
+ return <span className="stack">
+ <span className="row">
+ <input className="st-input" inputMode="numeric" size={7} aria-label={tr("Port (empty = automatic)")} placeholder={String(shell.defaultPort)} value={text}
+ onChange={e => setText(e.target.value.replace(/[^0-9]/g, '').slice(0, 5))} onBlur={() => void commit()} onKeyDown={e => { if (e.key === 'Enter') void commit(); }}/>
+ </span>
+ <span className="xs muted">{tr("Using port {0} now.", [shell.port])}</span>
+ {problem ? <span className="xs" role="alert">{problem}</span> : null}
+ </span>;
+}
diff --git a/apps/host/src/lib/attention.ts b/apps/host/src/lib/attention.ts
new file mode 100644
index 000000000..46d19c5fc
--- /dev/null
+++ b/apps/host/src/lib/attention.ts
@@ -0,0 +1,85 @@
+/**
+ * Telling the person that Strata needs them or has finished (#3586, #3477). Both are opt-in and off by default.
+ *
+ * - A short sound when an answer or task that took a while is finished, or when Strata is in the background (public/strata-done-sound.wav,
+ * made for Strata from sine waves, no sample).
+ * - A desktop notification when Manual mode waits for an approval and Strata is in the background. The desktop app shows it through its own
+ * shell (the host passes it on, so it also works while the window is hidden in the tray); a browser uses the page's notifications.
+ */
+import { api } from './client';
+import { tr } from './i18n';
+
+/** An answer that came back faster than this does not chime while the person is looking at the window. */
+export const QUICK_MS = 8000;
+const SOUND_URL = '/strata-done-sound.wav';
+const MIN_GAP_MS = 2000;
+let lastPlayed = 0;
+
+export interface DoneContext { enabled: boolean; durationMs: number; focused: boolean; now?: number }
+
+/** Whether the finished-work sound should play now: only when asked for, only for work that took a while or when the window is not in front. */
+export function shouldPlayDone({ enabled, durationMs, focused, now = Date.now() }: DoneContext): boolean {
+ if (!enabled) return false;
+ if (now - lastPlayed < MIN_GAP_MS) return false;
+ return !focused || durationMs >= QUICK_MS;
+}
+
+export const windowInFront = (): boolean => typeof document !== 'undefined' && document.visibilityState === 'visible' && document.hasFocus();
+
+export function playDoneSound(make: (url: string) => { volume: number; play(): Promise<void> | void } = url => new Audio(url)): boolean {
+ try {
+ const audio = make(SOUND_URL);
+ audio.volume = 0.6;
+ lastPlayed = Date.now();
+ const started = audio.play();
+ if (started && typeof (started as Promise<void>).catch === 'function') (started as Promise<void>).catch(() => { /* the browser asked for a click first: no sound this time */ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Called when an answer or a task is finished. */
+export function workFinished(enabled: boolean, durationMs: number): void {
+ if (shouldPlayDone({ enabled, durationMs, focused: windowInFront() })) playDoneSound();
+}
+
+export interface Notice { title: string; body: string }
+
+/** The sentence of the approval notification, in the person's language. */
+export function approvalNotice(tool: string): Notice {
+ return { title: tr('Strata needs your answer'), body: tr('The assistant wants to use {0}. Open Strata to approve or deny.', [tool || tr('a tool')]) };
+}
+
+/** Shows a notification through the desktop shell when there is one, else through the page. Returns whether something was shown. */
+export async function showNotice(notice: Notice, deps: { post?: (body: Notice) => Promise<{ shown?: boolean }>; page?: (notice: Notice) => boolean } = {}): Promise<boolean> {
+ const post = deps.post ?? (body => api.post<{ shown?: boolean }>('/api/shell/notify', body));
+ try {
+ const result = await post(notice);
+ if (result?.shown) return true;
+ } catch { /* no shell here: the page's own notification below */ }
+ return (deps.page ?? pageNotification)(notice);
+}
+
+function pageNotification(notice: Notice): boolean {
+ try {
+ if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return false;
+ new Notification(notice.title, { body: notice.body, tag: 'strata-approval' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Manual mode waits for an approval. Only a window that is not in front needs the notification. */
+export function approvalNeeded(enabled: boolean, tool: string, focused = windowInFront()): Promise<boolean> {
+ if (!enabled || focused) return Promise.resolve(false);
+ return showNotice(approvalNotice(tool));
+}
+
+/** Turning approval notifications on in a browser asks the page's permission once; the desktop shell needs none. */
+export async function askNotificationPermission(): Promise<void> {
+ try {
+ if (typeof Notification !== 'undefined' && Notification.permission === 'default') await Notification.requestPermission();
+ } catch { /* some web views have none */ }
+}
diff --git a/apps/host/src/lib/currency.ts b/apps/host/src/lib/currency.ts
new file mode 100644
index 000000000..3a7a7a51f
--- /dev/null
+++ b/apps/host/src/lib/currency.ts
@@ -0,0 +1,114 @@
+/**
+ * The currency of the Monitor's cost line (#3628): the person's own, found from the computer's region, never typed and never a guess.
+ *
+ * Order: the system (the host reads the regional format of Windows, macOS or Linux: its region, or its currency when the system names one),
+ * then the browser's language list, then the region of the app's language, and then no currency at all: the number is shown without a
+ * symbol rather than in a currency the person does not use. A currency picked in Settings overrides all of this.
+ */
+
+/** ISO 3166 region -> ISO 4217 currency. */
+const PAIRS = `AD:EUR AE:AED AF:AFN AG:XCD AI:XCD AL:ALL AM:AMD AO:AOA AR:ARS AS:USD AT:EUR AU:AUD AW:AWG AX:EUR AZ:AZN
+BA:BAM BB:BBD BD:BDT BE:EUR BF:XOF BG:EUR BH:BHD BI:BIF BJ:XOF BL:EUR BM:BMD BN:BND BO:BOB BQ:USD BR:BRL BS:BSD BT:BTN BV:NOK BW:BWP BY:BYN BZ:BZD
+CA:CAD CC:AUD CD:CDF CF:XAF CG:XAF CH:CHF CI:XOF CK:NZD CL:CLP CM:XAF CN:CNY CO:COP CR:CRC CU:CUP CV:CVE CW:XCG CX:AUD CY:EUR CZ:CZK
+DE:EUR DJ:DJF DK:DKK DM:XCD DO:DOP DZ:DZD EC:USD EE:EUR EG:EGP EH:MAD ER:ERN ES:EUR ET:ETB FI:EUR FJ:FJD FK:FKP FM:USD FO:DKK FR:EUR
+GA:XAF GB:GBP GD:XCD GE:GEL GF:EUR GG:GBP GH:GHS GI:GIP GL:DKK GM:GMD GN:GNF GP:EUR GQ:XAF GR:EUR GS:GBP GT:GTQ GU:USD GW:XOF GY:GYD
+HK:HKD HM:AUD HN:HNL HR:EUR HT:HTG HU:HUF ID:IDR IE:EUR IL:ILS IM:GBP IN:INR IO:USD IQ:IQD IR:IRR IS:ISK IT:EUR
+JE:GBP JM:JMD JO:JOD JP:JPY KE:KES KG:KGS KH:KHR KI:AUD KM:KMF KN:XCD KP:KPW KR:KRW KW:KWD KY:KYD KZ:KZT
+LA:LAK LB:LBP LC:XCD LI:CHF LK:LKR LR:LRD LS:LSL LT:EUR LU:EUR LV:EUR LY:LYD
+MA:MAD MC:EUR MD:MDL ME:EUR MF:EUR MG:MGA MH:USD MK:MKD ML:XOF MM:MMK MN:MNT MO:MOP MP:USD MQ:EUR MR:MRU MS:XCD MT:EUR MU:MUR MV:MVR MW:MWK MX:MXN MY:MYR MZ:MZN
+NA:NAD NC:XPF NE:XOF NF:AUD NG:NGN NI:NIO NL:EUR NO:NOK NP:NPR NR:AUD NU:NZD NZ:NZD OM:OMR
+PA:PAB PE:PEN PF:XPF PG:PGK PH:PHP PK:PKR PL:PLN PM:EUR PR:USD PS:ILS PT:EUR PW:USD PY:PYG QA:QAR RE:EUR RO:RON RS:RSD RU:RUB RW:RWF
+SA:SAR SB:SBD SC:SCR SD:SDG SE:SEK SG:SGD SH:SHP SI:EUR SJ:NOK SK:EUR SL:SLE SM:EUR SN:XOF SO:SOS SR:SRD SS:SSP ST:STN SV:USD SX:XCG SY:SYP SZ:SZL
+TC:USD TD:XAF TF:EUR TG:XOF TH:THB TJ:TJS TK:NZD TL:USD TM:TMT TN:TND TO:TOP TR:TRY TT:TTD TV:AUD TW:TWD TZ:TZS
+UA:UAH UG:UGX UM:USD US:USD UY:UYU UZ:UZS VA:EUR VC:XCD VE:VES VG:USD VI:USD VN:VND VU:VUV WF:XPF WS:WST XK:EUR YE:YER YT:EUR ZA:ZAR ZM:ZMW ZW:ZWG`;
+
+export const REGION_CURRENCY: Readonly<Record<string, string>> = Object.freeze(Object.fromEntries(PAIRS.split(/\s+/).map(pair => pair.split(':') as [string, string])));
+
+/** The region of each app language that has one region of its own; English and Spanish-speaking countries are many, so only the first is a guess. */
+export const LANGUAGE_REGION: Readonly<Record<string, string>> = Object.freeze({ zh: 'CN', ja: 'JP', de: 'DE', es: 'ES', ru: 'RU', pt: 'BR', ko: 'KR' });
+
+export const currencyForRegion = (region: string | null | undefined): string | null => (region ? REGION_CURRENCY[region.toUpperCase()] ?? null : null);
+
+/** The region in a language tag ("en-US", "de_DE.UTF-8", "zh-Hans-CN"), or null when the tag names none. */
+export function regionOfLocale(tag: string | null | undefined): string | null {
+ if (!tag) return null;
+ const clean = String(tag).replace(/[.@].*$/, '').replace(/_/g, '-');
+ try {
+ const region = new Intl.Locale(clean).region;
+ return region ?? null;
+ } catch {
+ const found = /-([A-Za-z]{2})(?:-|$)/.exec(clean);
+ return found ? found[1].toUpperCase() : null;
+ }
+}
+
+/** What the host read from the system (GET /api/locale). */
+export interface SystemLocale { locale: string | null; region: string | null; currency: string | null; source: string | null }
+
+export interface ResolvedCurrency { currency: string | null; locale: string; source: 'system' | 'browser' | 'language' | 'none' }
+
+/**
+ * The currency to show money in, and the locale to write the number in.
+ * `override` is the currency the person chose in Settings (empty: automatic).
+ */
+export function resolveCurrency({ system, browserLanguages = [], language, override = '' }: { system?: SystemLocale | null; browserLanguages?: readonly string[]; language: string; override?: string }): ResolvedCurrency {
+ const appTag = language === 'zh' ? 'zh-CN' : language;
+ const locale = system?.locale ?? browserLanguages.find(tag => regionOfLocale(tag)) ?? browserLanguages[0] ?? appTag;
+ if (/^[A-Za-z]{3}$/.test(override)) return { currency: override.toUpperCase(), locale, source: 'system' };
+ const fromSystem = system?.currency ?? currencyForRegion(system?.region);
+ if (fromSystem) return { currency: fromSystem, locale, source: 'system' };
+ for (const tag of browserLanguages) {
+ const found = currencyForRegion(regionOfLocale(tag));
+ if (found) return { currency: found, locale, source: 'browser' };
+ }
+ const fromLanguage = currencyForRegion(LANGUAGE_REGION[language]);
+ if (fromLanguage) return { currency: fromLanguage, locale, source: 'language' };
+ return { currency: null, locale, source: 'none' };
+}
+
+/** How many decimals this currency normally has (2 for dollars and euros, 0 for yen); 2 when there is no currency. */
+export function minorDigits(currency: string | null, locale: string): number {
+ if (!currency) return 2;
+ try { return new Intl.NumberFormat(locale, { style: 'currency', currency }).resolvedOptions().maximumFractionDigits ?? 2; } catch { return 2; }
+}
+
+/**
+ * An amount of money, written for the person's locale with the currency's usual digits ("$0.12", "$1.23", "1,23 €", "¥3").
+ * An amount below the smallest normal unit (one cent; one yen) is not shown as 0.00 or as a long run of decimals but as
+ * "less than $0.01" (`lessThan` writes the sentence in the person's language). With no currency the number is shown alone,
+ * and never in a currency that was only guessed.
+ */
+export function formatMoney(amount: number, { currency, locale, lessThan = shown => `less than ${shown}` }: { currency: string | null; locale: string; lessThan?: (shown: string) => string }): string {
+ if (!Number.isFinite(amount) || amount < 0) return '—';
+ const digits = minorDigits(currency, locale), unit = 10 ** -digits;
+ const write = (value: number): string => {
+ try {
+ if (currency) return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value);
+ } catch { /* an unknown currency code or locale: the number alone */ }
+ try {
+ return new Intl.NumberFormat(locale, { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value);
+ } catch {
+ return value.toFixed(digits);
+ }
+ };
+ return amount > 0 && amount < unit ? lessThan(write(unit)) : write(amount);
+}
+
+/** "USD ($)": the code and its symbol in the person's locale, for the Settings line. */
+export function currencyLabel(currency: string, locale: string): string {
+ try {
+ const symbol = new Intl.NumberFormat(locale, { style: 'currency', currency, currencyDisplay: 'narrowSymbol' }).formatToParts(0).find(part => part.type === 'currency')?.value;
+ return symbol && symbol !== currency ? `${currency} (${symbol})` : currency;
+ } catch {
+ return currency;
+ }
+}
+
+/** Every currency this web view knows, by name, for the override list. */
+export function currencyChoices(locale: string): { value: string; label: string }[] {
+ let codes: string[] = [];
+ try { codes = (Intl as unknown as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.('currency') ?? []; } catch { /* an older web view */ }
+ let names: Intl.DisplayNames | null = null;
+ try { names = new Intl.DisplayNames([locale], { type: 'currency' }); } catch { /* no names */ }
+ return codes.map(code => ({ value: code, label: `${code} – ${names?.of(code) ?? code}` }));
+}
diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts
index 952e3ca2e..628f1f372 100644
--- a/apps/host/src/lib/i18n.ts
+++ b/apps/host/src/lib/i18n.ts
@@ -23,6 +23,15 @@ 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';
+/* The strings of the 0.2.7 GitHub items (gh-<lang>.json, scripts/make-gh-locales.py). */
+import gh_en from '../locales/gh-en.json';
+import gh_zh from '../locales/gh-zh.json';
+import gh_ja from '../locales/gh-ja.json';
+import gh_de from '../locales/gh-de.json';
+import gh_es from '../locales/gh-es.json';
+import gh_ru from '../locales/gh-ru.json';
+import gh_pt from '../locales/gh-pt.json';
+import gh_ko from '../locales/gh-ko.json';
import base_zh from '../locales/zh.json';
import base_ja from '../locales/ja.json';
import base_de from '../locales/de.json';
@@ -36,8 +45,8 @@ 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. */
/* 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 english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en};
+const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko}] as Record<string,string>[];
const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,es,ru,pt,ko};
const entities:Record<string,string>={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'};
const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole);
diff --git a/apps/host/src/lib/money.ts b/apps/host/src/lib/money.ts
new file mode 100644
index 000000000..9da6d759d
--- /dev/null
+++ b/apps/host/src/lib/money.ts
@@ -0,0 +1,28 @@
+import { useEffect, useState } from 'react';
+import { tr } from './i18n';
+import { api } from './client';
+import { formatMoney, resolveCurrency, type ResolvedCurrency, type SystemLocale } from './currency';
+import { useStore } from './store';
+
+let asked: Promise<SystemLocale | null> | null = null;
+
+/** The computer's regional format, read once from the host (null in a browser build that has none, or while it loads). */
+export function useSystemLocale(): SystemLocale | null {
+ const [value, setValue] = useState<SystemLocale | null>(null);
+ useEffect(() => {
+ let alive = true;
+ asked ??= api.get<SystemLocale>('/api/locale').catch(() => null);
+ void asked.then(v => { if (alive) setValue(v); });
+ return () => { alive = false; };
+ }, []);
+ return value;
+}
+
+/** The person's currency and locale for money (#3628) and a function that writes an amount in them. */
+export function useMoney(): ResolvedCurrency & { format: (amount: number) => string; detected: string | null } {
+ const system = useSystemLocale(), language = useStore(s => s.language), override = useStore(s => s.electricityCurrency);
+ const browserLanguages = typeof navigator === 'undefined' ? [] : [...(navigator.languages ?? [navigator.language])].filter(Boolean);
+ const resolved = resolveCurrency({ system, browserLanguages, language, override });
+ const detected = override ? resolveCurrency({ system, browserLanguages, language }).currency : resolved.currency;
+ return { ...resolved, detected, format: amount => formatMoney(amount, { ...resolved, lessThan: shown => tr('less than {0}', [shown]) }) };
+}
diff --git a/apps/host/src/lib/native-monitor.ts b/apps/host/src/lib/native-monitor.ts
index f2c4bf5b0..16846852d 100644
--- a/apps/host/src/lib/native-monitor.ts
+++ b/apps/host/src/lib/native-monitor.ts
@@ -54,7 +54,9 @@ export function withHostSensors(live:MonitorState,host:MonitorState|null):Monito
const empty=(g:GpuReading)=>![g.utilizationPct,g.temperatureC,g.memoryUsedGb,g.powerW].some(hasReading);
const pick=<T,>(a:T,b:T)=>hasReading(a as unknown)?a:b;
return {...live,hardware:{...h,
- gpus:(h.gpus??[]).map(g=>{const sensor=s.gpus?.find(x=>x.id===g.id);return sensor&&empty(g)?{...g,...sensor}:g;}),
+ // The fan and the clock are the host's own readings; the engine's metrics do not carry them (#3628).
+ gpus:(h.gpus??[]).map(g=>{const sensor=s.gpus?.find(x=>x.id===g.id);const own=sensor&&empty(g)?{...g,...sensor}:g;return sensor?{...own,fanPct:own.fanPct??sensor.fanPct,clockMhz:own.clockMhz??sensor.clockMhz}:own;}),
+ cpuTempC:s.cpuTempC,ssdTempC:s.ssdTempC,energyWh:s.energyWh,
gpuLoad:pick(h.gpuLoad,s.gpuLoad),vramUsedGb:pick(h.vramUsedGb,s.vramUsedGb),vramTotalGb:pick(h.vramTotalGb,s.vramTotalGb),gpuTempC:pick(h.gpuTempC,s.gpuTempC),
powerW:pick(h.powerW,s.powerW),powerLimitW:pick(h.powerLimitW,s.powerLimitW),pcieRxMbs:pick(h.pcieRxMbs,s.pcieRxMbs)}};
}
diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts
index 3449089ab..76f06e3d0 100644
--- a/apps/host/src/lib/store.ts
+++ b/apps/host/src/lib/store.ts
@@ -5,6 +5,7 @@ import { updateAgent } from './agents';
import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop';
import { LoopScheduler } from './loop-runner';
import { applyStatusFrame, clearStatus } from './live-status';
+import { approvalNeeded, workFinished } from './attention';
import { applyGoalFrame } from './goal';
import { tidyAnswer } from './answer-text';
import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables';
@@ -82,6 +83,13 @@ export interface AppState {
transparency: 'translucent' | 'opaque';
/** Chrome scale, independent of the conversation's reading size. */
uiScale: number;
+ /** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */
+ electricityPrice: number;
+ electricityCurrency: string;
+ /** Opt-in: a short sound when a task finishes (#3586). */
+ doneSound: boolean;
+ /** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */
+ approvalNotify: boolean;
/** Governs anonymous usage reporting. Nothing is sent in this build; the
* choice is recorded so a version that does offer it starts from it. */
shareTelemetry: boolean;
@@ -143,6 +151,10 @@ export interface Prefs {
motion: 'system' | 'full' | 'reduced';
transparency: 'translucent' | 'opaque';
uiScale: number;
+ electricityPrice: number;
+ electricityCurrency: string;
+ doneSound: boolean;
+ approvalNotify: boolean;
/** Governs anonymous usage reporting. Nothing is sent in this build; the
* choice is recorded so a version that does offer it starts from it. */
shareTelemetry: boolean;
@@ -160,6 +172,10 @@ const PREFS_DEFAULTS: Prefs = {
motion: 'system',
transparency: 'translucent',
uiScale: 1,
+ electricityPrice: 0,
+ electricityCurrency: '',
+ doneSound: false,
+ approvalNotify: false,
shareTelemetry: false,
};
@@ -203,6 +219,11 @@ function loadPrefs(): Prefs {
language: validLanguage(parsed.language) ? parsed.language : 'en',
fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '',
contentFontSize: Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Number(parsed.contentFontSize) || 14)),
+ uiScale: [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2].includes(Number(parsed.uiScale)) ? Number(parsed.uiScale) : 1,
+ electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0,
+ electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '',
+ doneSound: parsed.doneSound === true,
+ approvalNotify: parsed.approvalNotify === true,
};
} catch {
/* fall through to the next key */
@@ -215,6 +236,9 @@ const prefs = loadPrefs();
// Use the saved language for the very first render, before host bootstrap.
setTranslationLanguage(prefs.language);
+/** The last approval question a notification was shown for, so one question is announced once. */
+let lastApprovalNotice = '';
+
let state: AppState = {
language: prefs.language,
fontFamily: prefs.fontFamily,
@@ -232,6 +256,10 @@ let state: AppState = {
motion: prefs.motion,
transparency: prefs.transparency,
uiScale: prefs.uiScale,
+ electricityPrice: prefs.electricityPrice,
+ electricityCurrency: prefs.electricityCurrency,
+ doneSound: prefs.doneSound,
+ approvalNotify: prefs.approvalNotify,
paletteOpen: false,
shortcutsOpen: false,
settingsSection: 'Appearance',
@@ -422,9 +450,11 @@ function applyPrefs() {
root.dataset.contrast = state.contrast;
root.dataset.density = state.density;
root.style.setProperty('--st-content-fs', `${state.contentFontSize}px`);
- // The chrome scale. The reading size is deliberately separate: someone who
- // needs larger prose does not necessarily want larger buttons.
- root.style.setProperty('--st-ui-scale', String(state.uiScale));
+ // The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were
+ // written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs
+ // larger prose does not necessarily want larger buttons.
+ root.style.setProperty('--st-ui-scale', '1');
+ root.style.setProperty('zoom', state.uiScale === 1 ? '' : String(state.uiScale));
// "system" means the OS decides, so the attribute is absent rather than set
// to a third value the stylesheet would have to special-case.
@@ -452,6 +482,10 @@ function savePrefs() {
motion: state.motion,
transparency: state.transparency,
uiScale: state.uiScale,
+ electricityPrice: state.electricityPrice,
+ electricityCurrency: state.electricityCurrency,
+ doneSound: state.doneSound,
+ approvalNotify: state.approvalNotify,
shareTelemetry: state.shareTelemetry,
};
try {
@@ -471,7 +505,17 @@ export function toggleRail() {
set({ rail: !state.rail });
savePrefs();
}
-export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();}
+export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();rememberShellLanguage(language);}
+let shellAnnounced = false;
+/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */
+function rememberShellLanguage(language:Language){api.post('/api/shell/prefs',{language}).catch(()=>undefined);}
+/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */
+async function announcePortNotice(){
+ try{
+ const shell=await api.get<{portNotice:{wanted:number;used:number}|null}>('/api/shell');
+ if(shell.portNotice)pushToast('warn',tr('Strata could not use its port'),tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.',[shell.portNotice.wanted,shell.portNotice.used]));
+ }catch{/* a browser or an older host has no shell */}
+}
export function setFontFamily(fontFamily:string){set({fontFamily:fontFamily.trim().slice(0,128).replace(/[\x00-\x1f]/g,'')});savePrefs();}
export function setFocus(focus: boolean) {
@@ -544,7 +588,24 @@ export function setTransparency(transparency: 'translucent' | 'opaque') {
savePrefs();
}
-export const UI_SCALES = [0.9, 1, 1.1, 1.25] as const;
+/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */
+export function setElectricity(price: number, currency: string) {
+ const ok = Number.isFinite(price) && price > 0 && price < 1000;
+ set({ electricityPrice: ok ? Math.round(price * 10000) / 10000 : 0, electricityCurrency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '' });
+ savePrefs();
+}
+
+export function setDoneSound(doneSound: boolean) {
+ set({ doneSound });
+ savePrefs();
+}
+
+export function setApprovalNotify(approvalNotify: boolean) {
+ set({ approvalNotify });
+ savePrefs();
+}
+
+export const UI_SCALES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const;
export function setUiScale(uiScale: number) {
set({ uiScale });
@@ -680,8 +741,8 @@ function applyEvent(e: StreamEvent) {
// A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed.
const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null };
if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? ''));
- else if (t.attention) pushToast('warn', 'Task needs your yes', String(t.title ?? ''));
- else if (t.status === 'done') pushToast('success', 'Task finished', String(t.title ?? ''));
+ else if (t.attention) { pushToast('warn', 'Task needs your yes', String(t.title ?? '')); void approvalNeeded(state.approvalNotify, String(t.title ?? '')); }
+ else if (t.status === 'done') { pushToast('success', 'Task finished', String(t.title ?? '')); workFinished(state.doneSound, Infinity); }
break;
}
case 'agent':
@@ -726,6 +787,7 @@ export async function bootstrap() {
connection: 'live',
});
applyProviders(providers);
+ if (!shellAnnounced) { shellAnnounced = true; void announcePortNotice(); rememberShellLanguage(state.language); }
closeEvents?.();
let reconnect = false;
closeEvents = onEvent(applyEvent, (status) => {
@@ -1746,6 +1808,12 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g
patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] }));
} else if (type === 'status') {
applyStatusFrame(sessionId, frame as Record<string, unknown>);
+ // Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question.
+ if (frame.code === 'waiting-approval' && lastApprovalNotice !== `${sessionId}:${String(frame.seq)}`) {
+ lastApprovalNotice = `${sessionId}:${String(frame.seq)}`;
+ const tool = (frame.args as { tool?: unknown } | undefined)?.tool;
+ void approvalNeeded(state.approvalNotify, typeof tool === 'string' ? tool : '');
+ }
} else if (type === 'goal') {
applyGoalFrame(sessionId, frame.goal);
} else if (type === 'plan') {
@@ -1820,6 +1888,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g
patchAssistant((m) => ({ ...m, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) }));
} else if (type === 'done') {
clearStatus(sessionId);
+ workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started));
patchSession(sessionId, (sess) => ({
...sess,
tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0),
diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts
index 28e044bd3..1e477540a 100644
--- a/apps/host/src/lib/types.ts
+++ b/apps/host/src/lib/types.ts
@@ -23,7 +23,7 @@ export interface HardwareCheck {
export interface ProcessorInfo { id:string; socket:string; model:string; cores:number; threads:number; arch:string; ghz:number; logicalIds?:number[] }
export interface CpuReading { id:string; utilizationPct:number|null }
-export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null }
+export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null; fanPct?:number|null; clockMhz?:number|null }
export interface GpuInfo {
id?: string;
@@ -285,6 +285,10 @@ export interface MonitorState {
powerW?: number | null;
powerLimitW?: number | null;
pcieRxMbs?: number | null;
+ /** CPU and SSD temperatures (only where this PC can give one) and the GPU energy used since the host started, in Wh (#3628). */
+ cpuTempC?: number | null;
+ ssdTempC?: number | null;
+ energyWh?: number | null;
diskReadGbs?: number | null;
diskWriteMbs?: number | null;
gpuLoad: number | null;
diff --git a/apps/host/src/locales/gh-de.json b/apps/host/src/locales/gh-de.json
new file mode 100644
index 000000000..d6a54a5a6
--- /dev/null
+++ b/apps/host/src/locales/gh-de.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "Energie seit dem Start",
+ "gh02": "Kosten seit dem Start",
+ "gh03": "GPU-Lüfter",
+ "gh04": "GPU-Takt",
+ "gh05": "CPU-Temperatur",
+ "gh06": "SSD-Temperatur",
+ "gh07": "Strompreis",
+ "gh08": "Preis einer Kilowattstunde. Der Monitor zeigt dann, was Ihre Grafikkarte seit dem Start von Strata gekostet hat. Leer lassen, um die Kosten auszublenden.",
+ "gh09": "Preis pro kWh",
+ "gh10": "Ton, wenn Arbeit fertig ist",
+ "gh11": "Spielt einen kurzen Ton, wenn eine Antwort oder Aufgabe, die länger gedauert hat, fertig ist oder wenn Strata im Hintergrund läuft.",
+ "gh12": "Ton abspielen",
+ "gh13": "Benachrichtigen, wenn Strata eine Antwort braucht",
+ "gh14": "Zeigt im manuellen Modus eine Desktop-Benachrichtigung, wenn der Assistent auf Ihre Freigabe wartet und Strata im Hintergrund läuft.",
+ "gh15": "Strata braucht Ihre Antwort",
+ "gh16": "Der Assistent möchte {0} verwenden. Öffnen Sie Strata, um zu erlauben oder abzulehnen.",
+ "gh17": "ein Werkzeug",
+ "gh18": "In den Infobereich minimieren",
+ "gh19": "Beim Schließen des Fensters läuft Strata im Infobereich neben der Uhr weiter. Wählen Sie im Menü des Symbols „Beenden“, um es zu stoppen. Gilt ab dem nächsten Start von Strata.",
+ "gh20": "App-Port",
+ "gh21": "Der Port, den das Fenster und die lokale Adresse von Strata verwenden. Leer lassen, damit Strata ihn wählt (47831, wenn frei). Gilt ab dem nächsten Start von Strata.",
+ "gh22": "Port (leer = automatisch)",
+ "gh23": "Aktuell wird Port {0} verwendet.",
+ "gh24": "Strata konnte seinen Port nicht verwenden",
+ "gh25": "Port {0} wird von einem anderen Programm verwendet, daher wurde Strata auf Port {1} gestartet. Unter Port {0} gespeicherte Chats und Einstellungen werden nicht angezeigt, bis Strata ihn wieder verwenden kann. Schließen Sie das andere Programm und starten Sie Strata neu.",
+ "gh26": "Wählen Sie einen Port zwischen 1024 und 65535 oder lassen Sie das Feld leer.",
+ "gh27": "Macht alle Texte, Schaltflächen und Menüs in Strata größer oder kleiner.",
+ "gh28": "Energie- und Temperaturwerte",
+ "gh29": "pro kWh, in {0}",
+ "gh30": "pro kWh",
+ "gh31": "Währung ändern",
+ "gh32": "Automatisch ({0})",
+ "gh33": "Währung",
+ "gh34": "weniger als {0}"
+}
diff --git a/apps/host/src/locales/gh-en.json b/apps/host/src/locales/gh-en.json
new file mode 100644
index 000000000..e1f124761
--- /dev/null
+++ b/apps/host/src/locales/gh-en.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "Energy since start",
+ "gh02": "Cost since start",
+ "gh03": "GPU fan",
+ "gh04": "GPU clock",
+ "gh05": "CPU temperature",
+ "gh06": "SSD temperature",
+ "gh07": "Electricity price",
+ "gh08": "Price of one kilowatt-hour. The Monitor then shows what your graphics card has cost since Strata started. Leave it empty to hide the cost.",
+ "gh09": "Price per kWh",
+ "gh10": "Sound when work finishes",
+ "gh11": "Plays a short sound when an answer or task that took a while is finished, or when Strata is in the background.",
+ "gh12": "Play sound",
+ "gh13": "Notify me when Strata needs an answer",
+ "gh14": "In Manual mode, shows a desktop notification when the assistant waits for your approval and Strata is in the background.",
+ "gh15": "Strata needs your answer",
+ "gh16": "The assistant wants to use {0}. Open Strata to approve or deny.",
+ "gh17": "a tool",
+ "gh18": "Minimise to tray",
+ "gh19": "Closing the window keeps Strata running in the tray, next to the clock. Choose Quit in the tray menu to stop it. Applies the next time Strata starts.",
+ "gh20": "App port",
+ "gh21": "The port Strata’s window and local address use. Leave it empty to let Strata choose (47831 when it is free). Applies the next time Strata starts.",
+ "gh22": "Port (empty = automatic)",
+ "gh23": "Using port {0} now.",
+ "gh24": "Strata could not use its port",
+ "gh25": "Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.",
+ "gh26": "Choose a port between 1024 and 65535, or leave it empty.",
+ "gh27": "Makes all text, buttons and menus in Strata larger or smaller.",
+ "gh28": "Energy and temperature readings",
+ "gh29": "per kWh, in {0}",
+ "gh30": "per kWh",
+ "gh31": "Change currency",
+ "gh32": "Automatic ({0})",
+ "gh33": "Currency",
+ "gh34": "less than {0}"
+}
diff --git a/apps/host/src/locales/gh-es.json b/apps/host/src/locales/gh-es.json
new file mode 100644
index 000000000..82538fef2
--- /dev/null
+++ b/apps/host/src/locales/gh-es.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "Energía desde el inicio",
+ "gh02": "Coste desde el inicio",
+ "gh03": "Ventilador de la GPU",
+ "gh04": "Reloj de la GPU",
+ "gh05": "Temperatura de la CPU",
+ "gh06": "Temperatura del SSD",
+ "gh07": "Precio de la electricidad",
+ "gh08": "Precio de un kilovatio hora. El Monitor mostrará entonces lo que ha costado tu tarjeta gráfica desde que se inició Strata. Déjalo vacío para ocultar el coste.",
+ "gh09": "Precio por kWh",
+ "gh10": "Sonido al terminar el trabajo",
+ "gh11": "Reproduce un sonido breve cuando termina una respuesta o tarea que tardó un rato, o cuando Strata está en segundo plano.",
+ "gh12": "Reproducir sonido",
+ "gh13": "Avisarme cuando Strata necesite una respuesta",
+ "gh14": "En el modo manual, muestra una notificación de escritorio cuando el asistente espera tu aprobación y Strata está en segundo plano.",
+ "gh15": "Strata necesita tu respuesta",
+ "gh16": "El asistente quiere usar {0}. Abre Strata para aprobar o denegar.",
+ "gh17": "una herramienta",
+ "gh18": "Minimizar a la bandeja",
+ "gh19": "Al cerrar la ventana, Strata sigue funcionando en la bandeja, junto al reloj. Elige Salir en el menú de la bandeja para detenerlo. Se aplica la próxima vez que se inicie Strata.",
+ "gh20": "Puerto de la aplicación",
+ "gh21": "El puerto que usan la ventana y la dirección local de Strata. Déjalo vacío para que Strata elija (47831 si está libre). Se aplica la próxima vez que se inicie Strata.",
+ "gh22": "Puerto (vacío = automático)",
+ "gh23": "Ahora se usa el puerto {0}.",
+ "gh24": "Strata no pudo usar su puerto",
+ "gh25": "El puerto {0} lo usa otro programa, así que Strata se inició en el puerto {1}. Los chats y ajustes guardados en el puerto {0} no se muestran hasta que Strata pueda volver a usarlo. Cierra el otro programa y reinicia Strata.",
+ "gh26": "Elige un puerto entre 1024 y 65535, o déjalo vacío.",
+ "gh27": "Hace más grandes o más pequeños todos los textos, botones y menús de Strata.",
+ "gh28": "Lecturas de energía y temperatura",
+ "gh29": "por kWh, en {0}",
+ "gh30": "por kWh",
+ "gh31": "Cambiar moneda",
+ "gh32": "Automática ({0})",
+ "gh33": "Moneda",
+ "gh34": "menos de {0}"
+}
diff --git a/apps/host/src/locales/gh-fr.json b/apps/host/src/locales/gh-fr.json
new file mode 100644
index 000000000..9d556360f
--- /dev/null
+++ b/apps/host/src/locales/gh-fr.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "Énergie depuis le démarrage",
+ "gh02": "Coût depuis le démarrage",
+ "gh03": "Ventilateur du GPU",
+ "gh04": "Fréquence du GPU",
+ "gh05": "Température du CPU",
+ "gh06": "Température du SSD",
+ "gh07": "Prix de l’électricité",
+ "gh08": "Prix d’un kilowattheure. Le Moniteur affiche alors ce que votre carte graphique a coûté depuis le démarrage de Strata. Laissez vide pour masquer le coût.",
+ "gh09": "Prix par kWh",
+ "gh10": "Son à la fin du travail",
+ "gh11": "Joue un court son quand une réponse ou une tâche qui a pris du temps est terminée, ou quand Strata est en arrière-plan.",
+ "gh12": "Jouer le son",
+ "gh13": "Me prévenir quand Strata a besoin d’une réponse",
+ "gh14": "En mode manuel, affiche une notification sur le bureau quand l’assistant attend votre accord et que Strata est en arrière-plan.",
+ "gh15": "Strata a besoin de votre réponse",
+ "gh16": "L’assistant veut utiliser {0}. Ouvrez Strata pour accepter ou refuser.",
+ "gh17": "un outil",
+ "gh18": "Réduire dans la zone de notification",
+ "gh19": "Fermer la fenêtre garde Strata actif dans la zone de notification, près de l’horloge. Choisissez Quitter dans le menu de l’icône pour l’arrêter. S’applique au prochain démarrage de Strata.",
+ "gh20": "Port de l’application",
+ "gh21": "Le port que la fenêtre et l’adresse locale de Strata utilisent. Laissez vide pour que Strata choisisse (47831 s’il est libre). S’applique au prochain démarrage de Strata.",
+ "gh22": "Port (vide = automatique)",
+ "gh23": "Port {0} utilisé en ce moment.",
+ "gh24": "Strata n’a pas pu utiliser son port",
+ "gh25": "Le port {0} est utilisé par un autre programme, donc Strata a démarré sur le port {1}. Les conversations et réglages enregistrés sur le port {0} ne s’affichent pas tant que Strata ne peut pas le réutiliser. Fermez l’autre programme et relancez Strata.",
+ "gh26": "Choisissez un port entre 1024 et 65535, ou laissez vide.",
+ "gh27": "Agrandit ou réduit tous les textes, boutons et menus de Strata.",
+ "gh28": "Relevés d’énergie et de température",
+ "gh29": "par kWh, en {0}",
+ "gh30": "par kWh",
+ "gh31": "Changer de devise",
+ "gh32": "Automatique ({0})",
+ "gh33": "Devise",
+ "gh34": "moins de {0}"
+}
diff --git a/apps/host/src/locales/gh-ja.json b/apps/host/src/locales/gh-ja.json
new file mode 100644
index 000000000..55229a696
--- /dev/null
+++ b/apps/host/src/locales/gh-ja.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "起動後の消費電力量",
+ "gh02": "起動後の電気代",
+ "gh03": "GPU ファン",
+ "gh04": "GPU クロック",
+ "gh05": "CPU 温度",
+ "gh06": "SSD 温度",
+ "gh07": "電気料金",
+ "gh08": "1キロワット時あたりの料金です。モニターに、Strata の起動後にグラフィックスカードが使った電気代が表示されます。空欄のままなら電気代は表示されません。",
+ "gh09": "1 kWh あたりの料金",
+ "gh10": "作業完了時の音",
+ "gh11": "回答や時間のかかった作業が終わったとき、または Strata がバックグラウンドにあるときに、短い音を鳴らします。",
+ "gh12": "音を鳴らす",
+ "gh13": "Strata の返答が必要なときに通知する",
+ "gh14": "手動モードで、アシスタントが承認を待っていて Strata がバックグラウンドにあるときに、デスクトップ通知を表示します。",
+ "gh15": "Strata があなたの返答を待っています",
+ "gh16": "アシスタントが {0} を使おうとしています。Strata を開いて承認または拒否してください。",
+ "gh17": "ツール",
+ "gh18": "トレイに最小化",
+ "gh19": "ウィンドウを閉じても、Strata は時計の横のトレイで動き続けます。止めるには、トレイのメニューで「終了」を選びます。次に Strata を起動したときから有効になります。",
+ "gh20": "アプリのポート",
+ "gh21": "Strata のウィンドウとローカルアドレスが使うポートです。空欄なら Strata が選びます(空いていれば 47831)。次に Strata を起動したときから有効になります。",
+ "gh22": "ポート(空欄 = 自動)",
+ "gh23": "現在のポートは {0} です。",
+ "gh24": "Strata は指定のポートを使えませんでした",
+ "gh25": "ポート {0} は別のプログラムが使っているため、Strata はポート {1} で起動しました。ポート {0} に保存されたチャットと設定は、Strata が再びそのポートを使えるようになるまで表示されません。他のプログラムを閉じて Strata を再起動してください。",
+ "gh26": "1024 から 65535 の間のポートを選ぶか、空欄にしてください。",
+ "gh27": "Strata のすべての文字、ボタン、メニューを大きくしたり小さくしたりします。",
+ "gh28": "消費電力量と温度の値",
+ "gh29": "1 kWh あたり、通貨は {0}",
+ "gh30": "1 kWh あたり",
+ "gh31": "通貨を変更",
+ "gh32": "自動({0})",
+ "gh33": "通貨",
+ "gh34": "{0} 未満"
+}
diff --git a/apps/host/src/locales/gh-ko.json b/apps/host/src/locales/gh-ko.json
new file mode 100644
index 000000000..24decc860
--- /dev/null
+++ b/apps/host/src/locales/gh-ko.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "시작 이후 에너지",
+ "gh02": "시작 이후 비용",
+ "gh03": "GPU 팬",
+ "gh04": "GPU 클럭",
+ "gh05": "CPU 온도",
+ "gh06": "SSD 온도",
+ "gh07": "전기 요금",
+ "gh08": "1킬로와트시의 요금입니다. 모니터에 Strata를 시작한 뒤 그래픽 카드에 든 전기 요금이 표시됩니다. 비워 두면 비용을 표시하지 않습니다.",
+ "gh09": "kWh당 요금",
+ "gh10": "작업이 끝났을 때 소리",
+ "gh11": "답변이나 오래 걸린 작업이 끝났을 때, 또는 Strata가 백그라운드에 있을 때 짧은 소리를 재생합니다.",
+ "gh12": "소리 재생",
+ "gh13": "Strata가 답을 필요로 할 때 알림",
+ "gh14": "수동 모드에서 어시스턴트가 승인을 기다리고 Strata가 백그라운드에 있을 때 데스크톱 알림을 표시합니다.",
+ "gh15": "Strata가 답을 기다리고 있습니다",
+ "gh16": "어시스턴트가 {0}을(를) 사용하려고 합니다. Strata를 열어 승인하거나 거부하세요.",
+ "gh17": "도구",
+ "gh18": "트레이로 최소화",
+ "gh19": "창을 닫아도 Strata는 시계 옆 트레이에서 계속 실행됩니다. 끝내려면 트레이 메뉴에서 '종료'를 선택하세요. 다음에 Strata를 시작할 때부터 적용됩니다.",
+ "gh20": "앱 포트",
+ "gh21": "Strata의 창과 로컬 주소가 사용하는 포트입니다. 비워 두면 Strata가 고릅니다(비어 있으면 47831). 다음에 Strata를 시작할 때부터 적용됩니다.",
+ "gh22": "포트(비움 = 자동)",
+ "gh23": "지금은 포트 {0}을(를) 사용 중입니다.",
+ "gh24": "Strata가 지정한 포트를 사용할 수 없었습니다",
+ "gh25": "포트 {0}을(를) 다른 프로그램이 사용 중이어서 Strata는 포트 {1}에서 시작했습니다. 포트 {0}에 저장된 채팅과 설정은 Strata가 다시 그 포트를 쓸 수 있을 때까지 표시되지 않습니다. 다른 프로그램을 닫고 Strata를 다시 시작하세요.",
+ "gh26": "1024에서 65535 사이의 포트를 고르거나 비워 두세요.",
+ "gh27": "Strata의 모든 글자, 버튼, 메뉴를 더 크게 또는 더 작게 만듭니다.",
+ "gh28": "에너지 및 온도 측정값",
+ "gh29": "kWh당, 통화 {0}",
+ "gh30": "kWh당",
+ "gh31": "통화 변경",
+ "gh32": "자동({0})",
+ "gh33": "통화",
+ "gh34": "{0} 미만"
+}
diff --git a/apps/host/src/locales/gh-pt.json b/apps/host/src/locales/gh-pt.json
new file mode 100644
index 000000000..ad331c491
--- /dev/null
+++ b/apps/host/src/locales/gh-pt.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "Energia desde o início",
+ "gh02": "Custo desde o início",
+ "gh03": "Ventoinha da GPU",
+ "gh04": "Clock da GPU",
+ "gh05": "Temperatura da CPU",
+ "gh06": "Temperatura do SSD",
+ "gh07": "Preço da eletricidade",
+ "gh08": "Preço de um quilowatt-hora. O Monitor passa a mostrar quanto a sua placa de vídeo custou desde que o Strata iniciou. Deixe vazio para ocultar o custo.",
+ "gh09": "Preço por kWh",
+ "gh10": "Som ao terminar o trabalho",
+ "gh11": "Toca um som curto quando uma resposta ou tarefa que demorou termina, ou quando o Strata está em segundo plano.",
+ "gh12": "Tocar som",
+ "gh13": "Avisar quando o Strata precisar de uma resposta",
+ "gh14": "No modo manual, mostra uma notificação na área de trabalho quando o assistente espera sua aprovação e o Strata está em segundo plano.",
+ "gh15": "O Strata precisa da sua resposta",
+ "gh16": "O assistente quer usar {0}. Abra o Strata para aprovar ou negar.",
+ "gh17": "uma ferramenta",
+ "gh18": "Minimizar para a bandeja",
+ "gh19": "Ao fechar a janela, o Strata continua em execução na bandeja, ao lado do relógio. Escolha Sair no menu da bandeja para encerrá-lo. Vale a partir da próxima vez que o Strata iniciar.",
+ "gh20": "Porta do aplicativo",
+ "gh21": "A porta usada pela janela e pelo endereço local do Strata. Deixe vazio para o Strata escolher (47831 quando estiver livre). Vale a partir da próxima vez que o Strata iniciar.",
+ "gh22": "Porta (vazio = automático)",
+ "gh23": "Usando a porta {0} agora.",
+ "gh24": "O Strata não conseguiu usar a sua porta",
+ "gh25": "A porta {0} está em uso por outro programa, então o Strata iniciou na porta {1}. Os chats e as configurações salvos na porta {0} não aparecem até o Strata poder usá-la de novo. Feche o outro programa e reinicie o Strata.",
+ "gh26": "Escolha uma porta entre 1024 e 65535, ou deixe vazio.",
+ "gh27": "Deixa todos os textos, botões e menus do Strata maiores ou menores.",
+ "gh28": "Leituras de energia e temperatura",
+ "gh29": "por kWh, em {0}",
+ "gh30": "por kWh",
+ "gh31": "Alterar moeda",
+ "gh32": "Automática ({0})",
+ "gh33": "Moeda",
+ "gh34": "menos de {0}"
+}
diff --git a/apps/host/src/locales/gh-ru.json b/apps/host/src/locales/gh-ru.json
new file mode 100644
index 000000000..51e56bf87
--- /dev/null
+++ b/apps/host/src/locales/gh-ru.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "Энергия с запуска",
+ "gh02": "Стоимость с запуска",
+ "gh03": "Вентилятор GPU",
+ "gh04": "Частота GPU",
+ "gh05": "Температура CPU",
+ "gh06": "Температура SSD",
+ "gh07": "Цена электричества",
+ "gh08": "Цена одного киловатт-часа. Тогда монитор покажет, во сколько видеокарта обошлась с запуска Strata. Оставьте поле пустым, чтобы скрыть стоимость.",
+ "gh09": "Цена за кВт·ч",
+ "gh10": "Звук по окончании работы",
+ "gh11": "Проигрывает короткий звук, когда закончился долгий ответ или задача, а также когда Strata работает в фоне.",
+ "gh12": "Проиграть звук",
+ "gh13": "Уведомлять, когда Strata нужен ответ",
+ "gh14": "В ручном режиме показывает уведомление на рабочем столе, когда помощник ждёт вашего подтверждения, а Strata работает в фоне.",
+ "gh15": "Strata нужен ваш ответ",
+ "gh16": "Помощник хочет использовать {0}. Откройте Strata, чтобы разрешить или отклонить.",
+ "gh17": "инструмент",
+ "gh18": "Сворачивать в трей",
+ "gh19": "При закрытии окна Strata продолжает работать в трее рядом с часами. Чтобы остановить её, выберите «Выход» в меню значка. Действует со следующего запуска Strata.",
+ "gh20": "Порт приложения",
+ "gh21": "Порт, который используют окно и локальный адрес Strata. Оставьте поле пустым, чтобы Strata выбрала сама (47831, если свободен). Действует со следующего запуска Strata.",
+ "gh22": "Порт (пусто = автоматически)",
+ "gh23": "Сейчас используется порт {0}.",
+ "gh24": "Strata не смогла использовать свой порт",
+ "gh25": "Порт {0} занят другой программой, поэтому Strata запустилась на порту {1}. Чаты и настройки, сохранённые на порту {0}, не показываются, пока Strata не сможет снова его использовать. Закройте другую программу и перезапустите Strata.",
+ "gh26": "Выберите порт от 1024 до 65535 или оставьте поле пустым.",
+ "gh27": "Увеличивает или уменьшает весь текст, кнопки и меню в Strata.",
+ "gh28": "Показания энергии и температуры",
+ "gh29": "за кВт·ч, в валюте {0}",
+ "gh30": "за кВт·ч",
+ "gh31": "Сменить валюту",
+ "gh32": "Автоматически ({0})",
+ "gh33": "Валюта",
+ "gh34": "меньше {0}"
+}
diff --git a/apps/host/src/locales/gh-zh.json b/apps/host/src/locales/gh-zh.json
new file mode 100644
index 000000000..eaa5e8fc6
--- /dev/null
+++ b/apps/host/src/locales/gh-zh.json
@@ -0,0 +1,36 @@
+{
+ "gh01": "启动以来的能耗",
+ "gh02": "启动以来的费用",
+ "gh03": "GPU 风扇",
+ "gh04": "GPU 频率",
+ "gh05": "CPU 温度",
+ "gh06": "SSD 温度",
+ "gh07": "电价",
+ "gh08": "每千瓦时的价格。监控页会据此显示 Strata 启动以来显卡用电的费用。留空则不显示费用。",
+ "gh09": "每千瓦时价格",
+ "gh10": "工作完成时的提示音",
+ "gh11": "回答或耗时较长的任务完成时,或 Strata 在后台时,播放一段简短的提示音。",
+ "gh12": "播放提示音",
+ "gh13": "Strata 需要您答复时通知我",
+ "gh14": "在手动模式下,当助手等待您批准而 Strata 在后台时,显示桌面通知。",
+ "gh15": "Strata 需要您的答复",
+ "gh16": "助手想使用 {0}。打开 Strata 以批准或拒绝。",
+ "gh17": "一个工具",
+ "gh18": "最小化到托盘",
+ "gh19": "关闭窗口后,Strata 会继续在托盘(时钟旁边)运行。要停止它,请在托盘菜单中选择“退出”。下次启动 Strata 时生效。",
+ "gh20": "应用端口",
+ "gh21": "Strata 窗口和本地地址使用的端口。留空则由 Strata 自行选择(空闲时为 47831)。下次启动 Strata 时生效。",
+ "gh22": "端口(留空 = 自动)",
+ "gh23": "当前使用端口 {0}。",
+ "gh24": "Strata 无法使用它的端口",
+ "gh25": "端口 {0} 已被其他程序占用,因此 Strata 改用端口 {1} 启动。在端口 {0} 上保存的聊天和设置在 Strata 能再次使用该端口之前不会显示。请关闭其他程序并重新启动 Strata。",
+ "gh26": "请选择 1024 到 65535 之间的端口,或留空。",
+ "gh27": "让 Strata 中的所有文字、按钮和菜单变大或变小。",
+ "gh28": "能耗和温度读数",
+ "gh29": "每千瓦时,币种 {0}",
+ "gh30": "每千瓦时",
+ "gh31": "更改货币",
+ "gh32": "自动({0})",
+ "gh33": "货币",
+ "gh34": "不足 {0}"
+}
diff --git a/apps/host/src/screens/Monitor.tsx b/apps/host/src/screens/Monitor.tsx
index 451ea29db..d75db79ac 100644
--- a/apps/host/src/screens/Monitor.tsx
+++ b/apps/host/src/screens/Monitor.tsx
@@ -15,6 +15,7 @@ import { contextLabel, duration, tokens, tps } from '../lib/format';
import { defaultGpuSet, gpuCapacity, gpuId, gpuMetric, gpuReported, hasReading, shortGpuName } from '../lib/monitor-hardware';
import { useStore } from '../lib/store';
import { api } from '../lib/client';
+import { useMoney } from '../lib/money';
import { useKept } from '../lib/kept-state';
import type { Hardware, MonitorState, ServeRequest } from '../lib/types';
import { useNative, nativeRouting, type NativeState } from '../lib/native';
@@ -72,6 +73,7 @@ function LegacyMonitorScreen({ native }: {
native: NativeState | null;
}) {
const storedLive = useStore(s => s.monitor), inventory = useStore(s => s.hardware);
+ const electricityPrice = useStore(s => s.electricityPrice), money = useMoney();
const storedRuntime = useStore(s => s.runtime), serving = useStore(s => s.serving);
const [instanceSelection, setInstanceSelection] = useState('all');
const routing = native ? nativeRouting(native, inventory) : null;
@@ -146,6 +148,16 @@ function LegacyMonitorScreen({ native }: {
const cacheMemory = cacheKnown ? data.expertCache.memoryGb : null;
const cachePercent = hasReading(cacheMemory) ? percent(cacheMemory, gpuCapacity(defaultDevices)) : cacheKnown ? percent(data.expertCache.used, data.expertCache.total) : null;
const ramPct = percent(data.hardware.ramUsedGb, data.hardware.ramTotalGb);
+ // The readings strip under the cards: what the GPU used and cost since Strata started, the fan and clock, and the temperatures this PC can give.
+ const energyWh = data.hardware.energyWh, fan = gpuValue('fanPct', 'max'), clock = gpuValue('clockMhz', 'max');
+ const readingsStrip = [
+ hasReading(energyWh) ? { label: 'Energy since start', value: energyWh >= 1000 ? `${number(energyWh / 1000, 2)} kWh` : `${number(energyWh, 1)} Wh` } : null,
+ hasReading(energyWh) && electricityPrice > 0 ? { label: 'Cost since start', value: money.format(energyWh / 1000 * electricityPrice) } : null,
+ hasReading(fan) ? { label: 'GPU fan', value: `${number(fan)} %` } : null,
+ hasReading(clock) ? { label: 'GPU clock', value: `${number(clock)} MHz` } : null,
+ hasReading(data.hardware.cpuTempC) ? { label: 'CPU temperature', value: `${number(data.hardware.cpuTempC)} °C` } : null,
+ hasReading(data.hardware.ssdTempC) ? { label: 'SSD temperature', value: `${number(data.hardware.ssdTempC)} °C` } : null,
+ ].filter((line): line is { label: string; value: string } => line !== null);
const history = data.history, timestamps = history.map(s => s.t);
const historyGpu = (key: Parameters<typeof gpuMetric>[2], fallback: 'gpuLoad' | 'vramUsedGb' | 'gpuTempC' | 'powerW' | 'pcieRxMbs', mode: Parameters<typeof gpuMetric>[3] = 'sum') => history.map(sample => sample.gpus ? gpuMetric(selectedGpus, sample.gpus, key, mode) : (sample.gpuIds ? selectedGpus.length === sample.gpuIds.length && selectedGpus.every(gpu => sample.gpuIds!.includes(gpuId(gpu))) : gpuChoice === 'all') ? sample[fallback] : null);
const historyCpu = history.map(sample => cpuChoice === 'all' ? sample.cpuLoad : sample.cpus?.find(p => p.id === cpuChoice)?.utilizationPct);
@@ -184,6 +196,7 @@ function LegacyMonitorScreen({ native }: {
<MonitorMetric label={tr("CPU")} icon="cpu" value={number(cpu)} unit={hasReading(cpu) ? '%' : ''} source={hasReading(cpu) ? 'Measured' : 'Unavailable'} sub={cpuName} chart={chart('CPU utilization', historyCpu, '%', 100)}/>
<MonitorMetric label={tr("Disk read")} icon="disk" value={number(hasReading(data.hardware.diskReadGbs) ? data.hardware.diskReadGbs >= 1 ? data.hardware.diskReadGbs : data.hardware.diskReadGbs * 1024 : null, 1)} unit={hasReading(data.hardware.diskReadGbs) ? data.hardware.diskReadGbs >= 1 ? 'GB/s' : 'MB/s' : ''} source={hasReading(data.hardware.diskReadGbs) ? 'Measured' : 'Unavailable'} sub={hasReading(data.hardware.diskWriteMbs) ? `Write ${number(data.hardware.diskWriteMbs, 1)} MB/s` : 'Read throughput'} chart={chart('Disk read', history.map(s => hasReading(s.diskReadGbs) ? s.diskReadGbs * 1024 : null), 'MB/s', undefined, 'var(--st-info)')}/>
</div>
+ {tr(readingsStrip.length ? <section className="st-card monitor-readings" aria-label={tr("Energy and temperature readings")}><dl>{readingsStrip.map(item => <div key={item.label}><dt>{tr(item.label)}</dt><dd className="num">{item.value}</dd></div>)}</dl></section> : null)}
<div className="monitor-context-requests">
<section className="st-card monitor-context"><h2 className="h4">{tr("Context fill")}</h2><div className="monitor-context__gauge"><Gauge value={contextPct ?? 0} label={tr(hasReading(contextPct) ? `${Math.round(contextPct)}%` : '—')} sub={contextKnown ? `${tokens(contextUsed)} / ${contextLabel(data.context.maxTokens)}` : selection === 'all' && (runtime?.instances.length ?? 0) > 1 ? 'Select a model to see context' : 'No recorded request usage'}/></div>
<div className="monitor-bar-reading"><span>{tr("Experts in VRAM")}</span><span className="muted num">{tr(cacheKnown ? `${number(data.expertCache.used)}${hasReading(cacheMemory) ? ` · ${number(cacheMemory, 1)} GB` : ''}` : '—')}</span></div><ReadingBar label={tr("Experts in VRAM")} value={cachePercent}/>
diff --git a/apps/host/src/screens/Settings.tsx b/apps/host/src/screens/Settings.tsx
index a14854f27..0361d7124 100644
--- a/apps/host/src/screens/Settings.tsx
+++ b/apps/host/src/screens/Settings.tsx
@@ -10,12 +10,15 @@ import { PrivacyNotes } from '../components/PrivacyNotes';
import { AboutVersions, SettingsUpdates } from '../components/SettingsUpdates';
import { NativeOperations } from '../components/NativeOperations';
import { FontChoice } from '../components/FontChoice';
+import { ElectricityPrice } from '../components/ElectricityPrice';
+import { ApprovalNotifySetting, DoneSoundSetting, PortSetting, TraySetting, useShellState } from '../components/ShellSettings';
import { LANGUAGES } from '../lib/i18n';
import { setLanguage } from '../lib/store';
import { CONTENT_FONT_RANGE, setContentFontSize, setDensity, setFocus, setMotion, setShortcuts, setTheme, setTransparency, setUiScale, UI_SCALES, useStore, setSettingsSection } from '../lib/store';
const PANELS = [{ name: 'Appearance', icon: 'sun', sections: ['General', 'Reading & focus'] }, { name: 'Models', icon: 'models', sections: [] }, { name: 'Tools', icon: 'tool', sections: [] }, { name: 'Storage', icon: 'disk', sections: ['Storage'] }, { name: 'Engine', icon: 'engine', sections: [] }, { name: 'About', icon: 'info', sections: ['About', 'Update', 'Privacy'] }] as const;
export function SettingsScreen() {
const prefs = useStore(s => s);
+ const [shell, saveShell] = useShellState();
const active = prefs.settingsSection;
const scrollRef = useRef<HTMLDivElement>(null);
const fields: {
@@ -26,11 +29,16 @@ export function SettingsScreen() {
control: ReactNode;
}[] = [
{ section: 'General', label: 'Language', hint: 'Choose the language used throughout Strata.', control: <Select translateLabels={false} ariaLabel={tr("Language")} value={prefs.language} options={[...LANGUAGES]} onChange={value => setLanguage(value as typeof prefs.language)}/> },
+ { section: 'General', label: 'Sound when work finishes', hint: 'Plays a short sound when an answer or task that took a while is finished, or when Strata is in the background.', aliases: 'audio chime done complete notification', control: <DoneSoundSetting /> },
+ { section: 'General', label: 'Notify me when Strata needs an answer', hint: 'In Manual mode, shows a desktop notification when the assistant waits for your approval and Strata is in the background.', aliases: 'approval permission alert notification manual', control: <ApprovalNotifySetting /> },
+ ...(shell?.tray ? [{ section: 'General', label: 'Minimise to tray', hint: 'Closing the window keeps Strata running in the tray, next to the clock. Choose Quit in the tray menu to stop it. Applies the next time Strata starts.', aliases: 'tray background close notification area', control: <TraySetting shell={shell} save={saveShell} /> }] : []),
+ ...(shell?.desktop ? [{ section: 'General', label: 'App port', hint: 'The port Strata’s window and local address use. Leave it empty to let Strata choose (47831 when it is free). Applies the next time Strata starts.', aliases: 'network address 47831 localhost api', control: <PortSetting shell={shell} save={saveShell} /> }] : []),
+ { section: 'General', label: 'Electricity price', hint: 'Price of one kilowatt-hour. The Monitor then shows what your graphics card has cost since Strata started. Leave it empty to hide the cost.', aliases: 'cost power energy kwh currency money', control: <ElectricityPrice /> },
{ section: 'Reading & focus', label: 'Font', hint: 'Choose an installed font for the interface and conversations.', control: <FontChoice /> },
{ section: 'General', label: 'Keyboard shortcuts', hint: 'Set the key combinations that feel natural to you.', aliases: 'command keys hotkeys', control: <Btn size="sm" onClick={() => setShortcuts(true)}>{tr("Edit shortcuts")}</Btn> },
{ section: 'Reading & focus', label: 'Appearance', hint: 'System follows your computer by default.', aliases: 'theme light dark system automatic', control: <Select value={prefs.theme} ariaLabel={tr("Appearance")} options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }, { value: 'system', label: 'System' }]} onChange={setTheme}/> },
{ section: 'Reading & focus', label: 'Reading size', hint: 'Conversation text size. Interface controls stay separate.', aliases: 'font text zoom', control: <label className="row"><input aria-label={tr("Reading text size")} type="range" className="st-slider" min={CONTENT_FONT_RANGE.min} max={CONTENT_FONT_RANGE.max} value={prefs.contentFontSize} onChange={e => setContentFontSize(Number(e.target.value))}/><output>{tr(prefs.contentFontSize)}{tr(" px")}</output></label> },
- { section: 'Reading & focus', label: 'Interface size', hint: 'Scale navigation and controls.', aliases: 'zoom scale 90% 100% 110% 125%', control: <Select value={String(prefs.uiScale)} ariaLabel={tr("Interface size")} options={UI_SCALES.map(v => ({ value: String(v), label: `${Math.round(v * 100)}%` }))} onChange={v => setUiScale(Number(v))}/> },
+ { section: 'Reading & focus', label: 'Interface size', hint: 'Makes all text, buttons and menus in Strata larger or smaller.', aliases: 'zoom scale font text size bigger smaller 4k 90% 100% 110% 125% 150% 175% 200%', control: <Select value={String(prefs.uiScale)} ariaLabel={tr("Interface size")} options={UI_SCALES.map(v => ({ value: String(v), label: `${Math.round(v * 100)}%` }))} onChange={v => setUiScale(Number(v))}/> },
{ section: 'Reading & focus', label: 'Spacing', hint: 'Comfortable spacing by default.', aliases: 'density comfortable compact', control: <Select value={prefs.density} ariaLabel={tr("Interface spacing")} options={[{ value: 'comfortable', label: 'Comfortable' }, { value: 'compact', label: 'Compact' }]} onChange={setDensity}/> },
{ section: 'Reading & focus', label: 'Motion', hint: 'Reduced motion also disables smooth scrolling.', aliases: 'animation system full reduced', control: <Select value={prefs.motion} ariaLabel={tr("Motion")} options={[{ value: 'system', label: 'Follow system' }, { value: 'full', label: 'Full' }, { value: 'reduced', label: 'Reduced' }]} onChange={setMotion}/> },
{ section: 'Reading & focus', label: 'Transparency', hint: 'Translucent controls or solid surfaces. Text stays opaque.', aliases: 'blur glass liquid opaque translucent', control: <Select value={prefs.transparency} ariaLabel={tr("Transparency")} options={[{ value: 'translucent', label: 'Translucent' }, { value: 'opaque', label: 'Opaque' }]} onChange={setTransparency}/> },
diff --git a/apps/host/src/styles/monitor.css b/apps/host/src/styles/monitor.css
index ba54c9c97..621c3a69c 100644
--- a/apps/host/src/styles/monitor.css
+++ b/apps/host/src/styles/monitor.css
@@ -89,3 +89,12 @@
.monitor-spark .spark__readout { right: auto; left: 0; max-width: 230px; }
.monitor-metric:nth-child(even) .monitor-spark .spark__readout { right: 0; left: auto; }
}
+
+/* The energy and temperature readings (#3628): one thin row under the cards, a label and a value each, wrapping to 3 and 2 columns on narrow windows. */
+.monitor-readings { padding: 12px 20px; }
+.monitor-readings dl { margin: 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px 24px; }
+.monitor-readings dl > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.monitor-readings dt { color: var(--st-ink-muted); font-size: 12px; }
+.monitor-readings dd { margin: 0; font-size: 15px; font-weight: 600; overflow-wrap: anywhere; }
+@media (max-width: 1100px) { .monitor-readings dl { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
+@media (max-width: 640px) { .monitor-readings { padding: 12px 16px; } .monitor-readings dl { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
diff --git a/apps/host/tests/currency.test.mjs b/apps/host/tests/currency.test.mjs
new file mode 100644
index 000000000..fa33c0a05
--- /dev/null
+++ b/apps/host/tests/currency.test.mjs
@@ -0,0 +1,105 @@
+// The currency of the Monitor's cost line (#3628): found from the computer's region, formatted for the person's locale, never guessed.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { build } from 'esbuild';
+import { parseLocaleTag, parseRegValue, detectRegion } from '../server/region.mjs';
+
+const compiled = await build({ stdin: { contents: "export * from './src/lib/currency';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node' });
+const norm = text => text.replace(/\s/g, ' '); // a no-break space becomes a space
+const C = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);
+
+test('a region maps to its currency, an unknown one to nothing', () => {
+ for (const [region, code] of [['DE', 'EUR'], ['SI', 'EUR'], ['BG', 'EUR'], ['US', 'USD'], ['GB', 'GBP'], ['JP', 'JPY'], ['CH', 'CHF'], ['BR', 'BRL'], ['KR', 'KRW'], ['CN', 'CNY'], ['IN', 'INR'], ['de', 'EUR']])
+ assert.equal(C.currencyForRegion(region), code, region);
+ assert.equal(C.currencyForRegion('ZZ'), null);
+ assert.equal(C.currencyForRegion(null), null);
+ assert.equal(C.currencyForRegion(''), null);
+ for (const code of Object.values(C.REGION_CURRENCY)) assert.match(code, /^[A-Z]{3}$/);
+ const known = new Set(Intl.supportedValuesOf('currency'));
+ const unknown = [...new Set(Object.values(C.REGION_CURRENCY))].filter(code => !known.has(code));
+ assert.ok(unknown.length <= 3, `currencies this runtime does not know: ${unknown}`);
+});
+
+test('the region comes out of a language tag, or the tag has none', () => {
+ assert.equal(C.regionOfLocale('en-US'), 'US');
+ assert.equal(C.regionOfLocale('de_DE.UTF-8'), 'DE');
+ assert.equal(C.regionOfLocale('zh-Hans-CN'), 'CN');
+ assert.equal(C.regionOfLocale('en'), null);
+ assert.equal(C.regionOfLocale(''), null);
+ assert.equal(C.regionOfLocale(undefined), null);
+});
+
+test('the currency: the override, then the system, then the browser, then the app language, then none', () => {
+ const windows = { locale: 'en-US', region: 'US', currency: null, source: 'windows' };
+ assert.deepEqual(C.resolveCurrency({ system: windows, language: 'en' }), { currency: 'USD', locale: 'en-US', source: 'system' });
+ assert.equal(C.resolveCurrency({ system: { locale: 'de-CH', region: 'CH', currency: 'EUR', source: 'linux' }, language: 'en' }).currency, 'EUR', 'a currency the system names wins over its region');
+ assert.equal(C.resolveCurrency({ system: windows, language: 'en', override: 'chf' }).currency, 'CHF', 'the picker overrides');
+ assert.equal(C.resolveCurrency({ system: windows, language: 'en', override: 'x' }).currency, 'USD', 'a bad override is ignored');
+ assert.deepEqual(C.resolveCurrency({ system: null, browserLanguages: ['en', 'sl-SI'], language: 'en' }), { currency: 'EUR', locale: 'sl-SI', source: 'browser' });
+ assert.deepEqual(C.resolveCurrency({ system: null, browserLanguages: [], language: 'ja' }), { currency: 'JPY', locale: 'ja', source: 'language' });
+ assert.equal(C.resolveCurrency({ system: null, browserLanguages: [], language: 'zh' }).currency, 'CNY');
+ assert.equal(C.resolveCurrency({ system: null, browserLanguages: [], language: 'pt' }).currency, 'BRL');
+ assert.deepEqual(C.resolveCurrency({ system: null, browserLanguages: ['en'], language: 'en' }), { currency: null, locale: 'en', source: 'none' }, 'English names no region: no currency, never EUR');
+ assert.equal(C.resolveCurrency({ system: { locale: null, region: null, currency: null, source: null }, language: 'en' }).currency, null);
+});
+
+test('money is written for the locale with the usual digits of the currency, and a tiny amount is "less than" one unit', () => {
+ const us = { currency: 'USD', locale: 'en-US' }, de = { currency: 'EUR', locale: 'de-DE' }, jp = { currency: 'JPY', locale: 'ja-JP' };
+ assert.equal(C.formatMoney(1.2345, us), '$1.23');
+ assert.equal(C.formatMoney(0.123456, us), '$0.12');
+ assert.equal(C.formatMoney(0.01, us), '$0.01');
+ assert.equal(C.formatMoney(12.5, us), '$12.50');
+ assert.equal(C.formatMoney(0, us), '$0.00');
+ assert.equal(C.formatMoney(0.0000339, us), 'less than $0.01', 'not 0.00 and not a run of decimals');
+ assert.equal(C.formatMoney(0.0099, us), 'less than $0.01');
+ assert.equal(norm(C.formatMoney(1.234, de)), norm('1,23 €'));
+ assert.equal(norm(C.formatMoney(0.004, de)), norm('less than 0,01 €'));
+ assert.match(C.formatMoney(3.2, jp), /^[¥¥]3$/);
+ assert.match(C.formatMoney(0.4, jp), /^less than [¥¥]1$/, 'a currency with no minor unit: below one yen');
+ assert.equal(norm(C.formatMoney(0.001, de)), norm('less than 0,01 €'));
+});
+
+test('the sentence for a tiny amount comes from the caller, so it can be translated', () => {
+ assert.equal(norm(C.formatMoney(0.001, { currency: 'EUR', locale: 'fr-FR', lessThan: shown => `moins de ${shown}` })), norm('moins de 0,01 €'));
+ assert.equal(C.minorDigits('USD', 'en-US'), 2);
+ assert.equal(C.minorDigits('JPY', 'en-US'), 0);
+ assert.equal(C.minorDigits(null, 'en-US'), 2);
+});
+
+test('with no currency the number is shown alone, and a broken code or locale never throws', () => {
+ assert.equal(C.formatMoney(1.2345, { currency: null, locale: 'en-US' }), '1.23');
+ assert.equal(C.formatMoney(0.0123456, { currency: null, locale: 'en-US' }), '0.01');
+ assert.equal(C.formatMoney(0.001, { currency: null, locale: 'en-US' }), 'less than 0.01');
+ assert.equal(C.formatMoney(0, { currency: null, locale: 'en-US' }), '0.00');
+ assert.equal(C.formatMoney(1.5, { currency: 'XXXX', locale: 'en-US' }), '1.50');
+ assert.equal(C.formatMoney(1.5, { currency: 'USD', locale: 'not a locale!' }), '1.50');
+ assert.equal(C.formatMoney(NaN, { currency: 'USD', locale: 'en-US' }), '—');
+});
+
+test('the Settings line names the currency with its symbol, and the picker lists every currency', () => {
+ assert.equal(C.currencyLabel('USD', 'en-US'), 'USD ($)');
+ assert.equal(C.currencyLabel('EUR', 'de-DE'), 'EUR (€)');
+ assert.equal(C.currencyLabel('ZZZ', 'en-US'), 'ZZZ');
+ const choices = C.currencyChoices('en-US');
+ assert.ok(choices.length > 100);
+ assert.ok(choices.some(c => c.value === 'JPY' && /Japanese Yen/.test(c.label)));
+});
+
+test('the host reads the regional format: Windows, macOS and Linux, and says nothing when there is none', () => {
+ assert.deepEqual(parseLocaleTag('en_US.UTF-8'), { locale: 'en-US', region: 'US' });
+ assert.deepEqual(parseLocaleTag('de_DE@euro'), { locale: 'de-DE', region: 'DE' });
+ assert.deepEqual(parseLocaleTag('zh-Hans-CN'), { locale: 'zh-CN', region: 'CN' });
+ assert.deepEqual(parseLocaleTag('fr'), { locale: 'fr', region: null });
+ assert.deepEqual(parseLocaleTag('C'), { locale: null, region: null });
+ assert.deepEqual(parseLocaleTag(undefined), { locale: null, region: null });
+ assert.equal(parseRegValue(' LocaleName REG_SZ en-US\r\n', 'LocaleName'), 'en-US');
+ const win = values => (cmd, args) => { const key = args.join(' '); for (const [needle, out] of Object.entries(values)) if (key.includes(needle)) return out; throw new Error('not found'); };
+ assert.deepEqual(detectRegion({ platform: 'win32', run: win({ LocaleName: ' LocaleName REG_SZ de-DE\r\n' }) }), { locale: 'de-DE', region: 'DE', currency: null, source: 'windows' });
+ assert.deepEqual(detectRegion({ platform: 'win32', run: win({ 'Geo /v Name': ' Name REG_SZ SI\r\n', LocaleName: ' LocaleName REG_SZ en\r\n' }) }), { locale: 'en-SI', region: 'SI', currency: null, source: 'windows' }, 'a regional format with no region uses the country setting');
+ assert.deepEqual(detectRegion({ platform: 'win32', run: () => { throw new Error('no registry'); } }), { locale: null, region: null, currency: null, source: null });
+ assert.deepEqual(detectRegion({ platform: 'darwin', run: () => 'de_CH@currency=EUR\n' }), { locale: 'de-CH', region: 'CH', currency: 'EUR', source: 'macos' });
+ assert.deepEqual(detectRegion({ platform: 'darwin', run: () => 'en_GB\n' }), { locale: 'en-GB', region: 'GB', currency: null, source: 'macos' });
+ assert.deepEqual(detectRegion({ platform: 'linux', env: { LANG: 'sl_SI.UTF-8' }, run: () => 'int_curr_symbol="EUR "\n' }), { locale: 'sl-SI', region: 'SI', currency: 'EUR', source: 'linux' });
+ assert.deepEqual(detectRegion({ platform: 'linux', env: { LC_ALL: 'C' }, run: () => { throw new Error('no locale command'); } }), { locale: null, region: null, currency: null, source: null });
+ assert.equal(detectRegion({ platform: 'linux', env: { LC_MONETARY: 'ja_JP.UTF-8', LANG: 'en_US.UTF-8' }, run: () => { throw new Error('x'); } }).region, 'JP', 'the monetary locale comes first');
+});
diff --git a/apps/host/tests/gh-app-features.test.mjs b/apps/host/tests/gh-app-features.test.mjs
new file mode 100644
index 000000000..7c12c2bc9
--- /dev/null
+++ b/apps/host/tests/gh-app-features.test.mjs
@@ -0,0 +1,230 @@
+// The 0.2.7 GitHub items done in f-027-gh-app: the Power card's readings (#3628), the finished-work sound (#3586), approval
+// notifications and the tray choice (#3477), the pinned port (#3402). Hermetic: scratch folders and fake fetch/spawn only.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { EventEmitter } from 'node:events';
+import { build } from 'esbuild';
+import { pickTemperatures, readLinuxTemperatures, parseSsdLine, createWindowsSsdReader } from '../server/temperature-telemetry.mjs';
+import { addEnergy, energyWh } from '../server/energy-meter.mjs';
+import { cleanPrefs, readShellPrefs, writeShellPrefs, parsePortNotice, createShellNotifier, validPort, DEFAULTS } from '../server/shell-prefs.mjs';
+import { parseNvidiaReadings } from '../server/device-probes.mjs';
+
+const compiled = await build({ stdin: { contents: "export * from './src/lib/attention'; export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });
+const A = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);
+
+test('temperatures: the hottest processor and drive sensor, nothing invented', () => {
+ assert.deepEqual(pickTemperatures([{ name: 'coretemp', temps: [51000, 56000] }, { name: 'nvme', temps: [41850] }, { name: 'amdgpu', temps: [70000] }]), { cpuTempC: 56, ssdTempC: 42 });
+ assert.deepEqual(pickTemperatures([{ name: 'nvme', temps: [-1, 0, 200000] }]), { cpuTempC: null, ssdTempC: null });
+ assert.deepEqual(pickTemperatures([]), { cpuTempC: null, ssdTempC: null });
+});
+
+test('Linux hwmon folders are read through the injected file functions', async () => {
+ const files = { '/h/hwmon0/name': 'k10temp\n', '/h/hwmon0/temp1_input': '48500\n', '/h/hwmon1/name': 'nvme\n', '/h/hwmon1/temp1_input': '39000\n', '/h/hwmon2/name': 'acpitz\n' };
+ const dirs = { '/h': ['hwmon0', 'hwmon1', 'hwmon2'], '/h/hwmon0': ['name', 'temp1_input'], '/h/hwmon1': ['name', 'temp1_input'], '/h/hwmon2': ['name'] };
+ const read = async path => { if (!(path in files)) throw new Error('ENOENT'); return files[path]; };
+ const list = async path => { if (!(path in dirs)) throw new Error('ENOENT'); return dirs[path]; };
+ assert.deepEqual(await readLinuxTemperatures({ base: '/h', read, list }), { cpuTempC: 49, ssdTempC: 39 });
+ assert.deepEqual(await readLinuxTemperatures({ base: '/missing', read, list }), { cpuTempC: null, ssdTempC: null });
+});
+
+test('the Windows SSD loop gives a value only for a plausible line and goes stale', () => {
+ assert.equal(parseSsdLine('ssd 53'), 53);
+ assert.equal(parseSsdLine('ssd -'), null);
+ assert.equal(parseSsdLine('ssd 400'), null);
+ assert.equal(parseSsdLine('something else'), undefined);
+ let clock = 1000;
+ const child = Object.assign(new EventEmitter(), { stdout: Object.assign(new EventEmitter(), { unref() {} }), unref() {}, kill() {} });
+ const reader = createWindowsSsdReader({ spawnFn: () => child, now: () => clock });
+ assert.equal(reader.read(), null, 'no line yet');
+ child.stdout.emit('data', 'ssd 47\r\n');
+ assert.equal(reader.read(), 47);
+ clock += 10 * 60 * 1000;
+ assert.equal(reader.read(), null, 'an old value is not shown');
+});
+
+test('GPU energy adds up the held power over the time between ticks, at most 5 s of a gap', () => {
+ const before = energyWh();
+ addEnergy(360, 10_000); // first tick: nothing to add yet
+ assert.equal(energyWh(), before);
+ addEnergy(360, 11_000); // 360 W for 1 s = 0.1 Wh
+ assert.ok(Math.abs(energyWh() - before - 0.1) < 1e-9);
+ addEnergy(360, 3_600_000); // a sleep of an hour counts as 5 s only
+ assert.ok(Math.abs(energyWh() - before - 0.6) < 1e-9);
+ addEnergy(null, 3_601_000); // no reading: nothing added
+ assert.ok(Math.abs(energyWh() - before - 0.6) < 1e-9);
+});
+
+test('nvidia-smi fan and clock are read, an unsupported field is no reading', () => {
+ const [a] = parseNvidiaReadings('GPU-1, 41, 5, 1024, 30.5, 200, 4, 4, 16, 35, 1800');
+ assert.equal(a.fanPct, 35); assert.equal(a.clockMhz, 1800);
+ const [b] = parseNvidiaReadings('GPU-1, 41, 5, 1024, 30.5, 200, 4, 4, 16, [N/A], [N/A]');
+ assert.equal(b.fanPct, null); assert.equal(b.clockMhz, null);
+ const [c] = parseNvidiaReadings('GPU-1, 41, 5, 1024');
+ assert.equal(c.fanPct, null);
+});
+
+test('the readings strip lists only what this PC can read and the Settings has the price', () => {
+ const monitor = readFileSync(new URL('../src/screens/Monitor.tsx', import.meta.url), 'utf8');
+ for (const label of ['Energy since start', 'Cost since start', 'GPU fan', 'GPU clock', 'CPU temperature', 'SSD temperature']) assert.ok(monitor.includes(`'${label}'`), label);
+ assert.match(monitor, /\.filter\(\(line\): line is/);
+ assert.match(monitor, /readingsStrip\.length \? <section className="st-card monitor-readings"/, 'the whole strip is left out when no reading is available');
+ assert.doesNotMatch(monitor, /lines=\{/, 'the Power card keeps its old height');
+ const settings = readFileSync(new URL('../src/screens/Settings.tsx', import.meta.url), 'utf8');
+ assert.match(settings, /label: 'Electricity price'/);
+});
+
+test('shell prefs: defaults, a valid port, automatic, a refused port, the tray, the language', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'strata-shell-prefs-'));
+ try {
+ const file = join(dir, 'sub', 'shell-prefs.json');
+ assert.deepEqual(readShellPrefs(file), DEFAULTS);
+ assert.deepEqual(writeShellPrefs({ port: 47900 }, file), { port: 47900, tray: false, language: 'en' });
+ assert.deepEqual(writeShellPrefs({ tray: true, language: 'de' }, file), { port: 47900, tray: true, language: 'de' });
+ assert.throws(() => writeShellPrefs({ port: 80 }, file), /between 1024 and 65535/);
+ assert.throws(() => writeShellPrefs({ port: 70000 }, file), /between 1024 and 65535/);
+ assert.equal(readShellPrefs(file).port, 47900, 'a refused port changes nothing');
+ assert.equal(writeShellPrefs({ port: null }, file).port, 0);
+ assert.equal(writeShellPrefs({ language: 'xx' }, file).language, 'de', 'an unknown language is ignored');
+ writeFileSync(file, '{ not json');
+ assert.deepEqual(readShellPrefs(file), DEFAULTS);
+ assert.deepEqual(cleanPrefs({ port: '47831', tray: 'yes', language: 'ko' }), { port: 0, tray: false, language: 'ko' });
+ assert.ok(validPort(1024) && validPort(65535) && !validPort(1023) && !validPort(65536) && !validPort(47.5));
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('the busy-port notice and the shell notifier come only from the shell', async () => {
+ assert.deepEqual(parsePortNotice('busy:47831:51234'), { wanted: 47831, used: 51234 });
+ assert.equal(parsePortNotice('busy:x:1'), null);
+ assert.equal(parsePortNotice(undefined), null);
+ assert.equal(createShellNotifier({ env: {} }), null, 'a browser or a source checkout has no shell');
+ assert.equal(createShellNotifier({ env: { STRATA_SHELL_BRIDGE: 'http://example.com:1', STRATA_SHELL_TOKEN: 't' } }), null, 'only a loopback bridge');
+ const seen = [];
+ const notifier = createShellNotifier({ env: { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:5555', STRATA_SHELL_TOKEN: 'secret' }, fetcher: async (url, init) => { seen.push([url, init]); return { ok: true, json: async () => ({ shown: true }) }; } });
+ assert.deepEqual(await notifier.notify({ title: 'Strata needs your answer', body: 'a & b?' }), { shown: true });
+ assert.equal(seen[0][0], 'http://127.0.0.1:5555/shell/notify?title=Strata%20needs%20your%20answer&body=a%20%26%20b%3F');
+ assert.equal(seen[0][1].headers.authorization, 'Bearer secret');
+ assert.equal(seen[0][1].method, 'POST');
+});
+
+test('the finished-work sound is opt-in, quiet for quick answers in front, and never twice in a row', async () => {
+ const base = { enabled: true, durationMs: 20_000, focused: true, now: 1_000_000 };
+ assert.equal(A.shouldPlayDone({ ...base, enabled: false }), false);
+ assert.equal(A.shouldPlayDone({ ...base, durationMs: 1000 }), false, 'a quick answer with the window in front');
+ assert.equal(A.shouldPlayDone({ ...base, durationMs: 1000, focused: false }), true, 'the window is in the background');
+ assert.equal(A.shouldPlayDone(base), true, 'work that took a while');
+ const played = [];
+ assert.equal(A.playDoneSound(url => ({ volume: 0, play() { played.push(url); return Promise.resolve(); } })), true);
+ assert.deepEqual(played, ['/strata-done-sound.wav']);
+ assert.equal(A.shouldPlayDone({ ...base, now: Date.now() + 100 }), false, 'a second chime within two seconds is skipped');
+ assert.equal(A.playDoneSound(() => { throw new Error('no audio'); }), false, 'a missing audio device is not an error');
+ const wav = readFileSync(new URL('../public/strata-done-sound.wav', import.meta.url));
+ assert.equal(wav.toString('latin1', 0, 4), 'RIFF');
+ assert.equal(wav.toString('latin1', 8, 12), 'WAVE');
+});
+
+test('approval notifications: shell first, the page second, nothing when off or when Strata is in front', async () => {
+ const notice = { title: 'T', body: 'B' };
+ const seen = [];
+ assert.equal(await A.showNotice(notice, { post: async () => ({ shown: true }), page: () => { seen.push('page'); return true; } }), true);
+ assert.deepEqual(seen, []);
+ assert.equal(await A.showNotice(notice, { post: async () => ({ shown: false }), page: () => { seen.push('page'); return true; } }), true);
+ assert.equal(await A.showNotice(notice, { post: async () => { throw new Error('no shell'); }, page: () => { seen.push('page2'); return false; } }), false);
+ assert.deepEqual(seen, ['page', 'page2']);
+ assert.equal(await A.approvalNeeded(false, 'write_file', false), false);
+ assert.equal(await A.approvalNeeded(true, 'write_file', true), false, 'the person is looking at Strata');
+ A.setTranslationLanguage('de');
+ assert.match(A.approvalNotice('write_file').body, /write_file/);
+ assert.notEqual(A.approvalNotice('write_file').title, 'Strata needs your answer');
+ A.setTranslationLanguage('en');
+ assert.equal(A.approvalNotice('').body, 'The assistant wants to use a tool. Open Strata to approve or deny.');
+});
+
+test('every new string exists in all eight languages with the same slots, and does not collide with another catalog', async () => {
+ const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];
+ const read = async name => JSON.parse(readFileSync(new URL(`../src/locales/${name}.json`, import.meta.url), 'utf8'));
+ const withFrench = [...languages, 'fr']; // French is a ninth language of this catalog; the app learns it with the i18n work
+ const gh = Object.fromEntries(await Promise.all(withFrench.map(async l => [l, await read(`gh-${l}`)])));
+ const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort();
+ const others = new Set();
+ for (const name of ['en', 'tune-en', 'tools-en', 'fix-en']) for (const v of Object.values(await read(name))) others.add(v);
+ for (const l of withFrench) {
+ assert.deepEqual(Object.keys(gh[l]), Object.keys(gh.en), l);
+ for (const [id, source] of Object.entries(gh.en)) {
+ assert.ok(gh[l][id].trim(), `${l}:${id} is empty`);
+ assert.deepEqual(slots(gh[l][id]), slots(source), `${l}:${id}`);
+ if (l !== 'en') assert.notEqual(gh[l][id], source, `${l}:${id} is still English`);
+ }
+ }
+ for (const [id, text] of Object.entries(gh.en)) assert.ok(!others.has(text), `already in another catalog: ${id} ${text}`);
+ const busyId = Object.keys(gh.en).find(id => gh.en[id].startsWith('Port {0} is used by another program'));
+ for (const l of languages) {
+ A.setTranslationLanguage(l);
+ assert.equal(A.tr('Energy since start'), gh[l].gh01, l);
+ assert.equal(A.tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.', [47831, 51234]),
+ gh[l][busyId].replaceAll('{0}', '47831').replaceAll('{1}', '51234'), l);
+ }
+ A.setTranslationLanguage('en');
+});
+
+test('the interface size scales the whole page, up to 200 percent, and a saved value is checked (#3970)', () => {
+ const store = readFileSync(new URL('../src/lib/store.ts', import.meta.url), 'utf8');
+ assert.match(store, /setProperty\('zoom', state\.uiScale === 1 \? '' : String\(state\.uiScale\)\)/);
+ assert.match(store, /setProperty\('--st-ui-scale', '1'\)/, 'the token stays at 1 so nothing is scaled twice');
+ assert.match(store, /UI_SCALES = \[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\]/);
+ assert.match(store, /\[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\]\.includes\(Number\(parsed\.uiScale\)\)/);
+ const settings = readFileSync(new URL('../src/screens/Settings.tsx', import.meta.url), 'utf8');
+ assert.match(settings, /Makes all text, buttons and menus in Strata larger or smaller\./);
+});
+
+test('the port, tray, sound and notification rows are in Settings, and only the desktop app shows the port and the tray', () => {
+ const settings = readFileSync(new URL('../src/screens/Settings.tsx', import.meta.url), 'utf8');
+ assert.match(settings, /label: 'Sound when work finishes'/);
+ assert.match(settings, /label: 'Notify me when Strata needs an answer'/);
+ assert.match(settings, /\.\.\.\(shell\?\.tray \? \[\{ section: 'General', label: 'Minimise to tray'/);
+ assert.match(settings, /\.\.\.\(shell\?\.desktop \? \[\{ section: 'General', label: 'App port'/);
+ const store = readFileSync(new URL('../src/lib/store.ts', import.meta.url), 'utf8');
+ assert.match(store, /frame\.code === 'waiting-approval'/);
+ assert.match(store, /workFinished\(state\.doneSound/);
+ assert.match(store, /announcePortNotice/);
+});
+
+test('the host route for the shell: a browser has no shell, the port choice is saved and checked, a notification is not shown', { timeout: 40000 }, async t => {
+ const { spawn } = await import('node:child_process');
+ const { once } = await import('node:events');
+ const { createServer } = await import('node:net');
+ const { mkdirSync } = await import('node:fs');
+ const free = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
+ const home = mkdtempSync(join(tmpdir(), 'strata-shell-route-'));
+ let child, exited;
+ t.after(async () => { if (child && child.exitCode === null) { child.kill(); await exited; } rmSync(home, { recursive: true, force: true, maxRetries: 3 }); });
+ mkdirSync(join(home, 'data'));
+ const port = await free(), base = `http://127.0.0.1:${port}`;
+ const env = { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_WORKSPACE: join(home, 'work'), STRATA_SETTINGS_FILE: join(home, 'settings.json'), STRATA_COMPONENTS_DIR: join(home, 'components'), STRATA_CONTROL_DIR: join(home, 'no-control'), STRATA_HARNESS_DIR: join(home, 'no-harness'), STRATA_NATIVE_REPO: join(home, 'no-repo'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await free()), STRATA_TUNNEL_PORT: String(await free()), STRATA_BIND: '127.0.0.1', STRATA_REAL_ENGINE: '0', STRATA_AGENT: 'off', STRATA_NO_ACQUIRE: '1', STRATA_PORT_NOTICE: 'busy:47831:' + port, STRATA_TEST_LOCALE: 'de-DE', LOCALAPPDATA: join(home, 'Local'), APPDATA: join(home, 'Roaming'), XDG_DATA_HOME: join(home, 'xdg-data'), XDG_STATE_HOME: join(home, 'xdg-state'), XDG_CONFIG_HOME: join(home, 'xdg-config') };
+ delete env.STRATA_SHELL_BRIDGE; delete env.STRATA_SHELL_TOKEN;
+ child = spawn(process.execPath, ['server/index.mjs'], { cwd: join(import.meta.dirname, '..'), windowsHide: true, stdio: 'ignore', env });
+ exited = once(child, 'exit');
+ let up = false;
+ for (let n = 0; n < 150 && !up; n++) { try { up = (await fetch(base + '/api/health')).ok; } catch { /* not yet */ } if (!up) await new Promise(r => setTimeout(r, 100)); }
+ assert.ok(up, 'the fixture host started');
+ const get = async path => (await fetch(base + path)).json();
+ const post = (path, body) => fetch(base + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ const first = await get('/api/shell');
+ assert.equal(first.desktop, false); assert.equal(first.tray, false); assert.equal(first.port, port); assert.equal(first.defaultPort, 47831);
+ assert.equal(first.pinnedPort, null); assert.equal(first.minimizeToTray, false);
+ assert.deepEqual(first.portNotice, { wanted: 47831, used: port });
+ assert.deepEqual(await get('/api/locale'), { locale: 'de-DE', region: 'DE', currency: null, source: 'test' }, 'the host names the regional format; the page maps it to a currency');
+ const saved = await post('/api/shell/prefs', { port: 47900, tray: true, language: 'de' });
+ assert.equal(saved.status, 200);
+ const after = await saved.json();
+ assert.equal(after.pinnedPort, 47900); assert.equal(after.minimizeToTray, true);
+ assert.deepEqual(JSON.parse(readFileSync(join(home, 'shell-prefs.json'), 'utf8')), { port: 47900, tray: true, language: 'de' });
+ const refused = await post('/api/shell/prefs', { port: 80 });
+ assert.equal(refused.status, 400);
+ assert.match((await refused.json()).error, /between 1024 and 65535/);
+ assert.equal((await get('/api/shell')).pinnedPort, 47900, 'a refused port changes nothing');
+ assert.equal((await (await post('/api/shell/prefs', { port: null })).json()).pinnedPort, null);
+ assert.deepEqual(await (await post('/api/shell/notify', { title: 'T', body: 'B' })).json(), { shown: false });
+});
diff --git a/apps/host/tests/locale-gaps.test.mjs b/apps/host/tests/locale-gaps.test.mjs
index 9e7c7ae70..a6682ca88 100644
--- a/apps/host/tests/locale-gaps.test.mjs
+++ b/apps/host/tests/locale-gaps.test.mjs
@@ -12,7 +12,7 @@ const { tr, setTranslationLanguage } = await import(`data:text/javascript;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));
+ for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-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 })) {