feat(daemon): sample host cpu, memory and disk for /info and /resources

The status page had no host figures: `/api/v1/info` only carried identity and
`/api/v1/resources` only carried instance RSS, so the CPU/mem/disk tiles fell
back to "—" and the memory tile faked its percentage from RSS over physical
memory.

src/core/sysinfo.ts is a zero-dependency sampler: CPU from the /proc/stat delta
(null on the first read, since it needs two samples), load average from
os.loadavg(), memory from os.freemem/os.totalmem, and disk via statfs on the
daemon's state dir. One sample is cached for ~1 s and shared between /info and
/resources, so polling both does not double the syscalls. /info gains additive
`cpu`, `mem`, `disk` percentages plus `cpuCores` and `loadAvg`; /resources gains
a `system` object with the byte counts, the disk path and `sampledAt`.

Every field is optional on the client side: an older daemon simply omits them.
This commit is contained in:
yuez committed 2026-10-28 08:13:58 +08:00
1 parent 1664227c3b
commit 88354ec078
7 files changed
+492 -5

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
import { describe, expect, it } from "vitest";
import {
cpuPercentBetween,
cpuTimesFromCpus,
createSysinfo,
diskFromStatfs,
parseMeminfo,
parseProcStat,
} from "../../src/core/sysinfo.js";
const mem = (available = "MemAvailable: 512 kB") => `MemTotal: 1024 kB\n${available}\nMemFree: 128 kB\nBuffers: 64 kB\nCached: 128 kB\n`;
const cpus = (user: number, idle: number) => [{ times: { user, nice: 0, sys: 0, idle, irq: 0 } }];
describe("sysinfo", () => {
it("parses meminfo using MemAvailable and fallback fields", () => {
expect(parseMeminfo(mem())).toEqual({ totalBytes: 1024 * 1024, availableBytes: 512 * 1024 });
expect(parseMeminfo(mem("MemFree: 128 kB"))).toEqual({ totalBytes: 1024 * 1024, availableBytes: 320 * 1024 });
expect(parseMeminfo("MemAvailable: 1 kB")).toBeNull();
});
it("parses proc stat and aggregates cpu times", () => {
expect(parseProcStat("cpu 10 2 3 40 5 6 7\ncpu0 1 0 0 1 0 0 0\n")).toEqual({ idle: 45, total: 73 });
expect(cpuTimesFromCpus(cpus(10, 40))).toEqual({ idle: 40, total: 50 });
});
it("calculates bounded CPU percentages", () => {
expect(cpuPercentBetween(null, { idle: 1, total: 2 })).toBeNull();
expect(cpuPercentBetween({ idle: 1, total: 2 }, { idle: 1, total: 2 })).toBeNull();
expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 5, total: 10 })).toBeNull();
expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 15, total: 30 })).toBe(50);
expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 0, total: 30 })).toBe(100);
expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 30, total: 30 })).toBe(0);
});
it("calculates disk usage and handles null cases", () => {
expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: 4 })).toEqual({ totalBytes: 1000, usedBytes: 600, percent: 60 });
expect(diskFromStatfs({ bsize: 100, blocks: 0, bfree: 0 })).toBeNull();
expect(diskFromStatfs({ bsize: 0, blocks: 10, bfree: 0 })).toBeNull();
expect(diskFromStatfs({ bsize: Number.NaN, blocks: 10, bfree: 0 })).toBeNull();
expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: 20 })).toEqual({
totalBytes: 1000,
usedBytes: 0,
percent: 0,
});
expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: -1 })).toBeNull();
});
it("clamps malformed memory sampler values", async () => {
const result = await createSysinfo({
now: () => 1,
platform: "darwin",
cpus: () => cpus(10, 10),
totalmem: () => Number.NaN,
freemem: () => Number.POSITIVE_INFINITY,
loadavg: () => [0, 0, 0],
statfs: async () => ({ bsize: 100, blocks: 10, bfree: 20 }),
}).sample();
expect(result.memTotalBytes).toBe(0);
expect(result.memUsedBytes).toBe(0);
expect(result.memPercent).toBe(0);
expect(result.diskPercent).toBe(0);
});
it("samples injected system data, caches, and expires", async () => {
let clock = 1000;
let reads = 0;
let stats = 0;
const sampler = createSysinfo({
now: () => clock,
platform: "linux",
diskPath: "/test",
readFile: async (path) => { reads++; return path === "/proc/stat" ? "cpu 10 0 0 10 0 0 0" : mem(); },
statfs: async () => { stats++; return { bsize: 100, blocks: 10, bfree: 4 }; },
cpus: () => cpus(10, 10),
totalmem: () => 999,
freemem: () => 1,
loadavg: () => [1.234, 2.345, 3.456],
cacheMs: 100,
});
const first = await sampler.sample();
expect(first).toEqual({ sampledAt: 1000, cpuPercent: null, cpuCores: 1, loadAvg: [1.23, 2.35, 3.46], memUsedBytes: 512 * 1024, memTotalBytes: 1024 * 1024, memPercent: 50, diskPath: "/test", diskUsedBytes: 600, diskTotalBytes: 1000, diskPercent: 60 });
await sampler.sample();
expect(reads).toBe(2);
expect(stats).toBe(1);
clock = 1100;
await sampler.sample();
expect(reads).toBe(4);
expect(stats).toBe(2);
});
it("resolves when total memory probing throws", async () => {
const sampler = createSysinfo({
platform: "darwin",
cpus: () => cpus(1, 1),
totalmem: () => { throw new Error("totalmem unavailable"); },
freemem: () => 25,
statfs: async () => ({ bsize: 1, blocks: 1, bfree: 0 }),
loadavg: () => [0, 0, 0],
});
await expect(sampler.sample()).resolves.toMatchObject({ memTotalBytes: 0, memUsedBytes: 0, memPercent: 0 });
});
it("falls back and resolves I/O failures with null CPU and disk", async () => {
const result = await createSysinfo({
now: () => 1,
platform: "linux",
readFile: async () => { throw new Error("read"); },
statfs: async () => { throw new Error("statfs"); },
cpus: () => { throw new Error("cpu"); },
totalmem: () => 0,
freemem: () => 0,
loadavg: () => { throw new Error("load"); },
}).sample();
expect(result.cpuPercent).toBeNull();
expect(result.loadAvg).toBeNull();
expect(result.diskUsedBytes).toBeNull();
expect(result.diskTotalBytes).toBeNull();
expect(result.diskPercent).toBeNull();
expect(result.memTotalBytes).toBe(0);
expect(result.memUsedBytes).toBe(0);
});
});
+24
View File
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { AuthStore } from "../../src/daemon/auth.js";
import { startServer, type StartedServer } from "../../src/daemon/server.js";
import type { Config, Limits } from "../../src/config.js";
import type { SysinfoSampler, SystemStats } from "../../src/core/sysinfo.js";
import type { WorkspaceInfo } from "../../src/protocol/types.js";
import { FakeBus, FakeInstanceManager, FakeWorkspaceStore } from "./fakes.js";
@@ -31,6 +32,26 @@ export function testConfig(overrides: Partial<Config> = {}): Config {
return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } };
}
/** Deterministic fake sampler returned when no override is provided. */
export const FAKE_SYSTEM_STATS: SystemStats = {
sampledAt: 1_700_000_000_000,
cpuPercent: 42,
cpuCores: 4,
loadAvg: [1.5, 1.2, 0.9],
memUsedBytes: 4 * 1024 ** 3,
memTotalBytes: 16 * 1024 ** 3,
memPercent: 25,
diskPath: "/tmp/pi2-test",
diskUsedBytes: 50 * 1024 ** 3,
diskTotalBytes: 200 * 1024 ** 3,
diskPercent: 25,
};
export function makeFakeSysinfoSampler(stats: Partial<SystemStats> = {}): SysinfoSampler {
const merged: SystemStats = { ...FAKE_SYSTEM_STATS, ...stats };
return { sample: async () => merged };
}
export interface HarnessOptions {
workspaces?: WorkspaceInfo[];
seedInstances?: string[];
@@ -45,6 +66,8 @@ export interface HarnessOptions {
snapshotWaitMs?: number;
measureBufferedAmount?: (socket: unknown) => number;
};
/** Override the sysinfo sampler; defaults to a deterministic fake (no real OS I/O). */
sysinfo?: SysinfoSampler;
}
export interface Harness {
@@ -107,6 +130,7 @@ export async function createHarness(options: HarnessOptions = {}): Promise<Harne
startedAt: Date.now(),
heartbeatMs: options.heartbeatMs,
ws: options.wsOverrides,
sysinfo: options.sysinfo ?? makeFakeSysinfoSampler(),
});
return {
+26
View File
@@ -425,6 +425,32 @@ describe("HTTP API", () => {
expect(res.status).toBe(401);
});
it("includes injected system stats in resources", async () => {
const custom = await createHarness({ sysinfo: (await import("./harness.js")).makeFakeSysinfoSampler({ cpuPercent: 42 }) });
try {
const customToken = custom.createToken();
const response = await fetch(`${custom.url}/api/v1/resources`, {
headers: { Authorization: `Bearer ${customToken}` },
});
expect(response.status).toBe(200);
expect((await response.json()).system).toEqual(expect.objectContaining({ cpuPercent: 42 }));
} finally {
await custom.cleanup();
}
});
it("includes system stats in info", async () => {
const response = await fetch(`${h.url}/api/v1/info`);
expect(response.status).toBe(200);
expect(await response.json()).toEqual(expect.objectContaining({
cpuCores: 4,
loadAvg: [1.5, 1.2, 0.9],
cpu: 42,
mem: 25,
disk: 25,
}));
});
it("redirects a scanned /pair/<code> link to the zero-input connect page", async () => {
const res = await fetch(`${h.url}/pair/abcd2345`, { redirect: "manual" });
expect(res.status).toBe(302);