import { useCallback, useEffect, useState } from "react"; import { Link, useParams, useSearchParams } from "react-router-dom"; import { api, type CurrentUser, type IntegrationSummary, type ManualTaskInput, type PortEntry, type ProxmoxGuest, type ScheduleType, type ServerDetail as ServerDetailResponse, type ServerLink, type TaskRecord, } from "../api/client"; import ServerPorts from "../components/ServerPorts"; import ServerTrends from "../components/ServerTrends"; import UptimeHistory from "../components/UptimeHistory"; import NotesCard from "../components/NotesCard"; import TodosCard from "../components/TodosCard"; import ServerActivity from "../components/ServerActivity"; import TimeAgo from "../components/TimeAgo"; import UptimeRibbon from "../components/UptimeRibbon"; import RunsOn from "../components/RunsOn"; import HostHealthCard from "../components/HostHealthCard"; import AgentDiagnostics from "../components/AgentDiagnostics"; import { toast } from "../utils/toast"; import { readableError } from "../utils/errors"; import ServerThresholds from "../components/ServerThresholds"; import RunPlaybook from "../components/RunPlaybook"; import RunbookPanel from "../components/RunbookPanel"; import UpdatesBadge from "../components/UpdatesBadge"; import { agentState, agentVersionWords } from "../utils/agent"; 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 { 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"; import HetznerServerCard from "../components/HetznerServerCard"; import ServerBlock, { ArrangeBar } from "../components/ServerBlock"; const SCHEDULE_TYPE_OPTIONS: { value: ScheduleType; label: string }[] = Object.entries(SCHEDULE_TYPE_LABELS).map( ([value, label]) => ({ value: value as ScheduleType, label }), ); function formatBytes(bytes: number | null | undefined): string { if (bytes === null || bytes === undefined) return "—"; const units = ["B", "KB", "MB", "GB", "TB", "PB"]; let value = bytes; let unit = 0; while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; } return `${value.toFixed(1)} ${units[unit]}`; } function formatUptime(seconds: number | null | undefined): string { if (!seconds) return "—"; const days = Math.floor(seconds / 86400); const hours = Math.floor((seconds % 86400) / 3600); if (days > 0) return `${days}d ${hours}h`; const minutes = Math.floor((seconds % 3600) / 60); return `${hours}h ${minutes}m`; } function usageBar(used: number | null | undefined, total: number | null | undefined) { if (!total) return null; const pct = Math.min(100, Math.round(((used ?? 0) / total) * 100)); return (
90 ? "bg-red" : pct > 75 ? "bg-yellow" : "bg-green"}`} style={{ width: `${pct}%` }} />
); } function DisksTable({ disks }: { disks: { mount: string; sizeBytes: number; usedBytes: number }[] }) { if (disks.length === 0) return null; return (
Disks
{disks.map((d) => ( ))}
{d.mount} {formatBytes(d.usedBytes)} / {formatBytes(d.sizeBytes)} {usageBar(d.usedBytes, d.sizeBytes)}
); } const emptyTaskForm = { scheduleType: "docker" as ScheduleType, name: "", command: "", scheduleExpression: "", 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"; const [detail, setDetail] = useState(null); useBreadcrumbTail(detail?.server.name); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [refreshing, setRefreshing] = useState(false); const [tasks, setTasks] = useState(null); const [taskForm, setTaskForm] = useState(null); const [editingTask, setEditingTask] = useState(null); const [savingTask, setSavingTask] = useState(false); const [proxmoxIntegrations, setProxmoxIntegrations] = useState(null); const [pickedIntegrationId, setPickedIntegrationId] = useState(null); const [proxmoxGuests, setProxmoxGuests] = useState(null); const [pickedGuestKey, setPickedGuestKey] = useState(""); const [linking, setLinking] = useState(false); const [linkError, setLinkError] = useState(null); const [actingOnGuest, setActingOnGuest] = useState(false); const [guestActionError, setGuestActionError] = useState(null); const [adminLinkForm, setAdminLinkForm] = useState<{ label: string; url: string } | null>(null); const [editingAdminLinkId, setEditingAdminLinkId] = useState(null); const [savingAdminLink, setSavingAdminLink] = useState(false); const [adminLinkError, setAdminLinkError] = useState(null); const [adminLinkPorts, setAdminLinkPorts] = useState(null); const [adminLinkPortPick, setAdminLinkPortPick] = useState(""); const loadDetail = useCallback(() => { setRefreshing(true); return api.servers .detail(serverId) .then((res) => { setDetail(res); setError(null); }) .catch((err) => setError(err instanceof Error ? err.message : String(err))) .finally(() => { setLoading(false); setRefreshing(false); }); }, [serverId]); const loadTasks = useCallback(() => { api.tasks .list({ serverId, includeStale: true }) .then((res) => setTasks(res.tasks)) .catch((err) => setError(err instanceof Error ? err.message : String(err))); }, [serverId]); useEffect(() => { loadDetail(); loadTasks(); }, [loadDetail, loadTasks]); useEffect(() => { if (!isAdmin) return; api.integrations .list() .then((res) => setProxmoxIntegrations(res.integrations.filter((i) => i.type === "proxmox" && i.enabled))) .catch(() => setProxmoxIntegrations([])); }, [isAdmin]); useEffect(() => { if (!pickedIntegrationId) { setProxmoxGuests(null); return; } api.integrations.proxmox .guests(pickedIntegrationId) .then((res) => setProxmoxGuests(res.guests)) .catch(() => setProxmoxGuests([])); }, [pickedIntegrationId]); async function linkProxmox() { if (!pickedIntegrationId || !pickedGuestKey) return; const guest = proxmoxGuests?.find((g) => `${g.node}/${g.type}/${g.vmid}` === pickedGuestKey); if (!guest) return; setLinking(true); setLinkError(null); try { await api.servers.update(serverId, { proxmoxIntegrationId: pickedIntegrationId, proxmoxNode: guest.node, proxmoxGuestType: guest.type, proxmoxVmid: guest.vmid, }); await loadDetail(); } catch (err) { setLinkError(err instanceof Error ? err.message : String(err)); } finally { setLinking(false); } } async function unlinkProxmox() { setLinking(true); setLinkError(null); try { await api.servers.update(serverId, { proxmoxIntegrationId: null, proxmoxNode: null, proxmoxGuestType: null, proxmoxVmid: null, }); setPickedIntegrationId(null); setPickedGuestKey(""); await loadDetail(); } catch (err) { setLinkError(err instanceof Error ? err.message : String(err)); } finally { setLinking(false); } } async function toggleHideProxmoxLink(hide: boolean) { try { await api.servers.update(serverId, { hideProxmoxLink: hide }); await loadDetail(); } catch (err) { setLinkError(err instanceof Error ? err.message : String(err)); } } function openAddTask() { setEditingTask(null); setTaskForm({ ...emptyTaskForm }); } function openEditTask(task: TaskRecord) { setEditingTask(task); setTaskForm({ scheduleType: task.scheduleType, name: task.name, command: task.command ?? "", scheduleExpression: task.scheduleExpression ?? "", enabled: task.enabled, }); } async function submitTask(e: React.FormEvent) { e.preventDefault(); if (!taskForm) return; setSavingTask(true); setError(null); try { const data: ManualTaskInput = { serverId, scheduleType: taskForm.scheduleType, name: taskForm.name, command: taskForm.command || undefined, scheduleExpression: taskForm.scheduleExpression || undefined, enabled: taskForm.enabled, }; if (editingTask) { await api.tasks.update(editingTask.id, data); } else { await api.tasks.create(data); } setTaskForm(null); setEditingTask(null); loadTasks(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setSavingTask(false); } } async function deleteTask(task: TaskRecord) { if (!(await confirmDialog({ title: "Delete task", message: `Delete "${task.name}"?`, confirmLabel: "Delete", danger: true }))) return; try { await api.tasks.remove(task.id); loadTasks(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } } function loadAdminLinkPorts() { setAdminLinkPortPick(""); api.servers.ports .list(serverId) .then((res) => setAdminLinkPorts(res.ports)) .catch(() => setAdminLinkPorts(null)); } function openAddAdminLink() { setEditingAdminLinkId(null); setAdminLinkError(null); setAdminLinkForm({ label: "", url: "" }); loadAdminLinkPorts(); } function startEditAdminLink(link: ServerLink) { setEditingAdminLinkId(link.id); setAdminLinkError(null); setAdminLinkForm({ label: link.label, url: link.url }); loadAdminLinkPorts(); } function pickAdminLinkPort(key: string) { setAdminLinkPortPick(key); const entry = adminLinkPorts?.find((p) => `${p.protocol}:${p.port}` === key); if (!entry || !adminLinkForm) return; const address = detail?.server.hostname || detail?.ipAddresses[0] || null; const url = guessAdminUrl(address, entry); setAdminLinkForm({ label: adminLinkForm.label || entry.label || entry.agent?.process || "", url: url ?? adminLinkForm.url, }); } function cancelAdminLinkForm() { setAdminLinkForm(null); setEditingAdminLinkId(null); setAdminLinkError(null); setAdminLinkPorts(null); setAdminLinkPortPick(""); } async function submitAdminLink(e: React.FormEvent) { e.preventDefault(); if (!adminLinkForm) return; setSavingAdminLink(true); setAdminLinkError(null); try { if (editingAdminLinkId) { await api.servers.updateLink(serverId, editingAdminLinkId, adminLinkForm); } else { await api.servers.addLink(serverId, adminLinkForm); } cancelAdminLinkForm(); await loadDetail(); } catch (err) { setAdminLinkError(err instanceof Error ? err.message : String(err)); } finally { setSavingAdminLink(false); } } async function removeAdminLink(link: ServerLink) { 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 ; if (error && !detail) return
{error}
; if (!detail) return null; const { server, hardware, ipAddresses, dnsMatches, links } = detail; async function guestAction(action: "start" | "stop" | "restart" | "shutdown") { if (!server.proxmoxIntegrationId || !server.proxmoxNode || !server.proxmoxGuestType || server.proxmoxVmid === null) return; if ( action === "stop" && !(await confirmDialog({ title: "Stop server", message: `Stop ${server.name} immediately? This is a hard power-off, not a graceful shutdown — use Shutdown instead if the guest OS should get a chance to close down cleanly.`, confirmLabel: "Stop now", danger: true, })) ) return; setActingOnGuest(true); setGuestActionError(null); try { await api.integrations.proxmox[action]( server.proxmoxIntegrationId, server.proxmoxNode, server.proxmoxGuestType, server.proxmoxVmid, ); await loadDetail(); } catch (err) { setGuestActionError(err instanceof Error ? err.message : String(err)); } finally { setActingOnGuest(false); } } return ( <>
← Servers

{server.name}

{server.description &&
{server.description}
}
setDetail((d) => (d ? { ...d, server: { ...d.server, tags } } : d))} /> ({ 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" && ( <>

Admin Links

{canEditTasks && !adminLinkForm && (
)}
{adminLinkForm && (
setAdminLinkForm({ ...adminLinkForm, label: e.target.value })} />
setAdminLinkForm({ ...adminLinkForm, url: e.target.value })} />
{!!adminLinkPorts?.length && (
)}
)} {links.length === 0 ? (
No admin links added yet — e.g. Dockge, Webmin, or Cockpit for this server.
) : (
{links.map((l) => (
{l.label} {canEditTasks && ( <> )}
))}
)}

Hardware & Network

{hardware.source === "none" && (
No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC (under Settings).
)} {hardware.error &&
{hardware.error}
} {hardware.source === "proxmox" && !hardware.error && ( <>
Synced live from Proxmox just now. {hardware.status && ( {hardware.status} )}
{canEditTasks && (
{hardware.status === "running" ? ( <> ) : ( )}
)}
CPU
{hardware.cpuCores ?? "—"} cores {hardware.cpuUsagePercent !== null && hardware.cpuUsagePercent !== undefined ? ` · ${hardware.cpuUsagePercent.toFixed(1)}% used` : ""}
Memory
{formatBytes(hardware.memUsedBytes)} / {formatBytes(hardware.memTotalBytes)}
{usageBar(hardware.memUsedBytes, hardware.memTotalBytes)}
Disk (allocated)
{formatBytes(hardware.diskBytes)}
Uptime
{formatUptime(hardware.uptime)}
{hardware.guestAgentAvailable === false && (
IP addresses unavailable — the QEMU guest agent isn't installed or running on this VM.
)} {server.proxmoxGuestType === "qemu" && hardware.guestAgentAvailable !== false && !hardware.disks?.length && hardware.status === "running" && (
Per-disk usage unavailable — the QEMU guest agent doesn't support reporting it (or is still starting up).
)} )} {hardware.source === "agent" && ( <>
Reported by the agent as of {server.lastSeenAt ? formatDateTime(new Date(server.lastSeenAt)) : "unknown"}.
CPU
{hardware.cpuModel || "Unknown model"} {hardware.cpuCores ? ` · ${hardware.cpuCores} cores` : ""}
{hardware.cpuLoadPercent !== null && hardware.cpuLoadPercent !== undefined && (
Load: {hardware.cpuLoadPercent.toFixed(1)}%
)}
Memory
{formatBytes(hardware.memUsedBytes)} / {formatBytes(hardware.memTotalBytes)}
{usageBar(hardware.memUsedBytes, hardware.memTotalBytes)}
)} {ipAddresses.length > 0 && (
IP addresses
    {ipAddresses.map((ip) => { const matches = dnsMatches.filter((m) => m.ip === ip); return (
  • {ip} {matches.length > 0 && ( {" "} — {matches.map((m) => `${m.recordName} (${m.providerName})`).join(", ")} )}
  • ); })}
)}

Identity

Hostname
{server.hostname ?? "—"}
OS type
{server.osType}
Token
{server.apiTokenPrefix}…
Created
{formatDateTime(new Date(server.createdAt))}
Last seen
{server.lastSeenAt ? : "never"}
Last 30 days
{detail.os && ( <>
System
{detail.os.product} {detail.os.state === "ended" && support ended} {detail.os.state === "soon" && support ends in {detail.os.daysLeft} {detail.os.daysLeft === 1 ? "day" : "days"}} {detail.os.state === "ok" && detail.os.endsOn &&
supported until {detail.os.endsOn}
}
)}
Runs on
void loadDetail()} />
{detail.relations.children.length > 0 && ( <>
Runs here
{detail.relations.children.map((c, i) => ( {i > 0 && ", "} {c.name} ))}
)} {server.lastSeenAt && ( <>
Agent
{agentVersionWords(server.agentVersion)}{" "} {agentState(server, detail.agentLatest) === "behind" ? ( update available ) : ( current )}
Updates
{server.updatesPendingSince && server.pendingUpdates && server.pendingUpdates.count > 0 && (
waiting since
)}
)}

Runbooks

)} {view === "health" && ( <> { try { // The list is part of the server's own limits; the rest of them are carried over as they are. await api.servers.update(server.id, { thresholds: { ...(server.thresholds ?? {}), ignoreServices: list.length > 0 ? list : undefined } }); toast.success(list.length > (server.thresholds?.ignoreServices?.length ?? 0) ? "Ignored. It no longer counts as failed on this server." : "Saved."); void loadDetail(); } catch (err) { toast.error(readableError(err)); } } : undefined } /> )} {view === "network" && ( <> )} {view === "history" && ( <> {hardware.source === "agent" && } {(user.role === "admin" || user.role === "operator") && } )} {view === "tasks" && ( <> {canEditTasks && (

Run a playbook

)}

Tasks

{canEditTasks && ( )}
{taskForm && (

{editingTask ? "Edit task" : "Add a task manually"}

setTaskForm({ ...taskForm, name: e.target.value })} />
setTaskForm({ ...taskForm, command: e.target.value })} />
setTaskForm({ ...taskForm, scheduleExpression: e.target.value })} />
)}
{tasks && tasks.length === 0 && (
No scheduled tasks found for this server yet.
)} {tasks && tasks.length > 0 && ( )}
)} {view === "settings" && ( <> {isAdmin && (server.proxmoxIntegrationId || !server.hideProxmoxLink) ? (

Proxmox link

{!server.proxmoxIntegrationId && (
)}
{server.proxmoxIntegrationId ? (
Linked to {hardware.integrationName ?? "a Proxmox integration"} — {server.proxmoxGuestType}/{server.proxmoxVmid} on{" "} {server.proxmoxNode}
) : (proxmoxIntegrations?.length ?? 0) === 0 ? (
No enabled Proxmox integrations configured yet.
) : (
{linkError && (
{linkError}
)}
)}
) : ( isAdmin && (
) )} d.mount)} canEdit={isAdmin} onChanged={() => void loadDetail()} /> )} ); }