Report uptime from the agents, and stop the Integrations page overflowing a phone

Linux agent 8 and Windows agent 7 say how long the machine has been up; the
server stores it (migration 0086) and shows it as Up for in the status strip
(left out while offline) and Uptime on the server page.

The Integrations header wraps and its button no longer squeezes, and
.table-responsive is positioned so hidden text in scrolled-off columns cannot
widen the page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-08 21:50:44 +01:00
1 parent d88a24b33a
commit 41fbbf3467
18 files changed
+9161 -10

No files matched your search

+1
View File
@@ -0,0 +1 @@
ALTER TABLE `servers` ADD `uptime_seconds` integer;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -603,6 +603,13 @@
"when": 1793832143749,
"tag": "0085_broad_skrulls",
"breakpoints": true
},
{
"idx": 86,
"version": "6",
"when": 1794155585495,
"tag": "0086_talented_starfox",
"breakpoints": true
}
]
}
+1
View File
@@ -442,6 +442,7 @@ export const servers = sqliteTable("servers", {
cpuLoadPercent: real("cpu_load_percent"),
memTotalBytes: integer("mem_total_bytes"),
memUsedBytes: integer("mem_used_bytes"),
uptimeSeconds: integer("uptime_seconds"), // how long the host had been up when it last reported
disks: text("disks"), // JSON string: {mount, sizeBytes, usedBytes}[]
listeningPorts: text("listening_ports"), // JSON string: {protocol, port, address, process}[] — what the agent sees bound on the host
lastPortScan: text("last_port_scan"), // JSON string: summary of the most recent network scan from this app
+5
View File
@@ -101,6 +101,11 @@ const systemSchema = z.object({
ip_addresses: z.array(text(100)).transform(cap(200)).optional(),
cpu: z.object({ model: text(200).optional(), cores: z.number().optional(), load_percent: z.number().nullable().optional() }).optional(),
memory: z.object({ total_bytes: z.number().optional(), used_bytes: z.number().optional() }).optional(),
// Lenient like the rest: a figure that makes no sense is dropped, never allowed to cost the agent its report.
uptime_seconds: z
.unknown()
.optional()
.transform((v) => (typeof v === "number" && Number.isFinite(v) && v > 0 && v < 3_000_000_000 ? Math.floor(v) : undefined)),
disks: z
.array(z.object({ mount: text(500), size_bytes: z.number(), used_bytes: z.number() }))
.transform(cap(500))
+2
View File
@@ -382,6 +382,7 @@ serversRouter.get("/:id/detail", asyncHandler(async (req, res) => {
cpuLoadPercent: server.cpuLoadPercent,
memTotalBytes: server.memTotalBytes,
memUsedBytes: server.memUsedBytes,
uptime: server.uptimeSeconds,
disks: server.disks ? JSON.parse(server.disks) : [],
};
} else {
@@ -424,6 +425,7 @@ serversRouter.get("/:id/detail", asyncHandler(async (req, res) => {
cpuLoadPercent: _cpuLoadPercent,
memTotalBytes: _memTotalBytes,
memUsedBytes: _memUsedBytes,
uptimeSeconds: _uptimeSeconds,
listeningPorts: _listeningPorts,
lastPortScan: _lastPortScan,
pendingUpdates: rawUpdates,
+1
View File
@@ -13,6 +13,7 @@
* 5 — Linux: also says what the machine is (maker, model, serial), for the inventory
* 6 — Linux (and Windows 5): also says what it could not collect and why, so the server can say what to fix
* 7 — Linux (and Windows 6): also says which operating system and release it runs, so the server can say when that release stops being supported
* 8 — Linux (and Windows 7): also says how long the machine has been up
*/
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
+4
View File
@@ -24,6 +24,8 @@ export interface IncomingSystemInfo {
ip_addresses?: string[];
cpu?: { model?: string; cores?: number; load_percent?: number | null };
memory?: { total_bytes?: number; used_bytes?: number };
/** Seconds the machine had been up. Absent from an agent that predates it. */
uptime_seconds?: number;
disks?: { mount: string; size_bytes: number; used_bytes: number }[];
listening_ports?: { protocol: "tcp" | "udp"; port: number; address: string; process?: string }[];
/** Updates waiting to be installed. Absent from an agent that doesn't report them (or couldn't find out this time). */
@@ -141,6 +143,8 @@ export async function syncServerTasks(serverId: number, report: AgentReport) {
...(system?.cpu?.load_percent !== undefined ? { cpuLoadPercent: system.cpu.load_percent } : {}),
...(system?.memory?.total_bytes !== undefined ? { memTotalBytes: system.memory.total_bytes } : {}),
...(system?.memory?.used_bytes !== undefined ? { memUsedBytes: system.memory.used_bytes } : {}),
// Only stored when said, so an agent that predates this doesn't wipe it.
...(system?.uptime_seconds !== undefined ? { uptimeSeconds: system.uptime_seconds } : {}),
...(system?.disks
? {
disks: JSON.stringify(
+2 -2
View File
@@ -129,7 +129,7 @@ describe("through a report, the page, the alerts and the figures", () => {
before(async () => {
await db.insert(users).values([{ oidcSub: "admin", name: "Ada", role: "admin" }]);
const [s] = await db.insert(servers).values({ name: "elsa", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t", lastSeenAt: new Date().toISOString(), agentVersion: 7 }).returning();
const [s] = await db.insert(servers).values({ name: "elsa", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t", lastSeenAt: new Date().toISOString(), agentVersion: 8 }).returning();
id = s.id;
const a = express();
a.use("/api/agent/report", agentReportRouter);
@@ -155,7 +155,7 @@ describe("through a report, the page, the alerts and the figures", () => {
});
const report = (system: unknown) =>
fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ hostname: "h", os_type: "linux", agent_version: 7, tasks: [], system }) });
fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ hostname: "h", os_type: "linux", agent_version: 8, tasks: [], system }) });
const detail = async () => await (await fetch(`${base}/servers/${id}/detail`)).json();
const patch = (body: unknown) => fetch(`${base}/servers/${id}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+126
View File
@@ -0,0 +1,126 @@
/**
* How long a server has been up, as its agent says it: taken from a report (and dropped if it makes no sense), kept when an older agent
* reports without it, given back on the server's page, and not claimed on the strip once the server has stopped reporting.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-uptime-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { serversRouter } = await import("../src/routes/servers.js");
const { agentReportRouter } = await import("../src/routes/agentReport.js");
const { hashToken } = await import("../src/services/tokens.js");
const { parseAgentVersion, latestAgentVersions, AGENT_DIR } = await import("../src/services/agentVersions.js");
const { serverStrip } = await import("../../web/src/utils/serverStrip.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
describe("a report's uptime", () => {
let app: Server;
let base = "";
let id = 0;
before(async () => {
await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "viewer" });
id = (await db.insert(servers).values({ name: "web-1", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t" }).returning({ id: servers.id }))[0].id;
const a = express();
a.use("/api/agent/report", agentReportRouter);
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "tester" } };
next();
});
a.use("/api/servers", serversRouter);
app = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const system = (extra: Record<string, unknown>) => ({ cpu: { model: "x", cores: 4, load_percent: 5 }, memory: { total_bytes: 1000, used_bytes: 100 }, disks: [], ...extra });
const report = (sys: unknown) => fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ os_type: "linux", system: sys, tasks: [] }) });
const stored = async () => (await db.select().from(servers).where(eq(servers.id, id)))[0].uptimeSeconds;
const detail = async () => (await (await fetch(`${base}/servers/${id}/detail`)).json()) as { hardware: { uptime?: number | null }; server: Record<string, unknown> };
test("a report with uptime stores it, whole seconds, and the server's page gives it back", async () => {
assert.equal((await report(system({ uptime_seconds: 1_234_567.8 }))).status, 202);
assert.equal(await stored(), 1_234_567);
const d = await detail();
assert.equal(d.hardware.uptime, 1_234_567);
assert.ok(!("uptimeSeconds" in d.server), "it is not handed out twice");
});
test("a newer report replaces it, and an older agent's report (with none) leaves it as it was", async () => {
await report(system({ uptime_seconds: 2_000_000 }));
assert.equal(await stored(), 2_000_000);
assert.equal((await report(system({}))).status, 202);
assert.equal(await stored(), 2_000_000);
});
test("a figure that makes no sense is dropped, never costing the report", async () => {
for (const bad of [-5, 0, "12", null, Number.MAX_SAFE_INTEGER, { a: 1 }]) {
assert.equal((await report(system({ uptime_seconds: bad }))).status, 202, JSON.stringify(bad));
assert.equal(await stored(), 2_000_000, `kept after ${JSON.stringify(bad)}`);
}
});
});
describe("the strip", () => {
const NOW = Date.parse("2026-06-10T12:00:00Z");
const base = { defaults: { serverOfflineMinutes: 15, diskUsagePercent: 90 }, alerts: [], windows: [], now: NOW } as never;
const make = (lastSeenAt: string) =>
serverStrip({ ...(base as object), server: { id: 1, name: "web-1", lastSeenAt, pendingUpdates: null, thresholds: null }, hardware: { source: "agent", uptime: 90_000 } } as never);
test("shows how long it has been up while it reports", () => {
const t = make(new Date(NOW - 60_000).toISOString()).find((x) => x.id === "uptime");
assert.equal(t?.value, "1d 1h");
});
test("says nothing of it once the server has stopped reporting — that is no longer how long it has been up", () => {
const tiles = make(new Date(NOW - 3 * 3600_000).toISOString());
assert.equal(tiles[0].value, "Offline");
assert.equal(tiles.find((x) => x.id === "uptime"), undefined);
});
});
describe("the agents", () => {
test("both say the new version, and the Linux one reads /proc/uptime and sends it as uptime_seconds", () => {
const latest = latestAgentVersions();
assert.equal(latest.linux, 8);
assert.equal(latest.windows, 7);
const sh = readFileSync(join(AGENT_DIR, "linux", "report-tasks.sh"), "utf8");
assert.equal(parseAgentVersion(sh, "linux"), 8);
assert.match(sh, /\/proc\/uptime/);
assert.match(sh, /uptime_seconds: \$uptime_seconds/);
});
test("the Windows one works it out from when Windows started, and the file stays plain ASCII", () => {
const ps = readFileSync(join(AGENT_DIR, "windows", "report-tasks.ps1"), "utf8");
assert.match(ps, /LastBootUpTime/);
assert.match(ps, /uptime_seconds\s*=\s*\$uptime/);
assert.ok(!/[^\x00-\x7f]/.test(ps), "downloaded as text, so no characters beyond ASCII");
});
});
+2 -2
View File
@@ -32,9 +32,9 @@ function run(snippet: string): unknown {
}
describe("the Windows agent's health parts", { skip: !havePwsh }, () => {
test("it says it is version 5, and stays plain ASCII", () => {
test("it says it is version 7, and stays plain ASCII", () => {
const text = readFileSync(script, "utf8");
assert.match(text, /^\$script:AgentVersion = 6\s*$/m);
assert.match(text, /^\$script:AgentVersion = 7\s*$/m);
assert.ok(!/[^\x00-\x7f]/.test(text));
});