feat: support Linux system monitoring

Add procfs memory and mount-aware disk collectors, Intel and AMD GPU backends, bounded Intel sampling, portable validation tools, and Linux setup documentation. Bump to 0.2.0 and verify on Windows and Ubuntu 24.04 under WSL2.
This commit is contained in:
David Meincke
2026-11-20 13:51:04 +01:00
parent 7ab4e9fd0b
commit aa8a5f35f6
15 changed files with 701 additions and 100 deletions
+21 -10
View File
@@ -1,6 +1,6 @@
import { createSignal, For, Show, type JSX } from "solid-js"
import type { MonitorClient } from "./client.js"
import { bytes, gpuPercent, percent, uptime } from "./format.js"
import { bytes, gpuMemoryLabel, gpuPercent, percent, uptime } from "./format.js"
import type { HistoryPoint } from "./types.js"
type Metric = "cpu" | "ram" | "gpu" | "disk"
@@ -73,7 +73,7 @@ export function Dashboard(props: {
</div>
</div>
<Show when={client.error()}><p role="alert" class="sm-error">{client.error()}. <Show when={client.snapshot()}>Showing the last successful reading.</Show></p></Show>
<Show when={client.snapshot()} fallback={<div class="sm-loading">Reading disk, memory, CPU, and Intel graphics…</div>}>
<Show when={client.snapshot()} fallback={<div class="sm-loading">Reading disk, memory, CPU, and graphics…</div>}>
{snapshot => <>
<div class="sm-machine"><strong>{snapshot().hostname}</strong><span>{snapshot().platform}</span><span>Uptime {uptime(snapshot().uptime)}</span><span class="sm-checked">Checked {client.age() < 2 ? "just now" : `${client.age()}s ago`}</span></div>
<div class="sm-cards">
@@ -96,25 +96,36 @@ export function Dashboard(props: {
<p class="sm-device">{disk.name} · {bytes(disk.total)} capacity</p>
<Bar value={disk.percent} label={`${disk.id} disk space used`} />
<div class="sm-pair"><span>{bytes(disk.used)} used</span><strong>{percent(disk.percent)} used</strong></div>
<div class="sm-disk-note"><span class="sm-dot" />{disk.percent >= 95 ? "Very little free space" : disk.percent >= 85 ? "Getting full" : "Plenty of free space"}<span>Checked every 30s</span></div>
<div class="sm-disk-note"><span class="sm-dot" />{disk.percent >= 95 ? "Very little free space" : disk.percent >= 85 ? "Getting full" : "Plenty of free space"}<span>Checked every 30s<Show when={disk.reserved > 0}> · {bytes(disk.reserved)} reserved</Show></span></div>
</Card>}</For>
<Show when={!snapshot().disks.items.length}><Card kind="disk" title="Disk space" badge="Unavailable"><p class="sm-error">{snapshot().disks.error ?? "No fixed drives detected"}</p></Card></Show>
<Card kind="gpu" title="Integrated graphics" badge="Intel">
<Card kind="gpu" title="Graphics" badge={snapshot().gpu.adapter?.vendor ?? "GPU"}>
<div class="sm-reading"><strong>{percent(gpuPercent(snapshot()))}</strong><span>used</span></div>
<p class="sm-device">{snapshot().gpu.adapter?.name ?? "Intel graphics"}</p>
<Bar value={gpuPercent(snapshot())} label="Intel integrated GPU utilization" />
<div class="sm-pair"><span>Shared RAM in use</span><strong>{bytes(snapshot().gpu.adapter?.sharedUsed)}</strong></div>
<p class="sm-device">{snapshot().gpu.adapter?.name ?? "No readable GPU counters"}</p>
<Bar value={gpuPercent(snapshot())} label="GPU utilization" />
<Show when={snapshot().gpu.adapter?.memoryKind !== "unknown" && snapshot().gpu.adapter}>
<div class="sm-pair"><span>{gpuMemoryLabel(snapshot().gpu.adapter)}</span><strong>{bytes(snapshot().gpu.adapter?.memoryUsed)}</strong></div>
</Show>
<Sparkline points={client.history()} metric="gpu" />
<Show when={snapshot().gpu.error}><p class="sm-error">{snapshot().gpu.error}</p></Show>
</Card>
</div>
<Show when={snapshot().disks.error && snapshot().disks.items.length}><p class="sm-error">Disk readings may be stale: {snapshot().disks.error}</p></Show>
<div class="sm-footer"><span><span class="sm-dot" />Local readings</span><span>Intel GPU checked {client.gpuAge()}s ago</span><button type="button" onClick={() => setDetails(!details())} aria-expanded={details()}>{details() ? "Hide details" : "Details"}</button></div>
<div class="sm-footer"><span><span class="sm-dot" />Local readings</span><span>GPU checked {client.gpuAge()}s ago</span><button type="button" onClick={() => setDetails(!details())} aria-expanded={details()}>{details() ? "Hide details" : "Details"}</button></div>
<Show when={details()}><div class="sm-details">
<h4>CPU utilization per logical processor</h4>
<div class="sm-cores"><For each={snapshot().cpu.perCore}>{(value, index) => <div title={`Thread ${index() + 1}: ${percent(value)}`}><span>{index() + 1}</span><Bar value={value} label={`CPU thread ${index() + 1}`} /><b>{percent(value)}</b></div>}</For></div>
<p>GPU utilization is the busiest engine on the Intel adapter, with process counters combined per engine. Other GPUs are excluded. GPU checks are limited to once every 5 seconds.</p>
<p>Integrated graphics borrows system RAM: {bytes(snapshot().gpu.adapter?.sharedUsed)} currently used, with a driver-reported limit of {bytes(snapshot().gpu.adapter?.sharedLimit)}. This is already part of memory usage, not extra dedicated VRAM.</p>
<p>GPU source: {snapshot().gpu.adapter?.source ?? "unavailable"}. Intel utilization is the busiest engine; AMD reports driver utilization. Only the selected adapter is measured. GPU checks run at most once every 5 seconds.</p>
<Show when={snapshot().gpu.adapter?.memoryKind === "shared"}>
<p>Integrated graphics borrows system RAM: {bytes(snapshot().gpu.adapter?.memoryUsed)} currently used, with a driver-reported limit of {bytes(snapshot().gpu.adapter?.memoryTotal)}. This is already part of memory usage, not extra dedicated VRAM.</p>
</Show>
<Show when={snapshot().gpu.adapter?.memoryKind === "vram"}>
<p>GPU memory: {bytes(snapshot().gpu.adapter?.memoryUsed)} of {bytes(snapshot().gpu.adapter?.memoryTotal)}, as reported by the driver. On an APU this may be reserved system RAM.</p>
</Show>
<Show when={snapshot().gpu.adapter?.memoryKind === "unknown"}>
<p>This GPU collector does not expose a whole-device memory reading.</p>
</Show>
<p>Linux RAM uses MemAvailable so reclaimable cache counts as available. Disk free space excludes filesystem-reserved blocks; used percentage follows df.</p>
<p>Sampling runs only while this dashboard is visible. Closing it or hiding this window stops automatic checks. Use /system to reopen it or /system_status for a one-time text report. History lives only in this window. Sizes use binary units (GiB).</p>
</div></Show>
</>}
+9 -4
View File
@@ -1,4 +1,4 @@
import type { Snapshot } from "./types.js"
import type { Gpu, Snapshot } from "./types.js"
export function bytes(value: number | null | undefined): string {
if (value == null || !Number.isFinite(value)) return "Unavailable"
@@ -17,6 +17,10 @@ export function gpuPercent(snapshot: Snapshot): number | null {
return snapshot.gpu.adapter?.percent ?? null
}
export function gpuMemoryLabel(gpu: Gpu | null | undefined): string {
return gpu?.memoryKind === "shared" ? "Shared RAM in use" : gpu?.memoryKind === "vram" ? "GPU memory in use" : "GPU memory"
}
export function uptime(seconds: number): string {
const hours = Math.floor(seconds / 3600)
return `${Math.floor(hours / 24)}d ${hours % 24}h ${Math.floor(seconds / 60) % 60}m`
@@ -30,10 +34,11 @@ export function report(snapshot: Snapshot): string {
`- **CPU:** ${percent(snapshot.cpu.percent)} used · ${snapshot.cpu.name} · ${snapshot.cpu.cores} logical processors`,
`- **RAM:** ${bytes(snapshot.ram.used)} / ${bytes(snapshot.ram.total)} used (${percent(snapshot.ram.percent)}) · ${bytes(snapshot.ram.free)} available`,
...snapshot.disks.items.map(disk => `- **Disk ${disk.id}** ${bytes(disk.free)} free / ${bytes(disk.total)} · ${percent(disk.percent)} used`),
`- **Integrated GPU:** ${percent(gpuPercent(snapshot))} used · ${snapshot.gpu.adapter?.name ?? "Intel graphics unavailable"}`,
...(snapshot.gpu.adapter ? [`- **GPU shared RAM:** ${bytes(snapshot.gpu.adapter.sharedUsed)} / ${bytes(snapshot.gpu.adapter.sharedLimit)} limit (included in system RAM)`] : []),
`- **GPU:** ${percent(gpuPercent(snapshot))} used · ${snapshot.gpu.adapter?.name ?? "GPU counters unavailable"}`,
...(snapshot.gpu.adapter?.memoryKind !== "unknown" && snapshot.gpu.adapter
? [`- **${gpuMemoryLabel(snapshot.gpu.adapter)}:** ${bytes(snapshot.gpu.adapter.memoryUsed)} / ${bytes(snapshot.gpu.adapter.memoryTotal)}${snapshot.gpu.adapter.memoryKind === "shared" ? " limit (included in system RAM)" : ""}`] : []),
]
if (snapshot.disks.error) lines.push(`- Disk check: ${snapshot.disks.error}`)
if (snapshot.gpu.error) lines.push(`- Integrated GPU check: ${snapshot.gpu.error}`)
if (snapshot.gpu.error) lines.push(`- GPU check: ${snapshot.gpu.error}`)
return lines.join("\n")
}
+4 -4
View File
@@ -34,16 +34,16 @@ export default Plugin.define({
}
ctx.add(Style, css)
ctx.add(Command, {
id: "open", title: "System Monitor", description: "Live disk space, RAM, CPU, and Intel integrated GPU",
keywords: "system monitor disk space memory ram cpu gpu intel",
id: "open", title: "System Monitor", description: "Live disk space, RAM, CPU, and GPU",
keywords: "system monitor disk space memory ram cpu gpu intel amd linux",
featured: true, slash: { name: "system", after: "open" }, run: openWindow,
})
ctx.add(SettingsPage, {
id: "system-monitor", title: "System Monitor", icon: "window-analytics",
entries: [{ id: "refresh", title: "System Monitor refresh interval", keywords: "cpu ram disk gpu intel refresh" }],
entries: [{ id: "refresh", title: "System Monitor refresh interval", keywords: "cpu ram disk gpu refresh" }],
render: () => <ctx.ui.SettingsLayout title="System Monitor" description="Use /system to open the dashboard. Live sampling runs only while its dialog is visible. /system_status takes a one-time reading.">
<ctx.ui.SettingsSection title="Sampling">
<ctx.ui.SettingsRow id="refresh" title="Refresh interval" description="While viewing the dashboard: Intel GPU checks at most every 5 seconds; disk capacity every 30 seconds.">
<ctx.ui.SettingsRow id="refresh" title="Refresh interval" description="While viewing the dashboard: GPU checks at most every 5 seconds; disk capacity every 30 seconds.">
<ctx.ui.Select label="Refresh interval" options={[2000, 3000, 5000, 10000].map(value => ({ value: String(value), label: `${value / 1000} seconds` }))} value={String(interval())} onChange={value => setInterval(Number(value))} />
</ctx.ui.SettingsRow>
</ctx.ui.SettingsSection>
+208
View File
@@ -0,0 +1,208 @@
import { execFile } from "node:child_process"
import { readFile, readdir, stat, statfs } from "node:fs/promises"
import type { Disk, Gpu, Snapshot } from "./types.js"
export type FilesystemStats = { blocks: number; bfree: number; bavail: number; bsize: number }
export type LinuxIO = {
readText(path: string): Promise<string>
readNames(path: string): Promise<string[]>
isDirectory(path: string): Promise<boolean>
filesystem(path: string): Promise<FilesystemStats>
sampleIntel(device: string): Promise<string>
}
// intel_gpu_top is a streaming tool. End this one-second sample with SIGINT,
// then enforce a hard deadline as well; no sampling process survives a request.
export function sampleIntelGpu(device: string): Promise<string> {
if (!/^\/dev\/dri\/card\d+$/.test(device)) return Promise.reject(new Error("Invalid DRM device"))
return new Promise((resolve, reject) => {
let stop: ReturnType<typeof setTimeout> | undefined
const child = execFile("intel_gpu_top", ["-J", "-p", "-s", "250", "-o", "-", "-d", `drm:${device}`], {
encoding: "utf8", timeout: 3000, maxBuffer: 2 * 1024 * 1024,
killSignal: "SIGKILL",
}, (error, stdout) => {
clearTimeout(stop)
if (error && error.signal !== "SIGINT") {
const code = (error as NodeJS.ErrnoException).code
reject(new Error(code === "ENOENT"
? "Install intel_gpu_top (intel-gpu-tools/igt-gpu-tools) for Intel GPU utilization"
: "Intel performance counters unavailable: check driver support and perf-counter permissions"))
} else resolve(stdout)
})
child.once("spawn", () => { stop = setTimeout(() => child.kill("SIGINT"), 1000) })
})
}
export const linuxIO: LinuxIO = {
readText: file => readFile(file, "utf8"),
readNames: directory => readdir(directory),
isDirectory: async file => (await stat(file)).isDirectory(),
filesystem: file => statfs(file),
sampleIntel: sampleIntelGpu,
}
export function parseMeminfo(text: string): Snapshot["ram"] {
const fields = new Map([...text.matchAll(/^(\w+):\s+(\d+)\s+kB$/gm)]
.map(match => [match[1], Number(match[2]) * 1024]))
const total = fields.get("MemTotal")
const available = fields.get("MemAvailable") ?? (
(fields.get("MemFree") ?? NaN) + (fields.get("Buffers") ?? 0) + (fields.get("Cached") ?? 0)
+ (fields.get("SReclaimable") ?? 0) - (fields.get("Shmem") ?? 0)
)
if (!total || !Number.isFinite(available)) throw new Error("Invalid /proc/meminfo")
const free = Math.max(0, Math.min(total, available))
return { total, free, used: total - free, percent: (1 - free / total) * 100 }
}
type Mount = { device: string; root: string; point: string; type: string; source: string }
const unescapeMount = (value: string) => value.replace(/\\([0-7]{3})/g, (_, octal: string) => String.fromCharCode(parseInt(octal, 8)))
const virtualFilesystems = new Set([
"proc", "sysfs", "devtmpfs", "devpts", "tmpfs", "ramfs", "cgroup", "cgroup2", "squashfs",
"autofs", "tracefs", "mqueue", "securityfs", "configfs", "debugfs", "fusectl", "nsfs",
"binfmt_misc", "hugetlbfs", "rpc_pipefs", "pstore", "bpf", "efivarfs",
])
const networkFilesystems = new Set(["nfs", "nfs4", "cifs", "smb3", "fuse.sshfs", "ceph", "glusterfs"])
export function parseMountinfo(text: string): Mount[] {
const mounts: Mount[] = []
for (const line of text.trim().split("\n")) {
const [left, right] = line.split(" - ")
if (!right) continue
const fields = left.split(" ")
const tail = right.split(" ")
if (fields.length < 6 || tail.length < 3 || !/^\d+:\d+$/.test(fields[2])) continue
const point = unescapeMount(fields[4])
const type = tail[0]
// Root is useful even in overlay-backed containers. Other read-only images,
// virtual and network filesystems are omitted. WSL's local Windows drives are OK.
if (point !== "/") {
if (fields[5].split(",").includes("ro")) continue
if (virtualFilesystems.has(type) || networkFilesystems.has(type) || type === "overlay") continue
if (type === "9p" && !right.includes("aname=drvfs")) continue
if (/^\/(?:proc|sys|dev|run)(?:\/|$)/.test(point)) continue
if (/^\/dev\/loop\d+$/.test(tail[1])) continue
}
mounts.push({ device: fields[2], root: unescapeMount(fields[3]), point, type, source: unescapeMount(tail[1]) })
}
// Prefer the topmost mount when mounts are stacked at an identical path.
const byPath = new Map(mounts.map(mount => [mount.point, mount]))
return [...byPath.values()].sort((a, b) => a.point.length - b.point.length || a.point.localeCompare(b.point))
}
export function diskFromStatfs(id: string, name: string, fs: FilesystemStats): Disk {
if (![fs.blocks, fs.bfree, fs.bavail, fs.bsize].every(Number.isFinite)
|| fs.blocks <= 0 || fs.bsize <= 0 || fs.bfree < 0 || fs.bfree > fs.blocks) {
throw new Error("Invalid filesystem capacity")
}
// Free means usable by an ordinary user. Reserved blocks are NOT used data.
const available = Math.max(0, Math.min(fs.bfree, fs.bavail))
const total = fs.blocks * fs.bsize
const used = (fs.blocks - fs.bfree) * fs.bsize
const free = available * fs.bsize
const reserved = (fs.bfree - available) * fs.bsize
return { id, name, total, used, free, reserved, percent: used + free > 0 ? used / (used + free) * 100 : 0 }
}
export async function readLinuxDisks(io: LinuxIO = linuxIO): Promise<Pick<Snapshot["disks"], "items" | "error">> {
let mounts: Mount[]
try { mounts = parseMountinfo(await io.readText("/proc/self/mountinfo")) }
catch { mounts = [] }
if (!mounts.some(mount => mount.point === "/")) {
mounts.unshift({ point: "/", device: "root", source: "/", root: "/", type: "filesystem" })
}
const seen = new Set<string>()
const items: Disk[] = []
const failures: string[] = []
for (const mount of mounts) {
// Bind mounts and btrfs subvolumes share capacity; list the filesystem once.
if (seen.has(mount.device)) continue
try {
if (!await io.isDirectory(mount.point)) continue
const fs = await io.filesystem(mount.point)
if (fs.blocks === 0) continue
items.push(diskFromStatfs(mount.point, `${mount.source} · ${mount.type}`, fs))
seen.add(mount.device)
} catch { failures.push(mount.point) }
}
return { items, error: failures.length ? `Could not read filesystem: ${failures.join(", ")}` : items.length ? null : "No mounted filesystems reported" }
}
// JSON is streamed as an array, and a killed process may leave a partial final
// object. Read complete top-level objects without relying on valid termination.
export function parseIntelGpuTop(text: string): number | null {
const samples: Record<string, unknown>[] = []
let depth = 0, start = -1, quoted = false, escaped = false
for (let index = 0; index < text.length; index++) {
const character = text[index]
if (quoted) {
if (escaped) escaped = false
else if (character === "\\") escaped = true
else if (character === '"') quoted = false
continue
}
if (character === '"') { quoted = true; continue }
if (character === "{") { if (depth++ === 0) start = index }
else if (character === "}" && depth > 0 && --depth === 0) {
try { samples.push(JSON.parse(text.slice(start, index + 1))) } catch { /* incomplete or invalid sample */ }
}
}
for (const sample of samples.reverse()) {
if (!sample.engines || typeof sample.engines !== "object") continue
const values = Object.values(sample.engines).map(engine => (engine as { busy?: unknown })?.busy)
.filter((busy): busy is number => typeof busy === "number" && Number.isFinite(busy) && busy >= 0 && busy <= 100)
if (values.length) return Math.max(...values)
}
return null
}
async function optionalText(io: LinuxIO, file: string): Promise<string | null> {
try { return (await io.readText(file)).trim() } catch { return null }
}
function numberOrNull(text: string | null): number | null {
if (text === null || !/^\d+(?:\.\d+)?$/.test(text)) return null
const value = Number(text)
return Number.isFinite(value) ? value : null
}
export async function readLinuxGpu(io: LinuxIO = linuxIO): Promise<Pick<Snapshot["gpu"], "adapter" | "error">> {
let names: string[] = []
try { names = await io.readNames("/sys/class/drm") } catch { /* headless machine */ }
const cards = (await Promise.all(names.filter(name => /^card\d+$/.test(name)).map(async card => {
const directory = `/sys/class/drm/${card}/device`
const vendor = (await optionalText(io, `${directory}/vendor`))?.toLowerCase()
return { card, directory, vendor }
}))).filter(card => card.vendor === "0x8086" || card.vendor === "0x1002")
.sort((a, b) => (a.vendor === "0x8086" ? 0 : 1) - (b.vendor === "0x8086" ? 0 : 1) || Number(a.card.slice(4)) - Number(b.card.slice(4)))
const selected = cards[0]
if (!selected) {
const release = await optionalText(io, "/proc/sys/kernel/osrelease")
return { adapter: null, error: /microsoft/i.test(release ?? "")
? "WSL does not expose native Intel/AMD GPU counters; CPU, RAM and disk monitoring remain available"
: "No supported Intel/AMD DRM adapter found; GPU may be absent or hidden in this VM/container" }
}
const vendor = selected.vendor === "0x8086" ? "Intel" : "AMD"
const product = await optionalText(io, `${selected.directory}/product_name`)
const adapter: Gpu = {
name: `${product || `${vendor} graphics`} (${selected.card})`, vendor, percent: null,
memoryUsed: null, memoryTotal: null, memoryKind: vendor === "AMD" ? "vram" : "unknown",
source: vendor === "AMD" ? "Linux amdgpu sysfs" : "Linux intel_gpu_top",
}
if (vendor === "AMD") {
const [busy, used, total] = await Promise.all([
optionalText(io, `${selected.directory}/gpu_busy_percent`),
optionalText(io, `${selected.directory}/mem_info_vram_used`),
optionalText(io, `${selected.directory}/mem_info_vram_total`),
])
const utilization = numberOrNull(busy)
adapter.percent = utilization !== null && utilization <= 100 ? utilization : null
adapter.memoryUsed = numberOrNull(used)
adapter.memoryTotal = numberOrNull(total)
return { adapter, error: adapter.percent === null ? "AMD driver did not expose a readable gpu_busy_percent counter" : null }
}
try {
adapter.percent = parseIntelGpuTop(await io.sampleIntel(`/dev/dri/${selected.card}`))
return { adapter, error: adapter.percent === null ? "intel_gpu_top returned no usable GPU engine samples" : null }
} catch (error) {
return { adapter, error: error instanceof Error ? error.message : "Unable to read Intel GPU counters" }
}
}
+41 -16
View File
@@ -5,6 +5,7 @@ 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"
import { diskFromStatfs, linuxIO, parseMeminfo, readLinuxDisks, readLinuxGpu, type LinuxIO } from "./linux.js"
type CpuTimes = { idle: number; total: number }
type Engine = { Name: string; UtilizationPercentage: number }
@@ -73,7 +74,12 @@ export class Monitor {
private lastDiskAttempt = 0
private lastGpuAttempt = 0
constructor(private readonly runner: Runner = run) {}
private readonly platform: NodeJS.Platform
private readonly linux: LinuxIO
constructor(private readonly runner: Runner = run, options: { platform?: NodeJS.Platform; linux?: LinuxIO } = {}) {
this.platform = options.platform ?? process.platform
this.linux = options.linux ?? linuxIO
}
// All callers share one in-flight collection, including multiple GUI windows.
snapshot(): Promise<Snapshot> {
@@ -88,7 +94,12 @@ export class Monitor {
this.lastDiskAttempt = Date.now()
try {
let items: Disk[]
if (process.platform === "win32") {
if (this.platform === "linux") {
const result = await readLinuxDisks(this.linux)
this.disks = { sampledAt: Date.now(), ...result }
return
}
if (this.platform === "win32") {
const text = await powershell(
"@(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | Select-Object DeviceID,VolumeName,Size,FreeSpace) | ConvertTo-Json -Compress",
this.runner,
@@ -99,13 +110,11 @@ export class Monitor {
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) }
return { id: String(drive.DeviceID), name: String(drive.VolumeName || drive.DeviceID), total, free, used: total - free, reserved: 0, 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) }]
items = [diskFromStatfs("/", "Root filesystem", disk)]
}
if (!items.length) throw new Error("No fixed drives reported")
this.disks = { sampledAt: Date.now(), items, error: null }
@@ -114,11 +123,16 @@ export class Monitor {
}
}
private async readIntelGpu(): Promise<void> {
private async readGpu(): Promise<void> {
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.platform === "linux") {
const result = await readLinuxGpu(this.linux)
this.gpu = { sampledAt: Date.now(), ...result }
return
}
if (this.platform !== "win32") throw new Error("GPU monitoring supports Windows and Linux")
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")
@@ -134,7 +148,10 @@ export class Monitor {
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 },
adapter: {
name: intel.name, vendor: "Intel", percent, memoryUsed: Number.isFinite(sharedUsed) ? sharedUsed : null,
memoryTotal: intel.sharedLimit, memoryKind: "shared", source: "Windows GPU engine counters",
},
error: percent === null ? "No Intel GPU-engine counters reported" : null,
}
} catch (error) {
@@ -144,17 +161,25 @@ export class Monitor {
}
}
private async readMemory(): Promise<Snapshot["ram"]> {
if (this.platform === "linux") {
try { return parseMeminfo(await this.linux.readText("/proc/meminfo")) }
catch { /* Fall back to OS counters in restricted environments without procfs. */ }
}
const total = os.totalmem()
const free = os.freemem()
return { total, free, used: total - free, percent: clamp((1 - free / total) * 100) }
}
private async collect(): Promise<Snapshot> {
// 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 [ram] = await Promise.all([
this.readMemory(), this.readDisks(), this.readGpu(), 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,
@@ -164,8 +189,8 @@ export class Monitor {
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) },
sampledAt: Date.now(), hostname: os.hostname(), platform: `${this.platform} ${os.arch()}`, uptime: os.uptime(),
cpu, ram,
disks: this.disks, gpu: this.gpu,
}
return this.cached
@@ -174,6 +199,6 @@ export class Monitor {
// 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 key = Symbol.for("local-system-monitor.collector.v3")
const globals = globalThis as unknown as Record<symbol, Monitor | undefined>
export const monitor = globals[key] ??= new Monitor()
+6 -2
View File
@@ -5,13 +5,17 @@ export type Disk = {
used: number
free: number
percent: number
reserved: number
}
export type Gpu = {
name: string
vendor: "Intel" | "AMD" | "Other"
percent: number | null
sharedUsed: number | null
sharedLimit: number | null
memoryUsed: number | null
memoryTotal: number | null
memoryKind: "shared" | "vram" | "unknown"
source: string
}
export type Snapshot = {