UniFi: servers plugged into switches; server page in sections; My work; settings search and undo

UniFi: the controller's client list is matched to servers by IP address, so a
server is connected through a switch or access point (and port). That is a
dependency made by itself, shown on the server page, the Network devices page
and the Connections map. IP Addresses can sync the devices' addresses.

A server's page is split into Overview, Health, Network, History, Tasks and
Settings, by ?view=; alerts link to the section they are about.

My work lists what has your name on it: alerts you have, maintenance you
started (extend, end with undo) and update runs you started, with a badge.

Settings has a search box (and the command palette lists every setting).
Removing a dependency, admin link, runbook, hand-made IP address, port opening
or restore test is undone from the message instead of asked about first.

Two backup tests used a fixed date and failed as days passed; they follow the
real clock now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 19:35:45 +02:00
1 parent 396e074108
commit 5e26e77340
45 files changed
+6224 -194

No files matched your search

+8 -8
View File
@@ -1,3 +1,4 @@
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { Link } from "react-router-dom";
import { api, type AdminLink, type CurrentUser, type PortEntry, type ServerRecord } from "../api/client";
@@ -5,7 +6,6 @@ import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh";
import { downloadCsv } from "../utils/csv";
import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
import { confirmDialog } from "../utils/dialogs";
import { ErrorNotice } from "../components/Notice";
import TableToolbar from "../components/TableToolbar";
import { EmptyRow, LoadingRow } from "../components/EmptyState";
@@ -137,14 +137,14 @@ export default function AdminLinks({ user }: { user: CurrentUser }) {
}
async function remove(link: AdminLink) {
if (!(await confirmDialog({ title: "Remove admin link", message: `Remove the "${link.label}" link from ${link.serverName}?`, confirmLabel: "Remove", danger: true }))) return;
setError(null);
try {
await api.servers.removeLink(link.serverId, link.id);
load();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
await removeWithUndo({
remove: () => api.servers.removeLink(link.serverId, link.id),
restore: () => api.servers.addLink(link.serverId, { label: link.label, url: link.url }),
message: `Removed the "${link.label}" link from ${link.serverName}.`,
reload: load,
onError: setError,
});
}
const showForm = adding || editing;
+11 -9
View File
@@ -1,7 +1,7 @@
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api, type BackupCoverage, type CoverageGuest, type CoverageStatus, type CurrentUser, type RestoreInfo, type RestoreResult, type RestoreStatus, type RestoreTestEntry } from "../api/client";
import { confirmDialog } from "../utils/dialogs";
import { toast } from "../utils/toast";
import Pagination from "../components/Pagination";
import SortableTh from "../components/SortableTh";
@@ -96,14 +96,16 @@ export default function Backups({ user }: { user?: CurrentUser }) {
}
async function removeTest(t: RestoreTestEntry) {
if (!(await confirmDialog({ title: "Remove a restore test", message: `Remove the test of "${t.label}" from ${t.testedAt}?`, confirmLabel: "Remove", danger: true }))) return;
try {
await api.backups.removeRestoreTest(t.id);
loadTests();
load();
} catch (err) {
setError(readableError(err));
}
await removeWithUndo({
remove: () => api.backups.removeRestoreTest(t.id),
restore: () => api.backups.recordRestoreTest({ key: t.subjectKey, label: t.label, testedAt: t.testedAt, result: t.result, note: t.note ?? undefined }),
message: `Removed the test of "${t.label}" from ${t.testedAt}.`,
reload: () => {
loadTests();
load();
},
onError: setError,
});
}
const [params, setParams] = useSearchParams();
+18
View File
@@ -1,3 +1,4 @@
import { useMyWork } from "../hooks/useMyWork";
import { isValidElement, useEffect, useState, type ReactNode } from "react";
import { IconArrowLeft, IconArrowRight, IconEye, IconEyeOff } from "@tabler/icons-react";
import TimeAgo from "../components/TimeAgo";
@@ -324,6 +325,22 @@ function formatBytes(bytes: number | null): string {
return `${value.toFixed(1)} ${units[unit]}`;
}
/** One line above the cards for those who follow things: how many of theirs want a look, and where to see them. Says nothing when none do. */
function MyWorkStrip() {
const { work } = useMyWork();
if (!work || work.needsAttention === 0) return null;
return (
<div className="alert alert-info d-flex flex-wrap align-items-center gap-2 py-2" role="status">
<span>
<strong>{work.needsAttention}</strong> {work.needsAttention === 1 ? "thing" : "things"} of yours {work.needsAttention === 1 ? "wants" : "want"} a look — alerts handed to you or about to run out, maintenance about to end, update runs still going.
</span>
<Link to="/my-work" className="btn btn-sm btn-primary ms-auto">
My work
</Link>
</div>
);
}
export default function Dashboard({ user }: { user: CurrentUser }) {
const { editing } = useDashboardLayout();
const problemsFirst = useProblemsFirst();
@@ -687,6 +704,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
Welcome back, {user.name ?? user.email ?? user.sub}.
</p>
<StatusStrip />
{(user.role === "admin" || user.role === "operator") && <MyWorkStrip />}
<WhatChanged role={user.role} />
{isAdmin && integrations !== null && dnsStats !== null && serverSummary !== null && secrets !== null && notifyConfigured !== null && (
<SetupGuide steps={setupSteps} />
+45 -11
View File
@@ -1,3 +1,5 @@
import { toast } from "../utils/toast";
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { api, type CurrentUser, type IpamEntry, type IpamInput } from "../api/client";
@@ -33,7 +35,7 @@ export default function Ipam({ user }: { user: CurrentUser }) {
const [adding, setAdding] = useState(false);
const [form, setForm] = useState<IpamInput>(emptyForm);
const [saving, setSaving] = useState(false);
const [syncing, setSyncing] = useState<"tailscale" | "proxmox" | "phpipam" | null>(null);
const [syncing, setSyncing] = useState<"tailscale" | "proxmox" | "phpipam" | "unifi" | null>(null);
const [syncResult, setSyncResult] = useState<string | null>(null);
const selection = useSelection<number>();
const [bulkDeleting, setBulkDeleting] = useState(false);
@@ -146,47 +148,76 @@ export default function Ipam({ user }: { user: CurrentUser }) {
}
}
/** What is needed to make an entry again; one that a sync made would come back as a hand-made one, so those are still asked about. */
const asInput = (e: IpamEntry): IpamInput => ({ ipAddress: e.ipAddress, label: e.label ?? undefined, vendor: e.vendor ?? undefined, location: e.location ?? undefined, notes: e.notes ?? undefined });
async function remove(entry: IpamEntry) {
if (!(await confirmDialog({ title: "Delete IP address", message: `Delete IP address "${entry.ipAddress}"?`, confirmLabel: "Delete", danger: true }))) return;
setError(null);
try {
await api.ipam.remove(entry.id);
load();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
if (entry.source) {
if (!(await confirmDialog({ title: "Delete IP address", message: `Delete IP address "${entry.ipAddress}"? A sync can bring it back.`, confirmLabel: "Delete", danger: true }))) return;
try {
await api.ipam.remove(entry.id);
load();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
return;
}
await removeWithUndo({
remove: () => api.ipam.remove(entry.id),
restore: () => api.ipam.create(asInput(entry)),
message: `Deleted ${entry.ipAddress}.`,
reload: load,
onError: setError,
});
}
async function bulkDelete() {
const ids = Array.from(selection.selected);
if (ids.length === 0) return;
if (!(await confirmDialog({ title: "Delete IP addresses", message: `Delete ${ids.length} IP address${ids.length !== 1 ? "es" : ""}?`, confirmLabel: "Delete", danger: true }))) return;
const picked = (entries ?? []).filter((e) => ids.includes(e.id));
const plain = picked.length === ids.length && picked.every((e) => !e.source);
if (!plain && !(await confirmDialog({ title: "Delete IP addresses", message: `Delete ${ids.length} IP address${ids.length !== 1 ? "es" : ""}? Those a sync made can be brought back by it.`, confirmLabel: "Delete", danger: true }))) return;
setError(null);
setBulkDeleting(true);
try {
const results = await Promise.allSettled(ids.map((id) => api.ipam.remove(id)));
const failed = results.filter((r) => r.status === "rejected").length;
if (failed > 0) setError(`${failed} of ${ids.length} deletions failed.`);
const gone = picked.filter((_, i) => results[ids.indexOf(picked[i].id)]?.status === "fulfilled");
selection.clear();
load();
if (plain && gone.length > 0) {
toast.success(`Deleted ${gone.length} IP address${gone.length !== 1 ? "es" : ""}.`, {
label: "Undo",
onClick: async () => {
const back = await Promise.allSettled(gone.map((e) => api.ipam.create(asInput(e))));
const lost = back.filter((r) => r.status === "rejected").length;
if (lost > 0) toast.error(`${lost} could not be put back.`);
else toast.info("Put back.");
load();
},
});
}
} finally {
setBulkDeleting(false);
}
}
const SYNC_LABELS: Record<"tailscale" | "proxmox" | "phpipam", string> = {
const SYNC_LABELS: Record<"tailscale" | "proxmox" | "phpipam" | "unifi", string> = {
tailscale: "Tailscale",
proxmox: "Proxmox",
phpipam: "phpIPAM",
unifi: "UniFi",
};
async function runSync(source: "tailscale" | "proxmox" | "phpipam") {
async function runSync(source: "tailscale" | "proxmox" | "phpipam" | "unifi") {
setError(null);
setSyncResult(null);
setSyncing(source);
try {
const res =
source === "tailscale" ? await api.ipam.syncTailscale() : source === "proxmox" ? await api.ipam.syncProxmox() : await api.ipam.syncPhpIpam();
source === "tailscale" ? await api.ipam.syncTailscale() : source === "proxmox" ? await api.ipam.syncProxmox() : source === "unifi" ? await api.ipam.syncUnifi() : await api.ipam.syncPhpIpam();
const parts = [`${res.added} added`, `${res.updated} updated`];
if (res.skipped > 0) parts.push(`${res.skipped} skipped (already tracked manually)`);
setSyncResult(`${SYNC_LABELS[source]}: ${parts.join(", ")}`);
@@ -378,6 +409,9 @@ export default function Ipam({ user }: { user: CurrentUser }) {
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("phpipam")} disabled={!!syncing}>
{syncing === "phpipam" ? "Syncing…" : "Sync from phpIPAM"}
</button>
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("unifi")} disabled={!!syncing}>
{syncing === "unifi" ? "Syncing…" : "Sync from UniFi"}
</button>
</>
)}
</>
+14 -7
View File
@@ -15,7 +15,7 @@ const COL_GAP = 130;
const STATUS_SYMBOL: Record<MapNode["status"], string> = { ok: "✓", bad: "✕", warn: "▲", unknown: "·" };
const STATUS_WORD: Record<MapNode["status"], string> = { ok: "working", bad: "problem", warn: "check", unknown: "no status" };
const KIND_WORD: Record<MapNode["kind"], string> = { host: "Proxmox host", server: "Server", dns: "DNS name", monitor: "Uptime Kuma monitor" };
const KIND_WORD: Record<MapNode["kind"], string> = { host: "Proxmox host", server: "Server", dns: "DNS name", monitor: "Uptime Kuma monitor", device: "Network device" };
interface Placed extends MapNode {
x: number;
@@ -30,15 +30,22 @@ function layout(data: MapData): { placed: Map<string, Placed>; width: number; he
neighbours.set(e.to, [...(neighbours.get(e.to) ?? []), e.from]);
}
const byKind = (kinds: MapNode["kind"][]) => data.nodes.filter((n) => kinds.includes(n.kind));
const hosts = byKind(["host"]).sort((a, b) => a.label.localeCompare(b.label));
// Proxmox hosts and the switches and access points servers are plugged into share the left-hand column.
const hosts = byKind(["host", "device"]).sort((a, b) => a.label.localeCompare(b.label));
const serverNodes = byKind(["server"]);
const rightNodes = byKind(["dns", "monitor"]);
// Servers grouped under their host, then those with none.
const hostOf = (s: MapNode) => (neighbours.get(s.id) ?? []).find((id) => id.startsWith("host:"));
const hostOf = (s: MapNode) => (neighbours.get(s.id) ?? []).find((id) => id.startsWith("host:")) ?? (neighbours.get(s.id) ?? []).find((id) => id.startsWith("device:"));
const servers: MapNode[] = [];
for (const h of hosts) servers.push(...serverNodes.filter((s) => hostOf(s) === h.id).sort((a, b) => a.label.localeCompare(b.label)));
servers.push(...serverNodes.filter((s) => !hostOf(s)).sort((a, b) => a.label.localeCompare(b.label)));
const placedServers = new Set<string>();
for (const h of hosts) {
for (const s of serverNodes.filter((s) => hostOf(s) === h.id && !placedServers.has(s.id)).sort((a, b) => a.label.localeCompare(b.label))) {
servers.push(s);
placedServers.add(s.id);
}
}
servers.push(...serverNodes.filter((s) => !placedServers.has(s.id)).sort((a, b) => a.label.localeCompare(b.label)));
const step = NODE_H + GAP_Y;
const placed = new Map<string, Placed>();
@@ -69,7 +76,7 @@ function layout(data: MapData): { placed: Map<string, Placed>; width: number; he
const height = all.length ? Math.max(...all.map((p) => p.y)) + NODE_H : 0;
const width = Math.max(...all.map((p) => p.x), 0) + NODE_W;
const columns = [
...(hasHosts ? [{ x: colX[0], title: "Proxmox hosts" }] : []),
...(hasHosts ? [{ x: colX[0], title: byKind(["host"]).length > 0 && byKind(["device"]).length > 0 ? "Proxmox hosts & network devices" : byKind(["device"]).length > 0 ? "Network devices" : "Proxmox hosts" }] : []),
...(servers.length > 0 ? [{ x: colX[1], title: "Servers" }] : []),
...(hasRight ? [{ x: colX[2], title: "DNS names & monitors" }] : []),
];
@@ -146,7 +153,7 @@ function ConnectionsMap() {
return (
<>
<p className="text-secondary">
How things connect: which Proxmox host a server runs on, which DNS names point at it, and which Uptime Kuma monitors watch it. Hover or tab to a box to light up what it is
How things connect: which Proxmox host a server runs on, which switch or access point it is plugged into (from a UniFi controller), which DNS names point at it, and which Uptime Kuma monitors watch it. Hover or tab to a box to light up what it is
connected to.
</p>
<ErrorNotice error={error} />
+241
View File
@@ -0,0 +1,241 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { api, type AlertItem, type CurrentUser, type MyWork } from "../api/client";
import AckDrawer from "../components/AckDrawer";
import EmptyState from "../components/EmptyState";
import { BlockSkeleton } from "../components/Skeleton";
import TimeAgo from "../components/TimeAgo";
import { useAlertsReport } from "../hooks/useAlertsReport";
import { useMyWork } from "../hooks/useMyWork";
import { formatRemaining } from "../utils/duration";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
const SEVERITY: Record<string, string> = { critical: "bg-red-lt text-red", warning: "bg-yellow-lt text-yellow", info: "bg-blue-lt text-blue" };
type Win = MyWork["windows"][number];
/**
* Everything with your name on it, in one place: the alerts you have taken or been handed, the acknowledgements about to run out, the maintenance you started that
* is about to end, and the update runs you are following. What is about to run out is marked, and comes first.
*/
export default function MyWorkPage({ user }: { user: CurrentUser }) {
const { work, reload } = useMyWork();
const { report, reload: reloadAlerts } = useAlertsReport();
const [acking, setAcking] = useState<AlertItem | null>(null);
const [busy, setBusy] = useState<number | null>(null);
const alertById = new Map((report?.alerts ?? []).map((a) => [a.id, a]));
function changed() {
reload();
reloadAlerts();
window.dispatchEvent(new Event("maintenance-changed"));
}
/** Minutes from now that a window should last to end `extra` minutes later than it does now (the server restarts the clock from now). */
const minutesFor = (w: Win, extra: number) => Math.min(7 * 24 * 60, Math.max(5, Math.ceil((Date.parse(w.endsAt) - Date.now()) / 60_000)) + extra);
async function extend(w: Win, extra: number, words: string) {
setBusy(w.id);
try {
await api.maintenance.start({ targetType: w.targetType as never, targetId: w.targetId, minutes: minutesFor(w, extra), reason: w.reason ?? undefined });
toast.success(`${w.targetName}: ${words} more.`);
changed();
} catch (err) {
toast.error(readableError(err));
} finally {
setBusy(null);
}
}
async function end(w: Win) {
setBusy(w.id);
try {
await api.maintenance.end(w.id);
toast.success(`Maintenance on ${w.targetName} ended.`, {
label: "Undo",
onClick: async () => {
try {
await api.maintenance.start({ targetType: w.targetType as never, targetId: w.targetId, minutes: minutesFor(w, 0), reason: w.reason ?? undefined });
toast.info("Put back.");
} catch (err) {
toast.error(readableError(err));
} finally {
changed();
}
},
});
changed();
} catch (err) {
toast.error(readableError(err));
} finally {
setBusy(null);
}
}
const nothing = work !== null && work.alerts.length === 0 && work.windows.length === 0 && work.updateRuns.length === 0;
return (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
<h2 className="page-title mb-0">My work</h2>
</div>
<div className="text-secondary mb-3">
What has your name on it: alerts you acknowledged or were handed, maintenance you started and update runs you started. Whatever is about to run out is marked, and listed first.
</div>
{work === null && <BlockSkeleton lines={4} />}
{nothing && (
<div className="card">
<EmptyState title="Nothing on your plate" hint="When you acknowledge an alert, are handed one, put something under maintenance or start an update run, it is listed here until it is done." />
</div>
)}
{work && work.alerts.length > 0 && (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Alerts you have</h3>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<tbody>
{work.alerts.map((a) => {
const full = alertById.get(a.alertId);
return (
<tr key={a.alertId}>
<td className="w-1">
<span className={`badge ${SEVERITY[a.severity] ?? ""}`}>{a.severity}</span>
</td>
<td className="stack-wide">
{a.link ? <Link to={a.link}>{a.message}</Link> : a.message}
<div className="small text-secondary">
{a.role === "handed" ? (a.ackedBy === (user.name ?? user.email ?? user.sub) ? "You took it" : `Handed to you by ${a.ackedBy}`) : "You acknowledged it"}
{a.note ? ` — ${a.note}` : ""}
</div>
</td>
<td className="stack-label text-nowrap" data-label="Lasts">
{a.until ? (
<span className={a.endsSoon ? "text-yellow" : "text-secondary"} title="When the acknowledgement runs out and the alert counts as nobody's again">
{a.endsSoon ? "Runs out " : "Until "}
<TimeAgo value={a.until} />
</span>
) : (
<span className="text-secondary">until the alert is gone</span>
)}
</td>
<td className="stack-wide text-nowrap">
<div className="btn-list flex-nowrap">
{full && (
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => setAcking(full)}>
Change…
</button>
)}
<Link to="/alerts" className="btn btn-sm btn-outline-secondary">
Alerts
</Link>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
)}
{work && work.windows.length > 0 && (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Maintenance you started</h3>
<div className="card-actions">
<Link to="/maintenance" className="small">
Maintenance
</Link>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<tbody>
{work.windows.map((w) => (
<tr key={w.id}>
<td className="stack-wide">
<strong>{w.targetName}</strong> <span className="text-secondary small">{w.targetKind}</span>
{w.reason && <div className="small text-secondary">{w.reason}</div>}
</td>
<td className="stack-label text-nowrap" data-label="Ends">
<span className={w.endsSoon ? "text-yellow" : "text-secondary"}>
Ends in {formatRemaining(w.endsAt)}
</span>
</td>
<td className="stack-wide text-nowrap">
<div className="btn-list flex-nowrap">
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy === w.id} onClick={() => void extend(w, 60, "1 hour")}>
+1 h
</button>
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy === w.id} onClick={() => void extend(w, 240, "4 hours")}>
+4 h
</button>
<button type="button" className="btn btn-sm btn-outline-danger" disabled={busy === w.id} onClick={() => void end(w)}>
End now
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{work && work.updateRuns.length > 0 && (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Update runs you started</h3>
<div className="card-actions">
<Link to="/updates" className="small">
Updates
</Link>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<tbody>
{work.updateRuns.map((r) => (
<tr key={r.id}>
<td className="stack-wide">
<Link to={`/servers/${r.serverId}`}>{r.serverName}</Link> <span className="text-secondary small">{r.templateName}</span>
{r.message && !r.running && <div className="small text-secondary">{r.message}</div>}
</td>
<td className="stack-label" data-label="State">
{r.running ? (
<span className="badge bg-blue-lt text-blue">Running</span>
) : r.status === "done" ? (
<span className="badge bg-green-lt text-green">Done</span>
) : (
<span className="badge bg-red-lt text-red">{r.status}</span>
)}
{!r.running && r.updatesBefore !== null && r.updatesAfter !== null && (
<span className="text-secondary small ms-2">
{r.updatesBefore} → {r.updatesAfter} waiting{r.rebootRequired ? ", restart needed" : ""}
</span>
)}
</td>
<td className="stack-label text-nowrap" data-label="Started">
<TimeAgo value={r.startedAt} />
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{acking && <AckDrawer alert={acking} me={user} onClose={() => setAcking(null)} onSaved={changed} />}
</>
);
}
+12
View File
@@ -277,6 +277,18 @@ export default function NetworkDevices({ user }: { user: CurrentUser }) {
{d.siteName && d.siteName !== "Default" ? ` · ${d.siteName}` : ""}
</div>
{d.mac && <div className="text-secondary small font-monospace">{d.mac}</div>}
{d.servers.length > 0 && (
<div className="small" title="Servers the controller says are plugged into this, matched by their IP address">
Plugged in:{" "}
{d.servers.map((s, i) => (
<span key={`${s.serverId}-${i}`}>
{i > 0 && ", "}
<Link to={`/servers/${s.serverId}`}>{s.serverName}</Link>
{s.port !== null ? ` (port ${s.port})` : s.wired ? "" : " (Wi-Fi)"}
</span>
))}
</div>
)}
</td>
<td className="stack-label" data-label="IP address">
{d.ip ? (
+9 -8
View File
@@ -1,3 +1,4 @@
import { removeWithUndo } from "../utils/undoable";
import { useEffect, useState, type FormEvent } from "react";
import TimeAgo from "../components/TimeAgo";
import { Link } from "react-router-dom";
@@ -15,7 +16,6 @@ import { usePagination } from "../hooks/usePagination";
import Pagination from "../components/Pagination";
import { downloadCsv } from "../utils/csv";
import { formatAgo } from "../utils/duration";
import { confirmDialog } from "../utils/dialogs";
import { ErrorNotice } from "../components/Notice";
import { EmptyRow, LoadingRow } from "../components/EmptyState";
@@ -167,14 +167,15 @@ export default function Ports({ user }: { user: CurrentUser }) {
}
async function remove(fwd: PortForward) {
if (!(await confirmDialog({ title: "Delete port opening", message: `Delete port opening "${fwd.label}"?`, confirmLabel: "Delete", danger: true }))) return;
setForwardError(null);
try {
await api.ports.forwards.remove(fwd.id);
loadForwards();
} catch (err) {
setForwardError(err instanceof Error ? err.message : String(err));
}
await removeWithUndo({
remove: () => api.ports.forwards.remove(fwd.id),
restore: () =>
api.ports.forwards.create({ label: fwd.label, externalPort: fwd.externalPort, protocol: fwd.protocol, serverId: fwd.serverId, destination: fwd.destination, internalPort: fwd.internalPort, source: fwd.source, comment: fwd.comment }),
message: `Deleted the port opening "${fwd.label}".`,
reload: loadForwards,
onError: setForwardError,
});
}
const showForm = adding || editing;
+161 -109
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { Link, useParams, useSearchParams } from "react-router-dom";
import {
api,
type CurrentUser,
@@ -32,9 +32,12 @@ import ServerTaskTable, { SCHEDULE_TYPE_LABELS } from "../components/ServerTaskT
import { formatDateTime } from "../utils/date";
import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
import { confirmDialog } from "../utils/dialogs";
import { removeWithUndo } from "../utils/undoable";
import { ErrorNotice } from "../components/Notice";
import { useBreadcrumbTail } from "../utils/breadcrumb";
import { PageSkeleton } from "../components/Skeleton";
import ViewTabs from "../components/ViewTabs";
import ConnectedThrough from "../components/ConnectedThrough";
const SCHEDULE_TYPE_OPTIONS: { value: ScheduleType; label: string }[] = Object.entries(SCHEDULE_TYPE_LABELS).map(
([value, label]) => ({ value: value as ScheduleType, label }),
@@ -101,8 +104,22 @@ const emptyTaskForm = {
enabled: true,
};
/** The sections of a server's page, switched by `?view=`: what it is, how it is doing, how it is connected, how it has been, what runs on it, and how it is set up. */
const SECTIONS = [
{ key: "overview", label: "Overview" },
{ key: "health", label: "Health" },
{ key: "network", label: "Network" },
{ key: "history", label: "History" },
{ key: "tasks", label: "Tasks" },
{ key: "settings", label: "Settings" },
] as const;
type SectionKey = (typeof SECTIONS)[number]["key"];
export default function ServerDetail({ user }: { user: CurrentUser }) {
const { id } = useParams<{ id: string }>();
const [searchParams] = useSearchParams();
const requested = searchParams.get("view");
const view: SectionKey = SECTIONS.some((t) => t.key === requested) ? (requested as SectionKey) : "overview";
const serverId = Number(id);
const isAdmin = user.role === "admin";
const canEditTasks = user.role === "admin" || user.role === "operator";
@@ -349,13 +366,13 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
}
async function removeAdminLink(link: ServerLink) {
if (!(await confirmDialog({ title: "Remove admin link", message: `Remove the "${link.label}" link?`, confirmLabel: "Remove", danger: true }))) return;
try {
await api.servers.removeLink(serverId, link.id);
await loadDetail();
} catch (err) {
setAdminLinkError(err instanceof Error ? err.message : String(err));
}
await removeWithUndo({
remove: () => api.servers.removeLink(serverId, link.id),
restore: () => api.servers.addLink(serverId, { label: link.label, url: link.url }),
message: `Removed the "${link.label}" link.`,
reload: () => void loadDetail(),
onError: setAdminLinkError,
});
}
if (loading) return <PageSkeleton />;
@@ -418,6 +435,13 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
onSaved={(tags) => setDetail((d) => (d ? { ...d, server: { ...d.server, tags } } : d))}
/>
<ViewTabs
label="Sections of this server's page"
tabs={SECTIONS.map((t) => ({ to: t.key === "overview" ? `/servers/${serverId}` : `/servers/${serverId}?view=${t.key}`, label: t.key === "tasks" && tasks && tasks.length > 0 ? `Tasks (${tasks.length})` : t.label, active: view === t.key }))}
/>
{view === "overview" && (
<>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Admin Links</h3>
@@ -510,91 +534,6 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</div>
</div>
{isAdmin && (server.proxmoxIntegrationId || !server.hideProxmoxLink) ? (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Proxmox link</h3>
{!server.proxmoxIntegrationId && (
<div className="card-actions">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(true)}>
Not a VM? Hide this
</button>
</div>
)}
</div>
<div className="card-body">
{server.proxmoxIntegrationId ? (
<div className="d-flex align-items-center gap-3">
<span className="text-secondary">
Linked to {hardware.integrationName ?? "a Proxmox integration"} — {server.proxmoxGuestType}/{server.proxmoxVmid} on{" "}
{server.proxmoxNode}
</span>
<button className="btn btn-outline-danger btn-sm ms-auto" onClick={unlinkProxmox} disabled={linking}>
Unlink
</button>
</div>
) : (proxmoxIntegrations?.length ?? 0) === 0 ? (
<div className="text-secondary">No enabled Proxmox integrations configured yet.</div>
) : (
<div className="row g-2 align-items-end">
<div className="col-md-4">
<label className="form-label">Proxmox integration</label>
<select
className="form-select"
value={pickedIntegrationId ?? ""}
onChange={(e) => {
setPickedIntegrationId(e.target.value ? Number(e.target.value) : null);
setPickedGuestKey("");
}}
>
<option value="">Choose…</option>
{proxmoxIntegrations?.map((i) => (
<option key={i.id} value={i.id}>
{i.name}
</option>
))}
</select>
</div>
<div className="col-md-5">
<label className="form-label">VM / LXC</label>
<select
className="form-select"
value={pickedGuestKey}
disabled={!proxmoxGuests}
onChange={(e) => setPickedGuestKey(e.target.value)}
>
<option value="">Choose…</option>
{proxmoxGuests?.map((g) => (
<option key={`${g.node}/${g.type}/${g.vmid}`} value={`${g.node}/${g.type}/${g.vmid}`}>
{g.name} ({g.type} #{g.vmid} on {g.node})
</option>
))}
</select>
</div>
<div className="col-md-3">
<button className="btn btn-primary w-100" onClick={linkProxmox} disabled={linking || !pickedGuestKey}>
{linking ? "Linking…" : "Link"}
</button>
</div>
{linkError && (
<div className="col-12">
<div className="alert alert-danger mb-0 mt-2">{linkError}</div>
</div>
)}
</div>
)}
</div>
</div>
) : (
isAdmin && (
<div className="mb-3">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(false)}>
+ Show Proxmox link options
</button>
</div>
)
)}
<div className="row row-cards mb-3">
<div className="col-lg-7">
<div className="card h-100">
@@ -604,7 +543,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
<div className="card-body">
{hardware.source === "none" && (
<div className="text-secondary">
No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC above.
No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC (under Settings).
</div>
)}
{hardware.error && <div className="alert alert-danger">{hardware.error}</div>}
@@ -812,6 +751,19 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</div>
</div>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Runbooks</h3>
</div>
<div className="card-body">
<RunbookPanel targetType="server" targetId={server.id} targetName={server.name} canEdit={canEditTasks} />
</div>
</div>
</>
)}
{view === "health" && (
<>
<HostHealthCard
health={server.hostHealth}
ignored={server.thresholds?.ignoreServices ?? []}
@@ -831,17 +783,30 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
}
/>
<AgentDiagnostics notes={detail.diagnostics ?? []} />
</>
)}
{view === "network" && (
<>
<ConnectedThrough serverId={serverId} />
<ServerPorts
serverId={serverId}
addresses={[...ipAddresses, ...(server.hostname && !ipAddresses.includes(server.hostname) ? [server.hostname] : [])]}
canEdit={canEditTasks}
/>
</>
)}
{view === "history" && (
<>
{hardware.source === "agent" && <ServerTrends serverId={serverId} />}
<ServerThresholds key={JSON.stringify(server.thresholds)} server={server} defaults={detail.thresholdDefaults} disks={(hardware.disks ?? []).map((d) => d.mount)} canEdit={isAdmin} onChanged={() => void loadDetail()} />
{(user.role === "admin" || user.role === "operator") && <ServerActivity serverId={serverId} />}
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Runbooks</h3>
</div>
<div className="card-body">
<RunbookPanel targetType="server" targetId={server.id} targetName={server.name} canEdit={canEditTasks} />
</div>
</div>
</>
)}
{view === "tasks" && (
<>
{canEditTasks && (
<div className="card mb-3">
<div className="card-header">
@@ -853,12 +818,6 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</div>
)}
<ServerPorts
serverId={serverId}
addresses={[...ipAddresses, ...(server.hostname && !ipAddresses.includes(server.hostname) ? [server.hostname] : [])]}
canEdit={canEditTasks}
/>
<div className="d-flex align-items-center mb-3">
<h3 className="mb-0">Tasks</h3>
{canEditTasks && (
@@ -956,6 +915,99 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
<ServerTaskTable tasks={tasks} canEditTasks={canEditTasks} onEdit={openEditTask} onDelete={deleteTask} />
)}
</div>
</>
)}
{view === "settings" && (
<>
{isAdmin && (server.proxmoxIntegrationId || !server.hideProxmoxLink) ? (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Proxmox link</h3>
{!server.proxmoxIntegrationId && (
<div className="card-actions">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(true)}>
Not a VM? Hide this
</button>
</div>
)}
</div>
<div className="card-body">
{server.proxmoxIntegrationId ? (
<div className="d-flex align-items-center gap-3">
<span className="text-secondary">
Linked to {hardware.integrationName ?? "a Proxmox integration"} — {server.proxmoxGuestType}/{server.proxmoxVmid} on{" "}
{server.proxmoxNode}
</span>
<button className="btn btn-outline-danger btn-sm ms-auto" onClick={unlinkProxmox} disabled={linking}>
Unlink
</button>
</div>
) : (proxmoxIntegrations?.length ?? 0) === 0 ? (
<div className="text-secondary">No enabled Proxmox integrations configured yet.</div>
) : (
<div className="row g-2 align-items-end">
<div className="col-md-4">
<label className="form-label">Proxmox integration</label>
<select
className="form-select"
value={pickedIntegrationId ?? ""}
onChange={(e) => {
setPickedIntegrationId(e.target.value ? Number(e.target.value) : null);
setPickedGuestKey("");
}}
>
<option value="">Choose…</option>
{proxmoxIntegrations?.map((i) => (
<option key={i.id} value={i.id}>
{i.name}
</option>
))}
</select>
</div>
<div className="col-md-5">
<label className="form-label">VM / LXC</label>
<select
className="form-select"
value={pickedGuestKey}
disabled={!proxmoxGuests}
onChange={(e) => setPickedGuestKey(e.target.value)}
>
<option value="">Choose…</option>
{proxmoxGuests?.map((g) => (
<option key={`${g.node}/${g.type}/${g.vmid}`} value={`${g.node}/${g.type}/${g.vmid}`}>
{g.name} ({g.type} #{g.vmid} on {g.node})
</option>
))}
</select>
</div>
<div className="col-md-3">
<button className="btn btn-primary w-100" onClick={linkProxmox} disabled={linking || !pickedGuestKey}>
{linking ? "Linking…" : "Link"}
</button>
</div>
{linkError && (
<div className="col-12">
<div className="alert alert-danger mb-0 mt-2">{linkError}</div>
</div>
)}
</div>
)}
</div>
</div>
) : (
isAdmin && (
<div className="mb-3">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(false)}>
+ Show Proxmox link options
</button>
</div>
)
)}
<ServerThresholds key={JSON.stringify(server.thresholds)} server={server} defaults={detail.thresholdDefaults} disks={(hardware.disks ?? []).map((d) => d.mount)} canEdit={isAdmin} onChanged={() => void loadDetail()} />
</>
)}
</>
);
}
+37 -2
View File
@@ -1,5 +1,6 @@
import type { CSSProperties } from "react";
import { NavLink, Outlet } from "react-router-dom";
import { useMemo, useState, type CSSProperties } from "react";
import { Link, NavLink, Outlet } from "react-router-dom";
import { searchSettings } from "../utils/settingsIndex";
const SUB_NAV = [
{ to: "/settings/notifications", label: "Notifications" },
@@ -12,10 +13,44 @@ const SUB_NAV = [
{ to: "/settings/data", label: "Data" },
];
/** A box that finds a setting by what it does ("quiet hours", "prometheus", "disk full") and goes to where it is set. */
function SettingsSearch() {
const [query, setQuery] = useState("");
const results = useMemo(() => searchSettings(query), [query]);
return (
<div className="mb-3 position-relative" style={{ maxWidth: 520 }}>
<input
type="search"
className="form-control"
placeholder="Find a setting…"
aria-label="Find a setting"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => e.key === "Escape" && setQuery("")}
/>
{query.trim() !== "" && (
<div className="list-group position-absolute w-100 shadow" style={{ zIndex: 20, top: "100%" }} role="listbox" aria-label="Matching settings">
{results.length === 0 ? (
<div className="list-group-item text-secondary">No setting matches that.</div>
) : (
results.map((r) => (
<Link key={r.title + r.to} to={r.to} className="list-group-item list-group-item-action" role="option" aria-selected={false} onClick={() => setQuery("")}>
<div>{r.title}</div>
<div className="small text-secondary">{r.where}</div>
</Link>
))
)}
</div>
)}
</div>
);
}
export default function Settings() {
return (
<>
<h2 className="page-title mb-3">Settings</h2>
<SettingsSearch />
<div className="row">
<div className="col-12 col-md-3 col-lg-2 mb-3 mb-md-0">
<div className="card">