feat(daemon): report host uptime, not only the daemon's process age

The status tile labelled "uptime" showed the age of the daemon *process*
(`/info.uptimeMs`), and `/info` was fetched once with a 30 s staleTime and no
refetch interval, so the figure also froze: on a box five days up, a
`pi2 update` restart made the tile read "3m" and it never moved again.

`os.uptime()` is now sampled with the other host figures and served as
`system.hostUptimeSec` — which the 3 s `/resources` poll already refreshes —
plus an additive `/info.hostUptimeMs`. The tile renders it through a
`LiveUptime` label that anchors the reported snapshot once and ticks locally,
so the counter advances without a refetch and cannot rewind on a re-render.
The daemon's own process age stays in the server card, relabelled
`status.daemonUptime`, next to the `pid`/`daemonId` that give it meaning.
This commit is contained in:
yuez committed 2026-10-30 16:18:48 +08:00
1 parent 01fd7b9922
commit 2f2f1bb518
16 files changed
+204 -10

No files matched your search

+2 -1
View File
@@ -93,7 +93,7 @@ Plugin obligations:
| Endpoint | Notes |
|---|---|
| `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/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}`; `uptimeMs` is the **daemon process** age, `hostUptimeMs` the host uptime (both omitted when unknown); 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/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) |
| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) |
@@ -123,6 +123,7 @@ figures sampled by the daemon itself:
| Field | Notes |
|---|---|
| `sampledAt` | epoch ms; a sample is cached ~1 s and shared across callers |
| `hostUptimeSec` | host uptime in whole seconds (`os.uptime()`), `null` when the OS has none. This is the figure a client shows as “uptime”; `/info.uptimeMs` stays the **daemon process** age, so a `pi2 update` restart does not reset it |
| `cpuPercent` | integer 0–100, `null` on the first sample (it is a delta between two reads) |
| `cpuCores` | logical core count |
| `loadAvg` | 3-tuple `[1m, 5m, 15m]`, or `null` where the OS has no load average |
+16
View File
@@ -46,6 +46,8 @@ export interface DiskUsage {
export interface SystemStats {
sampledAt: number;
/** Host uptime in whole seconds (`os.uptime()`), `null` when the OS has none. */
hostUptimeSec: number | null;
cpuPercent: number | null;
cpuCores: number;
loadAvg: [number, number, number] | null;
@@ -74,6 +76,7 @@ export interface SysinfoDeps {
cpus?: () => Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>;
totalmem?: () => number;
freemem?: () => number;
uptime?: () => number;
loadavg?: () => number[];
platform?: NodeJS.Platform;
/** Primary disk candidate; defaults to `/` (the home volume on macOS). */
@@ -279,6 +282,7 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
const cpus = deps.cpus ?? (() => nodeOs.cpus());
const totalmem = deps.totalmem ?? (() => nodeOs.totalmem());
const freemem = deps.freemem ?? (() => nodeOs.freemem());
const uptime = deps.uptime ?? (() => nodeOs.uptime());
const loadavg = deps.loadavg ?? (() => nodeOs.loadavg());
/**
@@ -394,6 +398,17 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
}
}
// ── Host uptime ──────────────────────────────────────────────
// The daemon's own process age lives on `/info.uptimeMs`; this is the
// figure a user reads as "how long has this box been up".
let hostUptimeSec: number | null = null;
try {
const raw = uptime();
if (Number.isFinite(raw) && raw >= 0) hostUptimeSec = Math.round(raw);
} catch {
hostUptimeSec = null;
}
// ── Memory ───────────────────────────────────────────────────
let memTotalBytes: number;
let memUsedBytes: number;
@@ -442,6 +457,7 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
return {
sampledAt,
hostUptimeSec,
cpuPercent,
cpuCores,
loadAvg: loadAvgResult,
+3
View File
@@ -205,7 +205,10 @@ export function createApp(deps: AppDeps): Hono<Env> {
hostname: osHostname(),
os: `${osPlatform()} ${osRelease()}`,
version: daemonVersion(),
// Process age of the daemon itself (`uptimeMs`), distinct from the host
// figure (`hostUptimeMs`) the status page shows as "uptime".
uptimeMs: Math.max(0, now() - startedAt),
...(typeof system?.hostUptimeSec === "number" ? { hostUptimeMs: system.hostUptimeSec * 1000 } : {}),
pid: process.pid,
port: config.port,
capabilities: ["ws", "sse", "devices", "attention"],
+35
View File
@@ -92,6 +92,7 @@ describe("sysinfo", () => {
// `/test` does not exist: the probe must land on the root filesystem
// instead of blanking the tile (the shipped bug).
stat: fakeStat(oneFs),
uptime: () => 4321.6,
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, type: 0xef53 }; },
cpus: () => cpus(10, 10),
@@ -103,6 +104,7 @@ describe("sysinfo", () => {
const first = await sampler.sample();
expect(first).toEqual({
sampledAt: 1000,
hostUptimeSec: 4322,
cpuPercent: null,
cpuCores: 1,
loadAvg: [1.23, 2.35, 3.46],
@@ -139,6 +141,39 @@ describe("sysinfo", () => {
await expect(sampler.sample()).resolves.toMatchObject({ memTotalBytes: 0, memUsedBytes: 0, memPercent: 0 });
});
it("reports a host uptime independently of the daemon's own age", async () => {
const result = await createSysinfo({
platform: "linux",
diskPath: "/",
sessionsPath: "/pi/sessions",
stat: fakeStat(oneFs),
statfs: async () => ({ bsize: 100, blocks: 10, bfree: 4 }),
uptime: () => 5 * 86_400 + 3 * 3_600,
cpus: () => cpus(1, 1),
totalmem: () => 1,
freemem: () => 0,
loadavg: () => [0, 0, 0],
}).sample();
expect(result.hostUptimeSec).toBe(442_800);
});
it("nulls a host uptime the OS cannot report", async () => {
const base = {
platform: "linux" as const,
diskPath: "/",
sessionsPath: "/pi/sessions",
stat: fakeStat(oneFs),
statfs: async () => ({ bsize: 100, blocks: 10, bfree: 4 }),
cpus: () => cpus(1, 1),
totalmem: () => 1,
freemem: () => 0,
loadavg: () => [0, 0, 0],
};
for (const uptime of [() => Number.NaN, () => -1, () => Number.POSITIVE_INFINITY, () => { throw new Error("no uptime"); }]) {
await expect(createSysinfo({ ...base, uptime }).sample()).resolves.toMatchObject({ hostUptimeSec: null });
}
});
it("reports a diskError instead of silent nulls when nothing can be sampled", async () => {
const result = await createSysinfo({
now: () => 1,
+2
View File
@@ -35,6 +35,8 @@ export function testConfig(overrides: Partial<Config> = {}): Config {
/** Deterministic fake sampler returned when no override is provided. */
export const FAKE_SYSTEM_STATS: SystemStats = {
sampledAt: 1_700_000_000_000,
// 5 days up, so the status tile and the daemon card differ on purpose.
hostUptimeSec: 432_000,
cpuPercent: 42,
cpuCores: 4,
loadAvg: [1.5, 1.2, 0.9],
+2
View File
@@ -483,6 +483,8 @@ describe("HTTP API", () => {
cpu: 42,
mem: 25,
disk: 25,
// Host uptime is additive and independent of `uptimeMs` (process age).
hostUptimeMs: 432_000_000,
}));
});
+9 -2
View File
@@ -3,7 +3,8 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons";
import { RelativeTime } from "@/components/shared/relative-time";
import type { DiskUsage, ResourcesResponse } from "@/lib/api";
import { formatBytes, formatUptime, type ServerIdentity } from "@/features/status/server";
import { formatBytes, type ServerIdentity } from "@/features/status/server";
import { LiveUptime } from "@/features/status/uptime";
import { ErrorBlock } from "./card-parts";
@@ -115,6 +116,10 @@ export function MetricsBlock({
// `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);
// Host uptime, not the daemon's: this tile answers "how long has the box been
// up", and the polled `/resources` sample keeps it fresh.
const hostUptimeMs =
system?.hostUptimeSec != null ? system.hostUptimeSec * 1000 : server.hostUptimeSec != null ? server.hostUptimeSec * 1000 : null;
const live = t("status.live", { defaultValue: "Live" });
const cpuMeta = system
? `${system.cpuCores} ${t("status.cores")}${system.loadAvg ? ` · ${t("status.load")} ${system.loadAvg[0].toFixed(2)}` : ""}`
@@ -171,7 +176,9 @@ export function MetricsBlock({
<div className="tile status-tile" data-res="uptime">
<div className="tile__label">{t("status.uptime")}</div>
<div className="tile__value">{formatUptime(server.uptimeSec)}</div>
<div className="tile__value">
<LiveUptime ms={hostUptimeMs} />
</div>
<div className="tile__meta">
<span>{t("status.lastHeartbeat")}</span>
<RelativeTime ts={server.lastHeartbeatAt} live={false} />
+7 -2
View File
@@ -5,7 +5,8 @@ import { StatusDot } from "@/components/ui/status-dot";
import { KV, KVList } from "@/components/ui/kv";
import type { ResourcesResponse } from "@/lib/api";
import type { ServerIdentity } from "@/features/status/server";
import { formatBytes, formatUptime } from "@/features/status/server";
import { formatBytes } from "@/features/status/server";
import { LiveUptime } from "@/features/status/uptime";
import { ErrorBlock, LoadingBlock, StatusCard } from "./card-parts";
@@ -49,7 +50,11 @@ export function ServerInfoCard({ server, resources, loading, error, onRetry }: S
{server.platform}
</KV>
<KV label={t("status.piVersion")}>{server.piVersion}</KV>
<KV label={t("status.uptime")}>{formatUptime(server.uptimeSec)}</KV>
{/* This card is the daemon's own identity (pid, daemonId): its uptime
is the *process* age, which resets on every restart. */}
<KV label={t("status.daemonUptime")}>
<LiveUptime ms={server.uptimeMs ?? (server.uptimeSec != null ? server.uptimeSec * 1000 : null)} />
</KV>
<KV label="daemonId" mono>
{server.daemonId}
</KV>
+5
View File
@@ -50,6 +50,7 @@ export function resolveServerStatus(input: ServerStatusInput): ServerStatusValue
export interface InfoExtras extends InfoResponse {
pid?: number;
kernel?: string;
/** Daemon process age (seconds); kept as a derived alias of `uptimeMs`. */
uptimeSec?: number;
lastHeartbeat?: number;
mdns?: string;
@@ -76,6 +77,8 @@ export interface ServerIdentity {
kernel: string;
uptimeSec: number | null;
uptimeMs: number | null;
/** Host uptime in seconds — what the status page labels “uptime”. */
hostUptimeSec: number | null;
pid: number | null;
status: ServerStatusValue;
wsConnected: boolean;
@@ -155,6 +158,7 @@ export function deriveServerIdentity({
const uptimeMs = finite(extras.uptimeMs);
const uptimeSec =
uptimeMs != null ? Math.floor(uptimeMs / 1000) : typeof extras.uptimeSec === "number" ? extras.uptimeSec : null;
const hostUptimeMs = finite(extras.hostUptimeMs);
return {
name,
@@ -171,6 +175,7 @@ export function deriveServerIdentity({
kernel: text(extras.kernel),
uptimeSec,
uptimeMs,
hostUptimeSec: hostUptimeMs != null ? Math.floor(hostUptimeMs / 1000) : null,
pid: finite(extras.pid),
status: resolvedStatus,
wsConnected: wsState === "open",
+48
View File
@@ -0,0 +1,48 @@
import { useEffect, useMemo, useReducer } from "react";
import { formatUptime } from "@/features/status/server";
/**
* Seconds elapsed since `baseAtMs`, clamped at zero.
*
* A duration, not a timestamp: the daemon only reports a snapshot
* (`hostUptimeSec` on the polled `/resources`, `hostUptimeMs` on the rarely
* refetched `/info`), so the counter has to advance locally.
*/
export function uptimeSecondsFrom(baseAtMs: number, now: number): number {
return Math.max(0, Math.floor((now - baseAtMs) / 1000));
}
/** Epoch ms the counted duration started at, or `null` for an unusable value. */
export function uptimeAnchor(ms: number | null | undefined, now = Date.now()): number | null {
if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) return null;
return now - ms;
}
export interface LiveUptimeProps {
/** Reported uptime in milliseconds; `null`/`undefined` renders an em dash. */
ms: number | null | undefined;
className?: string;
}
/**
* Ticking uptime label.
*
* `formatUptime` bottoms out at minutes, so a 30 s tick is enough. The anchor is
* memoised on `ms` alone: re-renders (and the 3 s `/resources` poll reporting the
* same second) never rewind or fast-forward the counter, while a genuinely newer
* sample re-anchors it.
*/
export function LiveUptime({ ms, className }: LiveUptimeProps) {
const [, tick] = useReducer((n: number) => n + 1, 0);
const anchor = useMemo(() => uptimeAnchor(ms), [ms]);
useEffect(() => {
if (anchor === null) return;
const timer = setInterval(tick, 30_000);
return () => clearInterval(timer);
}, [anchor]);
if (anchor === null) return <span className={className}>—</span>;
return <span className={className}>{formatUptime(uptimeSecondsFrom(anchor, Date.now()))}</span>;
}
+5
View File
@@ -256,7 +256,10 @@ export interface InfoResponse {
port?: number;
/** Additive identity fields (daemon ≥ 0.2): OS label and process uptime. */
os?: string;
/** **Daemon process** age; `hostUptimeMs` is the host figure. */
uptimeMs?: number;
/** Host uptime (daemon ≥ 0.1.8); absent on older builds. */
hostUptimeMs?: number;
/** Resource percentages from newer daemons (0..100). */
cpu?: number;
mem?: number;
@@ -315,6 +318,8 @@ export interface DiskUsage {
export interface SystemStats {
sampledAt: number;
/** Host uptime in whole seconds; `null`/absent on daemons < 0.1.8. */
hostUptimeSec?: number | null;
cpuPercent: number | null;
cpuCores: number;
loadAvg: [number, number, number] | null;
+1
View File
@@ -566,6 +566,7 @@
"status.cores": "cores",
"status.load": "load",
"status.created": "Created",
"status.daemonUptime": "Daemon uptime",
"status.deviceCount": "{n}",
"status.devices": "Paired devices",
"status.devicesError": "Failed to load paired devices",
+1
View File
@@ -566,6 +566,7 @@
"status.cores": "核心",
"status.load": "负载",
"status.created": "创建",
"status.daemonUptime": "守护进程运行时长",
"status.deviceCount": "{n} 台",
"status.devices": "已配对设备",
"status.devicesError": "加载已配对设备失败",
+13 -4
View File
@@ -25,7 +25,8 @@ import {
type PairMeta,
type PairTarget,
} from "@/features/connect/pairing";
import { deriveServerIdentity, formatUptime, type InfoExtras } from "@/features/status/server";
import { deriveServerIdentity, type InfoExtras } from "@/features/status/server";
import { LiveUptime } from "@/features/status/uptime";
import { useInfoQuery } from "@/features/status/queries";
import { getDeviceToken, setDeviceToken } from "@/lib/api";
import { useConnectionStore } from "@/stores/connection";
@@ -104,8 +105,14 @@ export function ConnectPage() {
});
const defaultDeviceName = t("connect.defaultDeviceName");
const osLabel = info.data?.os || info.data?.platform || server.os || "—";
const uptimeSeconds =
typeof info.data?.uptimeMs === "number" ? info.data.uptimeMs / 1000 : server.uptimeSec;
// Host uptime: this row labels it "uptime", and pinning it to the daemon
// process made a five-day-old box read "3m" after a restart.
const uptimeMs =
typeof info.data?.hostUptimeMs === "number"
? info.data.hostUptimeMs
: server.hostUptimeSec != null
? server.hostUptimeSec * 1000
: null;
const defaultPort = defaultPortFor(info.data?.port ?? server.port);
/**
@@ -286,7 +293,9 @@ export function ConnectPage() {
{info.data?.pluginVersion || meta?.server?.pluginVersion || "—"}
</KV>
<KV label={t("connect.os")}>{osLabel}</KV>
<KV label={t("connect.uptime")}>{formatUptime(uptimeSeconds)}</KV>
<KV label={t("connect.uptime")}>
<LiveUptime ms={uptimeMs} />
</KV>
<p className="cn-note">
<span className="cn-ico">
<Icon name="alert" />
+4 -1
View File
@@ -64,6 +64,8 @@ const resourcesBody = {
physicalMemoryBytes: 2048 * 1024 * 1024,
system: {
sampledAt: Date.now(),
// Host uptime, deliberately different from the daemon's own age in `infoBody`.
hostUptimeSec: 3 * 86_400,
cpuPercent: 37,
cpuCores: 8,
loadAvg: [1.23, 0.98, 0.75],
@@ -264,7 +266,8 @@ describe("StatusPage", () => {
expect(document.querySelector('.status-tile[data-res="disk"] .tile__meta')).toHaveTextContent("/var/lib/pi2");
expect(document.querySelector('.status-tile[data-res="cpu"] .tile__meta')).toHaveTextContent("8");
expect(document.querySelector('.status-tile[data-res="cpu"] .tile__meta')).toHaveTextContent("1.23");
expect(document.querySelector('.status-tile[data-res="uptime"] .tile__value')).toHaveTextContent("2h 5m");
// The tile shows the host, not the daemon process (`/info.uptimeMs` is 2h 5m).
expect(document.querySelector('.status-tile[data-res="uptime"] .tile__value')).toHaveTextContent("3d 0h 0m");
const counts = document.querySelector(".status-counts");
expect(counts).not.toBeNull();
+51
View File
@@ -0,0 +1,51 @@
import { act, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { LiveUptime, uptimeAnchor, uptimeSecondsFrom } from "@/features/status/uptime";
afterEach(() => {
vi.useRealTimers();
});
describe("uptime anchoring", () => {
it("anchors a reported duration at the matching epoch instant", () => {
expect(uptimeAnchor(5_000, 10_000)).toBe(5_000);
expect(uptimeAnchor(3 * 86_400_000, 1_000)).toBe(1_000 - 3 * 86_400_000);
});
it("rejects values a clock cannot start from", () => {
expect(uptimeAnchor(null)).toBeNull();
expect(uptimeAnchor(undefined)).toBeNull();
expect(uptimeAnchor(Number.NaN)).toBeNull();
expect(uptimeAnchor(Number.POSITIVE_INFINITY)).toBeNull();
// A negative duration would render as a rewind, not as uptime.
expect(uptimeAnchor(-1)).toBeNull();
});
it("counts forward and never below zero", () => {
expect(uptimeSecondsFrom(1_000, 62_000)).toBe(61);
expect(uptimeSecondsFrom(1_000, 1_000)).toBe(0);
expect(uptimeSecondsFrom(1_000, 0)).toBe(0);
});
});
describe("LiveUptime", () => {
it("renders an em dash when the daemon reports nothing", () => {
const { container } = render(<LiveUptime ms={null} />);
expect(container.textContent).toBe("—");
});
it("ticks without needing a fresh /info sample", () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
// `/info` was only fetched once; the label must keep counting locally.
const { container } = render(<LiveUptime ms={5 * 60_000} />);
expect(container.textContent).toBe("0h 5m");
act(() => {
vi.advanceTimersByTime(60_000);
});
expect(container.textContent).toBe("0h 6m");
});
});