diff --git a/docs/protocol.md b/docs/protocol.md index 7348a4c..795af5c 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -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 | diff --git a/src/core/sysinfo.ts b/src/core/sysinfo.ts index b76831b..3a274f8 100644 --- a/src/core/sysinfo.ts +++ b/src/core/sysinfo.ts @@ -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, diff --git a/src/daemon/http.ts b/src/daemon/http.ts index 5378d7c..1ae4def 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -205,7 +205,10 @@ export function createApp(deps: AppDeps): Hono { 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"], diff --git a/test/core/sysinfo.test.ts b/test/core/sysinfo.test.ts index 6f02d5a..d477a6b 100644 --- a/test/core/sysinfo.test.ts +++ b/test/core/sysinfo.test.ts @@ -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, diff --git a/test/daemon/harness.ts b/test/daemon/harness.ts index 423c2e2..2710c5d 100644 --- a/test/daemon/harness.ts +++ b/test/daemon/harness.ts @@ -35,6 +35,8 @@ export function testConfig(overrides: Partial = {}): 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], diff --git a/test/daemon/http.test.ts b/test/daemon/http.test.ts index e75c837..0e47140 100644 --- a/test/daemon/http.test.ts +++ b/test/daemon/http.test.ts @@ -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, })); }); diff --git a/web/src/features/status/metrics-block.tsx b/web/src/features/status/metrics-block.tsx index a613484..b9126e8 100644 --- a/web/src/features/status/metrics-block.tsx +++ b/web/src/features/status/metrics-block.tsx @@ -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({
{t("status.uptime")}
-
{formatUptime(server.uptimeSec)}
+
+ +
{t("status.lastHeartbeat")} diff --git a/web/src/features/status/server-info-card.tsx b/web/src/features/status/server-info-card.tsx index 0680490..230aa2f 100644 --- a/web/src/features/status/server-info-card.tsx +++ b/web/src/features/status/server-info-card.tsx @@ -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} {server.piVersion} - {formatUptime(server.uptimeSec)} + {/* This card is the daemon's own identity (pid, daemonId): its uptime + is the *process* age, which resets on every restart. */} + + + {server.daemonId} diff --git a/web/src/features/status/server.ts b/web/src/features/status/server.ts index d2bc7bd..d5c2a97 100644 --- a/web/src/features/status/server.ts +++ b/web/src/features/status/server.ts @@ -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", diff --git a/web/src/features/status/uptime.tsx b/web/src/features/status/uptime.tsx new file mode 100644 index 0000000..3686bc7 --- /dev/null +++ b/web/src/features/status/uptime.tsx @@ -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 —; + return {formatUptime(uptimeSecondsFrom(anchor, Date.now()))}; +} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 0f2a2e2..13d3051 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -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; diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 1512311..43bc742 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -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", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index 008ca5e..4247ca1 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -566,6 +566,7 @@ "status.cores": "核心", "status.load": "负载", "status.created": "创建", + "status.daemonUptime": "守护进程运行时长", "status.deviceCount": "{n} 台", "status.devices": "已配对设备", "status.devicesError": "加载已配对设备失败", diff --git a/web/src/pages/connect.tsx b/web/src/pages/connect.tsx index e2b1f76..91c7d2d 100644 --- a/web/src/pages/connect.tsx +++ b/web/src/pages/connect.tsx @@ -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 || "—"} {osLabel} - {formatUptime(uptimeSeconds)} + + +

diff --git a/web/tests/status-page.test.tsx b/web/tests/status-page.test.tsx index 025b5a6..edbb73a 100644 --- a/web/tests/status-page.test.tsx +++ b/web/tests/status-page.test.tsx @@ -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(); diff --git a/web/tests/uptime.test.tsx b/web/tests/uptime.test.tsx new file mode 100644 index 0000000..6ef5022 --- /dev/null +++ b/web/tests/uptime.test.tsx @@ -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(); + 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(); + expect(container.textContent).toBe("0h 5m"); + + act(() => { + vi.advanceTimersByTime(60_000); + }); + expect(container.textContent).toBe("0h 6m"); + }); +});