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:
David Meincke
2026-11-20 13:35:00 +01:00
commit 7ab4e9fd0b
26 changed files with 6862 additions and 0 deletions
+80
View File
@@ -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>
+123
View File
@@ -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>
}
+39
View File
@@ -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
View File
@@ -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>,
})
},
})
+45
View File
@@ -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
View File
@@ -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()
+32
View File
@@ -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
View File
@@ -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
View File
@@ -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; } }
+32
View File
@@ -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 }
+65
View File
@@ -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
`
}