import { useCallback, useEffect, useState, type CSSProperties } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { api, type AgentLatest, type CurrentUser, type ServerRecord } from "../api/client"; import CopyButton from "../components/CopyButton"; import { formatDateTime } from "../utils/date"; import TimeAgo from "../components/TimeAgo"; import UptimeRibbon from "../components/UptimeRibbon"; import { useSortable } from "../hooks/useSortable"; import SortableTh from "../components/SortableTh"; import { usePagination } from "../hooks/usePagination"; import Pagination from "../components/Pagination"; import { downloadCsv } from "../utils/csv"; import { TagBadges } from "../components/ServerTags"; import { AGENT_RUN_HINT, agentOsOf, installCommand, uninstallCommand, type AgentOs } from "../utils/agentCommands"; import { tagBadge, useTagColors } from "../utils/tags"; import { confirmDialog } from "../utils/dialogs"; import { ErrorNotice } from "../components/Notice"; import { toast } from "../utils/toast"; import { readableError } from "../utils/errors"; import { SearchBox } from "../components/TableToolbar"; import { useTableSearch } from "../hooks/useTableSearch"; import SaveViewButton from "../components/SaveViewButton"; import { agentState } from "../utils/agent"; import { BlockSkeleton } from "../components/Skeleton"; import EmptyState, { EmptyRow, LoadingRow } from "../components/EmptyState"; import BulkBar from "../components/BulkBar"; import { RunsOnBulkDrawer, SilenceBulkDrawer, TagBulkDrawer } from "../components/BulkDrawers"; import { doBulk, plural } from "../utils/bulk"; import { BrandTag } from "../components/BrandIcon"; export default function Servers({ user }: { user: CurrentUser }) { const isAdmin = user.role === "admin"; const [servers, setServers] = useState([]); // Until the first answer arrives there is nothing to say about "no servers", so show the page's shape instead of the empty message. const [loaded, setLoaded] = useState(false); const [agentLatest, setAgentLatest] = useState(null); // Whether agents that are behind replace themselves (an administrator's switch). const [autoUpdate, setAutoUpdate] = useState(null); const [error, setError] = useState(null); const [managingServers, setManagingServers] = useState(false); const [integrationColors, setIntegrationColors] = useState>({}); // The active tag filter lives in the URL, so a tag chip on a server's page can link straight to "everything with this tag". const [searchParams, setSearchParams] = useSearchParams(); const selectedTags = searchParams.getAll("tag"); // So is the status chosen ("?status=offline"), which the dashboard links to. const statusParam = searchParams.get("status"); const status: "offline" | "online" | null = statusParam === "offline" || statusParam === "online" ? statusParam : null; const [offlineIds, setOfflineIds] = useState | null>(null); // Picking servers to compare their trends side by side. const [comparing, setComparing] = useState(false); const [picked, setPicked] = useState([]); // Picking servers to change several at once (tags, maintenance, what they run on), and which form is open. const [selecting, setSelecting] = useState(false); const [chosen, setChosen] = useState>(new Set()); const [bulkForm, setBulkForm] = useState<"tag" | "silence" | "runson" | null>(null); const tagColors = useTagColors(); useEffect(() => { api.servers .summary() .then((res) => setOfflineIds(new Set(res.offline.map((o) => o.id)))) .catch(() => {}); }, []); useEffect(() => { api.settings.integrationColors().then((res) => setIntegrationColors(res.integrationColors)).catch(() => {}); }, []); const [serverName, setServerName] = useState(""); const [serverHostname, setServerHostname] = useState(""); const [serverDescription, setServerDescription] = useState(""); const [serverOs, setServerOs] = useState("linux"); const [newToken, setNewToken] = useState<{ server: ServerRecord; token: string } | null>(null); const [uninstallFor, setUninstallFor] = useState(null); const [insecureAgent, setInsecureAgent] = useState(false); const loadServers = useCallback(() => { return api.servers .list() .then((res) => { setServers(res.servers); setAgentLatest(res.agentLatest); setAutoUpdate(res.agentAutoUpdate); }) .catch((err) => setError(String(err))) .finally(() => setLoaded(true)); }, []); useEffect(() => { loadServers(); }, [loadServers]); async function changeAutoUpdate(value: boolean) { setAutoUpdate(value); try { await api.servers.setAgentAutoUpdate(value); toast.success(value ? "Agents that are behind will update themselves at their next run." : "Agents will no longer update themselves."); } catch (err) { setAutoUpdate(!value); toast.error(readableError(err)); } } async function createServer(e: React.FormEvent) { e.preventDefault(); setError(null); try { const result = await api.servers.create({ name: serverName, hostname: serverHostname || undefined, description: serverDescription || undefined, osType: serverOs, }); setNewToken(result); toast.success(`Added ${serverName}. Its install command is shown below.`); setServerName(""); setServerHostname(""); setServerDescription(""); await loadServers(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } } async function rotateToken(id: number) { try { const result = await api.servers.rotateToken(id); setNewToken(result); await loadServers(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } } async function deleteServer(id: number) { if (!(await confirmDialog({ title: "Remove server", message: "Remove this server and all its tracked tasks?", confirmLabel: "Remove", danger: true }))) return; try { await api.servers.remove(id); toast.success("Server removed."); await loadServers(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } } const tableSearch = useTableSearch(servers); const { sorted: sortedServers, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true }); const { pageItems: serverPageItems, page: serverPage, setPage: setServerPage, pageCount: serverPageCount, totalCount: serverTotalCount } = usePagination(sortedServers); const tagCounts = new Map(); for (const s of servers) for (const t of s.tags) tagCounts.set(t, (tagCounts.get(t) ?? 0) + 1); // A tag from the URL that no server has (any more) stays listed, so it can still be switched off. for (const t of selectedTags) if (!tagCounts.has(t)) tagCounts.set(t, 0); const allTags = [...tagCounts.keys()].sort((a, b) => a.localeCompare(b, "sv")); const matchesSearch = new Set((tableSearch.filtered ?? servers).map((s) => s.id)); const visibleServers = servers.filter((s) => { if (!selectedTags.every((t) => s.tags.includes(t))) return false; if (!matchesSearch.has(s.id)) return false; if (status === "offline") return offlineIds?.has(s.id) ?? false; if (status === "online") return !!s.lastSeenAt && !(offlineIds?.has(s.id) ?? false); return true; }); const offlineCount = servers.filter((s) => offlineIds?.has(s.id)).length; const onlineCount = servers.filter((s) => s.lastSeenAt && !offlineIds?.has(s.id)).length; // Change one part of the address and keep the rest (the search words, the sort). function changeParams(change: (next: URLSearchParams) => void) { setSearchParams( (prev) => { const next = new URLSearchParams(prev); change(next); return next; }, { replace: true }, ); } function toggleTag(tag: string) { changeParams((next) => { const current = next.getAll("tag"); next.delete("tag"); for (const t of current.includes(tag) ? current.filter((x) => x !== tag) : [...current, tag]) next.append("tag", t); }); } function setStatus(value: "offline" | "online" | null) { changeParams((next) => (value ? next.set("status", value) : next.delete("status"))); } // Operators and administrators can change several servers at once; a viewer only looks. const canChange = user.role === "admin" || user.role === "operator"; const MAX_COMPARE = 4; function togglePicked(id: number) { setPicked((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : prev.length >= MAX_COMPARE ? prev : [...prev, id])); } function stopComparing() { setComparing(false); setPicked([]); } function stopSelecting() { setSelecting(false); setChosen(new Set()); setBulkForm(null); } function toggleChosen(id: number) { setChosen((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); } const chosenIds = servers.filter((s) => chosen.has(s.id)).map((s) => s.id); async function runBulk(body: Record, done: (changed: number) => string): Promise { const r = await doBulk({ call: api.bulk.servers, body, done: (res) => done(res.changed), reload: () => void loadServers() }); if (r) { setBulkForm(null); setChosen(new Set()); } } const cardBody = (s: ServerRecord) => (
{s.name}
{s.hostname ?? "no hostname reported"}
{s.proxmoxIntegrationId ? ( ) : s.lastSeenAt ? ( agentState(s, agentLatest) === "behind" ? ( Agent behind ) : ( Agent ) ) : ( No data )}
{s.tags.length > 0 && (
)}
{s.lastSeenAt ? <>Last seen : "Never reported"}
); function exportCsv() { if (!sortedServers) return; downloadCsv( "servers.csv", ["Name", "Hostname", "Tags", "Token prefix", "Last seen"], sortedServers.map((s) => [ s.name, s.hostname ?? "", s.tags.join(" "), s.apiTokenPrefix, s.lastSeenAt ? formatDateTime(new Date(s.lastSeenAt)) : "never", ]), ); } return ( <>

Servers

{isAdmin && ( )}
{isAdmin && autoUpdate !== null && servers.length > 0 && (
An agent that is behind this app downloads the newer script from here, checks it against a checksum the server gives, and replaces itself at its next run. Off by default. An agent needs the update code to use it (Linux version 4 or later, Windows 3 or later); an older one needs its install command run once (Manage servers).
)} {managingServers ? ( <>

Add a server

setServerName(e.target.value)} />
setServerHostname(e.target.value)} />
setServerDescription(e.target.value)} />
{newToken && (

Agent token for {newToken.server.name}

This token is only shown once — copy it now.

{newToken.token}

{AGENT_RUN_HINT[agentOsOf(newToken.server.osType)].install}

                    {installCommand(agentOsOf(newToken.server.osType), window.location.origin, newToken.token, insecureAgent)}
                  
{agentOsOf(newToken.server.osType) === "windows" && insecureAgent && (
This form is for Windows PowerShell 5.1, the one built into Windows. In PowerShell 7 the download step needs{" "} -SkipCertificateCheck instead.
)}
)} {uninstallFor && (

Uninstall agent from {uninstallFor.name}

{AGENT_RUN_HINT[agentOsOf(uninstallFor.osType)].uninstall}

                    {uninstallCommand(agentOsOf(uninstallFor.osType), window.location.origin, insecureAgent)}
                  
)}
label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Hostname" sortKeyName="hostname" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Last seen" sortKeyName="lastSeenAt" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> {serverPageItems?.map((s) => ( ))} {!loaded && } {loaded && sortedServers?.length === 0 && ( tableSearch.setQuery("") : undefined} /> )}
Tags Token Last 30 days Actions
{s.name} {agentState(s, agentLatest) === "behind" && ( agent behind )} {s.hostname ?? "—"}
{s.apiTokenPrefix}… {s.lastSeenAt ? : "never"}
) : !loaded ? (
) : servers.length === 0 ? (
setManagingServers(true) } : undefined} />
) : ( <>
{servers.length > 1 && ( )} {canChange && ( )}
{comparing && (
Pick two to {MAX_COMPARE} servers to compare their load, memory and disks side by side. {picked.length} picked.
{picked.length >= 2 ? ( Compare {picked.length} servers ) : ( )}
)} {selecting && (
Pick the servers to change together, then choose what to do from the bar at the foot of the page. {chosenIds.length} picked.
)} {allTags.length > 0 && (
Tags {allTags.map((tag) => { const active = selectedTags.includes(tag); const look = tagBadge(tag, tagColors); return ( ); })} {selectedTags.length > 0 && ( )}
)} {visibleServers.length === 0 && (
{selectedTags.length > 0 && !status && !tableSearch.active ? `No server has ${selectedTags.length > 1 ? "all of those tags" : "that tag"}.` : "No server matches that."}
)}
{visibleServers.map((s) => (
{comparing ? ( ) : selecting ? ( ) : ( {cardBody(s)} )}
))}
)} {selecting && chosenIds.length > 0 && ( <>
setChosen(new Set())}> {isAdmin && ( )} )} {bulkForm === "tag" && ( setBulkForm(null)} onSubmit={(v) => runBulk({ action: v.mode === "add" ? "add_tag" : "remove_tag", ids: chosenIds, tag: v.tag }, (n) => (v.mode === "add" ? `Tagged ${plural(n, "server")} ${v.tag}.` : `Took ${v.tag} off ${plural(n, "server")}.`)) } /> )} {bulkForm === "silence" && ( setBulkForm(null)} onSubmit={(v) => runBulk({ action: "silence", ids: chosenIds, ...v }, (n) => `${plural(n, "server")} put under maintenance.`)} /> )} {bulkForm === "runson" && ( !chosen.has(s.id)).map((s) => ({ id: s.id, name: s.name }))} onClose={() => setBulkForm(null)} onSubmit={(parentServerId) => runBulk({ action: "set_parent", ids: chosenIds, parentServerId }, (n) => `${plural(n, "server")} changed.`)} /> )} ); }