"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import Link from "next/link"; import { useParams, useRouter } from "next/navigation"; import { Plus, Trash2, Upload } from "lucide-react"; import { api, errorText } from "@/lib/api"; import { ago, bytes, fmtDate } from "@/lib/format"; import { useServerPaged } from "@/lib/paging"; import { Field, Fields, FormError, Loading, Message, Modal, ModalButtons, PageMessage, PageTitle, Pager, ReadCard, ReleaseNotes, useSubmit } from "@/components/ui"; import { PercentChart, ServersNav, StatusPill, agentUpdate, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers"; import { ReleaseSelect } from "@/components/ReleaseSelect"; import type { AgentRelease } from "@/lib/types"; import { FrpConfig, type FrpState } from "@/components/FrpConfig"; type Msg = { type: "ok" | "err"; text: string } | null; type Detail = { server: ServerSummary; config: Record; 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 }[]; frp: FrpState; }; /** 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 (lowercase; checked when saved)" }, { 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" }, ]; /** The keys a church server's configuration shows: the suggested ones, then any others it has. */ const configKeys = (config: Record) => [...new Set([...SUGGESTED.map(x => x.key), ...Object.keys(config)])]; /** Hub 2.17.0: the server's configuration, edited in a popup. */ function ConfigModal({ id, config, onClose, onSaved }: { id: string; config: Record; onClose: () => void; onSaved: (text: string) => void }) { const initial = useMemo<[string, string][]>(() => configKeys(config).map(k => [k, config[k] ?? (k === "TRUST_PROXY" ? "loopback" : "")]), [config]); const [rows, setRows] = useState(initial); const { busy, error, run } = useSubmit(); 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 = (e: React.FormEvent) => { e.preventDefault(); run(async () => { await api(`/api/admin/servers/${id}/config`, { method: "PUT", body: { values: Object.fromEntries(rows.filter(r => r[0].trim())) } }); onSaved("Configuration saved. Jobs from now on carry it, sealed to this server's key."); }); }; return (

Values ending in _URL, KEY, SECRET or PASSWORD show as dots: leave them to keep them.

{rows.map(([k, v], i) => (
set(i, 0, e.target.value)} placeholder="NAME" aria-label="Name" /> set(i, 1, e.target.value)} placeholder={SUGGESTED.find(x => x.key === k)?.hint || "value"} aria-label={`${k} value`} />
))}
); } /** * Hub 2.17.0: Update agent in a popup; queuing it opens the job. 2.19.0: the version is picked from * the agent's releases (Latest by default; the one running here can't be picked), with its notes. */ function UpdateAgentModal({ current, onClose, queue }: { current: string | null; onClose: () => void; queue: (version: string) => Promise }) { const [version, setVersion] = useState(""); const [releases, setReleases] = useState(null); const { busy, error, run } = useSubmit(); useEffect(() => { api("/api/admin/agent-releases").then(setReleases).catch(() => setReleases([])); }, []); const chosen = releases?.find(r => (version ? r.version === version : r.latest)) || null; const nothingNew = !version && !!chosen && chosen.version === current; return (
{ e.preventDefault(); run(() => queue(version ? `agent@${version}` : "")); }} className="space-y-3">

The agent here is {current || "an unknown version"}. The new version is queued as a job on this server.

{!releases ? : }
{chosen && (
What's new in {chosen.version}{chosen.urgent ? " (urgent)" : ""}
{chosen.notes ? :

No notes for this version.

}
)} {nothingNew &&

This server already runs the latest agent.

}
); } export default function ServerPage() { const { id } = useParams<{ id: string }>(); const router = useRouter(); const [d, setD] = useState(null); // Hub 2.6.0: every job on this server, a page at a time (it showed the last 25). const jobsPaged = useServerPaged("/api/admin/jobs", { serverId: String(id) }, r => r.jobs as Job[], 20); const [range, setRange] = useState<"24h" | "7d" | "90d">("24h"); const [msg, setMsg] = useState(null); // Hub 2.17.0: the popup that's open. const [popup, setPopup] = useState<"config" | "agent" | null>(null); const load = useCallback(() => api(`/api/admin/servers/${id}?range=${range}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id, range]); useEffect(() => { load(); }, [load]); /** Queues a job and opens it; throws when the Hub refuses, for a popup to show. */ const queue = async (type: string, args: Record = {}) => { 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}`); }; const job = (type: string) => { setMsg(null); queue(type).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
{msg ? : }
; const s = d.server; return (
{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname} · agent {s.agentVersion}{agentUpdate(s) && ({agentUpdate(s)} available)} · last heard {ago(s.lastSeenAt)} } /> setMsg(null)} />
{!!d.alerts.filter(a => !a.resolvedAt).length && (
{d.alerts.filter(a => !a.resolvedAt).map(a =>
⚠ {a.message} (since {fmtDate(a.createdAt)})
)}
)}
{(["24h", "7d", "90d"] as const).map(r => )}
({ at: p.at, value: p.cpuPercent, peak: p.cpuPeak }))} /> ({ at: p.at, value: p.ramUsedPercent, peak: p.ramPeak }))} />

Resources now

RAM {pct(s.ram?.usedPercent)} used, {bytes(s.ram?.availableBytes)} free of {bytes(s.ram?.totalBytes)}

CPU {pct(s.cpu?.percent)} · load {s.cpu?.load1?.toFixed(2)} on {s.cpu?.cores} cores

{s.disk.map(x =>

Disk {x.mount}: {pct((x.usedBytes / Math.max(1, x.totalBytes)) * 100)} used, {bytes(x.freeBytes)} free

)}

Versions

{s.versions?.os}

Node {s.versions?.node} · PostgreSQL {s.versions?.postgres || "–"} · frpc {s.versions?.frpc || "–"}

{s.mode === "church" &&

frpc {s.frpcRunning === null ? "unknown" : s.frpcRunning ? "running" : not running}

} {s.frpConfigPath !== undefined &&

{s.mode === "central" ? "frps" : "frpc"} config: {s.frpConfigPath ? {s.frpConfigPath} : not found}

} {s.central &&

proxy_bind_addr {s.central.proxyBindAddr || not set}, allow_ports {s.central.allowPorts || "any"}

}

Actions

Asks the agent what's on the server. A site added there without the Hub (crosscode add, or by hand) is added to Installs and tied to its registration. It also runs by itself once a day when a registered site has no install record here.

{s.mode === "church" && ( setPopup("config")}>

The server layer of every install's .env here. Stored encrypted; sent only inside jobs, sealed to this server.

{configKeys(d.config).map(k => {d.config[k] ? {d.config[k]} : null})}
)} {popup === "config" && setPopup(null)} onSaved={text => { setPopup(null); setMsg({ type: "ok", text }); load(); }} />} {popup === "agent" && setPopup(null)} queue={version => queue("update-agent", { version })} />} {d.frp && { setMsg(m); load(); }} />} {s.mode === "church" && (

Sites on this server

{d.deployments.map(x => ( ))}
ChurchDomainVersionPorts (web, api)Status
{x.customer?.name} ({x.shortName}){x.domain}{x.version || "–"}{x.webPort}, {x.apiPort}
{!d.deployments.length &&

None yet. New install

}
)} {s.mode === "church" && (

Processes (PM2)

{d.processes.map(p => )}
NameChurchStatusMemoryCPURestarts
{p.name}{p.church || "–"}{p.status}{bytes(p.memoryBytes)}{Math.round(p.cpuPercent)}%{p.restarts}
)}

Jobs

{(jobsPaged.rows ?? d.jobs).map(j => )}
JobWhenStatusResult
{j.type} {String(j.args?.church || "")}{fmtDate(j.notBefore)}{j.message}
); }