import { useCallback, useEffect, useState } from "react"; import { Link, useParams } 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 ServerActivity from "../components/ServerActivity"; 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 { ErrorNotice } from "../components/Notice"; import { useBreadcrumbTail } from "../utils/breadcrumb"; import { PageSkeleton } from "../components/Skeleton"; 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, }; export default function ServerDetail({ user }: { user: CurrentUser }) { const { id } = useParams<{ id: string }>(); 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) { 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)); } } 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))} />

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 && ( <> )}
))}
)}
{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 && (
) )}

Hardware & Network

{hardware.source === "none" && (
No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC above.
)} {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 ? formatDateTime(new Date(server.lastSeenAt)) : "never"}
{hardware.source === "agent" && } {(user.role === "admin" || user.role === "operator") && }

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 && ( )}
); }