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++

Monitor: AMD cards keep their readings while an engine runs, Windows AMD temperature, no remote-console chip as a GPU (#3727)

Niko12215e8f47cfff4b
diff --git a/apps/host/server/device-probes.mjs b/apps/host/server/device-probes.mjs
index 80a68d8c5..b61fd8b94 100644
--- a/apps/host/server/device-probes.mjs
+++ b/apps/host/server/device-probes.mjs
@@ -62,6 +62,18 @@ export function parsePcieThroughput(raw) {
}
async function read(path) { try {return (await readFile(path,'utf8')).trim();} catch {return '';} }
async function list(path) {try{return await readdir(path);}catch{return [];}}
+/** A server's remote-console chip (ASPEED), a virtual display or a framebuffer is not a graphics card: no maker we know and no memory of its own. */
+export function isComputeAdapter(vendor,vramBytes) { return vendor!=='unknown'||vramBytes>0; }
+/**
+ * The temperature of an amdgpu card from its hwmon inputs [{label, milli}]: the edge sensor (what nvtop and rocm-smi show), else the
+ * junction, else the first one that has a plausible value. Cards such as the Instinct line have no edge sensor. 0 is no reading.
+ */
+export function pickGpuTemperature(inputs) {
+ const ok=inputs.filter(i=>i.milli!==null&&i.milli>0&&i.milli<=150000);
+ const first=re=>ok.find(i=>re.test(i.label??''));
+ const chosen=first(/edge|^gpu/i)??ok.find(i=>!i.label)??first(/junction|hotspot/i)??ok.find(i=>!/mem/i.test(i.label??''));
+ return chosen?chosen.milli/1000:null;
+}
export async function detectDrmGpus() {
const result=[];
for(const card of (await list('/sys/class/drm')).filter(n=>/^card\d+$/.test(n))) {
@@ -71,6 +83,7 @@ export async function detectDrmGpus() {
const vendor={'0x1002':'amd','0x8086':'intel','0x10de':'nvidia'}[vendorId]??'unknown';
const name=await probe('lspci',['-s',busId]);
const bytes=number(await read(`${device}/mem_info_vram_total`));
+ if(!isComputeAdapter(vendor,bytes))continue;
result.push({id:`drm:${busId}`,index:result.length,busId,vendor,name:name.replace(/^[^ ]+\s+[^:]+:\s*/,'')||`${vendor.toUpperCase()} GPU`,vramGb:bytes===null?0:round(bytes/1024**3,1),unified:vendor==='intel'&&!(bytes>0),backend:'vulkan',sensorPath:device});
}
return result;
@@ -89,7 +102,7 @@ export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, ru
if(gpu.vendor==='nvidia')reading={...reading,pcieRxMbs:transfer.get(gpu.sensorIndex??gpu.index)??null};
if(gpu.luid&&!nvidia.has(gpu.id)) {
const counters=windowsGpuReading(gpu.luid);
- if(counters)reading={...reading,utilizationPct:counters.utilizationPct,memoryUsedGb:round(counters.memoryUsedGb,2)};
+ if(counters)reading={...reading,utilizationPct:counters.utilizationPct,memoryUsedGb:round(counters.memoryUsedGb,2),temperatureC:counters.temperatureC??null};
}
if(gpu.sensorPath&&!nvidia.has(gpu.id)) {
let temperature=null,power=null,powerLimit=null,fanPwm=null,clockHz=null;
@@ -99,12 +112,9 @@ export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, ru
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;
- const milli=number(await read(`${folder}/${input}`));
- if(milli!==null&&milli>=0&&milli<=150000){temperature=milli/1000;break;}
- }
+ const sensors=[];
+ for(const input of inputs)sensors.push({label:await read(`${folder}/${input.replace('_input','_label')}`),milli:number(await read(`${folder}/${input}`))});
+ temperature=pickGpuTemperature(sensors);
if(temperature!==null)break;
}
const utilization=number(await read(`${gpu.sensorPath}/gpu_busy_percent`)),bytes=number(await read(`${gpu.sensorPath}/mem_info_vram_used`));
diff --git a/apps/host/server/monitor-dashboard.mjs b/apps/host/server/monitor-dashboard.mjs
index 3d09007a2..eba1f102c 100644
--- a/apps/host/server/monitor-dashboard.mjs
+++ b/apps/host/server/monitor-dashboard.mjs
@@ -1,12 +1,25 @@
+const MEASURES=['temperatureC','utilizationPct','memoryUsedGb','powerW','powerLimitW','pcieGen','pcieGenMax','pcieWidth','pcieRxMbs'];
+/** The engine's numbers win; a number the engine leaves out comes from the host's own reading of the same card. */
+export function mergeOwnReading(engine,own) {
+ if(!own)return engine;
+ const merged={...own,...Object.fromEntries(Object.entries(engine).filter(([,v])=>v!==null&&v!==undefined))};
+ const engineGave=MEASURES.some(k=>typeof engine[k]==='number');
+ return {...merged,source:engineGave?'engine':own.source};
+}
+
/** Translate the original Strata /metrics dashboard without inventing missing sensors. */
export function originalDashboard(raw, hardware, fallback) {
const live=raw.live,engine=raw.engine,hw=raw.hardware??{},history=raw.history??{},cache=raw.conversation_cache,totals=raw.totals;
const finite=n=>typeof n==='number'&&Number.isFinite(n);
const gb=n=>finite(n)?n/1024**3:null;
const devices=hardware?.gpus??[];
+ // The host's own sensor readings (nvidia-smi, amdgpu sysfs, the Windows GPU counters) fill in what the engine does not report:
+ // an AMD card on Windows has no engine reader at all, and the engine never gives the fan or the clock (#3727).
+ const own=new Map((fallback?.hardware?.gpus??[]).map(r=>[r.id,r]));
const readings=(hw.gpus??(devices.length===1?[{index:devices[0].index,util:hw.gpu_util,mem_used:hw.gpu_mem_used,temp:hw.gpu_temp,power:hw.gpu_power,power_limit:hw.gpu_power_limit,pcie_gen:hw.gpu_pcie_gen,pcie_gen_max:hw.gpu_pcie_gen_max,pcie_width:hw.gpu_pcie_width,pcie_rx_mb:hw.gpu_pcie_rx_mb}]:[])).map(g=>{
const device=devices.find(d=>d.index===g.index);
- return {id:device?.id??`${device?.vendor??'unknown'}:${g.index}`,source:'engine',sampledAt:new Date().toISOString(),temperatureC:g.temp??null,utilizationPct:g.util??null,memoryUsedGb:gb(g.mem_used),powerW:g.power??null,powerLimitW:g.power_limit??null,pcieGen:g.pcie_gen??null,pcieGenMax:g.pcie_gen_max??null,pcieWidth:g.pcie_width??null,pcieRxMbs:g.pcie_rx_mb??null};
+ const id=device?.id??`${device?.vendor??'unknown'}:${g.index}`;
+ return mergeOwnReading({id,source:'engine',sampledAt:new Date().toISOString(),temperatureC:g.temp??null,utilizationPct:g.util??null,memoryUsedGb:gb(g.mem_used),powerW:g.power??null,powerLimitW:g.power_limit??null,pcieGen:g.pcie_gen??null,pcieGenMax:g.pcie_gen_max??null,pcieWidth:g.pcie_width??null,pcieRxMbs:g.pcie_rx_mb??null},own.get(id));
});
const last=raw.requests?.[0],used=live.state!=='idle'&&live.state!=='unloaded'?(live.prompt_tokens??0)+(live.generated??0):(last?.prompt_tokens??0)+(last?.output_tokens??0);
const maximum=engine.max_context??fallback.context.maxTokens;
@@ -20,7 +33,7 @@ export function originalDashboard(raw, hardware, fallback) {
generation:{done:live.generated??null,total:live.max_tokens??null},
queue:{running:live.running??(['reading','generating'].includes(live.state)?1:0),waiting:live.queued??0},context:{usedTokens:used,maxTokens:maximum,pct:maxPct(used,maximum)},
expertCache:{used:engine.expert_slots??0,total:engine.experts??0,memoryGb:finite(engine.expert_cache_mib)?engine.expert_cache_mib/1024:null,source:finite(engine.expert_slots)?'engine':'none'},
- hardware:{...fallback.hardware,gpus:readings.length?readings:fallback.hardware.gpus,gpuLoad:hw.gpu_util??null,vramUsedGb:gb(hw.gpu_mem_used),vramTotalGb:gb(hw.gpu_mem_total)??fallback.hardware.vramTotalGb,gpuTempC:hw.gpu_temp??null,powerW:hw.gpu_power??null,powerLimitW:hw.gpu_power_limit??null,pcieRxMbs:hw.gpu_pcie_rx_mb??null,cpuLoad:hw.cpu??fallback.hardware.cpuLoad,ramUsedGb:gb(hw.ram_used)??fallback.hardware.ramUsedGb,ramTotalGb:gb(hw.ram_total)??fallback.hardware.ramTotalGb,diskReadGbs:finite(hw.disk_read_mb)?hw.disk_read_mb/1024:null,diskWriteMbs:hw.disk_write_mb??null},
+ hardware:{...fallback.hardware,gpus:readings.length?readings:fallback.hardware.gpus,gpuLoad:hw.gpu_util??fallback.hardware?.gpuLoad??null,vramUsedGb:gb(hw.gpu_mem_used)??fallback.hardware?.vramUsedGb??null,vramTotalGb:gb(hw.gpu_mem_total)??fallback.hardware.vramTotalGb,gpuTempC:hw.gpu_temp??fallback.hardware?.gpuTempC??null,powerW:hw.gpu_power??fallback.hardware?.powerW??null,powerLimitW:hw.gpu_power_limit??fallback.hardware?.powerLimitW??null,pcieRxMbs:hw.gpu_pcie_rx_mb??fallback.hardware?.pcieRxMbs??null,cpuLoad:hw.cpu??fallback.hardware.cpuLoad,ramUsedGb:gb(hw.ram_used)??fallback.hardware.ramUsedGb,ramTotalGb:gb(hw.ram_total)??fallback.hardware.ramTotalGb,diskReadGbs:finite(hw.disk_read_mb)?hw.disk_read_mb/1024:null,diskWriteMbs:hw.disk_write_mb??null},
history:samples.length?samples:fallback.history,requests,
totals:totals?{...fallback.totals,requests:totals.requests??0,tokensIn:totals.prompt_tokens??0,tokensOut:totals.output_tokens??0,cachedTokens:totals.reused??0,uncachedTokens:(totals.prompt_tokens??0)-(totals.reused??0),promptMs:totals.prompt_ms,decodeMs:totals.decode_ms,since:totals.since?new Date(totals.since*1000).toISOString():fallback.totals.since}:fallback.totals,
conversationCache:cache?{source:'engine',enabled:cache.enabled,parked:cache.parked,slots:cache.slots,memoryGb:gb(cache.bytes),budgetGb:finite(cache.budget_mib)?cache.budget_mib/1024:null,parks:cache.parks,restores:cache.restores,evictions:cache.evictions,lastEvent:cache.last_event,lastAt:cache.last_at,lastTokens:cache.last_tokens,requests:cache.requests,requestsReused:cache.requests_reused,lastPrompt:cache.last_prompt,lastReused:cache.last_reused}:fallback.conversationCache,
diff --git a/apps/host/server/windows-gpu.mjs b/apps/host/server/windows-gpu.mjs
index 8475f192c..06d57d035 100644
--- a/apps/host/server/windows-gpu.mjs
+++ b/apps/host/server/windows-gpu.mjs
@@ -3,7 +3,11 @@
* - size: the DirectX adapter list in the registry (HKLM\SOFTWARE\Microsoft\DirectX) has a 64-bit DedicatedVideoMemory and the adapter
* LUID. Win32_VideoController.AdapterRAM is 32 bits and reads 0 or 4 GB for a 16 GB card (#3727, #3836).
* - load and memory in use: the Windows GPU performance counters (the ones Task Manager shows), read by one long-lived PowerShell and
- * matched to the card by LUID. Temperature, power and the PCIe link need the vendor's own library, so they stay "not available".
+ * matched to the card by LUID.
+ * - temperature: the display driver's own D3DKMT adapter performance data (gdi32.dll, no vendor library, no administrator), asked for the
+ * same LUID. An AMD 7900 XTX gave the same value as ADLX at idle and under load (noctrex, #3727); the card answers in tenths of a degree.
+ * A driver that does not answer leaves the temperature "not available". Power, fan and the PCIe link stay "not available": D3DKMT gave
+ * 0 for power and for the PCIe rate on that card.
*/
import { createPowerShellLoop, endWithHost } from './windows-poll.mjs';
import { utf8Script } from './powershell-utf8.mjs';
@@ -55,20 +59,30 @@ export function windowsOtherGpus(videoRows, dx) {
return out;
}
-/** One counter line: "G <luid> <load percent> <dedicated bytes in use>". */
+/** The temperature D3DKMT reports in tenths of a degree -> whole degrees, or null when the driver gave nothing believable. */
+export function d3dkmtTemperatureC(deci) {
+ const c = Number(deci) / 10;
+ return Number.isFinite(c) && c > 0 && c <= 150 ? Math.round(c) : null;
+}
+
+/** One counter line: "G <luid> <load percent> <dedicated bytes in use> [<temperature in tenths of a degree>]". */
export function parseGpuCounterLine(line) {
- const m = /^G\s+(luid_0x[0-9a-f]+_0x[0-9a-f]+)\s+(\d+(?:\.\d+)?)\s+(\d+)\s*$/i.exec(String(line));
- return m ? { luid: m[1].toLowerCase(), utilizationPct: Math.max(0, Math.min(100, Number(m[2]))), memoryUsedGb: Number(m[3]) / 1024 ** 3 } : null;
+ const m = /^G\s+(luid_0x[0-9a-f]+_0x[0-9a-f]+)\s+(\d+(?:\.\d+)?)\s+(\d+)(?:\s+(-?\d+))?\s*$/i.exec(String(line));
+ return m ? { luid: m[1].toLowerCase(), utilizationPct: Math.max(0, Math.min(100, Number(m[2]))), memoryUsedGb: Number(m[3]) / 1024 ** 3, temperatureC: d3dkmtTemperatureC(m[4]) } : null;
}
+/** The C# that asks D3DKMT (KMTQAITYPE_ADAPTERPERFDATA = 62, 64-byte D3DKMT_ADAPTER_PERFDATA, Temperature at byte 56) for one LUID; -1 = no answer. */
+export const GPU_TEMP_CSHARP = 'using System;using System.Runtime.InteropServices;public static class StrataGpuTemp{[StructLayout(LayoutKind.Sequential)]struct Q{public uint L;public int H;public uint A;}[StructLayout(LayoutKind.Sequential)]struct Info{public uint A;public int T;public IntPtr P;public uint S;}[DllImport("gdi32.dll")]static extern int D3DKMTOpenAdapterFromLuid(ref Q q);[DllImport("gdi32.dll")]static extern int D3DKMTCloseAdapter(ref uint a);[DllImport("gdi32.dll")]static extern int D3DKMTQueryAdapterInfo(ref Info i);public static int Read(int high,uint low){Q q=new Q();q.L=low;q.H=high;if(D3DKMTOpenAdapterFromLuid(ref q)!=0)return -1;IntPtr buf=Marshal.AllocHGlobal(64);try{for(int k=0;k<64;k++)Marshal.WriteByte(buf,k,0);Info i=new Info();i.A=q.A;i.T=62;i.P=buf;i.S=64;if(D3DKMTQueryAdapterInfo(ref i)!=0)return -1;return Marshal.ReadInt32(buf,56);}finally{Marshal.FreeHGlobal(buf);uint a=q.A;D3DKMTCloseAdapter(ref a);}}}';
+
export function createWindowsGpuReader({ spawnFn, intervalSec = 4, maxStarts = 3, now = Date.now } = {}) {
const readings = new Map();
const script = utf8Script(
+ `$t=$false;try{Add-Type -TypeDefinition '${GPU_TEMP_CSHARP}';$t=$true}catch{};` +
`while($true){` +
`$e=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine);$m=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUAdapterMemory);` +
`$u=@{};foreach($r in $e){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)_phys_\\d+_eng_\\d+_engtype_(\\w+)'){$k=$matches[1].ToLower()+'|'+$matches[2];$u[$k]=[double]$u[$k]+[double]$r.UtilizationPercentage}};` +
`$b=@{};foreach($k in $u.Keys){$l=$k.Split('|')[0];if(-not $b.ContainsKey($l) -or $u[$k] -gt $b[$l]){$b[$l]=$u[$k]}};` +
- `foreach($r in $m){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)'){$l=$matches[1].ToLower();[Console]::Out.WriteLine('G '+$l+' '+[math]::Round([double]$b[$l],0)+' '+$r.DedicatedUsage)}};` +
+ `foreach($r in $m){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)'){$l=$matches[1].ToLower();$d=-1;if($t){try{$p=$l.Split('_');$d=[StrataGpuTemp]::Read([Convert]::ToInt32($p[1].Substring(2),16),[Convert]::ToUInt32($p[2].Substring(2),16))}catch{}};[Console]::Out.WriteLine('G '+$l+' '+[math]::Round([double]$b[$l],0)+' '+$r.DedicatedUsage+' '+$d)}};` +
`[Console]::Out.Flush();Start-Sleep -Seconds ${intervalSec}}`);
const loop = createPowerShellLoop({ script, spawnFn, maxStarts, onLine: line => {
const parsed = parseGpuCounterLine(line);
diff --git a/apps/host/tests/monitor-dashboard.test.mjs b/apps/host/tests/monitor-dashboard.test.mjs
index 47bdf5f03..86072c173 100644
--- a/apps/host/tests/monitor-dashboard.test.mjs
+++ b/apps/host/tests/monitor-dashboard.test.mjs
@@ -1,9 +1,9 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { parseCpuTopology, parseNvidiaReadings, parsePcieThroughput, gpuMemoryTotals } from '../server/device-probes.mjs';
+import { parseCpuTopology, parseNvidiaReadings, parsePcieThroughput, gpuMemoryTotals, pickGpuTemperature, isComputeAdapter } from '../server/device-probes.mjs';
import { cpuUtilization, diskRate, parseLinuxDiskCounters, parseMacDiskCounters } from '../server/system-telemetry.mjs';
import { parseEngineMetrics } from '../server/supervisor.mjs';
-import { originalDashboard } from '../server/monitor-dashboard.mjs';
+import { originalDashboard, mergeOwnReading } from '../server/monitor-dashboard.mjs';
import { gpuMetric, gpuCapacity, gpuReported, shortGpuName, defaultGpuSet, gpuId } from '../src/lib/monitor-hardware.ts';
import { referencePaths } from '../src/lib/monitor-chart.ts';
@@ -117,3 +117,50 @@ test('an RTX 5070 beside the unsupported Radeon iGPU: All GPUs is the RTX alone,
assert.deepEqual(defaultGpuSet([igpu]).map(g=>g.id),[igpu.id]);
assert.equal(defaultGpuSet([{...igpu,vramGb:96,unified:true},rtx]).length,2);
});
+
+// ---- 0.2.8: Monitor readings for AMD cards (#3727) ----
+const amd=(id,index)=>({id,index,unified:false,vramGb:16,name:'AMD Radeon RX 9070 XT',vendor:'amd',backend:'vulkan'});
+const ownReading=(id,extra={})=>({id,source:'sensor',sampledAt:'t0',temperatureC:null,utilizationPct:37,memoryUsedGb:5.5,powerW:null,powerLimitW:null,pcieGen:null,pcieGenMax:null,pcieWidth:null,pcieRxMbs:null,...extra});
+const shell=(own)=>({context:{maxTokens:32768},hardware:{gpus:own,gpuLoad:null},history:[],totals:{},telemetry:{}});
+const rawNoGpu={engine:{max_context:32768},live:{state:'generating'},hardware:{cpu:12},history:{}};
+
+test('Windows AMD, one card, engine running: the engine has no GPU reader, the host load and memory stay (#3727)',()=>{
+ const mapped=originalDashboard(rawNoGpu,{gpus:[amd('dx:1',0)]},shell([ownReading('dx:1')]));
+ assert.equal(mapped.hardware.gpus.length,1);
+ assert.equal(mapped.hardware.gpus[0].utilizationPct,37);
+ assert.equal(mapped.hardware.gpus[0].memoryUsedGb,5.5);
+ assert.equal(mapped.hardware.gpus[0].source,'sensor');
+ assert.equal(mapped.hardware.gpus[0].temperatureC,null,'a value nobody read stays unavailable');
+});
+test('engine numbers win, the host fills only the gaps (fan and clock come from the host)',()=>{
+ const raw={...rawNoGpu,hardware:{gpu_util:80,gpu_mem_used:4*1024**3,gpu_temp:61,gpu_power:200}};
+ const mapped=originalDashboard(raw,{gpus:[amd('a',0)]},shell([ownReading('a',{utilizationPct:10,temperatureC:50,fanPct:35,clockMhz:2400,powerLimitW:300})]));
+ const g=mapped.hardware.gpus[0];
+ assert.equal(g.utilizationPct,80); assert.equal(g.temperatureC,61); assert.equal(g.powerW,200);
+ assert.equal(g.powerLimitW,300); assert.equal(g.fanPct,35); assert.equal(g.clockMhz,2400); assert.equal(g.source,'engine');
+});
+test('a card the host has no reading for keeps the engine reading unchanged',()=>{
+ const e={id:'x',source:'engine',temperatureC:null,utilizationPct:5};
+ assert.equal(mergeOwnReading(e,undefined),e);
+});
+test('the headline aggregates fall back to the host when the engine reports none',()=>{
+ const fb=shell([ownReading('a')]); fb.hardware.gpuTempC=55; fb.hardware.vramUsedGb=5.5;
+ const mapped=originalDashboard(rawNoGpu,{gpus:[amd('a',0)]},fb);
+ assert.equal(mapped.hardware.gpuTempC,55); assert.equal(mapped.hardware.vramUsedGb,5.5);
+});
+test('amdgpu temperature: edge first (what nvtop shows), junction when there is no edge, 0 is no reading',()=>{
+ assert.equal(pickGpuTemperature([{label:'edge',milli:36000},{label:'junction',milli:38000},{label:'mem',milli:56000}]),36);
+ assert.equal(pickGpuTemperature([{label:'mem',milli:56000},{label:'junction',milli:48000}]),48);
+ assert.equal(pickGpuTemperature([{label:'',milli:41000}]),41);
+ assert.equal(pickGpuTemperature([{label:'edge',milli:0},{label:'junction',milli:44000}]),44);
+ assert.equal(pickGpuTemperature([{label:'edge',milli:0}]),null);
+ assert.equal(pickGpuTemperature([{label:'mem',milli:56000}]),null,'a memory sensor alone is not the GPU temperature');
+ assert.equal(pickGpuTemperature([]),null);
+});
+test('a remote-console chip with no memory is not a GPU; an unnamed card with memory and an Intel iGPU are',()=>{
+ assert.equal(isComputeAdapter('unknown',null),false);
+ assert.equal(isComputeAdapter('unknown',0),false);
+ assert.equal(isComputeAdapter('unknown',8*1024**3),true);
+ assert.equal(isComputeAdapter('intel',null),true);
+ assert.equal(isComputeAdapter('amd',34208743424),true);
+});
diff --git a/apps/host/tests/windows-gpu.test.mjs b/apps/host/tests/windows-gpu.test.mjs
index 3550e6ff5..0b2f11b2a 100644
--- a/apps/host/tests/windows-gpu.test.mjs
+++ b/apps/host/tests/windows-gpu.test.mjs
@@ -45,3 +45,44 @@ test('counter lines are read, and the load and VRAM in use reach the card by its
assert.equal(reader.read('luid_0x00000000_0x00099999'), null);
assert.equal(procs.length, 1, 'one process for every read');
});
+
+// ---- 0.2.8: the card's temperature from the display driver (D3DKMT), #3727 ----
+import { d3dkmtTemperatureC, GPU_TEMP_CSHARP } from '../server/windows-gpu.mjs';
+
+test('temperature comes in tenths of a degree; no answer, zero and nonsense are not a reading', () => {
+ assert.equal(d3dkmtTemperatureC(300), 30);
+ assert.equal(d3dkmtTemperatureC(437), 44);
+ assert.equal(d3dkmtTemperatureC(-1), null);
+ assert.equal(d3dkmtTemperatureC(0), null);
+ assert.equal(d3dkmtTemperatureC(4294967295), null);
+ assert.equal(d3dkmtTemperatureC(undefined), null);
+ assert.equal(d3dkmtTemperatureC('abc'), null);
+});
+
+test('a counter line carries the temperature; the older three-field line and a failed query still parse', () => {
+ assert.equal(parseGpuCounterLine('G luid_0x00000000_0x00016102 37 4294967296 430').temperatureC, 43);
+ assert.equal(parseGpuCounterLine('G luid_0x00000000_0x00016102 37 4294967296 -1').temperatureC, null);
+ const old = parseGpuCounterLine('G luid_0x00000000_0x00016102 37 4294967296');
+ assert.equal(old.temperatureC, null); assert.equal(old.utilizationPct, 37);
+});
+
+test('the temperature reaches the reader by LUID next to load and memory', () => {
+ const procs = [];
+ const reader = createWindowsGpuReader({ spawnFn: () => { const p = new EventEmitter(); p.stdout = new EventEmitter(); p.kill = () => {}; procs.push(p); return p; }, now: () => 5 });
+ reader.read('luid_0x00000000_0x00016102');
+ procs[0].stdout.emit('data', 'G luid_0x00000000_0x00016102 90 17000000000 465\n');
+ const r = reader.read('luid_0x00000000_0x00016102');
+ assert.equal(r.temperatureC, 47); assert.equal(r.utilizationPct, 90);
+});
+
+test('the PowerShell script that asks D3DKMT is single-quote safe and uses adapter performance data type 62 with the temperature at byte 56', () => {
+ assert.ok(!GPU_TEMP_CSHARP.includes("'"), 'it sits inside a single-quoted PowerShell string');
+ assert.match(GPU_TEMP_CSHARP, /i\.T=62/);
+ assert.match(GPU_TEMP_CSHARP, /ReadInt32\(buf,56\)/);
+ assert.match(GPU_TEMP_CSHARP, /AllocHGlobal\(64\)/);
+ let script = '';
+ createWindowsGpuReader({ spawnFn: (_cmd, args) => { script = args.at(-1); const p = new EventEmitter(); p.stdout = new EventEmitter(); p.kill = () => {}; return p; } }).read('x');
+ assert.ok(script.includes('Add-Type -TypeDefinition'), 'compiled once, before the loop');
+ assert.ok(script.indexOf('Add-Type') < script.indexOf('while($true)'));
+ assert.match(script, /try\{Add-Type[^]*\}catch\{\}/, 'a failed compile must not stop load and memory');
+});