Repository Public
1"use client";2import Link from "next/link";3import { useQueryClient } from "@tanstack/react-query";4import { usePathname, useRouter, useSearchParams } from "next/navigation";5import { Suspense, useState, type ReactNode } from "react";6import { apiDelete, apiPatch, type Schemas } from "@/api/client";7import { ApiError } from "@/api/errors";8import { invalidatePaths, useApiQuery } from "@/api/query";9import { ActionButton, requiredPermissions, useActionLauncher, useActionTypes, actionTitle } from "@/features/actions/ActionFlow";10import { METRIC_FAMILIES, metricLabel } from "@/features/shared/metrics";11import { useI18n } from "@/i18n";12import { Page, RequirePermission } from "@/shell/AppShell";13import { useSession } from "@/shell/session";14import { Banner, Button, ConfirmDialog, Count, CopyButton, DataStamp, Dialog, KeyValue, Menu, MetricValueView, QueryBoundary, Tabs, TabPanel, Tag, TextField, Unmeasured, useErrorMessage, useToast, type IconName, type MenuItem } from "@/ui";15import { formatPerfLevels, parseTags } from "./logic";16import { AgentTab, HealthTab, MaintenanceTab, MetricsTab, ProcessesTab, ServicesTab, StorageNetworkTab } from "./NodeTabs";17import { LastContact, NodeState } from "./parts";1819type Detail = Schemas["NodeDetail"];20const TABS = ["overview", "metrics", "processes", "services", "storage", "agent", "health", "maintenance"] as const;21type TabId = (typeof TABS)[number];2223export function NodeDetailScreen({ id }: { id: string }) {24 return (25 <RequirePermission permission="nodes.read">26 <Suspense fallback={null}>27 <Inner id={id} />28 </Suspense>29 </RequirePermission>30 );31}3233function Inner({ id }: { id: string }) {34 const { t } = useI18n();35 const q = useApiQuery("/nodes/{id}", { path: { id } }, { refetchInterval: 60_000 });36 return (37 <Page title={q.data ? q.data.node.alias : t("nodes.detail.title")} sub={q.data ? <span className="mono">{q.data.node.hostname}</span> : <span className="mono">{id}</span>}38 actions={<Link href="/nodes" className="mcc-btn mcc-btn-ghost">{t("nodes.detail.back")}</Link>}>39 <div data-testid="screen-node-detail" className="stack-lg">40 <QueryBoundary query={q}>{(d) => <Body detail={d} updatedAt={q.dataUpdatedAt} />}</QueryBoundary>41 </div>42 </Page>43 );44}4546function Body({ detail, updatedAt }: { detail: Detail; updatedAt: number }) {47 const { t, tn } = useI18n();48 const session = useSession();49 const router = useRouter();50 const pathname = usePathname();51 const params = useSearchParams();52 const raw = params.get("tab");53 const tab: TabId = (TABS as readonly string[]).includes(raw ?? "") ? (raw as TabId) : "overview";54 const setTab = (next: TabId) => {55 const p = new URLSearchParams(params);56 if (next === "overview") p.delete("tab");57 else p.set("tab", next);58 const s = p.toString();59 router.replace(s ? `${pathname}?${s}` : pathname, { scroll: false });60 };61 const n = detail.node;62 const [dialog, setDialog] = useState<"edit" | "retire" | null>(null);6364 return (65 <>66 <div className="nodes-head">67 <div className="row-wrap" role="status" data-testid="node-state" data-freshness={n.freshness}>68 <NodeState node={n} />69 <span className="muted">{t("nodes.col.lastContact")} : <LastContact at={n.last_seen_at} /></span>70 {n.open_alerts !== undefined && n.open_alerts > 0 ? <Link href={`/alerts?node_id=${n.id}`} className="row"><Count value={n.open_alerts} tone="warning" />{tn("nodes.openAlerts", n.open_alerts)}</Link> : null}71 <DataStamp at={updatedAt} freshness={n.freshness} />72 </div>73 <div className="row-wrap">74 <ActionButton request={{ type: "inventory.refresh", target: { kind: "node", id: n.id }, targetLabel: n.alias }} icon="refresh">{t("nodes.actions.inventory")}</ActionButton>75 <NodeActionsMenu node={n} />76 {session.can("nodes.write") ? <Button icon="edit" onClick={() => setDialog("edit")} data-testid="node-edit">{t("common.edit")}</Button> : null}77 {session.can("nodes.write") && !n.retired_at ? <Button icon="trash" variant="danger" onClick={() => setDialog("retire")} data-testid="node-retire">{t("nodes.retire.open")}</Button> : null}78 </div>79 </div>80 {n.maintenance ? (81 <Banner tone="maintenance" icon="wrench" actions={detail.active_maintenance_window_id ? <Link href={`/maintenance/${detail.active_maintenance_window_id}`} className="mcc-btn mcc-btn-sm">{t("nodes.maintenance.window")}</Link> : undefined}>82 <strong>{t("nodes.maintenance.on")}</strong> {n.maintenance_reason ? <span className="pre">{n.maintenance_reason}</span> : <span className="muted">{t("nodes.maintenance.noReason")}</span>}83 </Banner>84 ) : null}85 {n.retired_at ? <Banner tone="offline">{t("nodes.retire.retired")}</Banner> : null}8687 <Tabs label={t("nodes.detail.tabs")} idPrefix="node" value={tab} onChange={setTab} tabs={TABS.map((id) => ({ id, label: t(`nodes.tab.${id}`) }))} />88 <TabPanel idPrefix="node" id={tab}>89 {tab === "overview" ? <OverviewTab detail={detail} /> : null}90 {tab === "metrics" ? <MetricsTab detail={detail} /> : null}91 {tab === "processes" ? <ProcessesTab nodeId={n.id} /> : null}92 {tab === "services" ? <ServicesTab nodeId={n.id} /> : null}93 {tab === "storage" ? <StorageNetworkTab detail={detail} /> : null}94 {tab === "agent" ? <AgentTab detail={detail} /> : null}95 {tab === "health" ? <HealthTab nodeId={n.id} /> : null}96 {tab === "maintenance" ? <MaintenanceTab detail={detail} /> : null}97 </TabPanel>9899 {dialog === "edit" ? <EditDialog node={n} onClose={() => setDialog(null)} /> : null}100 {dialog === "retire" ? <RetireDialog node={n} onClose={() => setDialog(null)} /> : null}101 </>102 );103}104105const NODE_ACTIONS: { type: string; icon: IconName; danger?: boolean }[] = [106 { type: "diagnostic.run", icon: "terminal" },107 { type: "agent.restart", icon: "restart" },108 { type: "cache.purge", icon: "trash" },109 { type: "node.maintenance.set", icon: "wrench" },110 { type: "system.update.schedule", icon: "download" },111 { type: "system.reboot", icon: "restart", danger: true },112 { type: "system.shutdown", icon: "stop", danger: true },113];114115/** Node actions offered by the server catalog; an entry is disabled with its reason when it cannot be requested. */116function NodeActionsMenu({ node }: { node: Schemas["Node"] }) {117 const { t } = useI18n();118 const session = useSession();119 const launch = useActionLauncher();120 const types = useActionTypes();121 if (!session.can("actions.read")) return null;122 const catalog = types.data?.items ?? [];123 const items: MenuItem[] = NODE_ACTIONS.flatMap((a, i): MenuItem[] => {124 const type = catalog.find((x) => x.type === a.type && x.target_kinds.includes("node"));125 if (!type) return [];126 const lacking = requiredPermissions(type).filter((p) => !session.can(p));127 const reason = !type.available ? t("nodes.actions.notEnabled") : lacking.length > 0 ? t("nodes.actions.missing", { permission: lacking[0] ?? "" }) : undefined;128 return [{129 id: a.type, label: actionTitle(t, type), icon: a.icon, ...(a.danger ? { danger: true } : {}), disabled: reason !== undefined, ...(reason ? { hint: reason } : {}),130 separatorBefore: a.danger === true && !NODE_ACTIONS[i - 1]?.danger,131 onSelect: () => launch({ type: a.type, target: { kind: "node", id: node.id }, targetLabel: node.alias }),132 }];133 });134 const none = types.isError ? (types.error.notImplemented ? t("nodes.actions.catalogNotAvailable") : t("nodes.actions.catalogError")) : types.isLoading ? t("common.loading") : items.length === 0 ? t("nodes.actions.none") : null;135 return (136 <Menu label={t("nodes.actions.menu")} items={items} align="right"137 header={none ? <p className="mcc-menu-label muted" data-testid="node-actions-none">{none}</p> : undefined}138 trigger={(p) => <Button {...p} icon="bolt" data-testid="node-actions">{t("nodes.actions.menu")}</Button>} />139 );140}141142function OverviewTab({ detail }: { detail: Detail }) {143 const { t, fmt } = useI18n();144 const session = useSession();145 const n = detail.node;146 const priv = session.can("nodes.private.read");147 const missing = <Unmeasured availability="not_observed" />;148 const opt = <T,>(v: T | undefined | "", f: (v: T) => ReactNode): ReactNode => (v === undefined || v === "" ? missing : f(v as T));149 const secret = (v: string | undefined) => (v ? <span className="row"><code>{v}</code><CopyButton text={v} /></span> : priv ? missing : <span className="faint" data-testid="node-private-note">{t("nodes.private.requires")}</span>);150 return (151 <>152 <div className="cols-2">153 <section className="section" aria-labelledby="node-hw">154 <h2 id="node-hw">{t("nodes.hw.title")}</h2>155 <KeyValue items={[156 { label: t("nodes.hw.model"), value: opt(n.model, (v) => v) },157 { label: t("nodes.hw.chip"), value: opt(n.chip, (v) => v) },158 { label: t("nodes.hw.arch"), value: opt(n.arch, (v) => <span className="mono">{v}</span>) },159 { label: t("nodes.hw.cpuCores"), value: opt(n.cpu_cores, (v) => <span className="num">{fmt.integer(v)}</span>) },160 { label: t("nodes.hw.perfLevels"), value: detail.cpu_levels.length ? <span data-testid="node-perf-levels">{formatPerfLevels(detail.cpu_levels)}</span> : missing },161 { label: t("nodes.hw.gpuCores"), value: opt(n.gpu_cores, (v) => <span className="num">{fmt.integer(v)}</span>) },162 { label: t("nodes.hw.memory"), value: opt(n.mem_bytes, (v) => <span className="num">{fmt.bytes(v)}</span>) },163 { label: t("nodes.hw.storage"), value: opt(n.storage_bytes, (v) => <span className="num">{fmt.bytes(v)}</span>) },164 { label: t("nodes.hw.os"), value: n.os_name || n.os_version ? [n.os_name, n.os_version].filter(Boolean).join(" ") : missing },165 { label: t("nodes.hw.osBuild"), value: opt(detail.os_build, (v) => <span className="mono">{v}</span>) },166 { label: t("nodes.hw.inventoryAt"), value: opt(detail.inventory_at, (v) => <span className="num">{fmt.dateTime(v)}</span>) },167 ]} />168 </section>169 <section className="section" aria-labelledby="node-id">170 <h2 id="node-id">{t("nodes.identity.title")}</h2>171 <KeyValue items={[172 { label: t("nodes.col.alias"), value: <span className="mono">{n.alias}</span> },173 { label: t("nodes.identity.hostname"), value: <span className="mono">{n.hostname || "—"}</span> },174 { label: t("nodes.col.kind"), value: t(`states.nodeKind.${n.kind}`) },175 { label: t("nodes.col.site"), value: n.site || <span className="faint">{t("nodes.unset")}</span> },176 { label: t("nodes.col.role"), value: n.role || <span className="faint">{t("nodes.unset")}</span> },177 { label: t("nodes.field.environment"), value: n.environment || <span className="faint">{t("nodes.unset")}</span> },178 { label: t("nodes.col.tags"), value: n.tags.length ? <span className="nodes-tags">{n.tags.map((x) => <Tag key={x}>{x}</Tag>)}</span> : <span className="faint">{t("nodes.unset")}</span> },179 { label: t("nodes.identity.registeredVia"), value: t(`nodes.identity.via.${n.registered_via}`) },180 { label: t("common.created"), value: <span className="num">{fmt.dateTime(n.created_at)}</span> },181 { label: t("nodes.identity.id"), value: <span className="row"><code>{n.id}</code><CopyButton text={n.id} /></span> },182 { label: t("nodes.private.ip"), value: secret(n.primary_ip) },183 { label: t("nodes.private.serial"), value: secret(detail.serial_number) },184 { label: t("nodes.private.uuid"), value: secret(detail.hardware_uuid) },185 ]} />186 </section>187 </div>188 <section className="section" aria-labelledby="node-latest">189 <div className="section-head"><h2 id="node-latest">{t("nodes.latest.title")}</h2><DataStamp at={n.observed_at} freshness={n.freshness} label={t("nodes.latest.observed")} /></div>190 {Object.keys(detail.latest).length === 0 ? <p className="muted" data-testid="node-latest-empty">{t("nodes.latest.none")}</p> : (191 <div className="nodes-latest" data-testid="node-latest">192 {METRIC_FAMILIES.map((f) => {193 const names = f.metrics.filter((m) => detail.latest[m] !== undefined);194 if (names.length === 0) return null;195 return <LatestGroup key={f.id} title={t(`metrics.family.${f.id}`)} names={names} latest={detail.latest} />;196 })}197 <LatestGroup title={t("nodes.latest.other")} names={Object.keys(detail.latest).filter((m) => !METRIC_FAMILIES.some((f) => (f.metrics as readonly string[]).includes(m)))} latest={detail.latest} />198 </div>199 )}200 </section>201 </>202 );203}204205function LatestGroup({ title, names, latest }: { title: string; names: readonly string[]; latest: Detail["latest"] }) {206 const { t } = useI18n();207 if (names.length === 0) return null;208 return (209 <div className="nodes-latest-group">210 <h3 className="caps">{title}</h3>211 <dl>212 {names.map((m) => (213 <div key={m} data-metric={m}>214 <dt title={m}>{metricLabel(t, m)}</dt>215 <dd><MetricValueView metric={latest[m]} />{latest[m]?.reason && latest[m]?.value === undefined ? <span className="mcc-hint">{latest[m]?.reason}</span> : null}</dd>216 </div>217 ))}218 </dl>219 </div>220 );221}222223function EditDialog({ node, onClose }: { node: Schemas["Node"]; onClose: () => void }) {224 const { t } = useI18n();225 const qc = useQueryClient();226 const toast = useToast();227 const explain = useErrorMessage();228 const [alias, setAlias] = useState(node.alias);229 const [site, setSite] = useState(node.site);230 const [role, setRole] = useState(node.role);231 const [environment, setEnvironment] = useState(node.environment);232 const [tags, setTags] = useState(node.tags.join(", "));233 const [busy, setBusy] = useState(false);234 const [aliasError, setAliasError] = useState<string | undefined>();235 const [failure, setFailure] = useState<string | null>(null);236 const save = async () => {237 if (alias.trim() === "") { setAliasError(t("ui.schema.required", { limit: "" })); return; }238 setBusy(true);239 setAliasError(undefined);240 setFailure(null);241 try {242 await apiPatch("/nodes/{id}", { path: { id: node.id }, body: { alias: alias.trim(), site: site.trim(), role: role.trim(), environment: environment.trim(), tags: parseTags(tags) } });243 toast({ tone: "ok", title: t("nodes.edit.done") });244 await invalidatePaths(qc, "/nodes");245 onClose();246 } catch (e) {247 setBusy(false);248 if (e instanceof ApiError && e.code === "conflict") setAliasError(t("nodes.register.aliasTaken"));249 else { const m = explain(e); setFailure([m.title, m.detail].filter(Boolean).join(" — ")); }250 }251 };252 return (253 <Dialog open onClose={onClose} title={t("nodes.edit.title", { alias: node.alias })} description={t("nodes.edit.body")} dismissable={!busy}254 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} onClick={() => void save()} data-testid="node-edit-save">{t("common.save")}</Button></>}>255 <form className="mcc-form" onSubmit={(e) => { e.preventDefault(); void save(); }}>256 <TextField label={t("nodes.col.alias")} required mono value={alias} onChange={setAlias} error={aliasError} autoCapitalize="none" spellCheck={false} maxLength={64} />257 <div className="mcc-form-row">258 <TextField label={t("nodes.col.site")} value={site} onChange={setSite} maxLength={64} />259 <TextField label={t("nodes.col.role")} value={role} onChange={setRole} maxLength={64} />260 </div>261 <div className="mcc-form-row">262 <TextField label={t("nodes.field.environment")} value={environment} onChange={setEnvironment} maxLength={32} />263 <TextField label={t("nodes.col.tags")} hint={t("nodes.field.tagsHint")} value={tags} onChange={setTags} mono />264 </div>265 {failure ? <Banner tone="critical" role="alert">{failure}</Banner> : null}266 </form>267 </Dialog>268 );269}270271function RetireDialog({ node, onClose }: { node: Schemas["Node"]; onClose: () => void }) {272 const { t } = useI18n();273 const qc = useQueryClient();274 const router = useRouter();275 const toast = useToast();276 const explain = useErrorMessage();277 const [busy, setBusy] = useState(false);278 const [failure, setFailure] = useState<string | null>(null);279 const retire = async () => {280 setBusy(true);281 setFailure(null);282 try {283 await apiDelete("/nodes/{id}", { path: { id: node.id } });284 toast({ tone: "ok", title: t("nodes.retire.done", { alias: node.alias }) });285 await invalidatePaths(qc, "/nodes", "/cluster/overview");286 onClose();287 router.push("/nodes");288 } catch (e) {289 setBusy(false);290 const m = explain(e);291 setFailure([m.title, m.detail].filter(Boolean).join(" — "));292 }293 };294 return (295 <ConfirmDialog open onClose={onClose} onConfirm={() => void retire()} danger busy={busy} title={t("nodes.retire.title", { alias: node.alias })} body={t("nodes.retire.body")} confirmLabel={t("nodes.retire.confirm")}296 error={failure ? <Banner tone="critical" role="alert">{failure}</Banner> : undefined} />297 );298}299