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

+2
View File
@@ -16,6 +16,7 @@ import { join } from "node:path";
import { loadConfig, type Config, type ConfigEnv } from "../config.js";
import { dataDir, daemonSocketPath, daemonTokenPath, runtimeDir, stateDir } from "../core/paths.js";
import type { Logger } from "../core/interfaces.js";
import { createSysinfo } from "../core/sysinfo.js";
import { AuthStore } from "../daemon/auth.js";
import { InMemoryBus } from "../daemon/hub.js";
import { startServer, type ServerDeps, type StartedServer } from "../daemon/server.js";
@@ -144,6 +145,7 @@ export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon
machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"),
startedAt,
now,
sysinfo: createSysinfo({ now }),
...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }),
...(options.server?.ws === undefined ? {} : { ws: options.server.ws }),
};
+301
View File
@@ -0,0 +1,301 @@
/**
* Host sysinfo sampler — CPU / memory / disk with injectable I/O.
* Zero runtime dependencies; no OS calls at import time.
*/
import { statfs as nodeStatfs } from "node:fs/promises";
import * as nodeOs from "node:os";
import { readFile as nodeReadFile } from "node:fs/promises";
import { stateDir } from "./paths.js";
/* ------------------------------------------------------------------ */
/* Public types */
/* ------------------------------------------------------------------ */
export interface CpuTimes {
idle: number;
total: number;
}
export interface StatFsLike {
bsize: number;
blocks: number;
bfree: number;
}
export interface SystemStats {
sampledAt: number;
cpuPercent: number | null;
cpuCores: number;
loadAvg: [number, number, number] | null;
memUsedBytes: number;
memTotalBytes: number;
memPercent: number;
diskPath: string;
diskUsedBytes: number | null;
diskTotalBytes: number | null;
diskPercent: number | null;
}
export interface SysinfoSampler {
sample(): Promise<SystemStats>;
}
export interface SysinfoDeps {
now?: () => number;
readFile?: (path: string) => Promise<string>;
statfs?: (path: string) => Promise<StatFsLike>;
cpus?: () => Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>;
totalmem?: () => number;
freemem?: () => number;
loadavg?: () => number[];
platform?: NodeJS.Platform;
diskPath?: string;
cacheMs?: number;
}
/* ------------------------------------------------------------------ */
/* Pure parsing helpers (exported for tests) */
/* ------------------------------------------------------------------ */
/**
* Parse /proc/meminfo text.
* Tries MemAvailable; falls back to MemFree + Buffers + Cached.
*/
export function parseMeminfo(text: string): { totalBytes: number; availableBytes: number } | null {
const kbOf = (label: string): number | null => {
const m = new RegExp(`^${label}:\\s+(\\d+)\\s+kB`, "m").exec(text);
return m ? Number(m[1]) * 1024 : null;
};
const total = kbOf("MemTotal");
if (total === null) return null;
let available = kbOf("MemAvailable");
if (available === null) {
const free = kbOf("MemFree");
const buffers = kbOf("Buffers") ?? 0;
const cached = kbOf("Cached") ?? 0;
if (free === null) return null;
available = free + buffers + cached;
}
return { totalBytes: total, availableBytes: available };
}
/**
* Parse the aggregate `cpu ` line from /proc/stat.
* Returns cumulative idle and total jiffies.
*/
export function parseProcStat(text: string): CpuTimes | null {
const m = /^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/m.exec(text);
if (!m) return null;
const [, user, nice, sys, idle, iowait, irq, softirq] = m.map(Number);
const idleTime = idle! + iowait!;
const total = user! + nice! + sys! + idle! + iowait! + irq! + softirq!;
return { idle: idleTime, total };
}
/** Aggregate os.cpus() array into CpuTimes. */
export function cpuTimesFromCpus(
cpus: Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>,
): CpuTimes {
let idle = 0;
let total = 0;
for (const cpu of cpus) {
const t = cpu.times;
idle += t.idle;
total += t.user + t.nice + t.sys + t.idle + t.irq;
}
return { idle, total };
}
/**
* Derive CPU busy % from two successive CpuTimes snapshots.
* Returns null on the first sample (prev === null) or when the delta is zero.
*/
export function cpuPercentBetween(prev: CpuTimes | null, next: CpuTimes): number | null {
if (prev === null) return null;
const totalDelta = next.total - prev.total;
if (totalDelta <= 0) return null;
const idleDelta = next.idle - prev.idle;
const busy = 1 - idleDelta / totalDelta;
return Math.min(100, Math.max(0, Math.round(busy * 100)));
}
/**
* Derive disk usage from a statfs result.
* Returns null if blocks is 0 (pseudo-fs like tmpfs without a block count).
*/
export function diskFromStatfs(stats: StatFsLike): { totalBytes: number; usedBytes: number; percent: number } | null {
const { bsize, blocks, bfree } = stats;
if (![bsize, blocks, bfree].every((value) => Number.isFinite(value) && value >= 0)) return null;
if (blocks <= 0 || bsize <= 0) return null;
const totalBytes = blocks * bsize;
if (!Number.isFinite(totalBytes)) return null;
const rawUsedBytes = (blocks - bfree) * bsize;
const usedBytes = Math.min(totalBytes, Math.max(0, Number.isFinite(rawUsedBytes) ? rawUsedBytes : 0));
const percent = Math.min(100, Math.max(0, Math.round((usedBytes / totalBytes) * 100)));
return { totalBytes, usedBytes, percent };
}
/* ------------------------------------------------------------------ */
/* Sampler factory */
/* ------------------------------------------------------------------ */
export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
const now = deps.now ?? Date.now;
const cacheMs = deps.cacheMs ?? 1000;
const platform = deps.platform ?? process.platform;
const diskPath = deps.diskPath ?? stateDir();
// I/O callables — real by default, injectable for tests
const readFile = deps.readFile ?? ((path: string) => nodeReadFile(path, "utf8"));
const statfsImpl = deps.statfs ?? ((path: string) => nodeStatfs(path) as Promise<StatFsLike>);
const cpus = deps.cpus ?? (() => nodeOs.cpus());
const totalmem = deps.totalmem ?? (() => nodeOs.totalmem());
const freemem = deps.freemem ?? (() => nodeOs.freemem());
const loadavg = deps.loadavg ?? (() => nodeOs.loadavg());
let prevCpuTimes: CpuTimes | null = null;
let cachedResult: SystemStats | null = null;
let cachedAt = -Infinity;
let inFlight: Promise<SystemStats> | null = null;
async function doSample(): Promise<SystemStats> {
const sampledAt = now();
// ── CPU ──────────────────────────────────────────────────────
let nextCpuTimes: CpuTimes | null = null;
if (platform === "linux") {
try {
const text = await readFile("/proc/stat");
nextCpuTimes = parseProcStat(text);
} catch {
// fall through to os.cpus()
}
}
if (nextCpuTimes === null) {
try {
nextCpuTimes = cpuTimesFromCpus(cpus());
} catch {
nextCpuTimes = null;
}
}
const cpuPercent = nextCpuTimes !== null ? cpuPercentBetween(prevCpuTimes, nextCpuTimes) : null;
if (nextCpuTimes !== null) prevCpuTimes = nextCpuTimes;
let cpuCores = 1;
try {
cpuCores = Math.max(1, cpus().length);
} catch {
// keep 1
}
// ── loadAvg ──────────────────────────────────────────────────
let loadAvgResult: [number, number, number] | null = null;
if (platform !== "win32") {
try {
const raw = loadavg();
if (raw.length >= 3) {
loadAvgResult = [
Math.round(raw[0]! * 100) / 100,
Math.round(raw[1]! * 100) / 100,
Math.round(raw[2]! * 100) / 100,
];
}
} catch {
loadAvgResult = null;
}
}
// ── Memory ───────────────────────────────────────────────────
let memTotalBytes: number;
let memUsedBytes: number;
let parsed: { totalBytes: number; availableBytes: number } | null = null;
if (platform === "linux") {
try {
const text = await readFile("/proc/meminfo");
parsed = parseMeminfo(text);
} catch {
// fall through to os
}
}
if (parsed !== null && Number.isFinite(parsed.totalBytes) && parsed.totalBytes >= 0 &&
Number.isFinite(parsed.availableBytes) && parsed.availableBytes >= 0) {
memTotalBytes = parsed.totalBytes;
memUsedBytes = parsed.totalBytes - parsed.availableBytes;
} else {
let rawTotal = 0;
let rawFree = 0;
try {
rawTotal = totalmem();
} catch {
// leave the total at zero
}
try {
rawFree = freemem();
} catch {
// leave free memory at zero
}
memTotalBytes = Number.isFinite(rawTotal) && rawTotal >= 0 ? rawTotal : 0;
const freeBytes = Number.isFinite(rawFree) && rawFree >= 0 ? rawFree : 0;
memUsedBytes = memTotalBytes - freeBytes;
}
memUsedBytes = Math.min(memTotalBytes, Math.max(0, Number.isFinite(memUsedBytes) ? memUsedBytes : 0));
const memPercent = memTotalBytes > 0
? Math.min(100, Math.max(0, Math.round((memUsedBytes / memTotalBytes) * 100)))
: 0;
// ── Disk ─────────────────────────────────────────────────────
let diskUsedBytes: number | null = null;
let diskTotalBytes: number | null = null;
let diskPercent: number | null = null;
try {
const sf = await statfsImpl(diskPath);
const result = diskFromStatfs(sf);
if (result !== null) {
diskUsedBytes = result.usedBytes;
diskTotalBytes = result.totalBytes;
diskPercent = result.percent;
}
} catch {
// leave nulls
}
return {
sampledAt,
cpuPercent,
cpuCores,
loadAvg: loadAvgResult,
memUsedBytes,
memTotalBytes,
memPercent,
diskPath,
diskUsedBytes,
diskTotalBytes,
diskPercent,
};
}
return {
async sample(): Promise<SystemStats> {
const t = now();
if (cachedResult !== null && t - cachedAt < cacheMs) {
return cachedResult;
}
if (inFlight) return inFlight;
inFlight = doSample().then(
(result) => {
cachedResult = result;
cachedAt = now();
inFlight = null;
return result;
},
(err) => {
inFlight = null;
// should never throw, but just in case
throw err;
},
);
return inFlight;
},
};
}
+16 -5
View File
@@ -8,6 +8,7 @@ import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/inter
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
import type { Config } from "../config.js";
import type { SysinfoSampler } from "../core/sysinfo.js";
import { networkBases } from "../core/network.js";
import { encodeQr, fitsQr } from "../core/qr.js";
import type { AuthStore, DevicePublic } from "./auth.js";
@@ -39,6 +40,7 @@ export interface AppDeps {
startedAt?: number;
now?: () => number;
metrics?: () => DaemonMetrics;
sysinfo?: SysinfoSampler;
/** Redeem budget; injectable so tests can advance the clock. */
pairLimiter?: PairRateLimiter;
}
@@ -191,8 +193,9 @@ export function createApp(deps: AppDeps): Hono<Env> {
await next();
});
app.get("/api/v1/info", (c) =>
c.json({
app.get("/api/v1/info", async (c) => {
const system = await deps.sysinfo?.sample();
return c.json({
v: PROTOCOL_VERSION,
daemonId: deps.daemonId,
machineId: deps.machineId ?? deps.daemonId,
@@ -207,8 +210,13 @@ export function createApp(deps: AppDeps): Hono<Env> {
limits: config.limits,
host: config.host,
publicUrl: config.publicUrl,
}),
);
cpuCores: system?.cpuCores,
loadAvg: system?.loadAvg ?? null,
...(typeof system?.cpuPercent === "number" ? { cpu: system.cpuPercent } : {}),
...(typeof system?.memPercent === "number" ? { mem: system.memPercent } : {}),
...(typeof system?.diskPercent === "number" ? { disk: system.diskPercent } : {}),
});
});
/**
* Local-browser login handshake: loopback + the local CLI token only.
@@ -324,7 +332,10 @@ export function createApp(deps: AppDeps): Hono<Env> {
return c.body(null, 204);
});
app.get("/api/v1/resources", async (c) => c.json(await instances.resources()));
app.get("/api/v1/resources", async (c) => {
const [snapshot, system] = await Promise.all([instances.resources(), deps.sysinfo?.sample()]);
return c.json(system === undefined ? snapshot : { ...snapshot, system });
});
app.get("/api/v1/diagnostics", (c) => {
const metrics = deps.metrics?.() ?? { connections: 0 };
+1
View File
@@ -102,6 +102,7 @@ export async function startServer(config: Config, deps: ServerDeps): Promise<Sta
startedAt: deps.startedAt,
now: deps.now,
metrics: () => ({ connections: ws.connections(), eventsSent: ws.eventsSent() }),
sysinfo: deps.sysinfo,
});
let closing: Promise<void> | undefined;
+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);