fix(daemon): sample disk usage on the filesystems pi2d uses

The status tile read `—` on a fresh machine: the sampler ran `statfs` on the
daemon's state dir, which is created lazily on the first instance log, so the
call failed with ENOENT and `diskUsedBytes`/`diskTotalBytes`/`diskPercent` all
came back null — `/info` then dropped `disk` altogether and the failure was
indistinguishable from a full disk.

`probeMount()` now walks up to the nearest existing ancestor and then to the
filesystem boundary (`st_dev` change), so a sample describes a volume, not a
directory. Candidates are pi2d's own write targets — `/` (the home volume on
macOS, where `/` is the sealed read-only system volume), the pi session store
and the visible workspace roots — never a mount-table dump: an unrelated or
hung network mount must not stall the sampler. Rows are deduped by `st_dev`,
sorted most-constrained first, capped at four, and reported as `system.disks[]`
with the legacy scalars aliasing the worst row. A sample that yields nothing
now carries `diskError` instead of silent nulls.

The status tile shows the worst filesystem and, when several are in play, one
quiet row per mount instead of a single percentage that hides the full volume.
This commit is contained in:
yuez committed 2026-10-30 16:17:43 +08:00
1 parent 1d907c08fa
commit 01fd7b9922
9 files changed
+474 -31

No files matched your search

+10 -3
View File
@@ -93,7 +93,7 @@ Plugin obligations:
| Endpoint | Notes | | Endpoint | Notes |
|---|---| |---|---|
| `GET /api/v1/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}`; additive `cpu`, `mem`, `disk` (integer percent, each omitted when unknown), `cpuCores`, `loadAvg` | | `GET /api/v1/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}`; additive `cpu`, `mem`, `disk` (integer percent of the **most constrained** filesystem, each omitted when unknown), `cpuCores`, `loadAvg` |
| `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` | | `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` |
| `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) | | `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) |
| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) | | `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) |
@@ -127,8 +127,15 @@ figures sampled by the daemon itself:
| `cpuCores` | logical core count | | `cpuCores` | logical core count |
| `loadAvg` | 3-tuple `[1m, 5m, 15m]`, or `null` where the OS has no load average | | `loadAvg` | 3-tuple `[1m, 5m, 15m]`, or `null` where the OS has no load average |
| `memUsedBytes`, `memTotalBytes`, `memPercent` | **host** memory; `memPercent` is an integer. `totalRssBytes` stays the soft-limit input — it is instance RSS, not a host figure | | `memUsedBytes`, `memTotalBytes`, `memPercent` | **host** memory; `memPercent` is an integer. `totalRssBytes` stays the soft-limit input — it is instance RSS, not a host figure |
| `diskPath` | the filesystem the sample describes: the daemon's state dir | | `diskPath` | mount point of the most constrained filesystem (`disks[0]`), e.g. `/` or `/home`; the legacy scalar fields below alias that row |
| `diskUsedBytes`, `diskTotalBytes`, `diskPercent` | `diskPercent` integer, nullable; the byte counts are `null` when the stat fails | | `disks` | `DiskUsage[]`, at most 4, **most constrained first**. One row per distinct filesystem (`st_dev`) among the daemon's own write targets: `/` (the home volume on macOS), the pi session store and the visible (non-`secondary`) workspace roots. Not a mount-table dump — an unrelated or hung network mount is never touched |
| `disks[].mountPoint`, `disks[].fsType?`, `disks[].totalBytes`, `disks[].usedBytes`, `disks[].percent` | `mountPoint` is the filesystem boundary (never the sampled path), `fsType` a best-effort label (`ext4`, `btrfs`, …) omitted when unknown, `percent` an integer 0–100 |
| `diskUsedBytes`, `diskTotalBytes`, `diskPercent` | the worst row, for clients that predate `disks`; `null` when nothing could be sampled |
| `diskError` | present **only** when `disks` is empty — `"<path>: <code>"`, so a failed sample is distinguishable from a full disk instead of silently rendering `—` |
A candidate path that does not exist yet (the state dir is created lazily) no longer
blanks the sample: the probe walks up to the nearest existing ancestor and then to the
filesystem boundary, so `diskPercent` describes the volume, not a directory.
`GET /api/v1/models` no longer requires `workspaceId`. With one, the read is `GET /api/v1/models` no longer requires `workspaceId`. With one, the read is
relayed as before and may spawn that workspace's instance — the chat picker's relayed as before and may spawn that workspace's instance — the chat picker's
+12 -1
View File
@@ -145,7 +145,18 @@ export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon
machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"), machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"),
startedAt, startedAt,
now, now,
sysinfo: createSysinfo({ now }), sysinfo: createSysinfo({
now,
// Only the filesystems pi2d actually writes to: root, the pi session
// store (built in) and the visible workspace roots. Hidden/secondary
// rows are excluded so a stale ghost dir never adds a disk row.
diskPaths: () =>
(workspaceStore?.list() ?? [])
.filter((workspace) => workspace.exists && workspace.visibility !== "secondary")
.sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0))
.slice(0, 8)
.map((workspace) => workspace.cwd),
}),
...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }), ...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }),
...(options.server?.ws === undefined ? {} : { ws: options.server.ws }), ...(options.server?.ws === undefined ? {} : { ws: options.server.ws }),
}; };
+200 -18
View File
@@ -2,10 +2,11 @@
* Host sysinfo sampler — CPU / memory / disk with injectable I/O. * Host sysinfo sampler — CPU / memory / disk with injectable I/O.
* Zero runtime dependencies; no OS calls at import time. * Zero runtime dependencies; no OS calls at import time.
*/ */
import { statfs as nodeStatfs } from "node:fs/promises"; import { stat as nodeStat, statfs as nodeStatfs } from "node:fs/promises";
import * as nodeOs from "node:os"; import * as nodeOs from "node:os";
import { readFile as nodeReadFile } from "node:fs/promises"; import { readFile as nodeReadFile } from "node:fs/promises";
import { stateDir } from "./paths.js"; import { dirname, resolve as resolvePath } from "node:path";
import { IS_MAC, sessionsRoot, stateDir } from "./paths.js";
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Public types */ /* Public types */
@@ -20,6 +21,27 @@ export interface StatFsLike {
bsize: number; bsize: number;
blocks: number; blocks: number;
bfree: number; bfree: number;
/** Linux filesystem magic (`f_type`); used for the best-effort `fsType` label. */
type?: number;
}
/** The slice of `fs.Stats` the mount probe needs. */
export interface StatLike {
dev: number | bigint;
}
/**
* One sampled filesystem. `mountPoint` is the boundary the probe found by
* walking up while `st_dev` stayed the same — never the raw candidate path,
* which is usually a deep, user-irrelevant directory.
*/
export interface DiskUsage {
mountPoint: string;
/** Best-effort type label (`ext4`, `btrfs`, …); absent when unknown. */
fsType?: string;
totalBytes: number;
usedBytes: number;
percent: number;
} }
export interface SystemStats { export interface SystemStats {
@@ -30,10 +52,15 @@ export interface SystemStats {
memUsedBytes: number; memUsedBytes: number;
memTotalBytes: number; memTotalBytes: number;
memPercent: number; memPercent: number;
/** Mount point of the most constrained disk (`disks[0]`); legacy scalar fields alias it. */
diskPath: string; diskPath: string;
diskUsedBytes: number | null; diskUsedBytes: number | null;
diskTotalBytes: number | null; diskTotalBytes: number | null;
diskPercent: number | null; diskPercent: number | null;
/** At most `maxDisks` filesystems, most constrained first. */
disks: DiskUsage[];
/** Why no filesystem could be sampled; absent when `disks` is non-empty. */
diskError?: string;
} }
export interface SysinfoSampler { export interface SysinfoSampler {
@@ -49,7 +76,16 @@ export interface SysinfoDeps {
freemem?: () => number; freemem?: () => number;
loadavg?: () => number[]; loadavg?: () => number[];
platform?: NodeJS.Platform; platform?: NodeJS.Platform;
/** Primary disk candidate; defaults to `/` (the home volume on macOS). */
diskPath?: string; diskPath?: string;
/** Where pi keeps its sessions; sampled as a second candidate. Defaults to `sessionsRoot()`. */
sessionsPath?: string;
/** Extra candidates sampled per request (e.g. the visible workspace roots). */
diskPaths?: () => string[];
/** Whether two paths share a filesystem; injectable so tests never touch the disk. */
stat?: (path: string) => Promise<StatLike>;
/** How many filesystems to report; defaults to 4. */
maxDisks?: number;
cacheMs?: number; cacheMs?: number;
} }
@@ -120,6 +156,91 @@ export function cpuPercentBetween(prev: CpuTimes | null, next: CpuTimes): number
return Math.min(100, Math.max(0, Math.round(busy * 100))); return Math.min(100, Math.max(0, Math.round(busy * 100)));
} }
/** Linux `f_type` magics → a short label. Best effort: unknown magics stay unlabelled. */
const FS_MAGIC: Readonly<Record<number, string>> = {
0x01_02_19_94: "tmpfs",
0x2f_c1_2f_c1: "zfs",
0x41_50_46_53: "apfs",
0x4d_44: "vfat",
0x69_69: "nfs",
0x96_60: "iso9660",
0xef_53: "ext4",
0x20_11_ba_b0: "exfat",
0x53_46_54_4e: "ntfs",
0x58_46_53_42: "xfs",
0x73_71_73_68: "squashfs",
0x79_4c_76_30: "overlay",
0x91_23_68_3e: "btrfs",
0xf2_f5_20_10: "f2fs",
0xff_53_4d_42: "cifs",
};
/** Best-effort filesystem label from a `statfs.type` magic number. */
export function fsTypeFromMagic(magic: number | undefined): string | undefined {
if (magic === undefined || !Number.isFinite(magic)) return undefined;
return FS_MAGIC[magic];
}
export interface MountProbe {
/** Deepest existing ancestor of the candidate (what `statfs` may be called on). */
path: string;
/** Filesystem boundary above `path`; the user-facing label. */
mountPoint: string;
/** `st_dev` identity, stringified — the dedupe key. */
dev: string;
}
/**
* Resolve a candidate path to the filesystem that backs it.
*
* 1. Walk up until `stat` succeeds — `statfs` fails with `ENOENT` on a directory
* that does not exist yet (pi2d's state dir is created lazily), which used to
* null out the whole disk tile.
* 2. Keep walking up while the parent reports the same `st_dev`; the last dir
* that shares it is the mount point.
*
* Returns `null` when no ancestor exists (the path is on an unmounted tree).
*/
export async function probeMount(
candidate: string,
stat: (path: string) => Promise<StatLike>,
): Promise<MountProbe | null> {
let path = resolvePath(candidate);
let dev: string | null = null;
for (;;) {
try {
dev = String((await stat(path)).dev);
break;
} catch {
const parent = dirname(path);
if (parent === path) return null;
path = parent;
}
}
let mountPoint = path;
for (;;) {
const parent = dirname(mountPoint);
if (parent === mountPoint) break;
try {
if (String((await stat(parent)).dev) !== dev) break;
} catch {
break;
}
mountPoint = parent;
}
return { path, mountPoint, dev };
}
function describeError(path: string, err: unknown): string {
const code =
typeof err === "object" && err !== null && "code" in err
? String((err as { code?: unknown }).code)
: err instanceof Error
? err.message
: String(err);
return `${path}: ${code}`;
}
/** /**
* Derive disk usage from a statfs result. * Derive disk usage from a statfs result.
* Returns null if blocks is 0 (pseudo-fs like tmpfs without a block count). * Returns null if blocks is 0 (pseudo-fs like tmpfs without a block count).
@@ -144,16 +265,83 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
const now = deps.now ?? Date.now; const now = deps.now ?? Date.now;
const cacheMs = deps.cacheMs ?? 1000; const cacheMs = deps.cacheMs ?? 1000;
const platform = deps.platform ?? process.platform; const platform = deps.platform ?? process.platform;
const diskPath = deps.diskPath ?? stateDir(); // `/` on macOS is the sealed read-only system volume, which reports ~100%
// used forever; the home volume is the honest "system disk" answer there.
const diskPath = deps.diskPath ?? (platform === "darwin" ? nodeOs.homedir() : platform === "win32" ? stateDir() : "/");
const maxDisks = Math.max(1, deps.maxDisks ?? 4);
const sessionsPath = deps.sessionsPath ?? sessionsRoot();
const extraDiskPaths = deps.diskPaths ?? (() => []);
// I/O callables — real by default, injectable for tests // I/O callables — real by default, injectable for tests
const readFile = deps.readFile ?? ((path: string) => nodeReadFile(path, "utf8")); const readFile = deps.readFile ?? ((path: string) => nodeReadFile(path, "utf8"));
const statfsImpl = deps.statfs ?? ((path: string) => nodeStatfs(path) as Promise<StatFsLike>); const statfsImpl = deps.statfs ?? ((path: string) => nodeStatfs(path) as Promise<StatFsLike>);
const statImpl = deps.stat ?? ((path: string) => nodeStat(path) as Promise<StatLike>);
const cpus = deps.cpus ?? (() => nodeOs.cpus()); const cpus = deps.cpus ?? (() => nodeOs.cpus());
const totalmem = deps.totalmem ?? (() => nodeOs.totalmem()); const totalmem = deps.totalmem ?? (() => nodeOs.totalmem());
const freemem = deps.freemem ?? (() => nodeOs.freemem()); const freemem = deps.freemem ?? (() => nodeOs.freemem());
const loadavg = deps.loadavg ?? (() => nodeOs.loadavg()); const loadavg = deps.loadavg ?? (() => nodeOs.loadavg());
/**
* Sample one row per distinct filesystem. Candidates are pi2d's own write
* targets (root, the pi session store, the visible workspace roots), never
* an enumeration of `/proc/mounts`: `statfs` on an unrelated, hung network
* mount would otherwise stall the whole sample.
*/
async function sampleDisks(): Promise<{ disks: DiskUsage[]; error?: string }> {
const extra = (() => {
try {
return extraDiskPaths();
} catch {
return [];
}
})();
const candidates = [diskPath, sessionsPath, ...extra]
.filter((path, index, all) => typeof path === "string" && path !== "" && all.indexOf(path) === index)
.slice(0, maxDisks * 2);
const probes = new Map<string, MountProbe>();
const failures: string[] = [];
for (const candidate of candidates) {
try {
const probe = await probeMount(candidate, statImpl);
if (probe === null) {
failures.push(`${candidate}: no existing ancestor`);
continue;
}
// Same `st_dev` ⇒ same filesystem ⇒ same row, whatever the path.
if (!probes.has(probe.dev)) probes.set(probe.dev, probe);
} catch (err) {
failures.push(describeError(candidate, err));
}
}
const disks: DiskUsage[] = [];
for (const probe of probes.values()) {
try {
const sf = await statfsImpl(probe.mountPoint);
const usage = diskFromStatfs(sf);
if (usage === null) {
failures.push(`${probe.mountPoint}: no block count`);
continue;
}
const fsType = fsTypeFromMagic(sf.type);
disks.push({
mountPoint: probe.mountPoint,
...(fsType === undefined ? {} : { fsType }),
...usage,
});
} catch (err) {
failures.push(describeError(probe.mountPoint, err));
}
}
// Worst first: the tile's headline number is the disk closest to full.
disks.sort((a, b) => b.percent - a.percent || b.totalBytes - a.totalBytes);
const capped = disks.slice(0, maxDisks);
if (capped.length > 0) return { disks: capped };
return { disks: [], error: failures[0] ?? "no filesystem could be sampled" };
}
let prevCpuTimes: CpuTimes | null = null; let prevCpuTimes: CpuTimes | null = null;
let cachedResult: SystemStats | null = null; let cachedResult: SystemStats | null = null;
let cachedAt = -Infinity; let cachedAt = -Infinity;
@@ -245,20 +433,12 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
: 0; : 0;
// ── Disk ───────────────────────────────────────────────────── // ── Disk ─────────────────────────────────────────────────────
let diskUsedBytes: number | null = null; const sampled = await sampleDisks();
let diskTotalBytes: number | null = null; const worst = sampled.disks[0];
let diskPercent: number | null = null; const diskUsedBytes = worst?.usedBytes ?? null;
try { const diskTotalBytes = worst?.totalBytes ?? null;
const sf = await statfsImpl(diskPath); const diskPercent = worst?.percent ?? null;
const result = diskFromStatfs(sf); const diskMount = worst?.mountPoint ?? diskPath;
if (result !== null) {
diskUsedBytes = result.usedBytes;
diskTotalBytes = result.totalBytes;
diskPercent = result.percent;
}
} catch {
// leave nulls
}
return { return {
sampledAt, sampledAt,
@@ -268,10 +448,12 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
memUsedBytes, memUsedBytes,
memTotalBytes, memTotalBytes,
memPercent, memPercent,
diskPath, diskPath: diskMount,
diskUsedBytes, diskUsedBytes,
diskTotalBytes, diskTotalBytes,
diskPercent, diskPercent,
disks: sampled.disks,
...(sampled.error === undefined ? {} : { diskError: sampled.error }),
}; };
} }
+126 -4
View File
@@ -4,13 +4,29 @@ import {
cpuTimesFromCpus, cpuTimesFromCpus,
createSysinfo, createSysinfo,
diskFromStatfs, diskFromStatfs,
fsTypeFromMagic,
parseMeminfo, parseMeminfo,
parseProcStat, parseProcStat,
probeMount,
} from "../../src/core/sysinfo.js"; } 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 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 } }]; const cpus = (user: number, idle: number) => [{ times: { user, nice: 0, sys: 0, idle, irq: 0 } }];
/** `path -> st_dev` fake: anything absent throws ENOENT, like a real stat. */
type FsTree = Record<string, number | bigint>;
function fakeStat(tree: FsTree) {
return async (path: string) => {
const dev = tree[path];
if (dev === undefined) throw Object.assign(new Error(`ENOENT: ${path}`), { code: "ENOENT" });
return { dev };
};
}
/** Every sampler call below injects `stat`+`statfs`, so no test touches the disk. */
const oneFs: FsTree = { "/": 1, "/pi/sessions": 1 };
describe("sysinfo", () => { describe("sysinfo", () => {
it("parses meminfo using MemAvailable and fallback fields", () => { it("parses meminfo using MemAvailable and fallback fields", () => {
expect(parseMeminfo(mem())).toEqual({ totalBytes: 1024 * 1024, availableBytes: 512 * 1024 }); expect(parseMeminfo(mem())).toEqual({ totalBytes: 1024 * 1024, availableBytes: 512 * 1024 });
@@ -49,6 +65,9 @@ describe("sysinfo", () => {
const result = await createSysinfo({ const result = await createSysinfo({
now: () => 1, now: () => 1,
platform: "darwin", platform: "darwin",
diskPath: "/",
sessionsPath: "/pi/sessions",
stat: fakeStat(oneFs),
cpus: () => cpus(10, 10), cpus: () => cpus(10, 10),
totalmem: () => Number.NaN, totalmem: () => Number.NaN,
freemem: () => Number.POSITIVE_INFINITY, freemem: () => Number.POSITIVE_INFINITY,
@@ -69,8 +88,12 @@ describe("sysinfo", () => {
now: () => clock, now: () => clock,
platform: "linux", platform: "linux",
diskPath: "/test", diskPath: "/test",
sessionsPath: "/pi/sessions",
// `/test` does not exist: the probe must land on the root filesystem
// instead of blanking the tile (the shipped bug).
stat: fakeStat(oneFs),
readFile: async (path) => { reads++; return path === "/proc/stat" ? "cpu 10 0 0 10 0 0 0" : mem(); }, 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 }; }, statfs: async () => { stats++; return { bsize: 100, blocks: 10, bfree: 4, type: 0xef53 }; },
cpus: () => cpus(10, 10), cpus: () => cpus(10, 10),
totalmem: () => 999, totalmem: () => 999,
freemem: () => 1, freemem: () => 1,
@@ -78,7 +101,20 @@ describe("sysinfo", () => {
cacheMs: 100, cacheMs: 100,
}); });
const first = await sampler.sample(); 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 }); 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: "/",
diskUsedBytes: 600,
diskTotalBytes: 1000,
diskPercent: 60,
disks: [{ mountPoint: "/", fsType: "ext4", totalBytes: 1000, usedBytes: 600, percent: 60 }],
});
await sampler.sample(); await sampler.sample();
expect(reads).toBe(2); expect(reads).toBe(2);
expect(stats).toBe(1); expect(stats).toBe(1);
@@ -91,6 +127,9 @@ describe("sysinfo", () => {
it("resolves when total memory probing throws", async () => { it("resolves when total memory probing throws", async () => {
const sampler = createSysinfo({ const sampler = createSysinfo({
platform: "darwin", platform: "darwin",
diskPath: "/",
sessionsPath: "/pi/sessions",
stat: fakeStat(oneFs),
cpus: () => cpus(1, 1), cpus: () => cpus(1, 1),
totalmem: () => { throw new Error("totalmem unavailable"); }, totalmem: () => { throw new Error("totalmem unavailable"); },
freemem: () => 25, freemem: () => 25,
@@ -100,12 +139,15 @@ describe("sysinfo", () => {
await expect(sampler.sample()).resolves.toMatchObject({ memTotalBytes: 0, memUsedBytes: 0, memPercent: 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 () => { it("reports a diskError instead of silent nulls when nothing can be sampled", async () => {
const result = await createSysinfo({ const result = await createSysinfo({
now: () => 1, now: () => 1,
platform: "linux", platform: "linux",
diskPath: "/test",
sessionsPath: "/pi/sessions",
readFile: async () => { throw new Error("read"); }, readFile: async () => { throw new Error("read"); },
statfs: async () => { throw new Error("statfs"); }, stat: fakeStat(oneFs),
statfs: async () => { throw Object.assign(new Error("statfs"), { code: "ENOENT" }); },
cpus: () => { throw new Error("cpu"); }, cpus: () => { throw new Error("cpu"); },
totalmem: () => 0, totalmem: () => 0,
freemem: () => 0, freemem: () => 0,
@@ -116,7 +158,87 @@ describe("sysinfo", () => {
expect(result.diskUsedBytes).toBeNull(); expect(result.diskUsedBytes).toBeNull();
expect(result.diskTotalBytes).toBeNull(); expect(result.diskTotalBytes).toBeNull();
expect(result.diskPercent).toBeNull(); expect(result.diskPercent).toBeNull();
expect(result.disks).toEqual([]);
expect(result.diskError).toBe("/: ENOENT");
expect(result.diskPath).toBe("/test");
expect(result.memTotalBytes).toBe(0); expect(result.memTotalBytes).toBe(0);
expect(result.memUsedBytes).toBe(0); expect(result.memUsedBytes).toBe(0);
}); });
}); });
describe("disk probes", () => {
it("walks up to the nearest existing ancestor", async () => {
const tree: FsTree = { "/": 10, "/home": 20, "/home/u": 20 };
await expect(probeMount("/home/u/project", fakeStat(tree))).resolves.toEqual({
path: "/home/u",
mountPoint: "/home",
dev: "20",
});
// Nothing exists → null, not a throw.
await expect(probeMount("/nope", fakeStat({}))).resolves.toBeNull();
});
it("stops at the filesystem boundary, not at the root", async () => {
const tree: FsTree = { "/": 1, "/mnt": 1, "/mnt/data": 2, "/mnt/data/ws": 2 };
await expect(probeMount("/mnt/data/ws/x", fakeStat(tree))).resolves.toMatchObject({ mountPoint: "/mnt/data" });
await expect(probeMount("/mnt/data/ws/x", fakeStat(tree))).resolves.toMatchObject({ dev: "2" });
await expect(probeMount("/usr/lib", fakeStat(tree))).resolves.toMatchObject({ mountPoint: "/" });
});
it("labels known filesystem magics only", () => {
expect(fsTypeFromMagic(0xef53)).toBe("ext4");
expect(fsTypeFromMagic(0x9123683e)).toBe("btrfs");
expect(fsTypeFromMagic(0xdeadbeef)).toBeUndefined();
expect(fsTypeFromMagic(undefined)).toBeUndefined();
expect(fsTypeFromMagic(Number.NaN)).toBeUndefined();
});
it("dedupes by st_dev and reports the most constrained disk first", async () => {
const tree: FsTree = { "/": 1, "/pi/sessions": 1, "/home": 2, "/mnt/data": 3 };
const seen: string[] = [];
const result = await createSysinfo({
platform: "linux",
diskPath: "/",
sessionsPath: "/pi/sessions",
// Three workspace roots, two of them on the same filesystem as /home.
diskPaths: () => ["/home/a/one", "/home/a/two", "/mnt/data/ws"],
stat: fakeStat(tree),
statfs: async (path) => {
seen.push(path);
const freeBlocks = path === "/" ? 40 : path === "/home" ? 5 : 75;
return { bsize: 100, blocks: 100, bfree: freeBlocks, type: 0xef53 };
},
cpus: () => cpus(1, 1),
totalmem: () => 1,
freemem: () => 0,
loadavg: () => [0, 0, 0],
}).sample();
// One statfs per distinct filesystem: /home/a/one and /home/a/two collapsed.
expect(seen.sort()).toEqual(["/", "/home", "/mnt/data"]);
expect(result.disks.map((disk) => disk.mountPoint)).toEqual(["/home", "/", "/mnt/data"]);
expect(result.disks.map((disk) => disk.percent)).toEqual([95, 60, 25]);
// Legacy scalars alias the worst row.
expect(result.diskPath).toBe("/home");
expect(result.diskPercent).toBe(95);
expect(result.diskError).toBeUndefined();
});
it("caps the filesystem list", async () => {
const tree: FsTree = { "/": 1, "/pi/sessions": 1 };
for (let i = 0; i < 6; i += 1) tree[`/vol${i}`] = 10 + i;
const result = await createSysinfo({
platform: "linux",
diskPath: "/",
sessionsPath: "/pi/sessions",
diskPaths: () => [0, 1, 2, 3, 4, 5].map((i) => `/vol${i}/ws`),
stat: fakeStat(tree),
statfs: async () => ({ bsize: 100, blocks: 100, bfree: 5000 }),
cpus: () => cpus(1, 1),
totalmem: () => 1,
freemem: () => 0,
loadavg: () => [0, 0, 0],
}).sample();
expect(result.disks).toHaveLength(4);
});
});
+3
View File
@@ -45,6 +45,9 @@ export const FAKE_SYSTEM_STATS: SystemStats = {
diskUsedBytes: 50 * 1024 ** 3, diskUsedBytes: 50 * 1024 ** 3,
diskTotalBytes: 200 * 1024 ** 3, diskTotalBytes: 200 * 1024 ** 3,
diskPercent: 25, diskPercent: 25,
disks: [
{ mountPoint: "/tmp/pi2-test", fsType: "ext4", usedBytes: 50 * 1024 ** 3, totalBytes: 200 * 1024 ** 3, percent: 25 },
],
}; };
export function makeFakeSysinfoSampler(stats: Partial<SystemStats> = {}): SysinfoSampler { export function makeFakeSysinfoSampler(stats: Partial<SystemStats> = {}): SysinfoSampler {
+29 -1
View File
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it } from "vitest";
import * as os from "node:os"; import * as os from "node:os";
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js"; import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
import { createHarness, TEST_LIMITS, type Harness } from "./harness.js"; import { createHarness, makeFakeSysinfoSampler, TEST_LIMITS, type Harness } from "./harness.js";
import { DaemonError } from "../../src/daemon/errors.js"; import { DaemonError } from "../../src/daemon/errors.js";
import { ERROR_CODES } from "../../src/protocol/errors.js"; import { ERROR_CODES } from "../../src/protocol/errors.js";
import { WorkspaceError } from "../../src/workspaces/errors.js"; import { WorkspaceError } from "../../src/workspaces/errors.js";
@@ -486,6 +486,34 @@ describe("HTTP API", () => {
})); }));
}); });
it("relays the per-filesystem disk list on resources", async () => {
const custom = await createHarness({
sysinfo: makeFakeSysinfoSampler({
disks: [
{ mountPoint: "/home", fsType: "btrfs", usedBytes: 950, totalBytes: 1000, percent: 95 },
{ mountPoint: "/", fsType: "ext4", usedBytes: 500, totalBytes: 1000, percent: 50 },
],
diskPath: "/home",
diskPercent: 95,
}),
});
try {
const response = await fetch(`${custom.url}/api/v1/resources`, {
headers: { Authorization: `Bearer ${custom.createToken()}` },
});
expect(response.status).toBe(200);
const system = (await response.json()).system;
expect(system.disks).toEqual([
{ mountPoint: "/home", fsType: "btrfs", usedBytes: 950, totalBytes: 1000, percent: 95 },
{ mountPoint: "/", fsType: "ext4", usedBytes: 500, totalBytes: 1000, percent: 50 },
]);
// The /info scalar stays the worst row, so old clients keep working.
expect(system.diskPercent).toBe(95);
} finally {
await custom.cleanup();
}
});
it("resolves bare models without spawning when no instance is ready", async () => { it("resolves bare models without spawning when no instance is ready", async () => {
const bare = await createHarness(); const bare = await createHarness();
try { try {
+60 -4
View File
@@ -2,7 +2,7 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons"; import { Icon } from "@/components/icons";
import { RelativeTime } from "@/components/shared/relative-time"; import { RelativeTime } from "@/components/shared/relative-time";
import type { ResourcesResponse } from "@/lib/api"; import type { DiskUsage, ResourcesResponse } from "@/lib/api";
import { formatBytes, formatUptime, type ServerIdentity } from "@/features/status/server"; import { formatBytes, formatUptime, type ServerIdentity } from "@/features/status/server";
import { ErrorBlock } from "./card-parts"; import { ErrorBlock } from "./card-parts";
@@ -34,6 +34,53 @@ function readable(pct: number | null): string {
return pct == null ? "—" : `${Math.round(pct)}%`; return pct == null ? "—" : `${Math.round(pct)}%`;
} }
function diskTone(pct: number): string {
return pct > 90 ? "is-err" : pct > 80 ? "is-warn" : "";
}
/**
* Disk tile meta line. One filesystem reads `mountPoint · used / total`; several
* become a compact worst-first stack (the daemon caps the list at 4), because a
* single headline percent would hide the volume that is actually full.
*/
function DiskMeta({ disks, diskError, diskPath }: { disks: DiskUsage[]; diskError?: string; diskPath?: string }) {
if (disks.length === 0) {
const reason = diskError ?? diskPath ?? "—";
return (
<span className="faint truncate" title={reason}>
{reason}
</span>
);
}
const detail = (disk: DiskUsage) =>
[disk.mountPoint, disk.fsType, `${formatBytes(disk.usedBytes)} / ${formatBytes(disk.totalBytes)}`]
.filter(Boolean)
.join(" · ");
if (disks.length === 1) {
const disk = disks[0]!;
return (
<span className="faint truncate" title={detail(disk)}>
{disk.mountPoint} · {formatBytes(disk.usedBytes)} / {formatBytes(disk.totalBytes)}
</span>
);
}
return (
<div className="disk-rows">
{disks.map((disk) => (
<div className="disk-row" key={disk.mountPoint}>
<span className="disk-row__label truncate" title={detail(disk)}>
{disk.mountPoint}
</span>
<b className={`disk-row__pct ${diskTone(disk.percent)}`}>{readable(percent(disk.percent))}</b>
</div>
))}
</div>
);
}
export interface MetricsBlockProps { export interface MetricsBlockProps {
server: ServerIdentity; server: ServerIdentity;
resources: ResourcesResponse | undefined; resources: ResourcesResponse | undefined;
@@ -62,17 +109,26 @@ export function MetricsBlock({
}: MetricsBlockProps) { }: MetricsBlockProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const system = resources?.system; const system = resources?.system;
const disks = system?.disks ?? [];
const cpu = percent(system?.cpuPercent ?? server.cpu); const cpu = percent(system?.cpuPercent ?? server.cpu);
const mem = percent(system?.memPercent ?? server.mem); const mem = percent(system?.memPercent ?? server.mem);
const disk = percent(system?.diskPercent ?? server.disk); // `disks` is worst-first, so `[0]` is the number worth showing; the scalars are
// the same row on new daemons and the only source on old ones.
const disk = percent(disks[0]?.percent ?? system?.diskPercent ?? server.disk);
const live = t("status.live", { defaultValue: "Live" }); const live = t("status.live", { defaultValue: "Live" });
const cpuMeta = system const cpuMeta = system
? `${system.cpuCores} ${t("status.cores")}${system.loadAvg ? ` · ${t("status.load")} ${system.loadAvg[0].toFixed(2)}` : ""}` ? `${system.cpuCores} ${t("status.cores")}${system.loadAvg ? ` · ${t("status.load")} ${system.loadAvg[0].toFixed(2)}` : ""}`
: live; : live;
const memMeta = system ? `${formatBytes(system.memUsedBytes)} / ${formatBytes(system.memTotalBytes)}` : live; const memMeta = system ? `${formatBytes(system.memUsedBytes)} / ${formatBytes(system.memTotalBytes)}` : live;
const diskMeta = system ? ( const diskMeta = system ? (
<span className="faint truncate" title={system.diskPath}>{system.diskPath}</span> <DiskMeta
) : live; disks={disks}
{...(system.diskError === undefined ? {} : { diskError: system.diskError })}
{...(system.diskPath === undefined ? {} : { diskPath: system.diskPath })}
/>
) : (
live
);
const counts: Array<[string, string]> = [ const counts: Array<[string, string]> = [
[t("status.workspaces"), String(workspaceCount)], [t("status.workspaces"), String(workspaceCount)],
+15
View File
@@ -302,6 +302,17 @@ export interface ModelsResponse {
pendingReason?: "fetching" | "no-instance" | "no-live-session"; pendingReason?: "fetching" | "no-instance" | "no-live-session";
} }
/** One sampled filesystem (daemon ≥ 0.1.8; older daemons only send the scalars). */
export interface DiskUsage {
/** Filesystem boundary, e.g. `/`, `/home`, `/mnt/data`. */
mountPoint: string;
/** Best-effort type label (`ext4`, `btrfs`, …); absent when unknown. */
fsType?: string;
totalBytes: number;
usedBytes: number;
percent: number;
}
export interface SystemStats { export interface SystemStats {
sampledAt: number; sampledAt: number;
cpuPercent: number | null; cpuPercent: number | null;
@@ -314,6 +325,10 @@ export interface SystemStats {
diskUsedBytes: number | null; diskUsedBytes: number | null;
diskTotalBytes: number | null; diskTotalBytes: number | null;
diskPercent: number | null; diskPercent: number | null;
/** Most constrained first, at most 4 rows; absent on daemons < 0.1.8. */
disks?: DiskUsage[];
/** Present only when `disks` is empty — the sample failed, distinct from a full disk. */
diskError?: string;
} }
export interface ResourcesResponse { export interface ResourcesResponse {
+19
View File
@@ -104,6 +104,25 @@
gap: 4px; gap: 4px;
min-width: 0; min-width: 0;
} }
/* Multi-filesystem disk tile: one quiet row per mount, worst first. */
.status-tile .disk-rows {
display: flex;
flex-direction: column;
gap: 2px;
width: 100%;
min-width: 0;
}
.status-tile .disk-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 6px;
min-width: 0;
}
.status-tile .disk-row__label { min-width: 0; }
.status-tile .disk-row__pct { flex: none; font-weight: 600; font-variant-numeric: tabular-nums; }
.status-tile .disk-row__pct.is-warn { color: var(--warn); }
.status-tile .disk-row__pct.is-err { color: var(--err); }
/* 3px meter: a quiet hairline rather than a progress bar */ /* 3px meter: a quiet hairline rather than a progress bar */
.meter { .meter {