Merge #824: the header CPU reading shows CPU use, not the load average per core

Busy time across all cores, sampled over a window of at least a second (#823).
This commit is contained in:
Codeman maintainer committed 2026-11-20 03:59:10 +01:00
commit c31e4fc716
4 files changed
+141 -3

No files matched your search

+5
View File
@@ -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.
+52
View File
@@ -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<CpuInfo, 'times'>[],
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;
};
}
+7 -3
View File
@@ -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,
+77
View File
@@ -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<typeof core>[][], 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);
});
});