import { execFile } from "node:child_process" import { statfs } from "node:fs/promises" import os from "node:os" import path from "node:path" import { setTimeout as delay } from "node:timers/promises" import type { Disk, Snapshot } from "./types.js" import { intelAdapterScript, intelCountersScript } from "./windows-gpu.js" type CpuTimes = { idle: number; total: number } type Engine = { Name: string; UtilizationPercentage: number } type Runner = (file: string, args: string[]) => Promise const clamp = (value: number) => Math.max(0, Math.min(100, value)) const cleanError = (error: unknown) => { const code = (error as NodeJS.ErrnoException)?.code if (code === "ENOENT") return "Utility not found" if ((error as { killed?: boolean })?.killed) return "Check timed out" return error instanceof Error ? error.message.split("\n")[0].slice(0, 180) : "Check failed" } // Windows splits each engine's utilization by process. Sum the processes on the // SAME adapter/engine, then use the busiest engine; summing adapters overcounts. export function aggregateEngines(engines: Engine[]): number | null { const totals = new Map() for (const engine of engines) { const key = engine.Name?.match(/luid_.+_phys_\d+_eng_\d+_engtype_.*$/)?.[0] const value = Number(engine.UtilizationPercentage) if (!key || !Number.isFinite(value) || value < 0) continue totals.set(key, (totals.get(key) ?? 0) + value) } return totals.size ? clamp(Math.max(...totals.values())) : null } export function cpuUsage(previous: CpuTimes, current: CpuTimes): number | null { const total = current.total - previous.total const idle = current.idle - previous.idle if (total <= 0 || idle < 0 || idle > total) return null return clamp((1 - idle / total) * 100) } const cpuTimes = () => os.cpus().map(cpu => ({ idle: cpu.times.idle, total: Object.values(cpu.times).reduce((sum, value) => sum + value, 0), })) const sumTimes = (times: CpuTimes[]) => times.reduce( (sum, cpu) => ({ idle: sum.idle + cpu.idle, total: sum.total + cpu.total }), { idle: 0, total: 0 }, ) export const run: Runner = (file, args) => new Promise((resolve, reject) => { execFile(file, args, { windowsHide: true, timeout: 6000, maxBuffer: 2 * 1024 * 1024, encoding: "utf8", }, (error, stdout) => error ? reject(error) : resolve(stdout.replace(/^\uFEFF/, "").trim())) }) function powershell(script: string, runner: Runner): Promise { const executable = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe") const content = "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.Encoding]::UTF8; " + script return runner(executable, ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(content, "utf16le").toString("base64")]) } export class Monitor { private previous = cpuTimes() private lastCpuAt = 0 private cached?: Snapshot private pending?: Promise private disks: Snapshot["disks"] = { sampledAt: 0, items: [], error: null } private gpu: Snapshot["gpu"] = { sampledAt: 0, adapter: null, error: null } private intel?: { name: string; luid: string; sharedLimit: number } private lastDiskAttempt = 0 private lastGpuAttempt = 0 constructor(private readonly runner: Runner = run) {} // All callers share one in-flight collection, including multiple GUI windows. snapshot(): Promise { if (this.pending) return this.pending if (this.cached && Date.now() - this.cached.sampledAt < 1500) return Promise.resolve(this.cached) this.pending = this.collect().finally(() => { this.pending = undefined }) return this.pending } private async readDisks(): Promise { if (Date.now() - this.lastDiskAttempt < 30_000) return this.lastDiskAttempt = Date.now() try { let items: Disk[] if (process.platform === "win32") { const text = await powershell( "@(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | Select-Object DeviceID,VolumeName,Size,FreeSpace) | ConvertTo-Json -Compress", this.runner, ) const parsed = JSON.parse(text || "[]") const drives = Array.isArray(parsed) ? parsed : [parsed] items = drives.filter(drive => Number(drive.Size) > 0).map(drive => { const total = Number(drive.Size) const free = Number(drive.FreeSpace) if (!Number.isFinite(total) || !Number.isFinite(free) || free < 0 || free > total) throw new Error("Invalid disk capacity") return { id: String(drive.DeviceID), name: String(drive.VolumeName || drive.DeviceID), total, free, used: total - free, percent: clamp((1 - free / total) * 100) } }) } else { const disk = await statfs("/") const total = disk.blocks * disk.bsize const free = disk.bavail * disk.bsize items = [{ id: "/", name: "Root filesystem", total, free, used: total - free, percent: clamp((1 - free / total) * 100) }] } if (!items.length) throw new Error("No fixed drives reported") this.disks = { sampledAt: Date.now(), items, error: null } } catch (error) { this.disks = { ...this.disks, error: cleanError(error) } } } private async readIntelGpu(): Promise { if (Date.now() - this.lastGpuAttempt < 5000) return this.lastGpuAttempt = Date.now() try { if (process.platform !== "win32") throw new Error("Intel GPU monitoring currently supports Windows") if (!this.intel) { const identity = JSON.parse(await powershell(intelAdapterScript, this.runner)) if (!identity.name || !identity.luid || !Number.isFinite(identity.sharedLimit)) throw new Error("Invalid Intel adapter response") this.intel = identity } const intel = this.intel! const parsed = JSON.parse(await powershell(intelCountersScript(intel.luid), this.runner)) const engines = (Array.isArray(parsed.engines) ? parsed.engines : []).filter( (entry: Engine) => entry.Name?.toLowerCase().includes(`${intel.luid.toLowerCase()}_phys_`), ) const percent = aggregateEngines(engines) const memory = Array.isArray(parsed.memory) ? parsed.memory : [] const sharedUsed = memory.length ? memory.reduce((sum: number, entry: { SharedUsage: number }) => sum + Number(entry.SharedUsage), 0) : null this.gpu = { sampledAt: Date.now(), adapter: { name: intel.name, percent, sharedUsed: Number.isFinite(sharedUsed) ? sharedUsed : null, sharedLimit: intel.sharedLimit }, error: percent === null ? "No Intel GPU-engine counters reported" : null, } } catch (error) { this.intel = undefined // An unavailable reading must never masquerade as 0% utilization. this.gpu = { sampledAt: Date.now(), adapter: null, error: cleanError(error) } } } private async collect(): Promise { // After a long pause, measure a fresh CPU interval rather than averaging // utilization over the whole time the user wasn't viewing the monitor. const first = this.lastCpuAt === 0 || Date.now() - this.lastCpuAt > 15_000 if (first) this.previous = cpuTimes() await Promise.all([ this.readDisks(), this.readIntelGpu(), first ? delay(250) : Promise.resolve(), ]) const current = cpuTimes() const total = os.totalmem() const free = os.freemem() const cpu = { name: os.cpus()[0]?.model.trim() || "CPU", cores: current.length, percent: current.length === this.previous.length ? cpuUsage(sumTimes(this.previous), sumTimes(current)) : null, perCore: current.map((value, index) => this.previous[index] ? cpuUsage(this.previous[index], value) : null), } this.previous = current this.lastCpuAt = Date.now() this.cached = { sampledAt: Date.now(), hostname: os.hostname(), platform: `${os.platform()} ${os.arch()}`, uptime: os.uptime(), cpu, ram: { total, free, used: total - free, percent: clamp((1 - free / total) * 100) }, disks: this.disks, gpu: this.gpu, } return this.cached } } // Plugin setup runs once per project location. Collection remains machine-wide // and on demand: there are no background samplers when no client asks for data. const key = Symbol.for("local-system-monitor.collector.v2") const globals = globalThis as unknown as Record export const monitor = globals[key] ??= new Monitor()