From 9304f98efbd2c16d72402f240e813cd80cd5bcb9 Mon Sep 17 00:00:00 2001 From: Ludo Fourrage Date: Sun, 15 Nov 2026 14:56:33 -0800 Subject: [PATCH] fix(header): the CPU reading shows CPU use, not the load average per core The header's CPU figure was the 1-minute load average divided by the core count, capped at 100. Load counts runnable tasks, not busy time, so a host with bursty processes, or a VM whose vCPU threads count as runnable, read 100% while most cores were idle. It is now busy time across all cores since the previous reading, from os.cpus(), with a one-second minimum window on the monotonic clock. Co-Authored-By: Claude Opus 5.5 --- .changeset/header-cpu-use.md | 5 +++ src/cpu-usage.ts | 52 ++++++++++++++++++++++ src/web/routes/system-routes.ts | 10 +++-- test/cpu-usage.test.ts | 77 +++++++++++++++++++++++++++++++++ 4 files changed, 141 insertions(+), 3 deletions(-) create mode 100644 .changeset/header-cpu-use.md create mode 100644 src/cpu-usage.ts create mode 100644 test/cpu-usage.test.ts diff --git a/.changeset/header-cpu-use.md b/.changeset/header-cpu-use.md new file mode 100644 index 00000000..48ef904b --- /dev/null +++ b/.changeset/header-cpu-use.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +The header CPU reading shows CPU use: busy time across all cores since the previous reading, from `os.cpus()`. It used to show the 1-minute load average divided by the core count, capped at 100, which counts runnable tasks rather than busy time. A host with bursty short-lived processes, or with a VM whose vCPU threads count as runnable, read 100% while most of its cores were idle. Readings under a second apart reuse the last value, so several open browsers share one window. The load-average figure remains only as a fallback for a platform that reports no core times. diff --git a/src/cpu-usage.ts b/src/cpu-usage.ts new file mode 100644 index 00000000..03a8d93a --- /dev/null +++ b/src/cpu-usage.ts @@ -0,0 +1,52 @@ +/** + * @fileoverview The header CPU reading: CPU use over all cores since the previous reading, from each core's + * busy and idle time as `os.cpus()` reports it (the kernel's per-core counters on Linux, macOS and Windows). + * + * It replaces the 1-minute load average divided by the core count. Load counts runnable tasks, not busy time, + * so a host with bursty short-lived processes, or a VM whose vCPU threads count as runnable, read 100% while + * most of its cores were idle. + */ +import type { CpuInfo } from 'node:os'; + +/** Readings closer together than this reuse the last value, so several open browsers never shrink the window. */ +export const CPU_USAGE_MIN_WINDOW_MS = 1000; + +interface CpuTimes { + busy: number; + total: number; + at: number; +} + +/** + * A meter that answers the CPU use, 0 to 100, between this reading and the previous one. Without usable core + * times (none reported, or counters that went backwards, as when a core goes offline) it answers the last + * reading, else `fallback()`. The first reading covers the time since the meter was created. + */ +export function createCpuUsageMeter( + readCores: () => Pick[], + clock: () => number, + fallback: () => number +): () => number { + const sample = (): CpuTimes => { + let busy = 0; + let total = 0; + for (const { times } of readCores()) { + const all = times.user + times.nice + times.sys + times.idle + times.irq; + total += all; + busy += all - times.idle; + } + return { busy, total, at: clock() }; + }; + let base = sample(); + let last: number | undefined; + return () => { + const now = sample(); + if (last !== undefined && now.at - base.at < CPU_USAGE_MIN_WINDOW_MS) return last; + const busy = now.busy - base.busy; + const total = now.total - base.total; + base = now; + if (!(total > 0) || busy < 0) return last ?? fallback(); + last = Math.min(100, Math.max(0, Math.round((busy / total) * 100))); + return last; + }; +} diff --git a/src/web/routes/system-routes.ts b/src/web/routes/system-routes.ts index 560155b1..8b8851c9 100644 --- a/src/web/routes/system-routes.ts +++ b/src/web/routes/system-routes.ts @@ -14,6 +14,7 @@ import { execSync, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { dataPath } from '../../config/instance.js'; import { readHostSensors } from '../../host-sensors.js'; +import { createCpuUsageMeter } from '../../cpu-usage.js'; import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } from '../../types.js'; import { isExplicitlyEnabled, isUnauthenticatedTunnelAcknowledged } from '../network-auth-policy.js'; import { isMultiUserMode } from '../../config/multiuser.js'; @@ -93,6 +94,11 @@ const SCREENSHOTS_DIR = dataPath('screenshots'); /** Cached CPU count — doesn't change at runtime */ const CPU_COUNT = cpus().length; +/** Header CPU use; the 1-minute load average per core only when the platform reports no core times. */ +const cpuUsagePercent = createCpuUsageMeter(cpus, () => performance.now(), () => + Math.min(100, Math.round((loadavg()[0] / CPU_COUNT) * 100)) +); + function parseOptionalNumber(value: string | undefined): number | undefined { if (value === undefined || value.trim() === '') return undefined; const parsed = Number(value); @@ -125,9 +131,7 @@ function getSystemStats(): { usedMem = totalMem - freemem(); } - // CPU load average (1 min) as percentage (rough approximation) - const load = loadavg()[0]; - const cpuPercent = Math.min(100, Math.round((load / CPU_COUNT) * 100)); + const cpuPercent = cpuUsagePercent(); return { cpu: cpuPercent, diff --git a/test/cpu-usage.test.ts b/test/cpu-usage.test.ts new file mode 100644 index 00000000..e6818663 --- /dev/null +++ b/test/cpu-usage.test.ts @@ -0,0 +1,77 @@ +/** + * @fileoverview The header CPU reading's meter: busy time over all cores between readings, the minimum window + * that keeps several browsers from shrinking it, and the fallback when no usable core times exist. + */ +import { describe, expect, it } from 'vitest'; +import { createCpuUsageMeter } from '../src/cpu-usage.js'; + +const core = (busy: number, idle: number) => ({ times: { user: busy, nice: 0, sys: 0, idle, irq: 0 } }); + +function meterOver(samples: ReturnType[][], fallback = () => 999) { + let at = 0; + let index = 0; + const meter = createCpuUsageMeter( + () => samples[Math.min(index, samples.length - 1)], + () => at, + fallback + ); + return (ms: number) => { + at += ms; + index += 1; + return meter(); + }; +} + +describe('createCpuUsageMeter', () => { + it('reports busy time over all cores between readings', () => { + const next = meterOver([ + [core(0, 0), core(0, 0)], + [core(50, 50), core(50, 50)], + [core(150, 50), core(50, 150)], + ]); + expect(next(2000)).toBe(50); + expect(next(2000)).toBe(50); + }); + + it('counts nice, system and interrupt time as busy', () => { + const times = (user: number, nice: number, sys: number, irq: number, idle: number) => ({ + times: { user, nice, sys, idle, irq }, + }); + const meter = createCpuUsageMeter( + (() => { + let calls = 0; + return () => [calls++ === 0 ? times(0, 0, 0, 0, 0) : times(10, 20, 30, 15, 25)]; + })(), + (() => { + let at = 0; + return () => (at += 2000); + })(), + () => 999 + ); + expect(meter()).toBe(75); + }); + + it('reads idle cores as idle however long the run queue is', () => { + expect(meterOver([[core(0, 0)], [core(40, 60)]])(5000)).toBe(40); + }); + + it('reuses the last value for readings under a second apart and keeps the baseline', () => { + const next = meterOver([[core(0, 0)], [core(30, 70)], [core(30, 170)], [core(130, 170)]]); + expect(next(2000)).toBe(30); + expect(next(200)).toBe(30); + expect(next(2000)).toBe(50); + }); + + it('falls back without a bogus reading when there are no core times or the counters go backwards', () => { + expect(meterOver([[], []], () => 7)(2000)).toBe(7); + const next = meterOver([[core(100, 100)], [core(10, 10)], [core(60, 60)]], () => 7); + expect(next(2000)).toBe(7); + expect(next(2000)).toBe(50); + }); + + it('answers a whole number from 0 to 100', () => { + expect(meterOver([[core(0, 0)], [core(2, 1)]])(2000)).toBe(67); + expect(meterOver([[core(0, 0)], [core(0, 9)]])(2000)).toBe(0); + expect(meterOver([[core(0, 0)], [core(9, 0)]])(2000)).toBe(100); + }); +});