Servers and the agent, dashboard (2.1.0): servers, installs, updates, jobs, ports, download page

- Servers: add with a one-time join command, each server's CPU / RAM
  charts (24 h, 7 days, 90 days, spikes over 85% marked, table view),
  configuration, PM2 processes, sites, jobs and alerts.
- Installs: New install (server chooser with free RAM, CPU and sites),
  Link existing, FastPanel steps and Proxy done, schedule / emergency
  update, adopt, uninstall (2FA and the short name).
- Updates: one release to many installs (a batch), planned jobs.
- Jobs with their reports; Ports & defaults; the public download page
  that decrypts an export in the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 13:18:20 +02:00
co-authored by Claude Opus 5.5
parent 041461f2b5
commit c8359c77e9
13 changed files with 1075 additions and 4 deletions
@@ -0,0 +1,169 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { Plus, Trash2 } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes, fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { PercentChart, ServersNav, StatusPill, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = {
server: ServerSummary;
config: Record<string, string>;
processes: { name: string; church: string | null; product: string | null; status: string; memoryBytes: number; cpuPercent: number; restarts: number; uptimeSeconds: number }[];
stats: { at: string; cpuPercent: number; cpuPeak: number; ramUsedPercent: number; ramPeak: number; diskUsedPercent: number }[];
deployments: (Deployment & { customer: { id: string; name: string } })[];
jobs: Job[];
alerts: { id: string; type: string; level: string; message: string; createdAt: string; resolvedAt: string | null }[];
ports: { port: number; role: string; note: string | null; releasedAt: string | null }[];
};
/** The settings a church server's jobs need (§5); others can be added. */
const SUGGESTED: { key: string; hint: string }[] = [
{ key: "TRUST_PROXY", hint: "Behind frp: loopback" },
{ key: "DB_HOST", hint: "The PostgreSQL server the sites use (default localhost)" },
{ key: "DB_PORT", hint: "Default 5432" },
{ key: "DB_ADMIN_URL", hint: "postgresql://admin:…@host/postgres: may create databases and roles. Blank: the local PostgreSQL via sudo -u postgres" },
];
function ConfigEditor({ id, config, onSaved }: { id: string; config: Record<string, string>; onSaved: (m: Msg) => void }) {
const [rows, setRows] = useState<[string, string][]>(() => {
const keys = [...new Set([...SUGGESTED.map(s => s.key), ...Object.keys(config)])];
return keys.map(k => [k, config[k] ?? (k === "TRUST_PROXY" ? "loopback" : "")]);
});
const set = (i: number, j: 0 | 1, v: string) => setRows(rows.map((r, n) => (n === i ? (j === 0 ? [v.toUpperCase(), r[1]] : [r[0], v]) : r)));
const save = async () => {
try {
await api(`/api/admin/servers/${id}/config`, { method: "PUT", body: { values: Object.fromEntries(rows.filter(r => r[0].trim())) } });
onSaved({ type: "ok", text: "Configuration saved. Jobs from now on carry it, sealed to this server's key." });
} catch (e) { onSaved({ type: "err", text: errorText(e) }); }
};
return (
<div className="card">
<h2 className="font-medium">Configuration</h2>
<p className="mt-1 text-sm text-slate-500">The server layer of every install&apos;s .env here. Stored encrypted; sent only inside jobs, sealed to this server. Values ending in _URL, KEY, SECRET or PASSWORD show as dots: leave them to keep them.</p>
<div className="mt-3 space-y-2">
{rows.map(([k, v], i) => (
<div key={i} className="grid gap-2 md:grid-cols-[14rem_1fr_auto]">
<input className="input font-mono" value={k} onChange={e => set(i, 0, e.target.value)} placeholder="NAME" aria-label="Name" />
<input className="input font-mono" value={v} onChange={e => set(i, 1, e.target.value)} placeholder={SUGGESTED.find(s => s.key === k)?.hint || "value"} aria-label={`${k} value`} />
<button type="button" className="btn-secondary" onClick={() => setRows(rows.filter((_, n) => n !== i))} aria-label={`Remove ${k}`}><Trash2 className="h-4 w-4" /></button>
</div>
))}
</div>
<div className="mt-3 flex gap-2">
<button type="button" className="btn-secondary" onClick={() => setRows([...rows, ["", ""]])}><Plus className="h-4 w-4" /> Add a setting</button>
<button type="button" className="btn-primary" onClick={save}>Save</button>
</div>
</div>
);
}
export default function ServerPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const [d, setD] = useState<Detail | null>(null);
const [range, setRange] = useState<"24h" | "7d" | "90d">("24h");
const [msg, setMsg] = useState<Msg>(null);
const [agentVersion, setAgentVersion] = useState("");
const load = useCallback(() => api<Detail>(`/api/admin/servers/${id}?range=${range}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id, range]);
useEffect(() => { load(); }, [load]);
const job = async (type: string, args: Record<string, unknown> = {}) => {
setMsg(null);
try {
const r = await api<{ job: Job }>(`/api/admin/servers/${id}/jobs`, { method: "POST", body: { type, args } });
setMsg({ type: "ok", text: `Queued: the agent picks it up within 30 seconds.` });
router.push(`/jobs/${r.job.id}`);
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const remove = async () => {
if (!d || !window.confirm(`Remove ${d.server.name} from the Hub? Its agent stops getting jobs. (Uninstall the agent on the server too.)`)) return;
try { await api(`/api/admin/servers/${id}`, { method: "DELETE" }); router.push("/servers"); } catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
if (!d) return <div><ServersNav active="/servers" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const s = d.server;
return (
<div className="space-y-6">
<div>
<PageTitle title={s.name} subtitle={<>{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname} · agent {s.agentVersion} · last heard {ago(s.lastSeenAt)} <StatusPill status={s.online ? "online" : "offline"} /></>} />
<ServersNav active="/servers" />
<Message msg={msg} />
</div>
{!!d.alerts.filter(a => !a.resolvedAt).length && (
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
{d.alerts.filter(a => !a.resolvedAt).map(a => <div key={a.id}>⚠ {a.message} <span className="text-xs">(since {fmtDate(a.createdAt)})</span></div>)}
</div>
)}
<div className="flex flex-wrap items-center gap-2">
{(["24h", "7d", "90d"] as const).map(r => <button key={r} className={range === r ? "btn-primary" : "btn-secondary"} onClick={() => setRange(r)}>{r === "24h" ? "24 hours" : r === "7d" ? "7 days" : "90 days"}</button>)}
</div>
<div className="grid gap-4 lg:grid-cols-2">
<PercentChart title="CPU" points={d.stats.map(p => ({ at: p.at, value: p.cpuPercent, peak: p.cpuPeak }))} />
<PercentChart title="RAM used" points={d.stats.map(p => ({ at: p.at, value: p.ramUsedPercent, peak: p.ramPeak }))} />
</div>
<div className="grid gap-4 md:grid-cols-3">
<div className="card text-sm">
<h2 className="font-medium">Resources now</h2>
<p className="mt-2">RAM {pct(s.ram?.usedPercent)} used, {bytes(s.ram?.availableBytes)} free of {bytes(s.ram?.totalBytes)}</p>
<p>CPU {pct(s.cpu?.percent)} · load {s.cpu?.load1?.toFixed(2)} on {s.cpu?.cores} cores</p>
{s.disk.map(x => <p key={x.mount}>Disk {x.mount}: {pct((x.usedBytes / Math.max(1, x.totalBytes)) * 100)} used, {bytes(x.freeBytes)} free</p>)}
</div>
<div className="card text-sm">
<h2 className="font-medium">Versions</h2>
<p className="mt-2">{s.versions?.os}</p>
<p>Node {s.versions?.node} · PostgreSQL {s.versions?.postgres || "–"} · frpc {s.versions?.frpc || "–"}</p>
{s.mode === "church" && <p>frpc {s.frpcRunning === null ? "unknown" : s.frpcRunning ? "running" : <b className="text-red-700">not running</b>}</p>}
{s.central && <p>frps.ini: proxy_bind_addr {s.central.proxyBindAddr || <b className="text-red-700">not set</b>}, allow_ports {s.central.allowPorts || "any"}</p>}
</div>
<div className="card space-y-2 text-sm">
<h2 className="font-medium">Actions</h2>
<button className="btn-secondary w-full" onClick={() => job("status")}>Check status now</button>
<div className="flex gap-2"><input className="input" placeholder="agent@1.0.1" value={agentVersion} onChange={e => setAgentVersion(e.target.value)} aria-label="Agent version" /><button className="btn-secondary" disabled={!agentVersion} onClick={() => job("update-agent", { version: agentVersion })}>Update agent</button></div>
<button className="btn-danger w-full" onClick={remove}><Trash2 className="h-4 w-4" /> Remove server</button>
</div>
</div>
{s.mode === "church" && <ConfigEditor key={JSON.stringify(d.config)} id={s.id} config={d.config} onSaved={m => { setMsg(m); load(); }} />}
{s.mode === "church" && (
<div className="card overflow-x-auto">
<h2 className="font-medium">Sites on this server</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Church</th><th>Domain</th><th>Version</th><th>Ports (web, api)</th><th>Status</th></tr></thead>
<tbody>{d.deployments.map(x => (
<tr key={x.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${x.id}`}>{x.customer?.name} ({x.shortName})</Link></td><td>{x.domain}</td><td>{x.version || "–"}</td><td className="tabular-nums">{x.webPort}, {x.apiPort}</td><td><StatusPill status={x.status} /></td></tr>
))}</tbody>
</table>
{!d.deployments.length && <p className="mt-2 text-sm text-slate-500">None yet. <Link className="text-indigo-700 hover:underline" href="/servers/installs">New install</Link></p>}
</div>
)}
{s.mode === "church" && (
<div className="card overflow-x-auto">
<h2 className="font-medium">Processes (PM2)</h2>
<table className="mt-3 w-full text-sm tabular-nums">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Name</th><th>Church</th><th>Status</th><th className="text-right">Memory</th><th className="text-right">CPU</th><th className="text-right">Restarts</th></tr></thead>
<tbody>{d.processes.map(p => <tr key={p.name} className="border-t"><td className="py-1.5">{p.name}</td><td>{p.church || "–"}</td><td>{p.status}</td><td className="text-right">{bytes(p.memoryBytes)}</td><td className="text-right">{Math.round(p.cpuPercent)}%</td><td className="text-right">{p.restarts}</td></tr>)}</tbody>
</table>
</div>
)}
<div className="card overflow-x-auto">
<h2 className="font-medium">Recent jobs</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
<tbody>{d.jobs.map(j => <tr key={j.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link> <span className="text-xs text-slate-500">{String(j.args?.church || "")}</span></td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td></tr>)}</tbody>
</table>
</div>
</div>
);
}