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
+12
View File
@@ -1,5 +1,17 @@
# Changelog
## 0.2.0 — 2026-11-20
- Added native Linux collectors for mounted filesystems and available RAM.
- Accounted for Linux filesystem-reserved blocks and deduplicated bind mounts/subvolumes.
- Added AMD GPU utilization and memory readings through sysfs.
- Added bounded Intel GPU sampling through optional `intel_gpu_top`, without a persistent GPU process.
- Made GPU labels and memory descriptions match the detected vendor and collector.
- Added explicit unavailable states for headless, WSL, and unsupported GPU environments.
- Made Windows collector tests runnable on Linux; added Linux filesystem, memory, GPU, and end-to-end collector fixtures.
- Made smoke/integration tests portable, with optional `--require-gpu` hardware assertions.
- Verified a clean Ubuntu 24.04/WSL2 build, all 26 tests, and unprivileged live CPU/RAM/disk readings.
## 0.1.0 — 2026-11-20
Initial version:
+118 -45
View File
@@ -2,8 +2,8 @@
**Your computer's vital signs, one slash command away.**
A lightweight, on-demand dashboard for **OpenCode Desktop** showing disk space, RAM, CPU utilization, and
Intel integrated graphics. Inspired by [OpenCode Quota](https://github.com/slkiser/opencode-quota), with
A lightweight, on-demand dashboard for **OpenCode Desktop on Windows and Linux** showing disk space, RAM,
CPU utilization, and GPU activity. Inspired by [OpenCode Quota](https://github.com/slkiser/opencode-quota), with
theme-aware cards, utilization bars, and short live-history graphs.
Open `/system` when you need it. Close the dashboard when you're done. **Automatic sampling runs only while
@@ -11,10 +11,10 @@ the dashboard is visible.**
## Highlights
- **Disk space:** free, used, and total capacity for each fixed Windows drive.
- **Disk space:** fixed Windows drives or local Linux filesystems, including available space and reserved blocks.
- **Memory:** physical RAM usage and available memory.
- **CPU:** total utilization, plus a detailed breakdown by logical processor.
- **Intel integrated GPU:** utilization and shared system-memory usage, matched to the actual Intel adapter.
- **GPU:** Windows Intel integrated graphics; Linux Intel and AMD collectors with vendor-appropriate memory labels.
- **Live dashboard:** light/dark themes, three-minute history, pause/resume, and adjustable refresh intervals.
- **On demand:** no polling or UI clock timers while the dashboard is closed or its window is hidden.
- **Uncluttered:** no bottom bar, titlebar icon, side tab, or composer pill.
@@ -38,11 +38,13 @@ Unlike the dashboard, asking an AI agent about those metrics uses your normal mo
| --- | --- |
| OpenCode | Built and tested with **2.3.2** |
| Visual dashboard | **Desktop** application |
| Operating system | **Windows 10/11** |
| GPU | Intel integrated graphics with Windows GPU performance counters |
| Operating system | **Windows 10/11** or **Linux** |
| Windows GPU | Intel integrated graphics with Windows GPU performance counters |
| Linux GPU | Intel through optional `intel_gpu_top`; AMD through `amdgpu` sysfs |
| Development tools | Node.js **22.13+**, npm, and Git |
Windows PowerShell, CIM, and DXGI provide the Windows metrics. No NVIDIA tools are required or invoked.
Windows PowerShell, CIM, and DXGI provide the Windows metrics. Linux uses procfs, filesystem statistics, and DRM
device information. No NVIDIA tools are required or invoked; NVIDIA utilization is not currently implemented.
The full dashboard uses OpenCode's experimental GUI plugin API; the web and TUI clients receive text reports.
If a metric cannot be read, it is shown as unavailable rather than as a misleading `0%`.
@@ -50,7 +52,18 @@ If a metric cannot be read, it is shown as unavailable rather than as a misleadi
### 1. Clone and build
Run in PowerShell, from the directory where you keep your projects:
Clone the repository from the directory where you keep your projects.
**Linux:**
```bash
git clone https://git.davidmeincke.dk/david/opencode-system-monitor.git
cd opencode-system-monitor
npm ci
npm run build
```
**Windows PowerShell:**
```powershell
git clone https://git.davidmeincke.dk/david/opencode-system-monitor.git
@@ -66,9 +79,12 @@ dependency lockfile; `node_modules/` and the generated `dist/` directory are bui
Add the **absolute path to the cloned directory** to your global OpenCode configuration:
```text
%USERPROFILE%\.config\opencode\opencode.jsonc
```
| Platform | Default configuration path |
| --- | --- |
| Linux | `~/.config/opencode/opencode.jsonc` |
| Windows | `%USERPROFILE%\.config\opencode\opencode.jsonc` |
If `XDG_CONFIG_HOME` is set, use `$XDG_CONFIG_HOME/opencode/opencode.jsonc` instead.
For example:
@@ -77,13 +93,14 @@ For example:
"$schema": "https://opencode.ai/config.json",
"plugins": [
// Keep your existing plugin entries here.
"C:/Users/your-name/projects/opencode-system-monitor",
"/home/your-name/projects/opencode-system-monitor",
],
}
```
Use the folder path, not the path to an individual JavaScript file. Register it in `opencode.json(c)`,
the configuration used by Desktop plugins.
the configuration used by Desktop plugins. On Windows, a path such as
`"C:/Users/your-name/projects/opencode-system-monitor"` works.
OpenCode reloads configuration automatically. Run **`/system`** to open the dashboard. If the command has
not appeared yet, use **Settings → Extensions → Plugins → Reload** for this plugin.
@@ -92,13 +109,14 @@ not appeared yet, use **Settings → Extensions → Plugins → Reload** for thi
From the cloned directory:
```powershell
```bash
git pull --ff-only
npm.cmd ci
npm.cmd run build
npm ci
npm run build
```
OpenCode watches the local plugin and reloads the rebuilt bundle.
Use `npm.cmd` in PowerShell if `npm` is blocked by its script policy. OpenCode watches the local plugin
and reloads the rebuilt bundle.
### Uninstall
@@ -110,9 +128,9 @@ You can then delete the cloned directory if you no longer need it.
| Metric | Source | Refresh |
| --- | --- | --- |
| CPU | Deltas between OS CPU-time counters | Selected dashboard interval |
| RAM | Physical memory total and available memory | Selected dashboard interval |
| Disk | `Win32_LogicalDisk`, fixed drives only | At most once every **30 seconds** |
| Intel GPU | DXGI adapter identity + Windows GPU engine and memory counters | At most once every **5 seconds** |
| RAM | Windows OS memory; Linux `/proc/meminfo` `MemAvailable` | Selected dashboard interval |
| Disk | Windows `Win32_LogicalDisk`; Linux `/proc/self/mountinfo` + `statfs` | At most once every **30 seconds** |
| GPU | Windows DXGI/counters; Linux Intel `intel_gpu_top` or AMD sysfs | At most once every **5 seconds** |
The dashboard interval defaults to **3 seconds**, with **2, 3, 5, or 10 seconds** available.
GPU and disk refreshes are rate-limited independently; their next check happens on a dashboard request
@@ -131,24 +149,54 @@ literally zero memory usage. If another OpenCode window has the dashboard open,
### Resource use
CPU and RAM reads use Node's OS APIs. Windows disk and GPU checks use short-lived, hidden PowerShell processes.
These commands have timeouts and output limits. Concurrent requests share an in-flight collection and recent cached
CPU reads use Node's OS APIs. Linux RAM reads include reclaimable cache in available memory, rather than treating
all cache as application usage. Windows disk and GPU checks use short-lived, hidden PowerShell processes.
Linux disk and AMD GPU checks read local filesystem data. Intel GPU sampling runs `intel_gpu_top` for roughly
one second, sends it an interrupt, and enforces a three-second hard deadline. No collector invokes `sudo`.
Commands have timeouts and output limits. Concurrent requests share an in-flight collection and recent cached
results across OpenCode project locations.
History contains only the last three minutes in the current window. There is no continuous metrics log or
separate monitoring daemon. Exact CPU and memory overhead has not been benchmarked.
### What the GPU number means
### Linux filesystems
DXGI identifies the Intel adapter's **LUID**, the identifier used by Windows' GPU performance counters.
Only counters for that adapter are included:
The root filesystem and local mounted filesystems are reported. Bind mounts and btrfs subvolumes sharing the same
filesystem are listed once. Read-only non-root mounts, pseudo-filesystems, snap/loop images, and network mounts are omitted; WSL's local Windows
drive mounts are supported. In a container, the results describe that container's visible mount namespace.
1. Sum process utilization for each individual GPU engine.
2. Display the busiest engine's utilization.
3. Read shared memory usage for the same adapter.
Free space means space available to an ordinary user. Filesystem-reserved blocks are tracked separately, and
percentage used follows `df`: `used / (used + available)`. One unreadable mount does not discard healthy disks.
This avoids adding unrelated GPUs together or depending on adapter ordering. Integrated graphics borrows
system RAM; its shared-memory figure is **already included in system RAM usage**, not additional dedicated VRAM.
### GPU support
| Platform / GPU | Collection method | Additional setup |
| --- | --- | --- |
| Windows Intel | DXGI identifies the adapter LUID; Windows counters are combined per engine and the busiest engine is shown | Working Intel driver |
| Linux Intel | `intel_gpu_top -J -p` samples the selected `/dev/dri/cardN`; the busiest physical engine is shown | Install `intel_gpu_top`; the current user needs access to GPU performance counters |
| Linux AMD | `gpu_busy_percent` and `mem_info_vram_*` from the selected DRM device | A driver exposing readable `amdgpu` sysfs counters |
| Headless / unsupported GPU | GPU is explicitly unavailable; other metrics work | None |
On Linux, Intel is preferred when both Intel and AMD are present; otherwise the first AMD card is selected.
The exact DRM card appears in the dashboard. Other adapters' counters are never combined with the selected card.
Intel `i915`/`xe` support depends on the installed GPU-tools version and kernel driver.
For Intel on Debian/Ubuntu, the optional utility is usually available with:
```bash
sudo apt install intel-gpu-tools
```
Other distributions may call the package `igt-gpu-tools`. If performance-counter access is restricted, the
dashboard reports the problem and leaves utilization unavailable. The plugin does not change system permissions.
Windows integrated GPU shared memory is **already included in system RAM usage**. Linux AMD memory is the
driver's VRAM allocation (which can be reserved system RAM on an APU). Linux Intel whole-device memory is
currently unavailable and is not guessed from partial process statistics.
**WSL and VMs:** CPU, RAM, and disk monitoring work, but GPU passthrough does not necessarily expose native DRM/PMU
counters. In that case GPU shows unavailable. Linux CPU/RAM readings describe the Linux environment, not the full
Windows host.
Sizes are displayed in binary units such as **GiB**.
@@ -159,44 +207,68 @@ Sizes are displayed in binary units such as **GiB**.
| `/system` is missing | Use OpenCode Desktop, build the plugin, and register its directory in the global `opencode.json(c)`. |
| Desktop lists the plugin but it fails to load | Check **Settings → Extensions → Plugins** and confirm `dist/gui-experimental.cjs` exists. |
| No graphical dashboard in the web client | Use `/system_status`; this version does not add a web GUI. |
| GPU shows unavailable | Confirm Intel graphics is enabled and its driver exposes Windows GPU-engine counters. |
| GPU shows unavailable | Check the platform-specific GPU requirements above. This is expected when a VM/WSL instance does not expose native counters. |
| Disk numbers do not change immediately | Disk capacity is cached for up to 30 seconds between checks. |
| Live numbers stop updating | Check the dashboard's **Pause** button and whether the OpenCode window is hidden. |
| A check fails temporarily | The dashboard shows the failure; reopen it or use Refresh to retry. |
To diagnose live collection on a Windows machine with Intel graphics:
To diagnose live collection:
```powershell
npm.cmd run smoke
```bash
npm run smoke
# Also require a working hardware GPU reading:
npm run smoke -- --require-gpu
```
The ordinary smoke check validates CPU, RAM and disks, and reports whether GPU telemetry is available.
`--require-gpu` fails if hardware utilization cannot be read.
## Development
```powershell
npm.cmd ci
npm.cmd run verify
### Validation for v0.2.0
| Environment | Verified |
| --- | --- |
| Windows, Node 26.13 | Type-check/build, 24 tests, real CPU/RAM/disk/Intel GPU readings, installed OpenCode RPC and text command |
| Ubuntu 24.04 under WSL2, Node 22.23.5 | Clean dependency install, type-check/build, all 26 tests, real CPU/RAM/disk readings as an unprivileged user |
The two Linux-only process tests verify that Intel sampling exits cleanly and is forcibly terminated if it ignores
the interrupt. Linux GPU parsing, adapter selection, permissions/missing-tool behavior, and AMD sysfs collection are
covered by fixtures. **Native Linux Intel/AMD hardware telemetry has not yet been verified on a physical Linux host**;
WSL on the test machine did not expose the required counters.
### Build and test
```bash
npm ci
npm run verify
```
`verify` type-checks, builds the server and GUI, then runs the automated tests.
| Command | Purpose |
| --- | --- |
| `npm.cmd run typecheck` | Type-check the plugin and preview |
| `npm.cmd run build` | Compile server modules and the single-file Desktop GUI bundle |
| `npm.cmd test` | Run metric parsing, adapter isolation, caching, failure, and visibility/polling tests |
| `npm.cmd run smoke` | Validate real disk, RAM, CPU, and Intel GPU readings on this machine |
| `npm.cmd run preview` | Open a development server for the dashboard at `http://127.0.0.1:5098/preview.html` |
| `npm run typecheck` | Type-check the plugin and preview |
| `npm run build` | Compile server modules and the single-file Desktop GUI bundle |
| `npm test` | Run Windows/Linux collectors, adapter isolation, caching, failure, and visibility/polling tests |
| `npm run smoke` | Validate real disk, RAM, and CPU readings and report GPU availability |
| `npm run preview` | Open a development server for the dashboard at `http://127.0.0.1:5098/preview.html` |
Use `npm.cmd` for the same commands in Windows PowerShell when needed.
The preview uses live local readings and includes light/dark, compact-layout, and visibility controls.
It is a development tool and is never started by the installed plugin.
To test an installed plugin against a running OpenCode service:
```powershell
node scripts/integration.mjs "C:\path\to\opencode-cli.exe"
```bash
node scripts/integration.mjs /path/to/opencode
# Require live hardware GPU telemetry as well:
node scripts/integration.mjs /path/to/opencode --require-gpu
```
This checks plugin registration, GUI/RPC availability, Intel readings, and the `/system_status` command.
On Windows, pass the path to `opencode-cli.exe`. This checks plugin registration, GUI/RPC availability,
disk readings, and the `/system_status` command.
It creates a temporary test session and removes it afterwards.
### Project layout
@@ -206,6 +278,7 @@ src/
index.ts Server registration, text command, and agent tool
rpc.ts Dashboard ↔ server contract
metrics.ts On-demand collection and shared caching
linux.ts procfs memory, mounted filesystems, Intel/AMD GPU collectors
windows-gpu.ts Intel DXGI discovery and Windows counter queries
client.ts Visibility-aware polling, pause, and in-memory history
gui.tsx Desktop command, dialog, and settings
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-system-monitor",
"version": "0.1.0",
"version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-system-monitor",
"version": "0.1.0",
"version": "0.2.0",
"dependencies": {
"@opencode/plugin": "2.3.2"
},
+3 -3
View File
@@ -1,9 +1,9 @@
{
"name": "local-system-monitor",
"version": "0.1.0",
"version": "0.2.0",
"private": true,
"type": "module",
"description": "On-demand disk space, RAM, CPU and Intel integrated GPU monitoring for OpenCode Desktop.",
"description": "On-demand disk, RAM, CPU and GPU monitoring for OpenCode Desktop on Windows and Linux.",
"author": "David Meincke",
"homepage": "https://git.davidmeincke.dk/david/opencode-system-monitor",
"repository": {
@@ -16,7 +16,7 @@
"engines": {
"node": ">=22.13.0"
},
"keywords": ["opencode", "opencode-plugin", "system-monitor", "windows", "intel", "disk-space"],
"keywords": ["opencode", "opencode-plugin", "system-monitor", "windows", "linux", "intel", "amd", "disk-space"],
"exports": {
".": "./dist/index.js",
"./rpc": "./dist/rpc.js",
+5 -3
View File
@@ -16,10 +16,12 @@ assert.equal(plugin?.state.status, "active")
assert.equal(plugin.features.gui, true)
assert.equal(plugin.features.rpc, true)
const snapshot = api("post", "/api/rpc/local-system-monitor/snapshot", { input: {} }).output
assert.match(snapshot.gpu.adapter.name, /Intel/)
if (process.argv.includes("--require-gpu")) {
assert.equal(snapshot.gpu.error, null)
assert.ok(snapshot.gpu.adapter?.percent != null)
}
assert.ok(snapshot.disks.items.length > 0)
console.log("Installed plugin, GUI feature, RPC, and Intel-only readings: passed")
console.log("Installed plugin, GUI feature, RPC, and disk readings: passed")
let sessionID
try {
@@ -30,7 +32,7 @@ try {
const inbox = api("get", `/api/session/${sessionID}/inbox`)
const text = JSON.stringify(inbox)
assert.match(text, /local-system-monitor.report/)
assert.match(text, /Integrated GPU/)
assert.match(text, /\*\*GPU:\*\*/)
const messages = api("get", `/api/session/${sessionID}/message`)
assert.doesNotMatch(JSON.stringify(messages), /"type":"assistant"/)
console.log("/system_status posts a report without starting a model turn: passed")
+14 -4
View File
@@ -7,8 +7,18 @@ console.log(report(snapshot))
assert.ok(snapshot.cpu.percent !== null && snapshot.cpu.percent >= 0 && snapshot.cpu.percent <= 100)
assert.ok(snapshot.ram.total > 0 && snapshot.ram.used <= snapshot.ram.total)
assert.ok(snapshot.disks.items.length > 0, snapshot.disks.error ?? "No disks")
for (const disk of snapshot.disks.items) {
assert.ok(disk.free >= 0 && disk.used >= 0 && disk.reserved >= 0)
assert.equal(disk.free + disk.used + disk.reserved, disk.total)
}
if (process.argv.includes("--require-gpu")) {
assert.equal(snapshot.gpu.error, null)
assert.match(snapshot.gpu.adapter.name, /intel/i)
assert.ok(snapshot.gpu.adapter.percent !== null)
assert.ok(snapshot.gpu.adapter.sharedUsed !== null)
console.log("\nLive disk, CPU, RAM, and Intel GPU checks passed.")
assert.ok(snapshot.gpu.adapter?.percent !== null && snapshot.gpu.adapter)
}
if (snapshot.gpu.adapter?.percent != null) {
assert.ok(snapshot.gpu.adapter.percent >= 0 && snapshot.gpu.adapter.percent <= 100)
console.log(`\nLive GPU check passed: ${snapshot.gpu.adapter.name}`)
} else {
console.log("\nGPU utilization unavailable on this host; CPU/RAM/disk checks still apply.")
}
console.log("Live disk, CPU, and RAM checks passed.")
+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 = {
+47
View File
@@ -0,0 +1,47 @@
import { test } from "node:test"
import assert from "node:assert/strict"
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { parseIntelGpuTop, sampleIntelGpu } from "../dist/linux.js"
async function fakeGpuTool(t, ignoreInterrupt) {
const directory = await mkdtemp(path.join(os.tmpdir(), "system-monitor-gpu-test-"))
const pidFile = path.join(directory, "pid")
const originalPath = process.env.PATH
const source = `#!${process.execPath}
import { writeFileSync } from "node:fs";
writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));
process.stdout.write('[{"engines":{"Render/0":{"busy":31}}}');
process.on("SIGINT", () => { ${ignoreInterrupt ? "" : 'process.stdout.write("]"); process.exit(0);'} });
setInterval(() => {}, 1000);
`
await writeFile(path.join(directory, "intel_gpu_top"), source, { mode: 0o755 })
await writeFile(path.join(directory, "package.json"), '{"type":"module"}')
process.env.PATH = `${directory}:${originalPath}`
t.after(async () => {
process.env.PATH = originalPath
// Clean up our own fake process if an assertion or the collector fails.
try {
const pid = Number(await readFile(pidFile, "utf8"))
try { process.kill(pid, "SIGKILL") } catch { /* already exited */ }
} catch { /* process never started */ }
await rm(directory, { recursive: true, force: true })
})
return async () => Number(await readFile(pidFile, "utf8"))
}
test("Linux Intel sampling interrupts the streaming tool and leaves no process running", { skip: process.platform !== "linux" }, async t => {
const pid = await fakeGpuTool(t, false)
const output = await sampleIntelGpu("/dev/dri/card0")
assert.equal(parseIntelGpuTop(output), 31)
const childPID = await pid()
assert.throws(() => process.kill(childPID, 0), error => error.code === "ESRCH")
})
test("Linux Intel sampling forcibly terminates a tool that ignores its interrupt", { skip: process.platform !== "linux" }, async t => {
const pid = await fakeGpuTool(t, true)
await assert.rejects(sampleIntelGpu("/dev/dri/card0"), /counters unavailable/)
const childPID = await pid()
assert.throws(() => process.kill(childPID, 0), error => error.code === "ESRCH")
})
+203
View File
@@ -0,0 +1,203 @@
import { test } from "node:test"
import assert from "node:assert/strict"
import { Monitor } from "../dist/metrics.js"
import { diskFromStatfs, parseIntelGpuTop, parseMeminfo, parseMountinfo, readLinuxDisks, readLinuxGpu, sampleIntelGpu } from "../dist/linux.js"
import { report } from "../dist/format.js"
function fixtures({ files = {}, directories = {}, stats = {}, nondirectories = [], sampleIntel } = {}) {
return {
readText: async path => {
if (!(path in files)) throw Object.assign(new Error(`Missing fixture: ${path}`), { code: "ENOENT" })
return files[path]
},
readNames: async path => directories[path] ?? [],
isDirectory: async path => !nondirectories.includes(path),
filesystem: async path => {
if (!(path in stats)) throw new Error("Filesystem unavailable")
return stats[path]
},
sampleIntel: sampleIntel ?? (async () => { throw new Error("intel_gpu_top is not installed") }),
}
}
const fs = { blocks: 1000, bfree: 400, bavail: 350, bsize: 1024 }
const mountinfo = [
"24 1 8:1 / / rw - ext4 /dev/sda1 rw",
"25 24 8:2 / /home rw shared:1 - ext4 /dev/sda2 rw",
"26 24 8:2 /users /srv/users rw - ext4 /dev/sda2 rw",
"27 24 8:3 / /media/My\\040Disk rw - exfat /dev/sdb1 rw",
"28 24 0:1 / /proc rw - proc proc rw",
"29 24 0:2 / /run rw - tmpfs tmpfs rw",
"30 24 7:0 / /snap/app/1 ro - squashfs /dev/loop0 ro",
"31 24 0:3 / /network rw - nfs server:/export rw",
"32 24 8:4 / /etc/hosts rw - ext4 /dev/sdc1 rw",
"33 24 8:5 /headers /usr/src/linux-headers ro - ext4 /dev/sdd ro",
].join("\n")
test("Linux memory counts reclaimable cache as available, not as application usage", () => {
const result = parseMeminfo("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 600 kB\nCached: 500 kB\n")
assert.equal(result.total, 1000 * 1024)
assert.equal(result.free, 600 * 1024)
assert.equal(result.used, 400 * 1024)
assert.equal(result.percent, 40)
assert.throws(() => parseMeminfo("bad input"), /Invalid/)
})
test("Older Linux memory files fall back to free + reclaimable memory, and clamp estimates", () => {
const result = parseMeminfo("MemTotal: 1000 kB\nMemFree: 100 kB\nBuffers: 20 kB\nCached: 400 kB\nSReclaimable: 50 kB\nShmem: 30 kB\n")
assert.equal(result.free, 540 * 1024)
assert.equal(parseMeminfo("MemTotal: 100 kB\nMemAvailable: 500 kB\n").free, 100 * 1024)
})
test("Mount parser handles escaped paths and optional fields, and omits pseudo/network/loop mounts", () => {
const mounts = parseMountinfo(mountinfo)
assert.deepEqual(mounts.map(mount => mount.point), ["/", "/home", "/etc/hosts", "/srv/users", "/media/My Disk"])
assert.equal(mounts.find(mount => mount.point === "/media/My Disk").source, "/dev/sdb1")
assert.equal(parseMountinfo("invalid\n").length, 0)
const overlay = "1 0 0:1 / / rw - overlay overlay rw\n2 1 0:2 / /container rw - overlay overlay rw"
assert.deepEqual(parseMountinfo(overlay).map(mount => mount.point), ["/"])
})
test("Linux disks deduplicate bind mounts, skip file mounts, and keep independent filesystems", async () => {
const io = fixtures({
files: { "/proc/self/mountinfo": mountinfo },
stats: { "/": fs, "/home": fs, "/media/My Disk": fs },
nondirectories: ["/etc/hosts"],
})
const result = await readLinuxDisks(io)
assert.equal(result.error, null)
assert.deepEqual(result.items.map(disk => disk.id), ["/", "/home", "/media/My Disk"])
})
test("Filesystem reserved blocks are neither used data nor user-available free space", () => {
const disk = diskFromStatfs("/", "root", fs)
assert.equal(disk.total, 1000 * 1024)
assert.equal(disk.used, 600 * 1024)
assert.equal(disk.free, 350 * 1024)
assert.equal(disk.reserved, 50 * 1024)
assert.equal(disk.percent, 600 / 950 * 100)
assert.equal(disk.used + disk.free + disk.reserved, disk.total)
assert.equal(diskFromStatfs("/", "root", { ...fs, bavail: -1 }).free, 0)
assert.throws(() => diskFromStatfs("/", "broken", { ...fs, bfree: 2000 }), /Invalid/)
})
test("Failed mounts don't discard healthy disks, and missing procfs still reports root", async () => {
const partial = await readLinuxDisks(fixtures({ files: { "/proc/self/mountinfo": mountinfo }, stats: { "/": fs } }))
assert.equal(partial.items.length, 1)
assert.match(partial.error, /\/home/)
const root = await readLinuxDisks(fixtures({ stats: { "/": fs } }))
assert.equal(root.items[0].id, "/")
assert.equal(root.error, null)
})
test("WSL local Windows mounts are allowed, but unrelated 9p network mounts are skipped", () => {
const mounts = parseMountinfo("1 0 0:1 / /mnt/c rw - 9p C:\\134 rw,aname=drvfs;path=C:\\134\n2 0 0:2 / /remote rw - 9p remote rw")
assert.equal(mounts.length, 1)
assert.equal(mounts[0].point, "/mnt/c")
assert.equal(mounts[0].source, "C:\\")
})
test("Intel JSON sampler uses the last complete physical-engine sample, not client totals", () => {
const data = '[{"engines":{"Render/0":{"busy":10},"Video/0":{"busy":20}}},' +
'{"engines":{"Render/0":{"busy":23.5},"Video/0":{"busy":40}},"clients":{"1":{"busy":99}}},' +
'{"engines":{"Render/0":{"busy":'
assert.equal(parseIntelGpuTop(data), 40)
assert.equal(parseIntelGpuTop('[{"engines":{"Render":{"busy":0}}}]'), 0)
assert.equal(parseIntelGpuTop('[{"engines":{"Render":{"busy":null},"Video":{"busy":"---"}}}]'), null)
assert.equal(parseIntelGpuTop("Permission denied"), null)
assert.equal(parseIntelGpuTop('[{"engines":{"Render":{"busy":101}}}]'), null)
})
test("Intel sampler only accepts a discovered DRM device path", async () => {
await assert.rejects(sampleIntelGpu("/dev/dri/card0;whoami"), /Invalid DRM/)
})
test("AMD reads sysfs utilization and memory without launching external GPU tools", async () => {
const io = fixtures({
directories: { "/sys/class/drm": ["card1", "card1-DP-1", "renderD128"] },
files: {
"/sys/class/drm/card1/device/vendor": "0x1002\n",
"/sys/class/drm/card1/device/product_name": "AMD Radeon Graphics\n",
"/sys/class/drm/card1/device/gpu_busy_percent": "37\n",
"/sys/class/drm/card1/device/mem_info_vram_used": "268435456\n",
"/sys/class/drm/card1/device/mem_info_vram_total": "2147483648\n",
},
sampleIntel: () => { throw new Error("Unexpected Intel sampler call") },
})
const result = await readLinuxGpu(io)
assert.equal(result.error, null)
assert.equal(result.adapter.vendor, "AMD")
assert.equal(result.adapter.percent, 37)
assert.equal(result.adapter.memoryUsed, 268435456)
assert.equal(result.adapter.memoryKind, "vram")
})
test("Linux prefers Intel and selects its exact DRM device, not another adapter's counters", async () => {
let device
const result = await readLinuxGpu(fixtures({
directories: { "/sys/class/drm": ["card0", "card2", "card1"] },
files: {
"/sys/class/drm/card0/device/vendor": "0x10de",
"/sys/class/drm/card1/device/vendor": "0x1002",
"/sys/class/drm/card2/device/vendor": "0x8086",
},
sampleIntel: async path => { device = path; return '[{"engines":{"Render/0":{"busy":12}}}]' },
}))
assert.equal(device, "/dev/dri/card2")
assert.equal(result.adapter.vendor, "Intel")
assert.equal(result.adapter.percent, 12)
assert.equal(result.adapter.memoryUsed, null)
assert.equal(result.adapter.memoryKind, "unknown")
assert.equal(result.error, null)
})
test("Missing Intel tool, GPU permissions and unknown drivers remain unavailable rather than idle", async () => {
const result = await readLinuxGpu(fixtures({
directories: { "/sys/class/drm": ["card0"] },
files: { "/sys/class/drm/card0/device/vendor": "0x8086" },
}))
assert.equal(result.adapter.percent, null)
assert.match(result.error, /not installed/)
const wsl = await readLinuxGpu(fixtures({ files: { "/proc/sys/kernel/osrelease": "6.6.87-microsoft-standard-WSL2" } }))
assert.equal(wsl.adapter, null)
assert.match(wsl.error, /WSL/)
const headless = await readLinuxGpu(fixtures())
assert.equal(headless.adapter, null)
assert.match(headless.error, /No supported/)
})
test("Invalid AMD counters remain unavailable, while explicit zero means idle", async () => {
for (const [text, expected] of [["garbage", null], ["101", null], ["", null], ["0", 0]]) {
const result = await readLinuxGpu(fixtures({
directories: { "/sys/class/drm": ["card0"] },
files: { "/sys/class/drm/card0/device/vendor": "0x1002", "/sys/class/drm/card0/device/gpu_busy_percent": text },
}))
assert.equal(result.adapter.percent, expected)
assert.equal(result.adapter.memoryUsed, null)
}
})
test("Complete Linux collection uses procfs/sysfs and never invokes PowerShell", async () => {
const io = fixtures({
files: {
"/proc/meminfo": "MemTotal: 1000 kB\nMemAvailable: 600 kB\n",
"/proc/self/mountinfo": mountinfo,
"/sys/class/drm/card0/device/vendor": "0x1002",
"/sys/class/drm/card0/device/gpu_busy_percent": "24",
},
directories: { "/sys/class/drm": ["card0"] },
stats: { "/": fs, "/home": fs, "/media/My Disk": fs },
nondirectories: ["/etc/hosts"],
})
const monitor = new Monitor(async () => { throw new Error("Linux must not launch PowerShell") }, { platform: "linux", linux: io })
const first = monitor.snapshot()
assert.equal(first, monitor.snapshot())
const snapshot = await first
assert.equal(snapshot.ram.percent, 40)
assert.equal(snapshot.disks.items.length, 3)
assert.equal(snapshot.gpu.adapter.vendor, "AMD")
assert.equal(snapshot.gpu.adapter.percent, 24)
assert.equal(snapshot.gpu.error, null)
const text = report(snapshot)
assert.match(text, /AMD/)
assert.doesNotMatch(text.split("\n").filter(line => line.startsWith("- **GPU")).join("\n"), /Intel|included in system RAM/)
})
+6 -5
View File
@@ -34,7 +34,7 @@ test("Only a DXGI LUID can be inserted in the fixed PowerShell query", () => {
assert.throws(() => intelCountersScript("'; exit; '"), /Invalid GPU adapter identity/)
})
test("Intel-only collection excludes another GPU, coalesces concurrent calls, and caches", { skip: process.platform !== "win32" }, async () => {
test("Windows Intel-only collection excludes another GPU, coalesces concurrent calls, and caches", async () => {
let calls = 0
const collector = new Monitor(async (file, args) => {
calls++
@@ -46,20 +46,21 @@ test("Intel-only collection excludes another GPU, coalesces concurrent calls, an
engines: [engine(1, intel, 0, 12), engine(2, intel, 0, 8), engine(3, nvidia, 0, 99)],
memory: [{ SharedUsage: 256 * 1024 ** 2 }],
})
})
}, { platform: "win32" })
const first = collector.snapshot()
assert.equal(first, collector.snapshot())
const snapshot = await first
assert.equal(snapshot.gpu.adapter.percent, 20)
assert.equal(snapshot.gpu.adapter.sharedUsed, 256 * 1024 ** 2)
assert.equal(snapshot.gpu.adapter.memoryUsed, 256 * 1024 ** 2)
assert.equal(snapshot.gpu.adapter.memoryKind, "shared")
assert.equal(snapshot.disks.items[0].percent, 25)
assert.equal(snapshot.gpu.error, null)
assert.equal(await collector.snapshot(), snapshot)
assert.equal(calls, 3)
})
test("A missing GPU or failed disk query shows unavailable, never false idle/full values", { skip: process.platform !== "win32" }, async () => {
const collector = new Monitor(async () => { throw new Error("Permission denied") })
test("A missing GPU or failed Windows disk query shows unavailable, never false idle/full values", async () => {
const collector = new Monitor(async () => { throw new Error("Permission denied") }, { platform: "win32" })
const snapshot = await collector.snapshot()
assert.equal(snapshot.gpu.adapter, null)
assert.match(snapshot.gpu.error, /Permission denied/)