Phone card layout, status symbols, breadcrumbs, integration cards and server trends

Tables stack into labelled cards on a phone. Green, red and amber badges carry
a check, cross or triangle as well as their colour. Pages inside a menu group
show a breadcrumb, with the thing's name on a server's page. Integrations are
cards with an Open button and a live status (working, failing, not checked yet,
disabled). Agent-reported servers keep a short history of load, memory and disk
use (migration 0019, one sample per ten minutes for 35 days) and show it as a
Trends card with a days-until-full forecast for a filling disk.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-14 23:56:05 +02:00
1 parent 617dc1ea2f
commit 9965d94036
22 files changed
+2989 -73

No files matched your search

+19 -1
View File
@@ -24,7 +24,7 @@ what the app actually creates.
| **File** | `DATABASE_PATH`, default `../data/homelab-manager.sqlite` (relative to `server/`; `/app/data/...` in Docker). The folder is created if missing. |
| **Foreign keys** | Switched on for every connection (`PRAGMA foreign_keys = ON`), so the `ON DELETE` rules below are enforced. |
| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0014`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. |
| **Tables** | 23 application tables, plus drizzle's own `__drizzle_migrations`. |
| **Tables** | 24 application tables, plus drizzle's own `__drizzle_migrations`. |
**Not in the database:**
@@ -55,6 +55,7 @@ erDiagram
dns_providers ||--o{ dns_records_cache : "cascade"
servers ||--o{ scheduled_tasks : "cascade"
servers ||--o{ server_links : "cascade"
servers ||--o{ server_metrics : "cascade"
servers ||--o{ server_ports : "cascade"
servers ||--o{ port_forwards : "optional (set null)"
integrations ||--o{ servers : "proxmox link (app clears it)"
@@ -222,6 +223,23 @@ server's page and summarised under Operations → Admin Links.
| `label`, `url` | text NOT NULL | |
| `created_at` | text NOT NULL | SQLite UTC. |
#### `server_metrics`
A short history of each agent-reported server's load, memory and disk use, in
percent, for the Trends card on its page. At most one sample per server every
ten minutes however often its agent reports, kept for 35 days (older rows are
removed whenever a new sample is stored).
| Column | Type | Notes |
|---|---|---|
| `id` | integer PK | |
| `server_id` | integer NOT NULL → `servers.id`, **cascade** | |
| `metric` | text NOT NULL | `cpu`, `mem`, or `disk:<mount point>` (e.g. `disk:/data`). |
| `value` | real NOT NULL | Percent, 0–100, one decimal. |
| `recorded_at` | text NOT NULL | ISO. |
Index **`server_metrics_lookup_idx`** on (`server_id`, `metric`, `recorded_at`).
#### `server_ports`
A port on one server that's been seen open by a scan, or that someone wrote a
+6 -2
View File
@@ -84,8 +84,12 @@ All modules from the original plan are built:
both showing the same per-disk usage breakdown (an LXC's root filesystem
read straight from the host; a QEMU VM's actual mounts via its guest
agent, alongside the allocated size Proxmox already knew about without
one). Proxmox-linked servers also get start/stop/restart buttons right on the
detail page. The detail page also has an **Admin Links** section
one). Servers that report through the agent also get a **Trends** card: small
lines for CPU load, memory and each disk over the last 24 hours, 7 or 30 days
(a sample is kept about every ten minutes, for 35 days), and for a disk that is
filling, its rate of growth and roughly how many days until it is full — shown
only with at least a day of history. Proxmox-linked servers also get
start/stop/restart buttons right on the detail page. The detail page also has an **Admin Links** section
(operator/admin to add/edit/remove) for bookmarking that server's own
admin UIs — Dockge, Webmin, Cockpit, Portainer, or anything else reachable
by URL. **Operations → Admin Links** summarizes every server's admin links
+10
View File
@@ -0,0 +1,10 @@
CREATE TABLE `server_metrics` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`server_id` integer NOT NULL,
`metric` text NOT NULL,
`value` real NOT NULL,
`recorded_at` text NOT NULL,
FOREIGN KEY (`server_id`) REFERENCES `servers`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE INDEX `server_metrics_lookup_idx` ON `server_metrics` (`server_id`,`metric`,`recorded_at`);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -134,6 +134,13 @@
"when": 1791757001527,
"tag": "0018_even_marvel_zombies",
"breakpoints": true
},
{
"idx": 19,
"version": "6",
"when": 1792014514813,
"tag": "0019_complex_proudstar",
"breakpoints": true
}
]
}
+16
View File
@@ -93,6 +93,22 @@ export const maintenanceAliases = sqliteTable(
(table) => [uniqueIndex("maintenance_aliases_unique_idx").on(table.address, table.targetType, table.targetId)],
);
// A short history of each agent-reported server's load, memory and disk use, in percent — see services/serverMetrics.ts.
// `metric` is "cpu", "mem" or "disk:<mount point>".
export const serverMetrics = sqliteTable(
"server_metrics",
{
id: integer("id").primaryKey({ autoIncrement: true }),
serverId: integer("server_id")
.notNull()
.references(() => servers.id, { onDelete: "cascade" }),
metric: text("metric").notNull(),
value: real("value").notNull(),
recordedAt: text("recorded_at").notNull(), // ISO
},
(table) => [index("server_metrics_lookup_idx").on(table.serverId, table.metric, table.recordedAt)],
);
// ─── Settings (key/value) ───────────────────────────────────────────────────
export const settings = sqliteTable("settings", {
+8 -1
View File
@@ -24,6 +24,7 @@ import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
import { createPbsAdapter } from "../integrations/pbs/adapter.js";
import { createOsTicketAdapter } from "../integrations/osticket/adapter.js";
import { attachMatchedServers, summarizeMonitors, toMatchableServers } from "../services/uptimeKumaMatch.js";
import { getSourceStatus } from "../services/integrationHealthMonitor.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js";
@@ -48,7 +49,13 @@ integrationsRouter.get("/", asyncHandler(async (_req, res) => {
createdAt: integrations.createdAt,
})
.from(integrations);
res.json({ integrations: rows });
// How each one has been doing lately. Calls are logged under the integration's type, so a second integration of the same type shares its streak.
res.json({
integrations: rows.map((r) => ({
...r,
health: r.enabled ? getSourceStatus(r.type) : { status: "disabled" as const, consecutiveFailures: 0 },
})),
});
}));
const configValueSchema = z.union([z.string(), z.boolean()]);
+12
View File
@@ -6,6 +6,7 @@ import { servers, serverLinks, integrations, dnsRecordsCache, dnsZonesCache, dns
import { requireAuth, requireRole } from "../auth/middleware.js";
import { generateApiToken } from "../services/tokens.js";
import { recordAudit } from "../services/audit.js";
import { getServerMetrics, RETENTION_DAYS } from "../services/serverMetrics.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { ID_PATTERNS } from "../utils/pathSegment.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
@@ -189,6 +190,17 @@ serversRouter.get("/links", asyncHandler(async (_req, res) => {
res.json({ links: rows });
}));
// The recent history of an agent-reported server's load, memory and disks, for the trend lines on its page.
serversRouter.get("/:id/metrics", asyncHandler(async (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [server] = await db.select({ id: servers.id }).from(servers).where(eq(servers.id, id)).limit(1);
if (!server) return res.status(404).json({ error: "not_found" });
const requested = Number(req.query.days);
const days = Number.isFinite(requested) ? Math.min(RETENTION_DAYS, Math.max(1, Math.round(requested))) : 7;
res.json({ days, series: await getServerMetrics(id, days) });
}));
serversRouter.get("/:id/detail", asyncHandler(async (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
@@ -24,6 +24,18 @@ export function getFailingSources(): { source: string; consecutiveFailures: numb
.map(([source, state]) => ({ source, consecutiveFailures: state.consecutiveFailures, alerted: state.alerted }));
}
/**
* How a service has been doing since the app started: "failing" while its latest calls keep failing, "ok" once a call has gone
* through, and "unknown" when nothing has called it yet (this is a live streak, kept in memory, not a record).
*/
export function getSourceStatus(source: string): { status: "ok" | "failing" | "unknown"; consecutiveFailures: number } {
const state = health.get(source);
if (!state) return { status: "unknown", consecutiveFailures: 0 };
return state.consecutiveFailures > 0
? { status: "failing", consecutiveFailures: state.consecutiveFailures }
: { status: "ok", consecutiveFailures: 0 };
}
/** Called after every diagnostic-log entry is recorded, to track consecutive failures per source and alert on threshold-cross / recovery. */
export async function trackIntegrationHealth(source: string, ok: boolean): Promise<void> {
const state = health.get(source) ?? { consecutiveFailures: 0, alerted: false };
+169
View File
@@ -0,0 +1,169 @@
/**
* A short history of what each agent-reported server's load, memory and disks looked like, so a page can show a trend
* (and say how soon a filling disk will run out) instead of only the latest figure.
*
* One sample is kept per server every ten minutes at most, however often its agent reports, for 35 days. Everything here is a
* percentage: CPU load (as the agent reports it), memory in use, and each disk's used share.
*/
import { and, desc, eq, gte, lt } from "drizzle-orm";
import { db } from "../db/client.js";
import { serverMetrics } from "../db/schema.js";
import type { IncomingSystemInfo } from "./taskSync.js";
/** Reports closer together than this add no sample. */
export const MIN_GAP_MS = 10 * 60_000;
export const RETENTION_DAYS = 35;
const DAY_MS = 24 * 3600_000;
export interface Sample {
metric: string;
value: number;
}
const round1 = (n: number) => Math.round(n * 10) / 10;
const clampPercent = (n: number) => Math.min(100, Math.max(0, n));
/** The percentages in one agent report. Anything missing or nonsensical (no size, not a number) is left out. */
export function samplesFromSystem(system: IncomingSystemInfo | null | undefined): Sample[] {
if (!system) return [];
const out: Sample[] = [];
const load = system.cpu?.load_percent;
if (typeof load === "number" && Number.isFinite(load)) out.push({ metric: "cpu", value: round1(clampPercent(load)) });
const total = system.memory?.total_bytes;
const used = system.memory?.used_bytes;
if (typeof total === "number" && typeof used === "number" && total > 0) out.push({ metric: "mem", value: round1(clampPercent((used / total) * 100)) });
for (const d of system.disks ?? []) {
if (typeof d.mount !== "string" || !d.mount || !(d.size_bytes > 0) || typeof d.used_bytes !== "number") continue;
out.push({ metric: `disk:${d.mount}`, value: round1(clampPercent((d.used_bytes / d.size_bytes) * 100)) });
}
return out;
}
/** Records a report's figures, unless this server was sampled a moment ago. Returns whether anything was stored. */
export async function recordServerMetrics(serverId: number, system: IncomingSystemInfo | null | undefined, now: Date = new Date()): Promise<boolean> {
const samples = samplesFromSystem(system);
if (samples.length === 0) return false;
const [latest] = await db
.select({ at: serverMetrics.recordedAt })
.from(serverMetrics)
.where(eq(serverMetrics.serverId, serverId))
.orderBy(desc(serverMetrics.recordedAt))
.limit(1);
if (latest && now.getTime() - Date.parse(latest.at) < MIN_GAP_MS) return false;
const at = now.toISOString();
await db.insert(serverMetrics).values(samples.map((s) => ({ serverId, metric: s.metric, value: s.value, recordedAt: at })));
await db.delete(serverMetrics).where(and(eq(serverMetrics.serverId, serverId), lt(serverMetrics.recordedAt, new Date(now.getTime() - RETENTION_DAYS * DAY_MS).toISOString())));
return true;
}
export interface Point {
/** ISO time. */
t: string;
v: number;
}
/** Averages points into at most `maxPoints` equal slices of [from, to], so a month of samples draws as a short line. */
export function bucketPoints(points: { t: number; v: number }[], from: number, to: number, maxPoints: number): Point[] {
if (points.length === 0 || to <= from) return [];
const size = Math.max((to - from) / maxPoints, 1);
const buckets = new Map<number, { sum: number; n: number; tSum: number }>();
for (const p of points) {
if (p.t < from || p.t > to) continue;
const key = Math.min(maxPoints - 1, Math.floor((p.t - from) / size));
const b = buckets.get(key) ?? { sum: 0, n: 0, tSum: 0 };
b.sum += p.v;
b.n += 1;
b.tSum += p.t;
buckets.set(key, b);
}
return [...buckets.entries()]
.sort((a, b) => a[0] - b[0])
.map(([, b]) => ({ t: new Date(b.tSum / b.n).toISOString(), v: round1(b.sum / b.n) }));
}
export interface Trend {
/** Change in the percentage per day, from a straight line through the points. */
perDay: number;
/** For something that fills up: days until it reaches 100% at that rate. Null when it isn't rising or the rate is negligible. */
daysToFull: number | null;
}
/**
* A straight-line fit over the points. Needs at least six points covering at least a day; with less there is no honest trend to
* give. A slope under 0.05 points a day counts as flat, so a disk that wobbles by a fraction isn't forecast to fill in a century.
*/
export function trendOf(points: { t: number; v: number }[]): Trend | null {
if (points.length < 6) return null;
const span = points[points.length - 1].t - points[0].t;
if (span < DAY_MS) return null;
const t0 = points[0].t;
const xs = points.map((p) => (p.t - t0) / DAY_MS);
const ys = points.map((p) => p.v);
const n = points.length;
const meanX = xs.reduce((a, b) => a + b, 0) / n;
const meanY = ys.reduce((a, b) => a + b, 0) / n;
let num = 0;
let den = 0;
for (let i = 0; i < n; i++) {
num += (xs[i] - meanX) * (ys[i] - meanY);
den += (xs[i] - meanX) ** 2;
}
if (den === 0) return null;
const slope = num / den;
const perDay = Math.round(slope * 100) / 100;
const last = ys[n - 1];
const daysToFull = perDay >= 0.05 && last < 100 ? Math.ceil((100 - last) / perDay) : null;
return { perDay, daysToFull };
}
export interface MetricSeries {
metric: string;
kind: "cpu" | "mem" | "disk";
label: string;
points: Point[];
latest: number | null;
trend: Trend | null;
}
function describe(metric: string): { kind: MetricSeries["kind"]; label: string } {
if (metric === "cpu") return { kind: "cpu", label: "CPU load" };
if (metric === "mem") return { kind: "mem", label: "Memory" };
return { kind: "disk", label: `Disk ${metric.slice("disk:".length)}` };
}
const ORDER = { cpu: 0, mem: 1, disk: 2 } as const;
/** Every series recorded for a server over the last `days`, ready to draw. */
export async function getServerMetrics(serverId: number, days: number, now: Date = new Date()): Promise<MetricSeries[]> {
const to = now.getTime();
const from = to - days * DAY_MS;
const rows = await db
.select({ metric: serverMetrics.metric, value: serverMetrics.value, at: serverMetrics.recordedAt })
.from(serverMetrics)
.where(and(eq(serverMetrics.serverId, serverId), gte(serverMetrics.recordedAt, new Date(from).toISOString())))
.orderBy(serverMetrics.recordedAt);
const byMetric = new Map<string, { t: number; v: number }[]>();
for (const r of rows) {
const list = byMetric.get(r.metric) ?? [];
list.push({ t: Date.parse(r.at), v: r.value });
byMetric.set(r.metric, list);
}
return [...byMetric.entries()]
.map(([metric, raw]) => {
const { kind, label } = describe(metric);
return {
metric,
kind,
label,
points: bucketPoints(raw, from, to, 96),
latest: raw[raw.length - 1]?.v ?? null,
// A disk filling is the thing worth forecasting; load and memory go up and down by the hour.
trend: kind === "disk" ? trendOf(raw) : null,
};
})
.sort((a, b) => ORDER[a.kind] - ORDER[b.kind] || a.label.localeCompare(b.label));
}
+8
View File
@@ -1,6 +1,7 @@
import { and, eq, notInArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { scheduledTasks, servers } from "../db/schema.js";
import { recordServerMetrics } from "./serverMetrics.js";
export interface IncomingTask {
scheduleType: "cron" | "systemd_timer" | "windows_task";
@@ -121,4 +122,11 @@ export async function syncServerTasks(serverId: number, report: AgentReport) {
...(system?.listening_ports ? { listeningPorts: JSON.stringify(system.listening_ports) } : {}),
})
.where(eq(servers.id, serverId));
// Keep a little history of the figures too. A failure here must not lose the report itself, which is already saved.
try {
await recordServerMetrics(serverId, system, new Date(now));
} catch (err) {
console.error("[serverMetrics] couldn't record a sample:", err);
}
}
+83
View File
@@ -0,0 +1,83 @@
/**
* What the integration cards say about each integration: working, failing, not checked yet, or disabled.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, 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-int-status-"));
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, integrations } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { integrationsRouter } = await import("../src/routes/integrations.js");
const { trackIntegrationHealth, getSourceStatus } = await import("../src/services/integrationHealthMonitor.js");
await runMigrations();
describe("integration health on the list", () => {
let app: Server;
let base = "";
before(async () => {
await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "admin" });
await db.insert(integrations).values([
{ type: "proxmox", name: "Felicia", baseUrl: "https://pve.lab:8006", config: "{}" },
{ type: "gitea", name: "Gitea", baseUrl: "https://git.lab", config: "{}" },
{ type: "synology", name: "NAS", baseUrl: "https://nas.lab", config: "{}" },
{ type: "tailscale", name: "Off", baseUrl: "https://api.tailscale.com", config: "{}", enabled: false },
]);
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "tester" } };
next();
});
a.use("/api/integrations", integrationsRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/integrations`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("a service nothing has called yet is unknown, not healthy", () => {
assert.deepEqual(getSourceStatus("never-called"), { status: "unknown", consecutiveFailures: 0 });
});
test("failing, working, not checked yet and disabled are told apart", async () => {
await trackIntegrationHealth("proxmox", false);
await trackIntegrationHealth("proxmox", false);
await trackIntegrationHealth("gitea", true);
const list = (await (await fetch(base)).json()).integrations as { name: string; health: { status: string; consecutiveFailures: number } }[];
const by = (name: string) => list.find((i) => i.name === name)!.health;
assert.deepEqual(by("Felicia"), { status: "failing", consecutiveFailures: 2 });
assert.deepEqual(by("Gitea"), { status: "ok", consecutiveFailures: 0 });
assert.equal(by("NAS").status, "unknown");
assert.equal(by("Off").status, "disabled");
});
test("a call that goes through ends the failing streak", async () => {
await trackIntegrationHealth("proxmox", true);
assert.deepEqual(getSourceStatus("proxmox"), { status: "ok", consecutiveFailures: 0 });
});
});
+202
View File
@@ -0,0 +1,202 @@
/**
* The short history kept of each agent-reported server's load, memory and disks, and the trend drawn from it.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, 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-metrics-"));
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 { eq } = await import("drizzle-orm");
const { db } = await import("../src/db/client.js");
const { users, servers, serverMetrics } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { serversRouter } = await import("../src/routes/servers.js");
const { syncServerTasks } = await import("../src/services/taskSync.js");
const { samplesFromSystem, recordServerMetrics, bucketPoints, trendOf, getServerMetrics, MIN_GAP_MS, RETENTION_DAYS } = await import("../src/services/serverMetrics.js");
await runMigrations();
const DAY = 24 * 3600_000;
const system = (load: number, memUsed: number, diskUsed: number) => ({
cpu: { load_percent: load },
memory: { total_bytes: 1000, used_bytes: memUsed },
disks: [{ mount: "/", size_bytes: 1000, used_bytes: diskUsed }],
});
describe("samplesFromSystem", () => {
test("turns a report into percentages", () => {
assert.deepEqual(samplesFromSystem(system(12.34, 250, 900)), [
{ metric: "cpu", value: 12.3 },
{ metric: "mem", value: 25 },
{ metric: "disk:/", value: 90 },
]);
});
test("leaves out what is missing or makes no sense, and clamps to 0–100", () => {
assert.deepEqual(samplesFromSystem(null), []);
assert.deepEqual(samplesFromSystem({ cpu: { load_percent: null }, memory: { total_bytes: 0, used_bytes: 5 }, disks: [{ mount: "/x", size_bytes: 0, used_bytes: 1 }] }), []);
assert.equal(samplesFromSystem({ cpu: { load_percent: 250 } })[0].value, 100);
});
});
describe("bucketPoints", () => {
test("averages points into slices and keeps them in time order", () => {
const pts = [
{ t: 0, v: 10 },
{ t: 10, v: 20 },
{ t: 90, v: 50 },
{ t: 100, v: 70 },
];
const out = bucketPoints(pts, 0, 100, 2);
assert.equal(out.length, 2);
assert.deepEqual(out.map((p) => p.v), [15, 60]);
assert.ok(out[0].t < out[1].t);
});
test("points outside the range are ignored, and nothing gives nothing", () => {
assert.deepEqual(bucketPoints([], 0, 100, 4), []);
assert.deepEqual(bucketPoints([{ t: 500, v: 1 }], 0, 100, 4), []);
});
});
describe("trendOf", () => {
const line = (days: number, start: number, perDay: number, n = 20) =>
Array.from({ length: n }, (_, i) => ({ t: (i / (n - 1)) * days * DAY, v: start + perDay * (i / (n - 1)) * days }));
test("a rising disk gets a rate and a forecast", () => {
const t = trendOf(line(10, 50, 2))!;
assert.equal(t.perDay, 2);
assert.equal(t.daysToFull, Math.ceil((100 - 70) / 2));
});
test("a flat or falling one gets no forecast", () => {
assert.equal(trendOf(line(10, 50, 0))!.daysToFull, null);
assert.equal(trendOf(line(10, 80, -1))!.daysToFull, null);
});
test("too little data says nothing rather than guessing", () => {
assert.equal(trendOf(line(10, 50, 2, 4)), null, "fewer than six points");
assert.equal(trendOf(line(0.5, 50, 2)), null, "less than a day");
});
});
describe("recording and reading", () => {
let serverId = 0;
before(async () => {
serverId = (await db.insert(servers).values({ name: "elsa", apiTokenHash: "x", apiTokenPrefix: "x" }).returning())[0].id;
});
test("a report stores one sample per figure", async () => {
const t0 = new Date("2026-10-01T00:00:00Z");
assert.equal(await recordServerMetrics(serverId, system(10, 100, 500), t0), true);
const rows = await db.select().from(serverMetrics).where(eq(serverMetrics.serverId, serverId));
assert.deepEqual(rows.map((r) => r.metric).sort(), ["cpu", "disk:/", "mem"]);
});
test("a report a moment later adds nothing; one after the gap does", async () => {
const t0 = new Date("2026-10-01T00:00:00Z");
assert.equal(await recordServerMetrics(serverId, system(11, 100, 500), new Date(t0.getTime() + MIN_GAP_MS - 1000)), false);
assert.equal(await recordServerMetrics(serverId, system(12, 100, 500), new Date(t0.getTime() + MIN_GAP_MS + 1000)), true);
});
test("samples older than the retention period are dropped when a new one is stored", async () => {
await db.delete(serverMetrics);
const old = new Date("2026-01-01T00:00:00Z");
await recordServerMetrics(serverId, system(1, 1, 1), old);
const now = new Date(old.getTime() + (RETENTION_DAYS + 1) * DAY);
await recordServerMetrics(serverId, system(2, 2, 2), now);
const rows = await db.select().from(serverMetrics).where(eq(serverMetrics.serverId, serverId));
assert.ok(rows.every((r) => Date.parse(r.recordedAt) >= old.getTime() + DAY), "the old ones are gone");
assert.equal(rows.length, 3);
});
test("getServerMetrics draws a series per figure, with a forecast for a filling disk", async () => {
await db.delete(serverMetrics);
const now = new Date("2026-10-20T00:00:00Z");
// A disk gaining 2 points a day for ten days, sampled every 6 hours.
for (let i = 0; i <= 40; i++) {
const at = new Date(now.getTime() - (10 * DAY - i * 0.25 * DAY));
await recordServerMetrics(serverId, system(20, 300, 500 + (i / 4) * 20), at);
}
const series = await getServerMetrics(serverId, 14, now);
assert.deepEqual(series.map((s) => s.kind), ["cpu", "mem", "disk"]);
const disk = series.find((s) => s.kind === "disk")!;
assert.equal(disk.label, "Disk /");
assert.equal(disk.latest, 70);
assert.equal(disk.trend?.perDay, 2);
assert.equal(disk.trend?.daysToFull, 15);
assert.equal(series.find((s) => s.kind === "cpu")!.trend, null, "load is not forecast");
assert.ok(disk.points.length > 5 && disk.points.length <= 96);
});
test("an agent report goes through to the history", async () => {
await db.delete(serverMetrics);
await syncServerTasks(serverId, { tasks: [], system: system(33, 400, 600) });
const rows = await db.select().from(serverMetrics).where(eq(serverMetrics.serverId, serverId));
assert.equal(rows.length, 3);
});
test("deleting the server takes its history with it", async () => {
const [other] = await db.insert(servers).values({ name: "gone", apiTokenHash: "y", apiTokenPrefix: "y" }).returning();
await recordServerMetrics(other.id, system(1, 1, 1), new Date());
await db.delete(servers).where(eq(servers.id, other.id));
assert.equal((await db.select().from(serverMetrics).where(eq(serverMetrics.serverId, other.id))).length, 0);
});
});
describe("GET /api/servers/:id/metrics", () => {
let app: Server;
let base = "";
let serverId = 0;
before(async () => {
await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "viewer" });
serverId = (await db.insert(servers).values({ name: "route-test", apiTokenHash: "z", apiTokenPrefix: "z" }).returning())[0].id;
await recordServerMetrics(serverId, system(5, 100, 100), new Date());
const a = express();
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 s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/servers`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("anyone signed in can read it, and the number of days is kept within what is stored", async () => {
const res = await fetch(`${base}/${serverId}/metrics?days=9999`);
assert.equal(res.status, 200);
const body = await res.json();
assert.equal(body.days, RETENTION_DAYS);
assert.deepEqual(body.series.map((s: { kind: string }) => s.kind), ["cpu", "mem", "disk"]);
assert.equal((await fetch(`${base}/${serverId}/metrics`)).status, 200);
});
test("an unknown server is a 404 and a bad id a 400", async () => {
assert.equal((await fetch(`${base}/99999/metrics`)).status, 404);
assert.equal((await fetch(`${base}/abc/metrics`)).status, 400);
});
});
+13
View File
@@ -126,6 +126,16 @@ export interface SecretInput {
checkPort?: number | null;
}
export interface ServerMetricSeries {
metric: string;
kind: "cpu" | "mem" | "disk";
label: string;
points: { t: string; v: number }[];
latest: number | null;
/** Disks only: the rate of change in points a day, and the days until full when it is rising. */
trend: { perDay: number; daysToFull: number | null } | null;
}
export interface IpamEntry {
id: number;
ipAddress: string;
@@ -580,6 +590,8 @@ export interface IntegrationSummary {
baseUrl: string;
enabled: boolean;
createdAt: string;
/** How its latest calls have gone since the app started. Only present on the integrations list. */
health?: { status: "ok" | "failing" | "unknown" | "disabled"; consecutiveFailures: number };
}
export interface TailscaleDevice {
@@ -1235,6 +1247,7 @@ export const api = {
request<{ server: ServerRecord }>(`/api/servers/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
summary: () => request<ServerSummary>("/api/servers/summary"),
detail: (id: number) => request<ServerDetail>(`/api/servers/${id}/detail`),
metrics: (id: number, days: number) => request<{ days: number; series: ServerMetricSeries[] }>(`/api/servers/${id}/metrics?days=${days}`),
remove: (id: number) => request<void>(`/api/servers/${id}`, { method: "DELETE" }),
setTags: (id: number, tags: string[]) =>
request<{ tags: string[] }>(`/api/servers/${id}/tags`, { method: "PUT", body: JSON.stringify({ tags }) }),
+94
View File
@@ -0,0 +1,94 @@
import { useEffect, useState } from "react";
import { api, type ServerMetricSeries } from "../api/client";
import Sparkline from "./Sparkline";
const RANGES = [
{ days: 1, label: "24 hours" },
{ days: 7, label: "7 days" },
{ days: 30, label: "30 days" },
];
function levelColor(series: ServerMetricSeries): string {
const v = series.latest ?? 0;
if (series.kind === "disk") return v >= 90 ? "#f03e3e" : v >= 80 ? "#f59f00" : "#4299e1";
return "#4299e1";
}
/** One line of words about where a series is heading: a disk's rate and when it fills, or a load/memory range. */
function describeTrend(series: ServerMetricSeries): string {
if (series.kind === "disk" && series.trend) {
const { perDay, daysToFull } = series.trend;
if (daysToFull !== null) return `rising ${perDay.toFixed(1)} points a day — full in about ${daysToFull} day${daysToFull === 1 ? "" : "s"}`;
if (perDay <= -0.05) return `falling ${Math.abs(perDay).toFixed(1)} points a day`;
return "steady";
}
if (series.kind === "disk") return "not enough history for a trend yet";
const values = series.points.map((p) => p.v);
if (values.length === 0) return "";
return `${Math.round(Math.min(...values))}–${Math.round(Math.max(...values))}% over this time`;
}
/** How an agent-reported server's load, memory and disks have moved lately, with a forecast for a filling disk. */
export default function ServerTrends({ serverId }: { serverId: number }) {
const [days, setDays] = useState(7);
const [series, setSeries] = useState<ServerMetricSeries[] | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let alive = true;
setFailed(false);
api.servers
.metrics(serverId, days)
.then((res) => alive && setSeries(res.series))
.catch(() => alive && setFailed(true));
return () => {
alive = false;
};
}, [serverId, days]);
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Trends</h3>
<div className="card-actions">
<select className="form-select form-select-sm" value={days} onChange={(e) => setDays(Number(e.target.value))} aria-label="Time range">
{RANGES.map((r) => (
<option key={r.days} value={r.days}>
Last {r.label}
</option>
))}
</select>
</div>
</div>
<div className="card-body">
{failed ? (
<div className="text-secondary">Couldn't load the history.</div>
) : series === null ? (
<div className="text-secondary">Loading…</div>
) : series.length === 0 ? (
<div className="text-secondary">
No history yet. A sample is kept about every ten minutes once the agent has reported, so lines appear here after a short while.
</div>
) : (
<div className="trend-grid">
{series.map((s) => {
const words = describeTrend(s);
return (
<div key={s.metric} className="trend-row">
<div className="trend-label">{s.label}</div>
<Sparkline
points={s.points}
color={levelColor(s)}
label={`${s.label}, ${s.latest !== null ? `${Math.round(s.latest)}% now` : "no reading"}${words ? `, ${words}` : ""}`}
/>
<div className="trend-now">{s.latest !== null ? `${Math.round(s.latest)}%` : "—"}</div>
<div className="trend-words text-secondary small">{words}</div>
</div>
);
})}
</div>
)}
</div>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
/**
* A small line of how a percentage moved. The scale is always 0–100%, so a disk at 40% looks half-empty and one at 95% looks full
* however little it moved — a line that stretched to fit its own ups and downs would make every wobble look alarming.
*/
export default function Sparkline({
points,
color = "#4299e1",
label,
}: {
points: { t: string; v: number }[];
color?: string;
/** Read out by screen readers in place of the picture. */
label: string;
}) {
const W = 160;
const H = 36;
if (points.length < 2) {
return (
<svg viewBox={`0 0 ${W} ${H}`} className="sparkline" role="img" aria-label={label}>
<line x1="0" y1={H - 1} x2={W} y2={H - 1} stroke="currentColor" strokeOpacity="0.25" />
</svg>
);
}
const t0 = Date.parse(points[0].t);
const span = Math.max(Date.parse(points[points.length - 1].t) - t0, 1);
const xy = points.map((p) => {
const x = ((Date.parse(p.t) - t0) / span) * (W - 2) + 1;
const y = H - 2 - (Math.min(100, Math.max(0, p.v)) / 100) * (H - 4);
return `${x.toFixed(1)},${y.toFixed(1)}`;
});
return (
<svg viewBox={`0 0 ${W} ${H}`} className="sparkline" role="img" aria-label={label} preserveAspectRatio="none">
<polyline points={`1,${H - 1} ${xy.join(" ")} ${W - 1},${H - 1}`} fill={color} fillOpacity="0.15" stroke="none" />
<polyline points={xy.join(" ")} fill="none" stroke={color} strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
</svg>
);
}
+54
View File
@@ -0,0 +1,54 @@
import { useEffect } from "react";
const SORT_GLYPHS = /[↕↑↓▲▼⇅⇵]/g;
/** Writes each column's heading onto its cells (data-label), so the phone layout can show "Status: running" beside each value. */
function labelTable(table: HTMLTableElement): void {
const headRow = table.tHead?.rows[table.tHead.rows.length - 1];
if (!headRow) return;
const labels: string[] = [];
for (const th of Array.from(headRow.cells)) {
const text = (th.textContent ?? "").replace(SORT_GLYPHS, "").replace(/\s+/g, " ").trim();
for (let i = 0; i < Math.max(1, th.colSpan); i++) labels.push(text);
}
for (const body of Array.from(table.tBodies)) {
for (const row of Array.from(body.rows)) {
let col = 0;
for (const cell of Array.from(row.cells)) {
const label = cell.colSpan > 1 ? "" : (labels[col] ?? "");
if (label) {
if (cell.getAttribute("data-label") !== label) cell.setAttribute("data-label", label);
} else if (cell.hasAttribute("data-label")) {
cell.removeAttribute("data-label");
}
col += Math.max(1, cell.colSpan);
}
}
}
}
/**
* On a phone the wide tables are drawn as a stack of cards (see styles.css), which needs every cell to know its column's
* heading. This keeps that up to date as pages load, sort, filter and page — without each table having to do it.
*/
export function useStackedTables(): void {
useEffect(() => {
const root = document.querySelector(".page-body");
if (!root) return;
// A short timer rather than an animation frame: frames stop while the tab is in the background, and the labels should not.
let timer: ReturnType<typeof setTimeout> | null = null;
const run = () => {
timer = null;
root.querySelectorAll<HTMLTableElement>("table.card-table").forEach(labelTable);
};
const observer = new MutationObserver(() => {
if (!timer) timer = setTimeout(run, 30);
});
observer.observe(root, { childList: true, subtree: true });
run();
return () => {
observer.disconnect();
if (timer) clearTimeout(timer);
};
}, []);
}
+26
View File
@@ -43,6 +43,8 @@ import { DENSITIES, getDensity, setDensity, type Density } from "../utils/densit
import CommandPalette from "../components/CommandPalette";
import { isLightColor, useEnvironment } from "../utils/environment";
import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport";
import { useStackedTables } from "../hooks/useStackedTables";
import { useBreadcrumbTailValue } from "../utils/breadcrumb";
interface NavBadge {
text: string;
@@ -182,6 +184,8 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
const [density, setDensityState] = useState<Density>(() => getDensity());
const [maintenance, setMaintenance] = useState<MaintenanceWindow[]>([]);
const environment = useEnvironment();
useStackedTables();
const breadcrumbTail = useBreadcrumbTailValue();
const { report } = useAlertsReport();
const [menuOpen, setMenuOpen] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
@@ -223,6 +227,17 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
const nav = visibleNav(user.role);
const { pathname } = useLocation();
// Where this page sits in the menu: "Infrastructure › Servers", and on a page about one thing, that thing's name as well.
const crumbs: { label: string; to?: string }[] = [];
for (const entry of nav) {
if (!isGroup(entry)) continue;
const leaf = entry.items.find((item) => isCurrent(pathname, item.to));
if (!leaf) continue;
crumbs.push({ label: entry.label }, breadcrumbTail ? { label: leaf.label, to: leaf.to } : { label: leaf.label });
if (breadcrumbTail) crumbs.push({ label: breadcrumbTail });
break;
}
const [openGroups, setOpenGroups] = useState<Set<string>>(loadOpenGroups);
// The group holding the current page is always open, so you can see where you are (others stay as you left them).
@@ -437,6 +452,17 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
</div>
</div>
)}
{crumbs.length > 0 && (
<nav aria-label="breadcrumb" className="mb-2">
<ol className="breadcrumb breadcrumb-arrows mb-0">
{crumbs.map((c, i) => (
<li key={i} className={`breadcrumb-item ${i === crumbs.length - 1 ? "active" : ""}`} aria-current={i === crumbs.length - 1 ? "page" : undefined}>
{c.to ? <Link to={c.to}>{c.label}</Link> : c.label}
</li>
))}
</ol>
</nav>
)}
{children}
</div>
</div>
+105 -69
View File
@@ -1,10 +1,10 @@
import { useEffect, useState, type CSSProperties } from "react";
import { useSearchParams } from "react-router-dom";
import { Link, useSearchParams } from "react-router-dom";
import { api, type CurrentUser, type IntegrationSummary, type IntegrationType } from "../api/client";
import IntegrationForm from "../components/IntegrationForm";
import IntegrationEditForm from "../components/IntegrationEditForm";
import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh";
import TableToolbar from "../components/TableToolbar";
import { useTableSearch } from "../hooks/useTableSearch";
import { downloadCsv } from "../utils/csv";
import { confirmDialog } from "../utils/dialogs";
import { ErrorNotice } from "../components/Notice";
@@ -23,6 +23,48 @@ const TYPE_LABELS: Record<IntegrationType, string> = {
osticket: "osTicket",
};
/** The page each kind of integration gets once it is connected. */
const TYPE_PAGES: Record<IntegrationType, string> = {
tailscale: "/tailscale",
proxmox: "/proxmox",
synology: "/synology",
semaphore: "/semaphore",
gitea: "/gitea",
dockhand: "/docker",
uptimekuma: "/uptime-kuma",
phpipam: "/ipam",
pbs: "/pbs",
osticket: "/osticket",
};
/** "pve.example.lan" out of "https://pve.example.lan:8006/", or the text itself when it isn't an address. */
function hostOf(baseUrl: string): string {
if (!baseUrl) return "";
try {
return new URL(baseUrl).host;
} catch {
return baseUrl;
}
}
function HealthBadge({ i }: { i: IntegrationSummary }) {
const health = i.health;
if (!i.enabled || health?.status === "disabled") return <span className="badge bg-secondary-lt text-secondary">Disabled</span>;
if (health?.status === "failing") {
return (
<span className="badge bg-red-lt text-red">
Failing — last {health.consecutiveFailures} call{health.consecutiveFailures === 1 ? "" : "s"} failed
</span>
);
}
if (health?.status === "ok") return <span className="badge bg-green-lt text-green">Working</span>;
return (
<span className="badge bg-secondary-lt text-secondary" title="Nothing has called it since the app started. Use Test to check it now.">
Not checked yet
</span>
);
}
function typeBadgeStyle(colors: Record<string, string>, type: IntegrationType): CSSProperties {
const color = colors[type];
if (!color) return {};
@@ -93,7 +135,8 @@ export default function Integrations({ user }: { user: CurrentUser }) {
}
}
const { sorted: sortedIntegrations, sortKey, sortDir, requestSort } = useSortable(integrations);
const tableSearch = useTableSearch(integrations);
const sortedIntegrations = tableSearch.filtered ? [...tableSearch.filtered].sort((a, b) => a.name.localeCompare(b.name)) : null;
function exportCsv() {
if (!sortedIntegrations) return;
@@ -143,83 +186,78 @@ export default function Integrations({ user }: { user: CurrentUser }) {
)
)}
<div className="card">
<div className="card-header justify-content-end">
<button className="btn btn-outline-secondary btn-sm" onClick={exportCsv} disabled={!integrations || integrations.length === 0}>
Export CSV
</button>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<IntegrationSummary> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<IntegrationSummary> label="Type" sortKeyName="type" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<IntegrationSummary>
label="Status"
sortKeyName="enabled"
activeKey={sortKey}
direction={sortDir}
onSort={requestSort}
<div className="card mb-3">
<TableToolbar
search={tableSearch.query}
onSearch={tableSearch.setQuery}
placeholder="Search integrations…"
shown={sortedIntegrations?.length}
total={integrations?.length}
onExport={exportCsv}
exportDisabled={!integrations || integrations.length === 0}
/>
{isAdmin && <th className="w-1">Actions</th>}
</tr>
</thead>
<tbody>
{sortedIntegrations?.map((i) => (
<tr key={i.id}>
<td>{i.name}</td>
<td>
<span className="badge" style={typeBadgeStyle(integrationColors, i.type)}>
</div>
<div className="row row-cards">
{sortedIntegrations?.map((i) => {
const result = testResults[i.id];
const page = TYPE_PAGES[i.type];
return (
<div className="col-md-6 col-xl-4" key={i.id}>
<div className="card h-100">
<div className="card-body d-flex flex-column">
<div className="d-flex align-items-start gap-2 mb-2">
<div className="flex-fill" style={{ minWidth: 0 }}>
<div className="fw-bold text-truncate">{i.name}</div>
<div className="text-secondary small text-truncate">{hostOf(i.baseUrl) || "no web address"}</div>
</div>
<span className="badge flex-shrink-0" style={typeBadgeStyle(integrationColors, i.type)}>
{TYPE_LABELS[i.type]}
</span>
</td>
<td>
{isAdmin ? (
<button
className={`badge ${i.enabled ? "bg-green-lt text-green" : "bg-secondary-lt text-secondary"} border-0`}
onClick={() => toggleEnabled(i)}
>
{i.enabled ? "Enabled" : "Disabled"}
</button>
) : (
<span className={`badge ${i.enabled ? "bg-green-lt text-green" : "bg-secondary-lt text-secondary"}`}>
{i.enabled ? "Enabled" : "Disabled"}
</div>
<div className="mb-3">
<HealthBadge i={i} />
{result && testingId !== i.id && (
<span className={`badge ms-2 ${result.ok ? "bg-green-lt text-green" : "bg-red-lt text-red"}`}>
Test {result.ok ? `passed${result.latencyMs !== undefined ? ` (${result.latencyMs}ms)` : ""}` : "failed"}
</span>
)}
</td>
</div>
{result && !result.ok && testingId !== i.id && <div className="text-red small mb-3">{result.error}</div>}
<div className="btn-list mt-auto">
{i.enabled && (
<Link to={page} className="btn btn-sm btn-primary">
Open
</Link>
)}
{isAdmin && (
<td>
<div className="btn-list flex-nowrap align-items-center">
<>
<button className="btn btn-sm" onClick={() => testIntegration(i)} disabled={testingId === i.id}>
{testingId === i.id ? "Testing…" : "Test"}
</button>
{testResults[i.id] && testingId !== i.id && (
<span className={`badge ${testResults[i.id].ok ? "bg-green-lt text-green" : "bg-red-lt text-red"}`}>
{testResults[i.id].ok
? `OK${testResults[i.id].latencyMs !== undefined ? ` (${testResults[i.id].latencyMs}ms)` : ""}`
: "Failed"}
</span>
)}
<button className="btn btn-sm" onClick={() => setEditingIntegration(i)}>
Edit
</button>
<button className="btn btn-sm" onClick={() => toggleEnabled(i)}>
{i.enabled ? "Disable" : "Enable"}
</button>
<button className="btn btn-sm btn-outline-danger" onClick={() => removeIntegration(i)}>
Delete
</button>
</>
)}
</div>
{testResults[i.id] && !testResults[i.id].ok && testingId !== i.id && (
<div className="text-red small mt-1">{testResults[i.id].error}</div>
)}
</td>
)}
</tr>
))}
</div>
</div>
</div>
);
})}
{sortedIntegrations?.length === 0 && (
<tr>
<td colSpan={isAdmin ? 4 : 3} className="text-secondary text-center">
No integrations configured yet.
{isAdmin && (
<div className="col-12">
<div className="card">
<div className="card-body text-secondary text-center">
{tableSearch.active ? "Nothing matches that search." : "No integrations configured yet."}
{isAdmin && !tableSearch.active && (
<>
{" "}
<button className="btn btn-link p-0 align-baseline" onClick={() => setAdding(true)}>
@@ -228,13 +266,11 @@ export default function Integrations({ user }: { user: CurrentUser }) {
.
</>
)}
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
)}
</div>
</>
);
}
+5
View File
@@ -13,12 +13,14 @@ import {
type TaskRecord,
} from "../api/client";
import ServerPorts from "../components/ServerPorts";
import ServerTrends from "../components/ServerTrends";
import ServerTags from "../components/ServerTags";
import ServerTaskTable, { SCHEDULE_TYPE_LABELS } from "../components/ServerTaskTable";
import { formatDateTime } from "../utils/date";
import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
import { confirmDialog } from "../utils/dialogs";
import { ErrorNotice } from "../components/Notice";
import { useBreadcrumbTail } from "../utils/breadcrumb";
const SCHEDULE_TYPE_OPTIONS: { value: ScheduleType; label: string }[] = Object.entries(SCHEDULE_TYPE_LABELS).map(
([value, label]) => ({ value: value as ScheduleType, label }),
@@ -92,6 +94,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
const canEditTasks = user.role === "admin" || user.role === "operator";
const [detail, setDetail] = useState<ServerDetailResponse | null>(null);
useBreadcrumbTail(detail?.server.name);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
@@ -750,6 +753,8 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</div>
</div>
{hardware.source === "agent" && <ServerTrends serverId={serverId} />}
<ServerPorts
serverId={serverId}
addresses={[...ipAddresses, ...(server.hostname && !ipAddresses.includes(server.hostname) ? [server.hostname] : [])]}
+119
View File
@@ -145,6 +145,125 @@ html[data-env] .navbar-vertical {
background: color-mix(in srgb, currentColor 14%, transparent);
}
/* ── Status badges carry a symbol as well as a colour, so red, amber and green never have to be told apart by colour alone. ── */
.badge.bg-green-lt:not(:empty)::before,
.badge.bg-red-lt:not(:empty)::before,
.badge.bg-yellow-lt:not(:empty)::before {
display: inline-block;
margin-right: 0.35em;
font-weight: 700;
}
.badge.bg-green-lt:not(:empty)::before {
content: "✓";
content: "✓" / "";
}
.badge.bg-red-lt:not(:empty)::before {
content: "✕";
content: "✕" / "";
}
.badge.bg-yellow-lt:not(:empty)::before {
content: "▲";
content: "▲" / "";
font-size: 0.75em;
vertical-align: 0.1em;
}
/* ── On a phone, wide tables become a stack of cards: each row a card, each cell labelled with its column (data-label is set by useStackedTables). ── */
@media (max-width: 767.98px) {
.card > .table-responsive {
overflow: visible;
}
.card-table,
.card-table tbody,
.card-table tr {
display: block;
width: 100%;
}
.card-table thead {
display: none;
}
.card-table tbody tr {
padding: 0.5rem 0.9rem;
border-bottom: 1px solid var(--tblr-border-color);
}
.card-table tbody tr:last-child {
border-bottom: 0;
}
.card-table tbody td {
position: relative;
display: block;
min-height: 1.5rem;
padding: 0.25rem 0 0.25rem 40% !important;
overflow-wrap: anywhere;
text-align: left;
border: 0 !important;
}
.card-table tbody td[data-label]::before {
position: absolute;
top: 0.3rem;
left: 0;
width: 36%;
padding-right: 0.5rem;
font-size: 0.72rem;
font-weight: 600;
color: var(--tblr-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
content: attr(data-label);
}
/* Cells with no heading (a tick-box, the action buttons, a "nothing here" row) use the whole width. */
.card-table tbody td:not([data-label]) {
padding-left: 0 !important;
}
}
/* ── Trends on a server's page: a label, a small line, the latest figure, and a few words about where it is heading. ── */
.trend-row {
display: grid;
grid-template-columns: 9rem minmax(8rem, 14rem) 3.5rem 1fr;
align-items: center;
gap: 0.75rem;
padding: 0.4rem 0;
border-bottom: 1px solid var(--tblr-border-color);
}
.trend-row:last-child {
border-bottom: 0;
}
.trend-now {
font-weight: 600;
text-align: right;
}
.sparkline {
display: block;
width: 100%;
height: 2.25rem;
color: var(--tblr-secondary);
}
@media (max-width: 767.98px) {
.trend-row {
grid-template-columns: 1fr 3.5rem;
}
.trend-row .sparkline,
.trend-row .trend-words {
grid-column: 1 / -1;
}
}
/* Sidebar submenus: a little tighter than Tabler's dropdown rows, so several open groups still fit on one screen. */
.navbar-vertical .dropdown-menu .dropdown-item {
padding-top: 0.3rem;
+32
View File
@@ -0,0 +1,32 @@
import { useEffect, useSyncExternalStore } from "react";
// The last step of the breadcrumb on a page about one particular thing ("Infrastructure › Servers › elsa"). The pages that know
// the name — a server's detail page — set it with useBreadcrumbTail(); the shell draws the rest from the menu.
let tail: string | null = null;
const listeners = new Set<() => void>();
function set(next: string | null) {
if (next === tail) return;
tail = next;
for (const l of listeners) l();
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function useBreadcrumbTailValue(): string | null {
return useSyncExternalStore(subscribe, () => tail);
}
/** Names the thing this page is about, for the breadcrumb. Pass nothing (or undefined) until it is known. */
export function useBreadcrumbTail(name: string | null | undefined): void {
useEffect(() => {
set(name ?? null);
return () => set(null);
}, [name]);
}