Files
Homelab-manager/web/src/pages/ServerDetail.tsx
T
bobbanandClaude Sonnet 5.5 57fd4f8c52 Accessibility pass, command palette actions, row detail panel, server activity, map, wall display and setup guide
Accessibility: skip link, labelled landmarks, visible focus, page-change
announcements, sortable headings as real buttons, every label tied to its
field, named row checkboxes, and text contrast raised to 4.5:1 in both themes.
Command palette: also runs actions (silence/end maintenance, theme, density,
wall display, sign out) and is a proper dialog; g-then-letter shortcuts, "/" and
"?". Row detail panel for six tables. Server Activity card, with the health
check now recording offline/back-online and disk events in the audit log. Map
page of hosts, servers, DNS names and monitors. Full-screen wall display. A
getting-started checklist on the admin dashboard.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 21:10:56 +02:00

867 lines
33 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 (
<div className="progress progress-sm mt-1">
<div className={`progress-bar ${pct > 90 ? "bg-red" : pct > 75 ? "bg-yellow" : "bg-green"}`} style={{ width: `${pct}%` }} />
</div>
);
}
function DisksTable({ disks }: { disks: { mount: string; sizeBytes: number; usedBytes: number }[] }) {
if (disks.length === 0) return null;
return (
<div className="mt-3">
<div className="text-secondary small mb-1">Disks</div>
<table className="table table-sm table-vcenter mb-0">
<tbody>
{disks.map((d) => (
<tr key={d.mount}>
<td>{d.mount}</td>
<td>
{formatBytes(d.usedBytes)} / {formatBytes(d.sizeBytes)}
{usageBar(d.usedBytes, d.sizeBytes)}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
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<ServerDetailResponse | null>(null);
useBreadcrumbTail(detail?.server.name);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [tasks, setTasks] = useState<TaskRecord[] | null>(null);
const [taskForm, setTaskForm] = useState<typeof emptyTaskForm | null>(null);
const [editingTask, setEditingTask] = useState<TaskRecord | null>(null);
const [savingTask, setSavingTask] = useState(false);
const [proxmoxIntegrations, setProxmoxIntegrations] = useState<IntegrationSummary[] | null>(null);
const [pickedIntegrationId, setPickedIntegrationId] = useState<number | null>(null);
const [proxmoxGuests, setProxmoxGuests] = useState<ProxmoxGuest[] | null>(null);
const [pickedGuestKey, setPickedGuestKey] = useState<string>("");
const [linking, setLinking] = useState(false);
const [linkError, setLinkError] = useState<string | null>(null);
const [actingOnGuest, setActingOnGuest] = useState(false);
const [guestActionError, setGuestActionError] = useState<string | null>(null);
const [adminLinkForm, setAdminLinkForm] = useState<{ label: string; url: string } | null>(null);
const [editingAdminLinkId, setEditingAdminLinkId] = useState<number | null>(null);
const [savingAdminLink, setSavingAdminLink] = useState(false);
const [adminLinkError, setAdminLinkError] = useState<string | null>(null);
const [adminLinkPorts, setAdminLinkPorts] = useState<PortEntry[] | null>(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 <PageSkeleton />;
if (error && !detail) return <div className="alert alert-danger">{error}</div>;
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 (
<>
<div className="mb-3">
<Link to="/servers" className="text-secondary">
&larr; Servers
</Link>
</div>
<div className="d-flex align-items-center mb-3">
<div>
<h2 className="page-title mb-0">{server.name}</h2>
{server.description && <div className="text-secondary">{server.description}</div>}
</div>
<button className="btn btn-outline-secondary ms-auto" onClick={loadDetail} disabled={refreshing}>
{refreshing ? "Refreshing…" : "Refresh"}
</button>
</div>
<ErrorNotice error={error} />
<ServerTags
serverId={serverId}
tags={server.tags}
canEdit={canEditTasks}
onSaved={(tags) => setDetail((d) => (d ? { ...d, server: { ...d.server, tags } } : d))}
/>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Admin Links</h3>
{canEditTasks && !adminLinkForm && (
<div className="card-actions">
<button className="btn btn-sm btn-primary" onClick={openAddAdminLink}>
Add link
</button>
</div>
)}
</div>
<div className="card-body">
<ErrorNotice error={adminLinkError} />
{adminLinkForm && (
<form onSubmit={submitAdminLink} className="row g-2 align-items-end mb-3">
<div className="col-md-3">
<label className="form-label">Label</label>
<input
className="form-control"
required
placeholder="e.g. Dockge, Webmin, Cockpit"
value={adminLinkForm.label}
onChange={(e) => setAdminLinkForm({ ...adminLinkForm, label: e.target.value })}
/>
</div>
<div className="col-md-6">
<label className="form-label">URL</label>
<input
type="url"
className="form-control"
required
placeholder="http://10.0.0.5:5001"
value={adminLinkForm.url}
onChange={(e) => setAdminLinkForm({ ...adminLinkForm, url: e.target.value })}
/>
</div>
{!!adminLinkPorts?.length && (
<div className="col-12">
<label className="form-label">Fill from a known port (optional)</label>
<select
className="form-select"
style={{ maxWidth: 460 }}
value={adminLinkPortPick}
onChange={(e) => pickAdminLinkPort(e.target.value)}
>
<option value="">— pick a port to fill in the URL above —</option>
{adminLinkPorts.map((p) => (
<option key={`${p.protocol}:${p.port}`} value={`${p.protocol}:${p.port}`}>
{portOptionLabel(p)}
</option>
))}
</select>
</div>
)}
<div className="col-md-3 d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={savingAdminLink}>
{editingAdminLinkId ? "Save" : "Add"}
</button>
<button type="button" className="btn" onClick={cancelAdminLinkForm}>
Cancel
</button>
</div>
</form>
)}
{links.length === 0 ? (
<div className="text-secondary">No admin links added yet — e.g. Dockge, Webmin, or Cockpit for this server.</div>
) : (
<div className="d-flex flex-wrap gap-2">
{links.map((l) => (
<div className="btn-group" key={l.id}>
<a href={l.url} target="_blank" rel="noopener noreferrer" className="btn btn-outline-secondary btn-sm">
{l.label}
</a>
{canEditTasks && (
<>
<button className="btn btn-outline-secondary btn-sm" onClick={() => startEditAdminLink(l)} title="Edit">
✎
</button>
<button className="btn btn-outline-danger btn-sm" onClick={() => removeAdminLink(l)} title="Remove">
×
</button>
</>
)}
</div>
))}
</div>
)}
</div>
</div>
{isAdmin && (server.proxmoxIntegrationId || !server.hideProxmoxLink) ? (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Proxmox link</h3>
{!server.proxmoxIntegrationId && (
<div className="card-actions">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(true)}>
Not a VM? Hide this
</button>
</div>
)}
</div>
<div className="card-body">
{server.proxmoxIntegrationId ? (
<div className="d-flex align-items-center gap-3">
<span className="text-secondary">
Linked to {hardware.integrationName ?? "a Proxmox integration"} — {server.proxmoxGuestType}/{server.proxmoxVmid} on{" "}
{server.proxmoxNode}
</span>
<button className="btn btn-outline-danger btn-sm ms-auto" onClick={unlinkProxmox} disabled={linking}>
Unlink
</button>
</div>
) : (proxmoxIntegrations?.length ?? 0) === 0 ? (
<div className="text-secondary">No enabled Proxmox integrations configured yet.</div>
) : (
<div className="row g-2 align-items-end">
<div className="col-md-4">
<label className="form-label">Proxmox integration</label>
<select
className="form-select"
value={pickedIntegrationId ?? ""}
onChange={(e) => {
setPickedIntegrationId(e.target.value ? Number(e.target.value) : null);
setPickedGuestKey("");
}}
>
<option value="">Choose…</option>
{proxmoxIntegrations?.map((i) => (
<option key={i.id} value={i.id}>
{i.name}
</option>
))}
</select>
</div>
<div className="col-md-5">
<label className="form-label">VM / LXC</label>
<select
className="form-select"
value={pickedGuestKey}
disabled={!proxmoxGuests}
onChange={(e) => setPickedGuestKey(e.target.value)}
>
<option value="">Choose…</option>
{proxmoxGuests?.map((g) => (
<option key={`${g.node}/${g.type}/${g.vmid}`} value={`${g.node}/${g.type}/${g.vmid}`}>
{g.name} ({g.type} #{g.vmid} on {g.node})
</option>
))}
</select>
</div>
<div className="col-md-3">
<button className="btn btn-primary w-100" onClick={linkProxmox} disabled={linking || !pickedGuestKey}>
{linking ? "Linking…" : "Link"}
</button>
</div>
{linkError && (
<div className="col-12">
<div className="alert alert-danger mb-0 mt-2">{linkError}</div>
</div>
)}
</div>
)}
</div>
</div>
) : (
isAdmin && (
<div className="mb-3">
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(false)}>
+ Show Proxmox link options
</button>
</div>
)
)}
<div className="row row-cards mb-3">
<div className="col-lg-7">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Hardware &amp; Network</h3>
</div>
<div className="card-body">
{hardware.source === "none" && (
<div className="text-secondary">
No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC above.
</div>
)}
{hardware.error && <div className="alert alert-danger">{hardware.error}</div>}
{hardware.source === "proxmox" && !hardware.error && (
<>
<div className="d-flex align-items-center justify-content-between mb-3">
<div className="text-secondary small">
Synced live from Proxmox just now.
{hardware.status && (
<span
className={`badge ms-2 ${hardware.status === "running" ? "bg-green-lt text-green" : "bg-secondary-lt text-secondary"}`}
>
{hardware.status}
</span>
)}
</div>
{canEditTasks && (
<div className="btn-list flex-nowrap">
{hardware.status === "running" ? (
<>
<button className="btn btn-sm" onClick={() => guestAction("restart")} disabled={actingOnGuest}>
Restart
</button>
<button className="btn btn-sm" onClick={() => guestAction("shutdown")} disabled={actingOnGuest}>
Shutdown
</button>
<button
className="btn btn-sm btn-outline-danger"
onClick={() => guestAction("stop")}
disabled={actingOnGuest}
>
Stop
</button>
</>
) : (
<button className="btn btn-sm btn-primary" onClick={() => guestAction("start")} disabled={actingOnGuest}>
Start
</button>
)}
</div>
)}
</div>
<ErrorNotice error={guestActionError} />
<div className="row g-3">
<div className="col-sm-6">
<div className="text-secondary small">CPU</div>
<div>
{hardware.cpuCores ?? "—"} cores
{hardware.cpuUsagePercent !== null && hardware.cpuUsagePercent !== undefined
? ` · ${hardware.cpuUsagePercent.toFixed(1)}% used`
: ""}
</div>
</div>
<div className="col-sm-6">
<div className="text-secondary small">Memory</div>
<div>
{formatBytes(hardware.memUsedBytes)} / {formatBytes(hardware.memTotalBytes)}
</div>
{usageBar(hardware.memUsedBytes, hardware.memTotalBytes)}
</div>
<div className="col-sm-6">
<div className="text-secondary small">Disk (allocated)</div>
<div>{formatBytes(hardware.diskBytes)}</div>
</div>
<div className="col-sm-6">
<div className="text-secondary small">Uptime</div>
<div>{formatUptime(hardware.uptime)}</div>
</div>
</div>
<DisksTable disks={hardware.disks ?? []} />
{hardware.guestAgentAvailable === false && (
<div className="text-secondary small mt-3">
IP addresses unavailable — the QEMU guest agent isn't installed or running on this VM.
</div>
)}
{server.proxmoxGuestType === "qemu" &&
hardware.guestAgentAvailable !== false &&
!hardware.disks?.length &&
hardware.status === "running" && (
<div className="text-secondary small mt-3">
Per-disk usage unavailable — the QEMU guest agent doesn't support reporting it (or is still
starting up).
</div>
)}
</>
)}
{hardware.source === "agent" && (
<>
<div className="text-secondary small mb-3">
Reported by the agent as of {server.lastSeenAt ? formatDateTime(new Date(server.lastSeenAt)) : "unknown"}.
</div>
<div className="row g-3">
<div className="col-sm-6">
<div className="text-secondary small">CPU</div>
<div>
{hardware.cpuModel || "Unknown model"}
{hardware.cpuCores ? ` · ${hardware.cpuCores} cores` : ""}
</div>
{hardware.cpuLoadPercent !== null && hardware.cpuLoadPercent !== undefined && (
<div className="text-secondary small">Load: {hardware.cpuLoadPercent.toFixed(1)}%</div>
)}
</div>
<div className="col-sm-6">
<div className="text-secondary small">Memory</div>
<div>
{formatBytes(hardware.memUsedBytes)} / {formatBytes(hardware.memTotalBytes)}
</div>
{usageBar(hardware.memUsedBytes, hardware.memTotalBytes)}
</div>
</div>
<DisksTable disks={hardware.disks ?? []} />
</>
)}
{ipAddresses.length > 0 && (
<div className="mt-3">
<div className="text-secondary small mb-1">IP addresses</div>
<ul className="list-unstyled mb-0">
{ipAddresses.map((ip) => {
const matches = dnsMatches.filter((m) => m.ip === ip);
return (
<li key={ip} className="mb-1">
<code>{ip}</code>
{matches.length > 0 && (
<span className="text-secondary">
{" "}
— {matches.map((m) => `${m.recordName} (${m.providerName})`).join(", ")}
</span>
)}
</li>
);
})}
</ul>
</div>
)}
</div>
</div>
</div>
<div className="col-lg-5">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Identity</h3>
</div>
<div className="card-body">
<dl className="row mb-0">
<dt className="col-5">Hostname</dt>
<dd className="col-7">{server.hostname ?? "—"}</dd>
<dt className="col-5">OS type</dt>
<dd className="col-7">{server.osType}</dd>
<dt className="col-5">Token</dt>
<dd className="col-7 text-secondary">{server.apiTokenPrefix}…</dd>
<dt className="col-5">Created</dt>
<dd className="col-7">{formatDateTime(new Date(server.createdAt))}</dd>
<dt className="col-5">Last seen</dt>
<dd className="col-7">{server.lastSeenAt ? formatDateTime(new Date(server.lastSeenAt)) : "never"}</dd>
</dl>
</div>
</div>
</div>
</div>
{hardware.source === "agent" && <ServerTrends serverId={serverId} />}
{(user.role === "admin" || user.role === "operator") && <ServerActivity serverId={serverId} />}
<ServerPorts
serverId={serverId}
addresses={[...ipAddresses, ...(server.hostname && !ipAddresses.includes(server.hostname) ? [server.hostname] : [])]}
canEdit={canEditTasks}
/>
<div className="d-flex align-items-center mb-3">
<h3 className="mb-0">Tasks</h3>
{canEditTasks && (
<button className="btn btn-primary btn-sm ms-auto" onClick={openAddTask}>
Add task
</button>
)}
</div>
{taskForm && (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">{editingTask ? "Edit task" : "Add a task manually"}</h3>
</div>
<form onSubmit={submitTask}>
<div className="card-body row g-3">
<div className="col-md-3">
<label className="form-label">Schedule type</label>
<select
className="form-select"
value={taskForm.scheduleType}
onChange={(e) => setTaskForm({ ...taskForm, scheduleType: e.target.value as ScheduleType })}
>
{SCHEDULE_TYPE_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
<div className="col-md-9">
<label className="form-label">Name</label>
<input
className="form-control"
required
placeholder="e.g. postgres-backup"
value={taskForm.name}
onChange={(e) => setTaskForm({ ...taskForm, name: e.target.value })}
/>
</div>
<div className="col-md-6">
<label className="form-label">Command / description</label>
<input
className="form-control"
placeholder="e.g. docker exec pg-backup /backup.sh"
value={taskForm.command}
onChange={(e) => setTaskForm({ ...taskForm, command: e.target.value })}
/>
</div>
<div className="col-md-6">
<label className="form-label">Schedule</label>
<input
className="form-control"
placeholder="e.g. daily at 02:00, or 0 2 * * *"
value={taskForm.scheduleExpression}
onChange={(e) => setTaskForm({ ...taskForm, scheduleExpression: e.target.value })}
/>
</div>
<div className="col-12">
<label className="form-check">
<input
type="checkbox"
className="form-check-input"
checked={taskForm.enabled}
onChange={(e) => setTaskForm({ ...taskForm, enabled: e.target.checked })}
/>
<span className="form-check-label">Enabled</span>
</label>
</div>
</div>
<div className="card-footer d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={savingTask}>
{editingTask ? "Save changes" : "Add task"}
</button>
<button
type="button"
className="btn"
onClick={() => {
setTaskForm(null);
setEditingTask(null);
}}
>
Cancel
</button>
</div>
</form>
</div>
)}
<div className="card">
{tasks && tasks.length === 0 && (
<div className="card-body text-secondary">No scheduled tasks found for this server yet.</div>
)}
{tasks && tasks.length > 0 && (
<ServerTaskTable tasks={tasks} canEditTasks={canEditTasks} onEdit={openEditTask} onDelete={deleteTask} />
)}
</div>
</>
);
}