feat: add on-demand OpenCode system monitor
Add a Desktop dashboard and text status command for disk space, RAM, CPU and Intel integrated graphics. Include visibility-driven sampling, tests, development tooling, and installation documentation.
This commit is contained in:
@@ -0,0 +1,3 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.preview/
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 0.1.0 — 2026-11-20
|
||||||
|
|
||||||
|
Initial version:
|
||||||
|
|
||||||
|
- Added `/system`, a theme-aware OpenCode Desktop dashboard.
|
||||||
|
- Added fixed-drive free space, physical memory, CPU, and Intel integrated GPU readings.
|
||||||
|
- Added per-logical-processor details and three-minute, in-memory history.
|
||||||
|
- Added pause/resume, manual refresh, and configurable sampling intervals.
|
||||||
|
- Made sampling visibility-driven: no polling or elapsed-time timers while the dashboard is closed or hidden.
|
||||||
|
- Added `/system_status` for a one-time report in Desktop, web, or TUI without starting a model turn.
|
||||||
|
- Added the `system_monitor_status` agent tool.
|
||||||
|
- Added tests covering Intel adapter isolation, unavailable metrics, request coalescing, and polling lifecycle.
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
# System Monitor for OpenCode
|
||||||
|
|
||||||
|
**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
|
||||||
|
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
|
||||||
|
the dashboard is visible.**
|
||||||
|
|
||||||
|
## Highlights
|
||||||
|
|
||||||
|
- **Disk space:** free, used, and total capacity for each fixed Windows drive.
|
||||||
|
- **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.
|
||||||
|
- **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.
|
||||||
|
- **Local readings:** no external monitoring service, telemetry, API keys, or model calls for the dashboard.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
| Command | Result | Where it works |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `/system` | Opens the live graphical dashboard | OpenCode Desktop |
|
||||||
|
| `/system_status` | Posts a one-time text report without starting a model turn | Desktop, web, and TUI |
|
||||||
|
|
||||||
|
The plugin also exposes a `system_monitor_status` tool, so an agent can read the current metrics when asked.
|
||||||
|
Unlike the dashboard, asking an AI agent about those metrics uses your normal model session.
|
||||||
|
|
||||||
|
**Settings → System Monitor** changes the refresh interval. The same control is available inside the dashboard.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
| Component | Support |
|
||||||
|
| --- | --- |
|
||||||
|
| 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 |
|
||||||
|
| 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.
|
||||||
|
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%`.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
### 1. Clone and build
|
||||||
|
|
||||||
|
Run in PowerShell, from the directory where you keep your projects:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
git clone https://git.davidmeincke.dk/david/opencode-system-monitor.git
|
||||||
|
cd opencode-system-monitor
|
||||||
|
npm.cmd ci
|
||||||
|
npm.cmd run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Use credentials with access to the repository if it is private. The repository contains the source and
|
||||||
|
dependency lockfile; `node_modules/` and the generated `dist/` directory are built locally.
|
||||||
|
|
||||||
|
### 2. Register the plugin
|
||||||
|
|
||||||
|
Add the **absolute path to the cloned directory** to your global OpenCode configuration:
|
||||||
|
|
||||||
|
```text
|
||||||
|
%USERPROFILE%\.config\opencode\opencode.jsonc
|
||||||
|
```
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"plugins": [
|
||||||
|
// Keep your existing plugin entries here.
|
||||||
|
"C:/Users/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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Update
|
||||||
|
|
||||||
|
From the cloned directory:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
git pull --ff-only
|
||||||
|
npm.cmd ci
|
||||||
|
npm.cmd run build
|
||||||
|
```
|
||||||
|
|
||||||
|
OpenCode watches the local plugin and reloads the rebuilt bundle.
|
||||||
|
|
||||||
|
### Uninstall
|
||||||
|
|
||||||
|
Remove this plugin's directory from the `plugins` array in your global OpenCode configuration.
|
||||||
|
You can then delete the cloned directory if you no longer need it.
|
||||||
|
|
||||||
|
## How sampling works
|
||||||
|
|
||||||
|
| 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** |
|
||||||
|
|
||||||
|
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
|
||||||
|
after the corresponding interval has elapsed.
|
||||||
|
|
||||||
|
### When the dashboard is closed
|
||||||
|
|
||||||
|
- Automatic metric requests and the elapsed-time clock are stopped.
|
||||||
|
- Minimizing or hiding the OpenCode window also stops those timers.
|
||||||
|
- Opening the dashboard resumes sampling; a long pause starts a fresh CPU measurement interval.
|
||||||
|
- A request already in progress may finish, but it cannot restart the polling loop.
|
||||||
|
- `/system_status` and the agent tool can still request an explicit, one-time reading.
|
||||||
|
|
||||||
|
The plugin remains loaded in OpenCode with a small amount of state; **no idle polling** does not mean
|
||||||
|
literally zero memory usage. If another OpenCode window has the dashboard open, that window can still request readings.
|
||||||
|
|
||||||
|
### 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
|
||||||
|
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
|
||||||
|
|
||||||
|
DXGI identifies the Intel adapter's **LUID**, the identifier used by Windows' GPU performance counters.
|
||||||
|
Only counters for that adapter are included:
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Sizes are displayed in binary units such as **GiB**.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Check |
|
||||||
|
| --- | --- |
|
||||||
|
| `/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. |
|
||||||
|
| 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:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npm.cmd run smoke
|
||||||
|
```
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npm.cmd ci
|
||||||
|
npm.cmd 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` |
|
||||||
|
|
||||||
|
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"
|
||||||
|
```
|
||||||
|
|
||||||
|
This checks plugin registration, GUI/RPC availability, Intel readings, and the `/system_status` command.
|
||||||
|
It creates a temporary test session and removes it afterwards.
|
||||||
|
|
||||||
|
### Project layout
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/
|
||||||
|
index.ts Server registration, text command, and agent tool
|
||||||
|
rpc.ts Dashboard ↔ server contract
|
||||||
|
metrics.ts On-demand collection and shared caching
|
||||||
|
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
|
||||||
|
dashboard.tsx Cards, utilization bars, charts, and detail view
|
||||||
|
style.css Theme-aware dashboard styling
|
||||||
|
tests/ Automated metric and lifecycle checks
|
||||||
|
scripts/ Smoke test, integration test, and live preview
|
||||||
|
```
|
||||||
|
|
||||||
|
The package is private and not published to npm. The stable plugin ID remains `local-system-monitor`,
|
||||||
|
which also scopes its saved refresh setting.
|
||||||
|
|
||||||
|
## Credits
|
||||||
|
|
||||||
|
Dashboard interaction patterns are inspired by [OpenCode Quota](https://github.com/slkiser/opencode-quota).
|
||||||
|
This is an independent implementation built with the [OpenCode plugin SDK](https://opencode.ai/docs/build/plugins).
|
||||||
Generated
+5448
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"name": "local-system-monitor",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"description": "On-demand disk space, RAM, CPU and Intel integrated GPU monitoring for OpenCode Desktop.",
|
||||||
|
"author": "David Meincke",
|
||||||
|
"homepage": "https://git.davidmeincke.dk/david/opencode-system-monitor",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://git.davidmeincke.dk/david/opencode-system-monitor.git"
|
||||||
|
},
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://git.davidmeincke.dk/david/opencode-system-monitor/issues"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.13.0"
|
||||||
|
},
|
||||||
|
"keywords": ["opencode", "opencode-plugin", "system-monitor", "windows", "intel", "disk-space"],
|
||||||
|
"exports": {
|
||||||
|
".": "./dist/index.js",
|
||||||
|
"./rpc": "./dist/rpc.js",
|
||||||
|
"./gui-experimental": "./dist/gui-experimental.cjs"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"build:server": "tsc -p tsconfig.server.json",
|
||||||
|
"build": "npm run build:server && vite build",
|
||||||
|
"test": "node --conditions=browser --test tests/*.test.mjs",
|
||||||
|
"smoke": "node scripts/smoke.mjs",
|
||||||
|
"preview": "node scripts/preview.mjs",
|
||||||
|
"verify": "npm run typecheck && npm run build && npm test"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@opencode/plugin": "2.3.2"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.12.2",
|
||||||
|
"solid-js": "1.9.17",
|
||||||
|
"typescript": "^5.9.3",
|
||||||
|
"vite": "7.3.7",
|
||||||
|
"vite-plugin-solid": "2.11.14"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>System Monitor · Live preview</title></head>
|
||||||
|
<body style="margin:0"><div id="root"></div><script type="module" src="/src/preview.tsx"></script></body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { execFileSync } from "node:child_process"
|
||||||
|
|
||||||
|
const cli = process.argv[2]
|
||||||
|
if (!cli) throw new Error("Pass the OpenCode CLI executable path")
|
||||||
|
function api(method, route, body) {
|
||||||
|
const args = ["api", method, route]
|
||||||
|
if (body !== undefined) args.push("--data", JSON.stringify(body))
|
||||||
|
const result = execFileSync(cli, args, { encoding: "utf8", windowsHide: true, timeout: 20000 })
|
||||||
|
return result.trim() ? JSON.parse(result) : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const plugins = api("get", "/api/plugin").data
|
||||||
|
const plugin = plugins.find(item => item.id === "local-system-monitor")
|
||||||
|
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/)
|
||||||
|
assert.equal(snapshot.gpu.error, null)
|
||||||
|
assert.ok(snapshot.disks.items.length > 0)
|
||||||
|
console.log("Installed plugin, GUI feature, RPC, and Intel-only readings: passed")
|
||||||
|
|
||||||
|
let sessionID
|
||||||
|
try {
|
||||||
|
const result = api("post", "/api/session", { title: "System Monitor self-test" })
|
||||||
|
sessionID = (result.data ?? result).id
|
||||||
|
assert.ok(sessionID)
|
||||||
|
api("post", `/api/session/${sessionID}/command`, { name: "system_status", text: "" })
|
||||||
|
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/)
|
||||||
|
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")
|
||||||
|
} finally {
|
||||||
|
if (sessionID) api("delete", `/api/session/${sessionID}`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// Development-only live visual test. Never loaded by the installed plugin.
|
||||||
|
import { createServer } from "vite"
|
||||||
|
import solid from "vite-plugin-solid"
|
||||||
|
import { monitor } from "../dist/metrics.js"
|
||||||
|
|
||||||
|
const server = await createServer({
|
||||||
|
configFile: false,
|
||||||
|
plugins: [solid(), {
|
||||||
|
name: "local-monitor-preview",
|
||||||
|
configureServer(server) {
|
||||||
|
server.middlewares.use("/__metrics", async (_request, response) => {
|
||||||
|
try {
|
||||||
|
response.setHeader("Content-Type", "application/json")
|
||||||
|
response.setHeader("Cache-Control", "no-store")
|
||||||
|
response.end(JSON.stringify(await monitor.snapshot()))
|
||||||
|
} catch {
|
||||||
|
response.statusCode = 503
|
||||||
|
response.end('{"error":"Collection failed"}')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
server: { host: "127.0.0.1", port: 5098, strictPort: true },
|
||||||
|
})
|
||||||
|
await server.listen()
|
||||||
|
console.log("System Monitor live preview: http://127.0.0.1:5098/preview.html")
|
||||||
|
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, async () => { await server.close(); process.exit(0) })
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { monitor } from "../dist/metrics.js"
|
||||||
|
import { report } from "../dist/format.js"
|
||||||
|
|
||||||
|
const snapshot = await monitor.snapshot()
|
||||||
|
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")
|
||||||
|
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.")
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { createEffect, createMemo, createSignal, onCleanup, untrack } from "solid-js"
|
||||||
|
import { gpuPercent } from "./format.js"
|
||||||
|
import type { HistoryPoint, Snapshot } from "./types.js"
|
||||||
|
|
||||||
|
export function createMonitorClient(
|
||||||
|
load: () => Promise<Snapshot>,
|
||||||
|
refreshMs: () => number,
|
||||||
|
viewVisible: () => boolean,
|
||||||
|
) {
|
||||||
|
const [snapshot, setSnapshot] = createSignal<Snapshot>()
|
||||||
|
const [history, setHistory] = createSignal<HistoryPoint[]>([])
|
||||||
|
const [error, setError] = createSignal<string>()
|
||||||
|
const [busy, setBusy] = createSignal(false)
|
||||||
|
const [paused, setPaused] = createSignal(false)
|
||||||
|
const [windowVisible, setWindowVisible] = createSignal(document.visibilityState !== "hidden")
|
||||||
|
const viewing = createMemo(() => viewVisible() && windowVisible())
|
||||||
|
const active = createMemo(() => viewing() && !paused())
|
||||||
|
const [now, setNow] = createSignal(Date.now())
|
||||||
|
let disposed = false
|
||||||
|
let pending: Promise<void> | undefined
|
||||||
|
|
||||||
|
const refresh = () => {
|
||||||
|
if (disposed || !viewing()) return Promise.resolve()
|
||||||
|
if (pending) return pending
|
||||||
|
setBusy(true)
|
||||||
|
pending = Promise.resolve().then(() => disposed || !viewing() ? undefined : load()).then(data => {
|
||||||
|
if (disposed || !data) return
|
||||||
|
setSnapshot(data)
|
||||||
|
setError(undefined)
|
||||||
|
setHistory(previous => {
|
||||||
|
if (previous.at(-1)?.at === data.sampledAt) return previous
|
||||||
|
return [...previous, { at: data.sampledAt, cpu: data.cpu.percent, ram: data.ram.percent, gpu: gpuPercent(data) }]
|
||||||
|
.filter(point => point.at > data.sampledAt - 180_000).slice(-180)
|
||||||
|
})
|
||||||
|
}).catch(error => {
|
||||||
|
if (!disposed) setError(error instanceof Error ? error.message : "Unable to read system metrics")
|
||||||
|
}).finally(() => {
|
||||||
|
pending = undefined
|
||||||
|
if (!disposed) setBusy(false)
|
||||||
|
})
|
||||||
|
return pending
|
||||||
|
}
|
||||||
|
|
||||||
|
const visibilityChanged = () => setWindowVisible(document.visibilityState !== "hidden")
|
||||||
|
document.addEventListener("visibilitychange", visibilityChanged)
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
if (!active()) return
|
||||||
|
const interval = Math.max(2000, refreshMs())
|
||||||
|
let stopped = false
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
const poll = async () => {
|
||||||
|
if (stopped || !active()) return
|
||||||
|
await untrack(refresh)
|
||||||
|
if (!stopped && active()) timer = setTimeout(poll, interval)
|
||||||
|
}
|
||||||
|
void poll()
|
||||||
|
onCleanup(() => { stopped = true; clearTimeout(timer) })
|
||||||
|
})
|
||||||
|
// The "checked … ago" clock is also stopped while no monitor view is visible.
|
||||||
|
createEffect(() => {
|
||||||
|
if (!viewing()) return
|
||||||
|
setNow(Date.now())
|
||||||
|
const clock = setInterval(() => setNow(Date.now()), 1000)
|
||||||
|
onCleanup(() => clearInterval(clock))
|
||||||
|
})
|
||||||
|
onCleanup(() => {
|
||||||
|
disposed = true
|
||||||
|
document.removeEventListener("visibilitychange", visibilityChanged)
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
snapshot, history, error, busy, paused, setPaused, refresh, viewing, active,
|
||||||
|
stale: () => active() && !!snapshot() && now() - snapshot()!.sampledAt > Math.max(15_000, refreshMs() * 3),
|
||||||
|
age: () => snapshot() ? Math.max(0, Math.floor((now() - snapshot()!.sampledAt) / 1000)) : 0,
|
||||||
|
gpuAge: () => snapshot() ? Math.max(0, Math.floor((now() - snapshot()!.gpu.sampledAt) / 1000)) : 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MonitorClient = ReturnType<typeof createMonitorClient>
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import { createSignal, For, Show, type JSX } from "solid-js"
|
||||||
|
import type { MonitorClient } from "./client.js"
|
||||||
|
import { bytes, gpuPercent, percent, uptime } from "./format.js"
|
||||||
|
import type { HistoryPoint } from "./types.js"
|
||||||
|
|
||||||
|
type Metric = "cpu" | "ram" | "gpu" | "disk"
|
||||||
|
const paths = {
|
||||||
|
cpu: "M8 3v3m4-3v3m4-3v3M8 18v3m4-3v3m4-3v3M3 8h3m-3 4h3m-3 4h3m12-8h3m-3 4h3m-3 4h3M7 6h10a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1Zm2 3h6v6H9Z",
|
||||||
|
ram: "M4 7h16v10H4ZM7 17v3m4-3v3m4-3v3m4-3v3M8 10v4m4-4v4m4-4v4M2 10h2m-2 4h2m16-4h2m-2 4h2",
|
||||||
|
gpu: "M3 6h17v12H3ZM20 10h2m-2 4h2M6 18v3m4-3v3m4-3v3M7 10h4v4H7Zm8 0h2m-2 4h2",
|
||||||
|
disk: "M5 5h14l3 10v5H2v-5Zm-3 10h20M6 18h.01M9 18h.01",
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MetricIcon(props: { type: Metric }) {
|
||||||
|
return <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d={paths[props.type]} /></svg>
|
||||||
|
}
|
||||||
|
|
||||||
|
function Bar(props: { value: number | null; label: string; kind?: Metric }) {
|
||||||
|
return <div class="sm-bar" role="progressbar" aria-label={props.label} aria-valuemin={0} aria-valuemax={100}
|
||||||
|
aria-valuenow={props.value === null ? undefined : Math.round(props.value)}
|
||||||
|
aria-valuetext={props.value === null ? "Unavailable" : `${Math.round(props.value)}% used`}
|
||||||
|
data-level={props.value !== null && props.value >= 95 ? "critical" : props.value !== null && props.value >= 85 ? "warning" : "normal"}>
|
||||||
|
<div style={{ width: `${props.value ?? 0}%` }} />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function Sparkline(props: { points: HistoryPoint[]; metric: "cpu" | "ram" | "gpu" }) {
|
||||||
|
const points = () => props.points.filter(point => point[props.metric] !== null)
|
||||||
|
const coordinates = () => {
|
||||||
|
const end = props.points.at(-1)?.at ?? 0
|
||||||
|
return points().map(point => `${Math.max(0, 300 - (end - point.at) / 600)},${36 - (point[props.metric] ?? 0) * .32}`).join(" ")
|
||||||
|
}
|
||||||
|
return <div class="sm-trend" aria-label={`${props.metric.toUpperCase()} recent utilization`}>
|
||||||
|
<svg viewBox="0 0 300 40" preserveAspectRatio="none" role="img" aria-label="Recent utilization, 0 to 100 percent">
|
||||||
|
<path d="M0 39H300M0 20H300" class="sm-gridline" />
|
||||||
|
<Show when={points().length > 1}><polyline points={coordinates()} fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke" /></Show>
|
||||||
|
</svg>
|
||||||
|
<span>{points().length > 1 ? "Last 3 minutes · this window" : "Collecting history…"}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
function Card(props: { title: string; badge: string; kind: Metric; children: JSX.Element }) {
|
||||||
|
return <section class={`sm-card sm-${props.kind}`} aria-label={props.title}>
|
||||||
|
<header class="sm-card-head"><span class="sm-icon"><MetricIcon type={props.kind} /></span><h3>{props.title}</h3><span class="sm-chip">{props.badge}</span></header>
|
||||||
|
{props.children}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Dashboard(props: {
|
||||||
|
client: MonitorClient
|
||||||
|
mode: "light" | "dark"
|
||||||
|
compact?: boolean
|
||||||
|
refreshMs: number
|
||||||
|
setRefreshMs: (value: number) => void
|
||||||
|
openWindow?: () => void
|
||||||
|
}) {
|
||||||
|
const client = props.client
|
||||||
|
const [details, setDetails] = createSignal(false)
|
||||||
|
return <div class="sm-root sm-dashboard" data-mode={props.mode} data-compact={props.compact ? "true" : "false"}>
|
||||||
|
<div class="sm-toolbar">
|
||||||
|
<div class="sm-live" data-state={!client.active() ? "paused" : client.error() || client.stale() ? "error" : "live"}>
|
||||||
|
<span class="sm-dot" />{!client.active() ? "Paused" : client.error() ? "Connection error" : client.stale() ? "Stale readings" : "Live system overview"}
|
||||||
|
</div>
|
||||||
|
<div class="sm-controls">
|
||||||
|
<select aria-label="Refresh interval" value={props.refreshMs} onChange={event => props.setRefreshMs(Number(event.currentTarget.value))}>
|
||||||
|
<option value="2000">Every 2s</option><option value="3000">Every 3s</option><option value="5000">Every 5s</option><option value="10000">Every 10s</option>
|
||||||
|
</select>
|
||||||
|
<button type="button" aria-pressed={client.paused()} onClick={() => client.setPaused(!client.paused())}>{client.paused() ? "Resume" : "Pause"}</button>
|
||||||
|
<button type="button" aria-label="Refresh system readings" title="Refresh system readings" disabled={client.busy()} onClick={() => void client.refresh()}>
|
||||||
|
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M20 7v5h-5M4 17v-5h5M5.5 8a7 7 0 0 1 11.7-3L20 8M4 16l2.8 3A7 7 0 0 0 18.5 16" /></svg>
|
||||||
|
</button>
|
||||||
|
<Show when={props.compact && props.openWindow}><button type="button" onClick={() => props.openWindow?.()}>Expand</button></Show>
|
||||||
|
</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>}>
|
||||||
|
{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">
|
||||||
|
<Card kind="cpu" title="CPU" badge={`${snapshot().cpu.cores} threads`}>
|
||||||
|
<div class="sm-reading"><strong>{percent(snapshot().cpu.percent)}</strong><span>used</span></div>
|
||||||
|
<p class="sm-device">{snapshot().cpu.name}</p>
|
||||||
|
<Bar value={snapshot().cpu.percent} label="CPU utilization" />
|
||||||
|
<div class="sm-pair"><span>All logical processors</span><span>{percent(snapshot().cpu.percent === null ? null : 100 - snapshot().cpu.percent!)} idle</span></div>
|
||||||
|
<Sparkline points={client.history()} metric="cpu" />
|
||||||
|
</Card>
|
||||||
|
<Card kind="ram" title="Memory" badge="RAM">
|
||||||
|
<div class="sm-reading"><strong>{percent(snapshot().ram.percent)}</strong><span>used</span></div>
|
||||||
|
<p class="sm-device">{bytes(snapshot().ram.used)} of {bytes(snapshot().ram.total)}</p>
|
||||||
|
<Bar value={snapshot().ram.percent} label="RAM utilization" />
|
||||||
|
<div class="sm-pair"><span>Available memory</span><strong>{bytes(snapshot().ram.free)}</strong></div>
|
||||||
|
<Sparkline points={client.history()} metric="ram" />
|
||||||
|
</Card>
|
||||||
|
<For each={snapshot().disks.items}>{disk => <Card kind="disk" title="Disk space" badge={disk.id}>
|
||||||
|
<div class="sm-reading sm-space"><strong>{bytes(disk.free)}</strong><span>free</span></div>
|
||||||
|
<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>
|
||||||
|
</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">
|
||||||
|
<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>
|
||||||
|
<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>
|
||||||
|
<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>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>
|
||||||
|
</>}
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import type { Snapshot } from "./types.js"
|
||||||
|
|
||||||
|
export function bytes(value: number | null | undefined): string {
|
||||||
|
if (value == null || !Number.isFinite(value)) return "Unavailable"
|
||||||
|
const units = ["B", "KiB", "MiB", "GiB", "TiB"]
|
||||||
|
let index = 0
|
||||||
|
let size = Math.max(0, value)
|
||||||
|
while (size >= 1024 && index < units.length - 1) { size /= 1024; index++ }
|
||||||
|
return `${size.toLocaleString(undefined, { maximumFractionDigits: index >= 3 ? 1 : 0 })} ${units[index]}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function percent(value: number | null | undefined): string {
|
||||||
|
return value == null || !Number.isFinite(value) ? "—" : `${Math.round(value)}%`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function gpuPercent(snapshot: Snapshot): number | null {
|
||||||
|
return snapshot.gpu.adapter?.percent ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
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`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function report(snapshot: Snapshot): string {
|
||||||
|
const lines = [
|
||||||
|
`## System Monitor · ${snapshot.hostname}`,
|
||||||
|
`Checked ${new Date(snapshot.sampledAt).toLocaleString()} · uptime ${uptime(snapshot.uptime)}`,
|
||||||
|
"",
|
||||||
|
`- **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)`] : []),
|
||||||
|
]
|
||||||
|
if (snapshot.disks.error) lines.push(`- Disk check: ${snapshot.disks.error}`)
|
||||||
|
if (snapshot.gpu.error) lines.push(`- Integrated GPU check: ${snapshot.gpu.error}`)
|
||||||
|
return lines.join("\n")
|
||||||
|
}
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
import { Command, Plugin, SettingsPage, Store, Style } from "@opencode/plugin/gui"
|
||||||
|
import { Schema } from "effect"
|
||||||
|
import { createSignal, onCleanup, onMount } from "solid-js"
|
||||||
|
import { createMonitorClient } from "./client.js"
|
||||||
|
import { Dashboard } from "./dashboard.js"
|
||||||
|
import { SystemMonitor } from "./rpc.js"
|
||||||
|
import type { Snapshot } from "./types.js"
|
||||||
|
import css from "./style.css?inline"
|
||||||
|
|
||||||
|
export default Plugin.define({
|
||||||
|
stores: {
|
||||||
|
refresh: Store.global(Schema.Struct({
|
||||||
|
refreshMs: Schema.Number,
|
||||||
|
}), { refreshMs: 3000 }, ["plugin.local-system-monitor.prefs"]),
|
||||||
|
},
|
||||||
|
i18n: { en: { title: "System Monitor", open: "Open System Monitor" } },
|
||||||
|
setup(ctx) {
|
||||||
|
const prefs = ctx.stores.refresh
|
||||||
|
const [openDialogs, setOpenDialogs] = createSignal(0)
|
||||||
|
const interval = () => [2000, 3000, 5000, 10000].includes(prefs.value.refreshMs) ? prefs.value.refreshMs : 3000
|
||||||
|
const client = createMonitorClient(async () => await ctx.client.rpc(SystemMonitor).snapshot({}) as Snapshot, interval, () => openDialogs() > 0)
|
||||||
|
const setInterval = (value: number) => {
|
||||||
|
if ([2000, 3000, 5000, 10000].includes(value)) prefs.update(draft => { draft.refreshMs = value })
|
||||||
|
}
|
||||||
|
const dashboard = () => <Dashboard client={client} mode={ctx.appearance.mode()} refreshMs={interval()} setRefreshMs={setInterval} />
|
||||||
|
function MonitorDialog() {
|
||||||
|
let mounted = false
|
||||||
|
onMount(() => { mounted = true; setOpenDialogs(count => count + 1) })
|
||||||
|
onCleanup(() => { if (mounted) setOpenDialogs(count => count - 1) })
|
||||||
|
return <ctx.ui.Dialog title="System Monitor" size="x-large">{dashboard()}</ctx.ui.Dialog>
|
||||||
|
}
|
||||||
|
function openWindow() {
|
||||||
|
ctx.dialogs.open(() => <MonitorDialog />)
|
||||||
|
}
|
||||||
|
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",
|
||||||
|
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" }],
|
||||||
|
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.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>
|
||||||
|
</ctx.ui.SettingsLayout>,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { Plugin } from "@opencode/plugin"
|
||||||
|
import { monitor } from "./metrics.js"
|
||||||
|
import { report } from "./format.js"
|
||||||
|
import { SystemMonitor } from "./rpc.js"
|
||||||
|
|
||||||
|
const reportKey = "local-system-monitor.report"
|
||||||
|
|
||||||
|
export default Plugin.define({
|
||||||
|
id: "local-system-monitor",
|
||||||
|
async setup(ctx) {
|
||||||
|
await ctx.rpc.register(SystemMonitor, { snapshot: () => monitor.snapshot() })
|
||||||
|
await ctx.tool.transform(editor => {
|
||||||
|
editor.add({
|
||||||
|
name: "system_monitor_status",
|
||||||
|
description: "Read this computer's live disk free space, RAM, CPU and GPU utilization.",
|
||||||
|
input: { type: "object", properties: {}, additionalProperties: false },
|
||||||
|
execute: async () => ({ content: report(await monitor.snapshot()) }),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
await ctx.command.transform(editor => {
|
||||||
|
editor.add({
|
||||||
|
name: "system_status",
|
||||||
|
description: "Show disk, RAM, CPU and GPU readings in chat without a model request.",
|
||||||
|
execute: async ({ sessionID }) => {
|
||||||
|
await ctx.session.wait({ sessionID })
|
||||||
|
await ctx.session.prompt({
|
||||||
|
sessionID, text: report(await monitor.snapshot()),
|
||||||
|
metadata: { [reportKey]: true }, resume: false, delivery: "steer",
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
for (const hook of ["context", "compaction", "generate"] as const) {
|
||||||
|
await ctx.session.hook(hook, event => {
|
||||||
|
event.messages = event.messages.filter(message => !message.metadata?.[reportKey])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
await ctx.session.hook("title", event => {
|
||||||
|
const hadReport = event.messages.some(message => message.metadata?.[reportKey])
|
||||||
|
if (!hadReport) return
|
||||||
|
event.messages = event.messages.filter(message => !message.metadata?.[reportKey])
|
||||||
|
if (!event.messages.length) event.result = ""
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
+179
@@ -0,0 +1,179 @@
|
|||||||
|
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<string>
|
||||||
|
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<string, number>()
|
||||||
|
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<string> {
|
||||||
|
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<Snapshot>
|
||||||
|
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<Snapshot> {
|
||||||
|
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<void> {
|
||||||
|
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<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.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<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 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<symbol, Monitor | undefined>
|
||||||
|
export const monitor = globals[key] ??= new Monitor()
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { render } from "solid-js/web"
|
||||||
|
import { createSignal, Show } from "solid-js"
|
||||||
|
import { Dashboard } from "./dashboard.js"
|
||||||
|
import { createMonitorClient } from "./client.js"
|
||||||
|
import css from "./style.css?inline"
|
||||||
|
|
||||||
|
function Preview() {
|
||||||
|
const [refreshMs, setRefreshMs] = createSignal(3000)
|
||||||
|
const [mode, setMode] = createSignal<"light" | "dark">("dark")
|
||||||
|
const [compact, setCompact] = createSignal(false)
|
||||||
|
const [visible, setVisible] = createSignal(true)
|
||||||
|
const client = createMonitorClient(async () => {
|
||||||
|
const response = await fetch("/__metrics")
|
||||||
|
if (!response.ok) throw new Error("System check failed")
|
||||||
|
return response.json()
|
||||||
|
}, refreshMs, visible)
|
||||||
|
return <main style={{ background: mode() === "dark" ? "#11131b" : "#f5f7fb", color: mode() === "dark" ? "#e9ecf5" : "#172033", "min-height": "100vh", padding: "32px", "font-family": "Segoe UI, sans-serif" }}>
|
||||||
|
<style>{css}</style>
|
||||||
|
<div style={{ "max-width": compact() ? "360px" : "850px", margin: "0 auto" }}>
|
||||||
|
<header style={{ display: "flex", "align-items": "center", gap: "12px", "margin-bottom": "22px" }}>
|
||||||
|
<h1 style={{ "font-size": "16px", "font-weight": "600", margin: "0 auto 0 0" }}>System Monitor</h1>
|
||||||
|
<button onClick={() => setMode(mode() === "dark" ? "light" : "dark")}>Theme</button>
|
||||||
|
<button onClick={() => setCompact(!compact())}>Layout</button>
|
||||||
|
<button onClick={() => setVisible(!visible())}>{visible() ? "Hide monitor" : "Show monitor"}</button>
|
||||||
|
</header>
|
||||||
|
<Show when={visible()} fallback={<p>Monitoring paused. Open the monitor to resume.</p>}>
|
||||||
|
<Dashboard client={client} mode={mode()} compact={compact()} refreshMs={refreshMs()} setRefreshMs={setRefreshMs} openWindow={() => setCompact(false)} />
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
}
|
||||||
|
render(() => <Preview />, document.getElementById("root")!)
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
import { Rpc } from "@opencode/plugin/rpc"
|
||||||
|
|
||||||
|
export const SystemMonitor = Rpc.define({
|
||||||
|
id: "local-system-monitor",
|
||||||
|
events: {},
|
||||||
|
methods: {
|
||||||
|
snapshot: {
|
||||||
|
input: { type: "object", properties: {}, additionalProperties: false },
|
||||||
|
output: {
|
||||||
|
type: "object",
|
||||||
|
required: ["sampledAt", "hostname", "cpu", "ram", "disks", "gpu"],
|
||||||
|
properties: {
|
||||||
|
sampledAt: { type: "number" }, hostname: { type: "string" },
|
||||||
|
cpu: { type: "object" }, ram: { type: "object" }, disks: { type: "object" }, gpu: { type: "object" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
.sm-root {
|
||||||
|
--sm-text: var(--text-strong, #172033);
|
||||||
|
--sm-muted: var(--text-weak, #7b8496);
|
||||||
|
--sm-secondary: var(--text-base, #536079);
|
||||||
|
--sm-border: var(--border-weak-base, #dfe4ed);
|
||||||
|
--sm-card: var(--surface-raised-base, #fff);
|
||||||
|
--sm-hover: var(--surface-base-hover, #f0f3f8);
|
||||||
|
--sm-track: color-mix(in srgb, var(--sm-muted) 17%, transparent);
|
||||||
|
--sm-blue: #4c93ee;
|
||||||
|
--sm-teal: #27b99a;
|
||||||
|
--sm-purple: #a184f1;
|
||||||
|
--sm-green: #78ad2e;
|
||||||
|
--sm-warning: #d59e35;
|
||||||
|
--sm-critical: #e96576;
|
||||||
|
font-family: inherit;
|
||||||
|
color: var(--sm-text);
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.5;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.sm-root[data-mode="dark"] {
|
||||||
|
--sm-text: var(--text-strong, #e9ecf5);
|
||||||
|
--sm-muted: var(--text-weak, #909bb1);
|
||||||
|
--sm-secondary: var(--text-base, #b3bed6);
|
||||||
|
--sm-border: var(--border-weak-base, #30364a);
|
||||||
|
--sm-card: var(--surface-raised-base, #191c28);
|
||||||
|
--sm-hover: var(--surface-base-hover, #242938);
|
||||||
|
}
|
||||||
|
.sm-root *, .sm-root *::before, .sm-root *::after { box-sizing: border-box; }
|
||||||
|
.sm-dashboard { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||||
|
.sm-root button, .sm-root select { font: inherit; color: var(--sm-secondary); border: 1px solid var(--sm-border); border-radius: 7px; background: var(--sm-hover); min-height: 28px; padding: 3px 9px; cursor: pointer; }
|
||||||
|
.sm-root button { display: inline-flex; align-items: center; justify-content: center; gap: 5px; }
|
||||||
|
.sm-root button:hover, .sm-root select:hover { color: var(--sm-text); border-color: var(--sm-muted); }
|
||||||
|
.sm-root button:focus-visible, .sm-root select:focus-visible { outline: 2px solid var(--sm-blue); outline-offset: 3px; }
|
||||||
|
.sm-root button:disabled { opacity: .45; cursor: wait; }
|
||||||
|
.sm-root select { color-scheme: light; }
|
||||||
|
.sm-root[data-mode="dark"] select { color-scheme: dark; }
|
||||||
|
.sm-toolbar, .sm-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; }
|
||||||
|
.sm-toolbar { justify-content: space-between; gap: 10px; }
|
||||||
|
.sm-live { display: flex; align-items: center; gap: 7px; font-size: 10px; font-weight: 650; text-transform: uppercase; letter-spacing: 1.3px; color: var(--sm-secondary); }
|
||||||
|
.sm-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: var(--sm-green); flex: none; }
|
||||||
|
.sm-live[data-state="paused"] .sm-dot { background: var(--sm-muted); }
|
||||||
|
.sm-live[data-state="error"] .sm-dot { background: var(--sm-critical); }
|
||||||
|
.sm-machine { display: flex; flex-wrap: wrap; align-items: center; gap: 5px 16px; padding: 9px 12px; border: 1px solid var(--sm-border); border-radius: 9px; font-size: 11px; color: var(--sm-muted); }
|
||||||
|
.sm-machine strong { color: var(--sm-secondary); font-weight: 550; }
|
||||||
|
.sm-checked { margin-left: auto; }
|
||||||
|
.sm-cards { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||||
|
.sm-card { border: 1px solid var(--sm-border); border-radius: 13px; background: var(--sm-card); padding: 14px 16px 12px; min-width: 0; box-shadow: inset 0 2px 0 color-mix(in srgb, var(--sm-accent) 30%, transparent); }
|
||||||
|
.sm-cpu { --sm-accent: var(--sm-blue); }
|
||||||
|
.sm-ram { --sm-accent: var(--sm-teal); }
|
||||||
|
.sm-disk { --sm-accent: var(--sm-green); }
|
||||||
|
.sm-gpu { --sm-accent: var(--sm-purple); }
|
||||||
|
.sm-card-head { display: flex; align-items: center; gap: 8px; margin-bottom: 14px; }
|
||||||
|
.sm-icon { color: var(--sm-accent); display: inline-flex; }
|
||||||
|
.sm-card h3 { margin: 0; font-size: 13px; font-weight: 600; letter-spacing: -.1px; }
|
||||||
|
.sm-chip { margin-left: auto; background: var(--sm-hover); color: var(--sm-secondary); border-radius: 99px; padding: 2px 7px; font-size: 10px; white-space: nowrap; }
|
||||||
|
.sm-reading { display: flex; align-items: baseline; gap: 8px; line-height: 1.2; }
|
||||||
|
.sm-reading strong { font-size: 32px; font-weight: 600; letter-spacing: -1.3px; }
|
||||||
|
.sm-reading > span { color: var(--sm-muted); font-size: 12px; }
|
||||||
|
.sm-space strong { font-size: 28px; }
|
||||||
|
.sm-device { font-size: 11px; color: var(--sm-muted); margin: 5px 0 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.sm-bar { height: 7px; overflow: hidden; border-radius: 4px; background: var(--sm-track); }
|
||||||
|
.sm-bar > div { height: 100%; border-radius: inherit; background: var(--sm-accent, var(--sm-blue)); transition: width .35s ease; }
|
||||||
|
.sm-bar[data-level="warning"] > div { background: var(--sm-warning); }
|
||||||
|
.sm-bar[data-level="critical"] > div { background: var(--sm-critical); }
|
||||||
|
.sm-pair { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 4px 8px; font-size: 11px; color: var(--sm-muted); margin-top: 8px; }
|
||||||
|
.sm-pair strong { font-weight: 500; color: var(--sm-secondary); }
|
||||||
|
.sm-trend { margin-top: 12px; color: var(--sm-accent); position: relative; }
|
||||||
|
.sm-trend svg { width: 100%; height: 38px; display: block; }
|
||||||
|
.sm-trend > span { font-size: 9px; color: var(--sm-muted); display: block; text-align: right; margin-top: 4px; }
|
||||||
|
.sm-gridline { stroke: var(--sm-border); stroke-width: .5; stroke-dasharray: 3 4; fill: none; }
|
||||||
|
.sm-disk-note { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; font-size: 11px; color: var(--sm-secondary); margin-top: 22px; }
|
||||||
|
.sm-disk-note > span:last-child { width: 100%; margin-top: 4px; color: var(--sm-muted); font-size: 9px; }
|
||||||
|
.sm-footer { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 14px; color: var(--sm-muted); font-size: 10px; }
|
||||||
|
.sm-footer > span:first-child { display: flex; align-items: center; gap: 6px; }
|
||||||
|
.sm-footer button { margin-left: auto; border: 0; background: transparent; font-size: 11px; padding: 0 3px; min-height: 22px; }
|
||||||
|
.sm-error { color: var(--sm-critical); background: color-mix(in srgb, var(--sm-critical) 9%, transparent); padding: 8px 10px; border-radius: 7px; margin: 0; font-size: 12px; overflow-wrap: anywhere; }
|
||||||
|
.sm-loading { padding: 40px 12px; text-align: center; color: var(--sm-muted); }
|
||||||
|
.sm-details { padding: 14px; border: 1px solid var(--sm-border); border-radius: 9px; font-size: 11px; color: var(--sm-muted); }
|
||||||
|
.sm-details h4 { margin: 0 0 12px; font-size: 12px; font-weight: 550; color: var(--sm-secondary); }
|
||||||
|
.sm-details p { margin: 10px 0 0; }
|
||||||
|
.sm-cores { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px 14px; }
|
||||||
|
.sm-cores > div { display: grid; grid-template-columns: 14px 1fr 28px; align-items: center; gap: 5px; }
|
||||||
|
.sm-cores b { font-size: 10px; font-weight: 400; text-align: right; }
|
||||||
|
.sm-panel { height: 100%; overflow: auto; padding: 14px; }
|
||||||
|
.sm-dashboard[data-compact="true"] .sm-cards { grid-template-columns: 1fr; }
|
||||||
|
.sm-dashboard[data-compact="true"] .sm-machine { gap: 3px 10px; }
|
||||||
|
.sm-dashboard[data-compact="true"] .sm-card { padding: 12px 14px; }
|
||||||
|
.sm-dashboard[data-compact="true"] .sm-card-head { margin-bottom: 10px; }
|
||||||
|
.sm-dashboard[data-compact="true"] .sm-reading strong { font-size: 27px; }
|
||||||
|
.sm-dashboard[data-compact="true"] .sm-trend { display: none; }
|
||||||
|
.sm-dashboard[data-compact="true"] .sm-disk-note { margin-top: 10px; }
|
||||||
|
.sm-dashboard[data-compact="true"] .sm-cores { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||||
|
.sm-status { display: flex; width: 100%; padding: 2px 12px; justify-content: flex-end; min-height: 26px; border-top: 1px solid var(--sm-border); }
|
||||||
|
.sm-status button { display: flex; flex-wrap: wrap; gap: 5px 14px; font-size: 11px; border: 0; padding: 0; background: none; min-height: 21px; }
|
||||||
|
.sm-status-item { display: inline-flex; align-items: center; gap: 5px; }
|
||||||
|
.sm-status-item i { width: 5px; height: 5px; border-radius: 50%; background: var(--sm-accent); }
|
||||||
|
.sm-status-item b { font-weight: 500; color: var(--sm-text); }
|
||||||
|
.sm-status-warning { color: var(--sm-critical); }
|
||||||
|
@media (max-width: 640px) { .sm-cards { grid-template-columns: 1fr; } .sm-cores { grid-template-columns: repeat(2, minmax(0,1fr)); } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .sm-bar > div { transition: none; } }
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
export type Disk = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
total: number
|
||||||
|
used: number
|
||||||
|
free: number
|
||||||
|
percent: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Gpu = {
|
||||||
|
name: string
|
||||||
|
percent: number | null
|
||||||
|
sharedUsed: number | null
|
||||||
|
sharedLimit: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Snapshot = {
|
||||||
|
sampledAt: number
|
||||||
|
hostname: string
|
||||||
|
platform: string
|
||||||
|
uptime: number
|
||||||
|
cpu: { name: string; cores: number; percent: number | null; perCore: (number | null)[] }
|
||||||
|
ram: { total: number; used: number; free: number; percent: number }
|
||||||
|
disks: { sampledAt: number; items: Disk[]; error: string | null }
|
||||||
|
gpu: {
|
||||||
|
sampledAt: number
|
||||||
|
adapter: Gpu | null
|
||||||
|
error: string | null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type HistoryPoint = { at: number; cpu: number | null; ram: number; gpu: number | null }
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// DXGI supplies the exact adapter LUID used by Windows' GPU performance
|
||||||
|
// counters. Device order is NOT a reliable way to distinguish Intel/NVIDIA.
|
||||||
|
export const intelAdapterScript = String.raw`
|
||||||
|
Add-Type -TypeDefinition @'
|
||||||
|
using System;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
public static class MonitorDxgi {
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
public struct Luid { public uint Low; public int High; }
|
||||||
|
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||||
|
public struct Desc {
|
||||||
|
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string Description;
|
||||||
|
public uint VendorId, DeviceId, SubSysId, Revision;
|
||||||
|
public UIntPtr DedicatedVideoMemory, DedicatedSystemMemory, SharedSystemMemory;
|
||||||
|
public Luid AdapterLuid;
|
||||||
|
public uint Flags;
|
||||||
|
}
|
||||||
|
[DllImport("dxgi.dll", CallingConvention = CallingConvention.StdCall)]
|
||||||
|
static extern int CreateDXGIFactory1(ref Guid riid, out IntPtr factory);
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||||
|
delegate int EnumAdapter(IntPtr self, uint index, out IntPtr adapter);
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||||
|
delegate int GetDesc(IntPtr self, out Desc desc);
|
||||||
|
public static Desc Intel() {
|
||||||
|
Guid id = new Guid("770aae78-f26f-4dba-a829-253c83d1b387");
|
||||||
|
IntPtr factory;
|
||||||
|
Marshal.ThrowExceptionForHR(CreateDXGIFactory1(ref id, out factory));
|
||||||
|
try {
|
||||||
|
IntPtr vtable = Marshal.ReadIntPtr(factory);
|
||||||
|
EnumAdapter enumerate = (EnumAdapter)Marshal.GetDelegateForFunctionPointer(
|
||||||
|
Marshal.ReadIntPtr(vtable, 12 * IntPtr.Size), typeof(EnumAdapter));
|
||||||
|
for (uint i = 0; i < 32; i++) {
|
||||||
|
IntPtr adapter;
|
||||||
|
int hr = enumerate(factory, i, out adapter);
|
||||||
|
if (hr == unchecked((int)0x887A0002)) break;
|
||||||
|
Marshal.ThrowExceptionForHR(hr);
|
||||||
|
try {
|
||||||
|
GetDesc read = (GetDesc)Marshal.GetDelegateForFunctionPointer(
|
||||||
|
Marshal.ReadIntPtr(Marshal.ReadIntPtr(adapter), 10 * IntPtr.Size), typeof(GetDesc));
|
||||||
|
Desc desc;
|
||||||
|
Marshal.ThrowExceptionForHR(read(adapter, out desc));
|
||||||
|
if (desc.VendorId == 0x8086 && (desc.Flags & 2) == 0) return desc;
|
||||||
|
} finally { Marshal.Release(adapter); }
|
||||||
|
}
|
||||||
|
throw new Exception("Intel graphics adapter not found");
|
||||||
|
} finally { Marshal.Release(factory); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'@
|
||||||
|
$adapter = [MonitorDxgi]::Intel()
|
||||||
|
[PSCustomObject]@{
|
||||||
|
name = $adapter.Description
|
||||||
|
luid = ('luid_0x{0:X8}_0x{1:X8}' -f $adapter.AdapterLuid.High, $adapter.AdapterLuid.Low)
|
||||||
|
sharedLimit = $adapter.SharedSystemMemory.ToUInt64()
|
||||||
|
} | ConvertTo-Json -Compress
|
||||||
|
`
|
||||||
|
|
||||||
|
export function intelCountersScript(luid: string): string {
|
||||||
|
if (!/^luid_0x[0-9a-f]{8}_0x[0-9a-f]{8}$/i.test(luid)) throw new Error("Invalid GPU adapter identity")
|
||||||
|
return `
|
||||||
|
$engines = @(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine -Filter "Name LIKE '%${luid}%'" | Where-Object { $_.Name -like '*${luid}_phys_*' } | Select-Object Name,UtilizationPercentage)
|
||||||
|
$memory = @(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUAdapterMemory -Filter "Name LIKE '${luid}%'" | Where-Object { $_.Name -like '${luid}_phys_*' } | Select-Object SharedUsage,DedicatedUsage)
|
||||||
|
[PSCustomObject]@{ engines=$engines; memory=$memory } | ConvertTo-Json -Compress -Depth 4
|
||||||
|
`
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import { test } from "node:test"
|
||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { createRoot, createSignal } from "solid-js"
|
||||||
|
import { createMonitorClient } from "../dist/client.js"
|
||||||
|
|
||||||
|
const flush = () => new Promise(resolve => setImmediate(resolve))
|
||||||
|
|
||||||
|
function harness(t, customLoad) {
|
||||||
|
let time = 1_800_000_000_000
|
||||||
|
let sequence = 0
|
||||||
|
let calls = 0
|
||||||
|
const timers = new Map()
|
||||||
|
const addTimer = (callback, ms, repeat) => {
|
||||||
|
const id = ++sequence
|
||||||
|
timers.set(id, { callback, at: time + ms, repeat: repeat ? ms : 0 })
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
t.mock.method(globalThis, "setTimeout", (callback, ms) => addTimer(callback, ms, false))
|
||||||
|
t.mock.method(globalThis, "setInterval", (callback, ms) => addTimer(callback, ms, true))
|
||||||
|
t.mock.method(globalThis, "clearTimeout", id => timers.delete(id))
|
||||||
|
t.mock.method(globalThis, "clearInterval", id => timers.delete(id))
|
||||||
|
t.mock.method(Date, "now", () => time)
|
||||||
|
const original = globalThis.document
|
||||||
|
const page = new EventTarget()
|
||||||
|
page.visibilityState = "visible"
|
||||||
|
globalThis.document = page
|
||||||
|
const sample = () => ({
|
||||||
|
sampledAt: time, hostname: "test", platform: "win32", uptime: 1,
|
||||||
|
cpu: { name: "CPU", cores: 1, percent: 10, perCore: [10] },
|
||||||
|
ram: { total: 100, used: 50, free: 50, percent: 50 },
|
||||||
|
disks: { sampledAt: time, items: [], error: null },
|
||||||
|
gpu: { sampledAt: time, adapter: null, error: null },
|
||||||
|
})
|
||||||
|
const state = createRoot(dispose => {
|
||||||
|
const [visible, setVisible] = createSignal(false)
|
||||||
|
const [interval, setInterval] = createSignal(3000)
|
||||||
|
const client = createMonitorClient(() => {
|
||||||
|
calls++
|
||||||
|
return customLoad ? customLoad(sample) : Promise.resolve(sample())
|
||||||
|
}, interval, visible)
|
||||||
|
return { client, setVisible, setInterval, dispose }
|
||||||
|
})
|
||||||
|
t.after(() => { state.dispose(); globalThis.document = original })
|
||||||
|
return {
|
||||||
|
...state, timers, sample, calls: () => calls,
|
||||||
|
windowVisible(value) {
|
||||||
|
page.visibilityState = value ? "visible" : "hidden"
|
||||||
|
page.dispatchEvent(new Event("visibilitychange"))
|
||||||
|
},
|
||||||
|
async advance(ms) {
|
||||||
|
const target = time + ms
|
||||||
|
for (;;) {
|
||||||
|
const next = [...timers].filter(([, timer]) => timer.at <= target).sort((a, b) => a[1].at - b[1].at)[0]
|
||||||
|
if (!next) break
|
||||||
|
const [id, timer] = next
|
||||||
|
time = timer.at
|
||||||
|
if (timer.repeat) timer.at += timer.repeat
|
||||||
|
else timers.delete(id)
|
||||||
|
timer.callback()
|
||||||
|
await flush()
|
||||||
|
}
|
||||||
|
time = target
|
||||||
|
await flush()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test("No requests or timers until a dashboard opens; closing it stops all polling", async t => {
|
||||||
|
const app = harness(t)
|
||||||
|
await flush()
|
||||||
|
assert.equal(app.calls(), 0)
|
||||||
|
assert.equal(app.timers.size, 0)
|
||||||
|
await app.advance(60_000)
|
||||||
|
await app.client.refresh()
|
||||||
|
assert.equal(app.calls(), 0)
|
||||||
|
|
||||||
|
app.setVisible(true)
|
||||||
|
await flush()
|
||||||
|
assert.equal(app.calls(), 1)
|
||||||
|
assert.equal(app.client.active(), true)
|
||||||
|
await app.advance(3000)
|
||||||
|
assert.equal(app.calls(), 2)
|
||||||
|
app.setVisible(false)
|
||||||
|
assert.equal(app.client.active(), false)
|
||||||
|
assert.equal(app.timers.size, 0)
|
||||||
|
const cached = app.client.snapshot()
|
||||||
|
await app.advance(120_000)
|
||||||
|
assert.equal(app.calls(), 2)
|
||||||
|
assert.equal(app.client.snapshot(), cached)
|
||||||
|
|
||||||
|
app.setVisible(true)
|
||||||
|
await flush()
|
||||||
|
assert.equal(app.calls(), 3)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("Minimizing the window removes timers and showing it resumes only with an open dashboard", async t => {
|
||||||
|
const app = harness(t)
|
||||||
|
app.setVisible(true)
|
||||||
|
await flush()
|
||||||
|
app.windowVisible(false)
|
||||||
|
assert.equal(app.timers.size, 0)
|
||||||
|
await app.advance(30_000)
|
||||||
|
assert.equal(app.calls(), 1)
|
||||||
|
app.windowVisible(true)
|
||||||
|
await flush()
|
||||||
|
assert.equal(app.calls(), 2)
|
||||||
|
app.setVisible(false)
|
||||||
|
app.windowVisible(false)
|
||||||
|
app.windowVisible(true)
|
||||||
|
await app.advance(30_000)
|
||||||
|
assert.equal(app.calls(), 2)
|
||||||
|
assert.equal(app.timers.size, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("A request finishing after closure cannot restart the polling loop", async t => {
|
||||||
|
let resolve
|
||||||
|
const app = harness(t, () => new Promise(done => { resolve = done }))
|
||||||
|
app.setVisible(true)
|
||||||
|
await flush()
|
||||||
|
assert.equal(app.calls(), 1)
|
||||||
|
app.setVisible(false)
|
||||||
|
resolve(app.sample())
|
||||||
|
await flush()
|
||||||
|
assert.equal(app.timers.size, 0)
|
||||||
|
await app.advance(60_000)
|
||||||
|
assert.equal(app.calls(), 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("Pause, refresh-rate changes, manual refresh, and cleanup respect visibility", async t => {
|
||||||
|
const app = harness(t)
|
||||||
|
app.setVisible(true)
|
||||||
|
await flush()
|
||||||
|
app.client.setPaused(true)
|
||||||
|
const before = app.calls()
|
||||||
|
await app.advance(30_000)
|
||||||
|
assert.equal(app.calls(), before)
|
||||||
|
await app.client.refresh()
|
||||||
|
assert.equal(app.calls(), before + 1)
|
||||||
|
app.setInterval(10_000)
|
||||||
|
app.client.setPaused(false)
|
||||||
|
await flush()
|
||||||
|
const resumed = app.calls()
|
||||||
|
await app.advance(9000)
|
||||||
|
assert.equal(app.calls(), resumed)
|
||||||
|
await app.advance(1000)
|
||||||
|
assert.equal(app.calls(), resumed + 1)
|
||||||
|
app.dispose()
|
||||||
|
assert.equal(app.timers.size, 0)
|
||||||
|
app.windowVisible(false)
|
||||||
|
app.windowVisible(true)
|
||||||
|
await app.advance(60_000)
|
||||||
|
assert.equal(app.calls(), resumed + 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("Closing immediately after opening cancels a queued but not started request", async t => {
|
||||||
|
const app = harness(t)
|
||||||
|
app.setVisible(true)
|
||||||
|
app.setVisible(false)
|
||||||
|
await flush()
|
||||||
|
assert.equal(app.calls(), 0)
|
||||||
|
assert.equal(app.timers.size, 0)
|
||||||
|
})
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { test } from "node:test"
|
||||||
|
import assert from "node:assert/strict"
|
||||||
|
import { Monitor, aggregateEngines, cpuUsage } from "../dist/metrics.js"
|
||||||
|
import { intelCountersScript } from "../dist/windows-gpu.js"
|
||||||
|
import { bytes, percent } from "../dist/format.js"
|
||||||
|
|
||||||
|
const intel = "luid_0x00000000_0x000242BD"
|
||||||
|
const nvidia = "luid_0x00000000_0x00024847"
|
||||||
|
const engine = (pid, luid, index, value) => ({
|
||||||
|
Name: `pid_${pid}_${luid}_phys_0_eng_${index}_engtype_3D`,
|
||||||
|
UtilizationPercentage: value,
|
||||||
|
})
|
||||||
|
|
||||||
|
test("Windows engine readings sum processes per engine, never different engines or adapters", () => {
|
||||||
|
assert.equal(aggregateEngines([
|
||||||
|
engine(1, intel, 0, 30), engine(2, intel, 0, 40),
|
||||||
|
engine(1, intel, 1, 55), engine(3, nvidia, 0, 60),
|
||||||
|
]), 70)
|
||||||
|
assert.equal(aggregateEngines([engine(1, intel, 0, 80), engine(2, intel, 0, 40)]), 100)
|
||||||
|
assert.equal(aggregateEngines([]), null)
|
||||||
|
assert.equal(aggregateEngines([{ Name: "invalid", UtilizationPercentage: 99 }]), null)
|
||||||
|
assert.equal(aggregateEngines([engine(1, intel, 0, 0)]), 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("CPU counters handle normal deltas, idle, missing intervals, and counter resets", () => {
|
||||||
|
assert.equal(cpuUsage({ idle: 100, total: 200 }, { idle: 150, total: 400 }), 75)
|
||||||
|
assert.equal(cpuUsage({ idle: 100, total: 200 }, { idle: 200, total: 300 }), 0)
|
||||||
|
assert.equal(cpuUsage({ idle: 100, total: 200 }, { idle: 100, total: 200 }), null)
|
||||||
|
assert.equal(cpuUsage({ idle: 100, total: 200 }, { idle: 10, total: 20 }), null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("Only a DXGI LUID can be inserted in the fixed PowerShell query", () => {
|
||||||
|
assert.match(intelCountersScript(intel), /luid_0x00000000_0x000242BD/)
|
||||||
|
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 () => {
|
||||||
|
let calls = 0
|
||||||
|
const collector = new Monitor(async (file, args) => {
|
||||||
|
calls++
|
||||||
|
assert.match(file, /powershell\.exe$/)
|
||||||
|
const script = Buffer.from(args.at(-1), "base64").toString("utf16le")
|
||||||
|
if (script.includes("Add-Type")) return JSON.stringify({ name: "Intel(R) Graphics", luid: intel, sharedLimit: 16 * 1024 ** 3 })
|
||||||
|
if (script.includes("Win32_LogicalDisk")) return JSON.stringify([{ DeviceID: "C:", VolumeName: "OS", Size: 1000, FreeSpace: 750 }])
|
||||||
|
return JSON.stringify({
|
||||||
|
engines: [engine(1, intel, 0, 12), engine(2, intel, 0, 8), engine(3, nvidia, 0, 99)],
|
||||||
|
memory: [{ SharedUsage: 256 * 1024 ** 2 }],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
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.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") })
|
||||||
|
const snapshot = await collector.snapshot()
|
||||||
|
assert.equal(snapshot.gpu.adapter, null)
|
||||||
|
assert.match(snapshot.gpu.error, /Permission denied/)
|
||||||
|
assert.equal(snapshot.disks.items.length, 0)
|
||||||
|
assert.match(snapshot.disks.error, /Permission denied/)
|
||||||
|
assert.ok(snapshot.ram.total > 0)
|
||||||
|
assert.equal(percent(null), "—")
|
||||||
|
assert.equal(bytes(null), "Unavailable")
|
||||||
|
assert.match(bytes(1024 ** 3), /1 GiB/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
"jsxImportSource": "solid-js",
|
||||||
|
"noEmit": true,
|
||||||
|
"types": ["node", "vite/client"],
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"]
|
||||||
|
},
|
||||||
|
"include": ["src", "vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"noEmit": false,
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src",
|
||||||
|
"declaration": true
|
||||||
|
},
|
||||||
|
"include": ["src/index.ts", "src/rpc.ts", "src/metrics.ts", "src/types.ts", "src/format.ts", "src/client.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { defineConfig } from "vite"
|
||||||
|
import { gui } from "@opencode/plugin/gui/vite"
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [gui()],
|
||||||
|
build: { emptyOutDir: false },
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user