From 7c971883b1b767c62975e498e4ac6363ff46e7c7 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sat, 14 Nov 2026 13:59:02 -0500 Subject: [PATCH] Put detail overviews on the dashboard grid The Overview tab of the server and service pages is now a board on the dashboard's widget grid: the same frames, library, editor and fullscreen view. Each page's cards are blocks, placed next to dashboard widgets bound to the page's own server, and "Edit overview layout" in the page menu lets a user rearrange them. The layout is saved per user and kind, so it applies to every server (or service) page. A block that has nothing to render leaves the layout until it does. Rows are half a dashboard row so blocks of very different heights pack without large gaps; dashboard widgets keep their size at twice the row count. --- .../components/dashboard/grid/DashGrid.jsx | 16 +- .../src/components/detail/OverviewBoard.jsx | 447 +++++++++++++++++ .../serverdetail/ServerHealthCard.jsx | 57 ++- .../serverdetail/ServerOverviewTab.jsx | 166 ++++--- .../components/service-detail/OverviewTab.jsx | 469 +++++++++--------- frontend/src/i18n/locales/en.json | 16 + frontend/src/pages/ServerDetail.jsx | 3 + frontend/src/pages/ServiceDetail.jsx | 6 + frontend/src/services/api/dashboards.js | 18 + .../src/styles/components/_detail-page.scss | 58 +++ 10 files changed, 937 insertions(+), 319 deletions(-) create mode 100644 frontend/src/components/detail/OverviewBoard.jsx diff --git a/frontend/src/components/dashboard/grid/DashGrid.jsx b/frontend/src/components/dashboard/grid/DashGrid.jsx index 1ab51d26..a40e21c6 100644 --- a/frontend/src/components/dashboard/grid/DashGrid.jsx +++ b/frontend/src/components/dashboard/grid/DashGrid.jsx @@ -36,6 +36,9 @@ export function DashGrid({ onChange, ctx, onWidgetMenu, + // Height of one grid row. The home dashboard uses the default; a host can + // pass a finer row for layouts that need smaller height steps. + rowHeight = GRID_ROW, }) { const { t } = useTranslation(); const hostRef = useRef(null); @@ -44,7 +47,10 @@ export function DashGrid({ // Detach function for the in-flight pointer gesture, so a mid-drag unmount // (or a pointer released outside the viewport) never leaves listeners behind. const detachRef = useRef(null); - const types = useWidgetTypes(); + // A host with its own widget types (an entity overview's page blocks) + // passes them through ctx; the home dashboard uses the registry. + const registeredTypes = useWidgetTypes(); + const types = ctx?.types || registeredTypes; useEffect(() => { const element = hostRef.current; @@ -68,7 +74,7 @@ export function DashGrid({ ? (hostWidth - GRID_GAP * (GRID_COLS - 1)) / GRID_COLS : 0; const stepX = cell + GRID_GAP; - const stepY = GRID_ROW + GRID_GAP; + const stepY = rowHeight + GRID_GAP; // While dragging we paint the previewed layout instead of the committed one. const list = drag ? drag.preview : widgets; @@ -142,9 +148,9 @@ export function DashGrid({ left: widget.x * stepX, top: widget.y * stepY, width: widget.w * cell + (widget.w - 1) * GRID_GAP, - height: widget.h * GRID_ROW + (widget.h - 1) * GRID_GAP, + height: widget.h * rowHeight + (widget.h - 1) * GRID_GAP, zIndex: drag?.id === widget.i ? 5 : 1, - }), [drag, cell, stepX, stepY]); + }), [drag, cell, stepX, stepY, rowHeight]); const hostClassName = useMemo(() => [ 'skw-grid', @@ -156,7 +162,7 @@ export function DashGrid({
{ if (edit && event.target === event.currentTarget) onSelect?.(null); }} diff --git a/frontend/src/components/detail/OverviewBoard.jsx b/frontend/src/components/detail/OverviewBoard.jsx new file mode 100644 index 00000000..a60ba9fc --- /dev/null +++ b/frontend/src/components/detail/OverviewBoard.jsx @@ -0,0 +1,447 @@ +import { Children, isValidElement, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { createPortal } from 'react-dom'; +import { useNavigate, useSearchParams } from 'react-router-dom'; +import { Grid2x2, History, LayoutGrid, Plus } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import api from '@/services/api'; +import { useAuth } from '@/contexts/useAuth'; +import { useToast } from '@/contexts/useToast'; +import useEditingSession from '@/hooks/useEditingSession'; +import { useUnsavedChangesGuard } from '@/hooks/useUnsavedChangesGuard'; +import { usePolling } from '@/hooks/usePolling'; +import { Button } from '@/components/ui/button'; +import ChangeBar from '@/components/ds/ChangeBar'; +import { DashGrid } from '@/components/dashboard/grid/DashGrid'; +import { WidgetLibrary } from '@/components/dashboard/grid/WidgetLibrary'; +import { WidgetEditor } from '@/components/dashboard/grid/WidgetEditor'; +import { WidgetFullscreen } from '@/components/dashboard/grid/WidgetFullscreen'; +import { GRID_GAP, GRID_ROW, compact, findFreeSpot, nextWidgetId, pushDown } from '@/components/dashboard/grid/layout'; +import { useWidgetTypes, getWidgetType } from '@/components/dashboard/widgets/registry'; +import { toastError } from '@/utils/errorMessage'; + +// The Overview tab of an entity detail page, laid out on the dashboard's widget +// grid: the same frames, library, editor and fullscreen view, with the page's +// own cards available as blocks next to the dashboard's widgets. +// +// +// +// …the card… +// +// +// +// A user has one layout per kind (every server page shares their server +// layout; the page's own entity is the board's variable), stored on the server +// like a dashboard. Until they save one, the layout is the sections in the +// order the page declares them. + +// ?layout=edit puts the board in edit mode, so the page's menu can link to it. +const EDIT_PARAM = 'layout'; +const EDIT_VALUE = 'edit'; + +// How often dashboard widgets on the board re-read their data. +const REFRESH_MS = 15000; +// Time range the board's metric widgets read. Fixed for now: the page has no +// range picker of its own. +const BOARD_RANGE = '1h'; + +// The board's rows are half a dashboard row tall: page blocks vary a lot in +// height, and a full row (88px) is too coarse a step for them. Two half rows +// plus the gap between them are exactly one dashboard row, so a dashboard +// widget keeps its size here at twice its row count. +const ROWS_PER_DASHBOARD_ROW = 2; +const BOARD_ROW = (GRID_ROW - GRID_GAP) / ROWS_PER_DASHBOARD_ROW; + +const SECTION_TYPE_PREFIX = 'overview.'; +const sectionTypeId = (kind, id) => `${SECTION_TYPE_PREFIX}${kind}.${id}`; +const isSectionWidget = (widget) => String(widget?.type || '').startsWith(SECTION_TYPE_PREFIX); + +// Declares one block of the page. Renders nothing itself: OverviewBoard reads +// its props and mounts the children where the layout places the block. +// id, title, icon, w (of 12 columns), h (board rows, see BOARD_ROW) +// placed in the default layout unless false +// lead placed ahead of the board's leading dashboard widgets (a notice) +export function OverviewSection() { + return null; +} + +// A section's frame body. The section's content lives in a host element the +// board renders into once; the frame only adopts that element, so moving, +// resizing or opening a block fullscreen never remounts the card inside it. +function SectionWidget({ widget, ctx }) { + const slotRef = useRef(null); + const host = ctx.sectionHosts.get(widget.cfg?.section); + const { adoptVersion, releaseSection } = ctx; + + // Take the section's element whenever it is free to take (first mount, or + // after another frame showing the same section let go of it). + useEffect(() => { + const slot = slotRef.current; + if (slot && host && host.parentNode !== slot) slot.appendChild(host); + }, [host, adoptVersion]); + + // Hand it back only when this frame really goes away. + useEffect(() => { + if (!host) return undefined; + return () => releaseSection(host); + }, [host, releaseSection]); + + return
; +} + +const NO_WIDGET_TYPES = []; +const NO_LEADING_WIDGETS = []; + +// widgetTypes ids of dashboard widget types offered on this board +// leading dashboard widgets placed ahead of the sections in the default +// layout: [{ type, w, h, cfg }], h in board rows +// Pass both as module-level constants: they define the board, they are not state. +export function OverviewBoard({ + kind, entityId, entityLabel, widgetTypes = NO_WIDGET_TYPES, leading = NO_LEADING_WIDGETS, children, +}) { + const sections = Children.toArray(children).filter(isValidElement).map((child) => child.props); + return ( + + ); +} + +function OverviewBoardInner({ kind, entityId, entityLabel, widgetTypeIds, leading, sections }) { + const { t } = useTranslation(); + const toast = useToast(); + const navigate = useNavigate(); + const { isAdmin } = useAuth(); + const [query, setQuery] = useSearchParams(); + const edit = query.get(EDIT_PARAM) === EDIT_VALUE; + + // ---- section hosts ------------------------------------------------------ + // One detached element per section, created once and kept for the life of + // the board. Sections that are not on the grid wait in the hidden park. + const hostsRef = useRef(new Map()); + const parkRef = useRef(null); + const sectionIds = sections.map((section) => section.id); + sectionIds.forEach((id) => { + if (!hostsRef.current.has(id)) { + const host = document.createElement('div'); + host.className = 'sk-overview-section__host'; + hostsRef.current.set(id, host); + } + }); + const sectionKey = sectionIds.join('|'); + // Everything about the sections that shapes the board (not their content, + // which re-renders through the portals below on every pass). + const sectionSignature = sections + .map((section) => [section.id, section.title, section.w, section.h, section.placed, section.lead].join(':')) + .join('|'); + // The same descriptors object for as long as the signature holds, so the + // memos below depend on a real value instead of re-running every render. + const metaRef = useRef({ signature: null, meta: [] }); + if (metaRef.current.signature !== sectionSignature) { + metaRef.current = { + signature: sectionSignature, + meta: sections.map(({ id, title, icon, w, h, placed, lead }) => ({ id, title, icon, w, h, placed, lead })), + }; + } + const sectionMeta = metaRef.current.meta; + + const [adoptVersion, setAdoptVersion] = useState(0); + const releaseSection = useCallback((host) => { + // Park the element, then let any frame that still wants it take it back + // (closing fullscreen returns the block to its frame on the grid). + if (parkRef.current && host.parentNode !== parkRef.current) parkRef.current.appendChild(host); + setAdoptVersion((version) => version + 1); + }, []); + + // Which sections currently render something. A card that hides itself (no + // traffic yet, feature not applicable) simply leaves the layout. + const [present, setPresent] = useState(() => new Set()); + useEffect(() => { + const park = parkRef.current; + const observers = []; + const measure = () => { + const next = new Set(); + hostsRef.current.forEach((host, id) => { if (host.childElementCount > 0) next.add(id); }); + setPresent((current) => ( + current.size === next.size && [...next].every((id) => current.has(id)) ? current : next + )); + }; + hostsRef.current.forEach((host) => { + if (!host.parentNode && park) park.appendChild(host); + const observer = new MutationObserver(measure); + observer.observe(host, { childList: true }); + observers.push(observer); + }); + measure(); + return () => observers.forEach((observer) => observer.disconnect()); + }, [sectionKey]); + + // ---- widget types ------------------------------------------------------- + const registered = useWidgetTypes(); + const types = useMemo(() => { + const sectionTypes = sectionMeta.map((section) => ({ + id: sectionTypeId(kind, section.id), + name: section.title, + icon: section.icon || LayoutGrid, + cat: 'Overview', + desc: section.title, + w: section.w || 6, + h: section.h || 3, + min: [3, 2], + defaultCfg: { section: section.id }, + component: SectionWidget, + section: section.id, + })); + // Dashboard widgets keep their size on the finer rows. + const shared = registered.filter((type) => widgetTypeIds.includes(type.id)).map((type) => ({ + ...type, + h: type.h * ROWS_PER_DASHBOARD_ROW, + min: [type.min?.[0] ?? 2, (type.min?.[1] ?? 1) * ROWS_PER_DASHBOARD_ROW], + })); + return [...sectionTypes, ...shared]; + }, [kind, sectionMeta, registered, widgetTypeIds]); + + const defaults = useMemo(() => { + const widgets = []; + const place = (type, w, h, cfg) => { + widgets.push({ i: nextWidgetId(widgets), type, ...findFreeSpot(widgets, w, h), w, h, cfg }); + }; + const placeSection = (section) => place( + sectionTypeId(kind, section.id), section.w || 6, section.h || 3, { section: section.id }, + ); + const placed = sectionMeta.filter((section) => section.placed !== false); + placed.filter((section) => section.lead).forEach(placeSection); + leading.forEach((item) => place(item.type, item.w, item.h, { ...item.cfg })); + placed.filter((section) => !section.lead).forEach(placeSection); + return widgets; + }, [kind, sectionMeta, leading]); + + // Drop anything a saved layout references that this page no longer offers. + const sanitize = useCallback( + (widgets) => widgets.filter((widget) => getWidgetType(types, widget.type)), + [types], + ); + + // ---- persistence -------------------------------------------------------- + // `board` is the saved row, null while the user is on the shipped layout, + // undefined until the first read returns. + const [board, setBoard] = useState(undefined); + useEffect(() => { + let cancelled = false; + api.getOverviewBoard(kind) + .then((saved) => { if (!cancelled) setBoard(saved); }) + // A failed read must not hide the page: fall back to the default layout. + .catch(() => { if (!cancelled) setBoard(null); }); + return () => { cancelled = true; }; + }, [kind]); + const saved = useMemo( + () => (board?.widgets ? sanitize(board.widgets) : defaults), + [board, defaults, sanitize], + ); + + // ---- editing ------------------------------------------------------------ + const editing = useEditingSession({ baseline: [] }); + const { draft, isDirty, reset: resetEditing, save: saveEditing, transaction } = editing; + const [selectedId, setSelectedId] = useState(null); + const [libraryOpen, setLibraryOpen] = useState(false); + const [fullscreen, setFullscreen] = useState(null); + const [tick, setTick] = useState(0); + usePolling(() => setTick((value) => value + 1), REFRESH_MS, { immediate: false }); + + // Entering edit mode starts a fresh draft from what is on screen. + const wasEditing = useRef(false); + useEffect(() => { + if (edit && !wasEditing.current && board !== undefined) resetEditing(saved); + wasEditing.current = edit && board !== undefined; + }, [edit, board, saved, resetEditing]); + + const setEditing = useCallback((on) => { + const next = new URLSearchParams(query); + if (on) next.set(EDIT_PARAM, EDIT_VALUE); + else next.delete(EDIT_PARAM); + setQuery(next, { replace: true }); + if (!on) { setSelectedId(null); setLibraryOpen(false); } + }, [query, setQuery]); + + const { requestLeave } = useUnsavedChangesGuard({ + isDirty: edit && isDirty, + confirmOptions: { + title: t('app.overviewBoard.discardTitle', 'Discard layout changes?'), + message: t('app.overviewBoard.discardMessage', 'Your saved overview layout stays as it was.'), + confirmText: t('common.actions.discard', 'Discard'), + }, + }); + + const discard = useCallback(async () => { + if (isDirty && !(await requestLeave())) return; + setEditing(false); + }, [isDirty, requestLeave, setEditing]); + + const save = useCallback(async () => { + try { + await saveEditing(async (widgets) => { + // Saving the shipped layout means "no layout of my own": drop + // the saved row so later changes to the default still reach + // this user, instead of pinning them to today's copy of it. + if (JSON.stringify(widgets) === JSON.stringify(defaults)) { + if (board?.id) await api.deleteDashboard(board.id); + setBoard(null); + return widgets; + } + const stored = await api.saveOverviewBoard(kind, widgets); + setBoard(stored); + return stored?.widgets || widgets; + }); + setEditing(false); + toast.success(t('app.overviewBoard.saved', 'Overview layout saved')); + } catch (err) { + toastError(toast, t('app.overviewBoard.couldNotSave', "Couldn't save the overview layout."), err); + } + }, [board, defaults, kind, saveEditing, setEditing, t, toast]); + + const restoreDefaults = useCallback(() => transaction(defaults), [defaults, transaction]); + + const widgets = edit ? draft : saved; + const selected = widgets.find((widget) => widget.i === selectedId) || null; + + // Out of edit mode, blocks with nothing to show leave the layout and the + // rest close the gap. In edit mode every block stays where it was put. + const shown = useMemo(() => { + if (edit) return widgets; + const visible = widgets.filter((widget) => !isSectionWidget(widget) || present.has(widget.cfg?.section)); + if (visible.length === widgets.length) return widgets; + // Re-place the remaining blocks in reading order, keeping their sizes: + // floating them straight up would leave a hole beside a block whose + // neighbour is the one that went away. + const placed = []; + [...visible].sort((a, b) => a.y - b.y || a.x - b.x).forEach((widget) => { + placed.push({ ...widget, ...findFreeSpot(placed, widget.w, widget.h) }); + }); + return placed; + }, [edit, widgets, present]); + + const startEditing = useCallback(() => { if (!edit) setEditing(true); }, [edit, setEditing]); + + const addWidget = (type) => { + const widget = { + i: nextWidgetId(widgets), + type: type.id, + ...findFreeSpot(widgets, type.w, type.h), + w: type.w, + h: type.h, + cfg: structuredClone(type.defaultCfg || {}), + }; + transaction(compact([...widgets, widget])); + setLibraryOpen(false); + setSelectedId(widget.i); + }; + const removeWidget = (widget) => { + transaction(compact(widgets.filter((item) => item.i !== widget.i))); + setSelectedId(null); + }; + const duplicateWidget = (widget) => { + // A page block exists once; only dashboard widgets can be duplicated. + if (isSectionWidget(widget)) return; + const copy = { ...structuredClone(widget), i: nextWidgetId(widgets), ...findFreeSpot(widgets, widget.w, widget.h) }; + transaction([...widgets, copy]); + setSelectedId(copy.i); + }; + const onWidgetMenu = (action, widget) => { + if (action === 'full') { setFullscreen(widget); return; } + // The other actions change the layout, so they open edit mode first. + // The draft is seeded from the saved layout on the next render, so only + // "configure" can be applied straight away; the rest are edit-mode only. + if (!edit) { startEditing(); if (action === 'config') setSelectedId(widget.i); return; } + if (action === 'config') setSelectedId(widget.i); + if (action === 'del') removeWidget(widget); + if (action === 'dup') duplicateWidget(widget); + }; + + const ctx = useMemo(() => ({ + range: BOARD_RANGE, + tick, + // Dashboard widgets bound to `$server` read this page's server. + serverVar: kind === 'server' ? entityId : undefined, + isAdmin, + navigate, + types, + entity: { kind, id: entityId }, + sectionHosts: hostsRef.current, + adoptVersion, + releaseSection, + emptyLabel: t('app.overviewBoard.nothingToShow', 'Nothing to show here right now.'), + }), [tick, kind, entityId, isAdmin, navigate, types, adoptVersion, releaseSection, t]); + + // Page blocks already on the board are not offered again. + const placedSections = new Set(widgets.filter(isSectionWidget).map((widget) => widget.cfg?.section)); + const libraryTypes = types.filter((type) => !type.section || !placedSections.has(type.section)); + const resources = kind === 'server' ? [{ id: entityId, label: entityLabel || String(entityId), kind: 'server' }] : []; + + return ( +
+ {/* Every section renders exactly once, into its own host element. */} + {sections.map((section) => createPortal(section.children, hostsRef.current.get(section.id), section.id))} + + ); +} diff --git a/frontend/src/components/serverdetail/ServerHealthCard.jsx b/frontend/src/components/serverdetail/ServerHealthCard.jsx index 28d8dc84..2e2e3b63 100644 --- a/frontend/src/components/serverdetail/ServerHealthCard.jsx +++ b/frontend/src/components/serverdetail/ServerHealthCard.jsx @@ -15,19 +15,22 @@ const checkKind = (status) => { return 'gray'; }; +// Two overview cards that read the same agent report; `part` picks one: +// 'permission' (the agent's permission level) or 'health' (status + checks). // Read-only by design: the permission level is enforced by the agent and can // only be changed on the server itself, so there is deliberately no control. -const ServerHealthCard = ({ server }) => { +const ServerHealthCard = ({ server, part }) => { const { t } = useTranslation(); const [alerts, setAlerts] = useState([]); useEffect(() => { + if (part !== 'health') return undefined; let alive = true; api.getFleetAlerts({ server_id: server.id, status: 'active', limit: 20 }) .then((res) => { if (alive) setAlerts((Array.isArray(res) ? res : []).filter((a) => a.detail)); }) .catch(() => { if (alive) setAlerts([]); }); return () => { alive = false; }; - }, [server.id, server.status, server.last_report_at]); + }, [part, server.id, server.status, server.last_report_at]); const level = server.permission_level_effective || 'full'; const health = serverHealth(server); @@ -48,8 +51,8 @@ const ServerHealthCard = ({ server }) => { { key: 'checked', headerKey: 'app.serverHealthCard.lastChecked', header: 'Last checked', sortable: false, cellClassName: 'sk-cell-dim', render: (c) => (c.checked_at ? formatDateTime(c.checked_at) : '—') }, ]; - return ( - <> + if (part === 'permission') { + return (

{t('app.serverHealthCard.permissionLevel', 'Permission level')}

@@ -74,28 +77,36 @@ const ServerHealthCard = ({ server }) => {

{SET_HINT}
+ ); + } -
-

{t('app.serverHealthCard.health', 'Health')} {health.code}

+ return ( +
+

{t('app.serverHealthCard.health', 'Health')}

+ + + {health.code} + {server.last_report_at && ( -

- {t('app.serverHealthCard.lastReport', 'Last report')}: {formatDateTime(server.last_report_at)} -

+ )} - {alerts.length > 0 && ( -
    - {alerts.map((a) =>
  • {a.detail}
  • )} -
- )} - -
- + + {alerts.length > 0 && ( +
    + {alerts.map((a) =>
  • {a.detail}
  • )} +
+ )} + +
); }; diff --git a/frontend/src/components/serverdetail/ServerOverviewTab.jsx b/frontend/src/components/serverdetail/ServerOverviewTab.jsx index 070efe02..2002811c 100644 --- a/frontend/src/components/serverdetail/ServerOverviewTab.jsx +++ b/frontend/src/components/serverdetail/ServerOverviewTab.jsx @@ -2,10 +2,12 @@ import { serverStatusKind } from './serverDetailData'; import { Pill, KpiBand, MetricCard, Gauge } from '../ds'; import OnboardingWizard from '../server/OnboardingWizard'; import SystemStatusCard from './SystemStatusCard'; +import { OverviewBoard, OverviewSection } from '@/components/detail/OverviewBoard'; import ServerHealthCard from './ServerHealthCard'; import { formatBytes } from '@/utils/formatBytes'; import { InfoList, InfoItem } from '../InfoList'; import { useTranslation } from 'react-i18next'; +import { Bot, Cpu, HeartPulse, ListChecks, Server as ServerGlyph, ShieldCheck } from 'lucide-react'; import { formatDateTime } from '@/utils/intl'; import { PulseIcon, @@ -14,19 +16,33 @@ import { MemoryIcon, DiskIcon, OfflineIcon, - ServerIcon, HostIcon, NetworkIcon, FolderTinyIcon, - ChipIcon, OsIcon, ArchIcon, - AgentIcon, TagIcon, HashIcon, DockerMiniIcon, } from './serverDetailShared'; +// Dashboard widget types a server overview can carry besides its own blocks. +const SERVER_WIDGET_TYPES = ['stat', 'gauge', 'timeseries', 'specs', 'note']; + +// Dashboard widgets that open the default layout. `$server` is the board's +// variable: on this page it is always the server being viewed. Titles come +// from the metric, so nothing here needs translating. +const SERVER_LEADING_WIDGETS = [ + { type: 'stat', w: 3, h: 4, cfg: { metric: 'cpu', agg: 'last', resource: '$server', spark: true, thresholds: [70, 90] } }, + { type: 'stat', w: 3, h: 4, cfg: { metric: 'ram', agg: 'last', resource: '$server', spark: true, thresholds: [80, 92] } }, + { type: 'stat', w: 3, h: 4, cfg: { metric: 'disk', agg: 'last', resource: '$server', spark: true, thresholds: [75, 90] } }, + { type: 'stat', w: 3, h: 4, cfg: { metric: 'net_in', agg: 'last', resource: '$server', spark: true, thresholds: null } }, + { + type: 'timeseries', w: 8, h: 6, + cfg: { series: [{ resource: '$server', metric: 'cpu' }, { resource: '$server', metric: 'ram' }], legend: true, fill: true }, + }, +]; + // Usage thresholds for the CPU / memory / disk tiles. const USAGE_DANGER_PERCENT = 85; const USAGE_WARN_PERCENT = 70; @@ -95,61 +111,73 @@ const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => />
)} - - } - tone={isOnline ? 'green' : server.status === 'connecting' ? 'amber' : 'red'} - value={statusLabel.charAt(0).toUpperCase() + statusLabel.slice(1)} - label={t('common.labels.status', 'Status')} - /> - } - tone="accent" - value={isOnline ? formatUptime(metrics?.uptime) : '—'} - label={t('common.labels.uptime', 'Uptime')} - > - {isOnline && metrics?.uptime ?
{t('app.serverOverviewTab.sinceLastBoot', 'since last boot')}
: null} -
- } - label="CPU" - percent={isOnline ? metrics?.cpu_percent : null} - color="var(--accent-bright)" - sub={cpuCores ? `${cpuCores} cores` : null} - /> - } - label={t('common.labels.memory', 'Memory')} - percent={isOnline ? metrics?.memory_percent : null} - color="var(--cyan)" - sub={totalMemory ? formatBytes(totalMemory) : null} - /> - } - label={t('common.labels.disk', 'Disk')} - percent={isOnline ? metrics?.disk_percent : null} - color="var(--green)" - sub={totalDisk ? formatBytes(totalDisk) : null} - /> -
+ + {/* Only renders while the agent is unreachable, so it leaves + the layout on its own once the server is back. */} + + {!isOnline && ( +
+ +

{t('app.serverOverviewTab.serverOffline', 'Server offline')}

+

+ {server.status === 'pending' + ? t('app.serverOverviewTab.waitingForAgentInstall', 'Waiting for the agent to be installed…') + : t('app.serverOverviewTab.cantReachAgent', "Couldn't connect to the server agent.")} +

+
+ )} +
- {!isOnline && ( -
-
- -

{t('app.serverOverviewTab.serverOffline', 'Server offline')}

-

- {server.status === 'pending' - ? t('app.serverOverviewTab.waitingForAgentInstall', 'Waiting for the agent to be installed…') - : t('app.serverOverviewTab.cantReachAgent', "Couldn't connect to the server agent.")} -

-
-
- )} + {/* The agent's live readings (no history needed). Offered in + the block library; the default layout opens with the + dashboard's metric widgets instead. */} + + + } + tone={isOnline ? 'green' : server.status === 'connecting' ? 'amber' : 'red'} + value={statusLabel.charAt(0).toUpperCase() + statusLabel.slice(1)} + label={t('common.labels.status', 'Status')} + /> + } + tone="accent" + value={isOnline ? formatUptime(metrics?.uptime) : '—'} + label={t('common.labels.uptime', 'Uptime')} + > + {isOnline && metrics?.uptime ?
{t('app.serverOverviewTab.sinceLastBoot', 'since last boot')}
: null} +
+ } + label="CPU" + percent={isOnline ? metrics?.cpu_percent : null} + color="var(--accent-bright)" + sub={cpuCores ? `${cpuCores} cores` : null} + /> + } + label={t('common.labels.memory', 'Memory')} + percent={isOnline ? metrics?.memory_percent : null} + color="var(--cyan)" + sub={totalMemory ? formatBytes(totalMemory) : null} + /> + } + label={t('common.labels.disk', 'Disk')} + percent={isOnline ? metrics?.disk_percent : null} + color="var(--green)" + sub={totalDisk ? formatBytes(totalDisk) : null} + /> +
+
-
-
-

{t('app.serverOverviewTab.serverInformation', 'Server information')}

+ {t('common.labels.status', 'Status')}}> {server.status} @@ -162,10 +190,9 @@ const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => value={server.last_seen ? formatDateTime(server.last_seen) : 'Never'} /> -
+ -
-

{t('app.serverOverviewTab.systemInformation', 'System information')}

+ {t('app.serverOverviewTab.operatingSystem', 'Operating system')}} value={osLabel} /> {t('app.serverOverviewTab.architecture', 'Architecture')}} value={systemInfo?.architecture || server.architecture || 'N/A'} /> @@ -178,22 +205,29 @@ const ServerOverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => {t('app.serverOverviewTab.totalMemory', 'Total memory')}} value={formatBytes(totalMemory, { defaultValue: 'N/A' })} /> {t('app.serverOverviewTab.totalDisk', 'Total disk')}} value={formatBytes(totalDisk, { defaultValue: 'N/A' })} /> -
+ -
-

{t('app.serverOverviewTab.agentInformation', 'Agent information')}

+ {t('app.serverOverviewTab.agentVersion', 'Agent version')}} value={server.agent_version || 'Not installed'} mono /> {t('app.serverOverviewTab.agentId', 'Agent ID')}} value={server.agent_id || 'N/A'} mono /> {t('app.serverOverviewTab.dockerVersion', 'Docker version')}} value={server.docker_version || systemInfo?.docker_version || 'N/A'} mono /> {t('common.labels.uptime', 'Uptime')}} value={formatUptime(metrics?.uptime)} /> -
+ - + + + - -
+ + + + + + + +
); }; diff --git a/frontend/src/components/service-detail/OverviewTab.jsx b/frontend/src/components/service-detail/OverviewTab.jsx index e055aba7..93800c61 100644 --- a/frontend/src/components/service-detail/OverviewTab.jsx +++ b/frontend/src/components/service-detail/OverviewTab.jsx @@ -14,6 +14,7 @@ import AttachmentsCard from './AttachmentsCard'; import PoolerCard from './PoolerCard'; import SlotsCard from './SlotsCard'; import HintsCard from './HintsCard'; +import { OverviewBoard, OverviewSection } from '@/components/detail/OverviewBoard'; import { Pill, Gauge, EnvTag, statusKind } from '@/components/ds'; import { usePolling } from '@/hooks/usePolling'; import { useTranslation } from 'react-i18next'; @@ -32,6 +33,9 @@ const ENV_LABEL = { staging: 'STAGING', }; +// Dashboard widget types a service overview can carry besides its own blocks. +const SERVICE_WIDGET_TYPES = ['note']; + const OverviewTab = ({ app, deployConfig }) => { const { t } = useTranslation(); const [metrics, setMetrics] = useState(null); @@ -114,263 +118,278 @@ const OverviewTab = ({ app, deployConfig }) => { return (
-
- {/* Service Info Card */} -
-

{t('app.overviewTab.serviceInfo', 'Service info')}

- - - - - {app.typeInfo.label} - - - - {app.domain && ( - + + +
+

{t('app.overviewTab.serviceInfo', 'Service info')}

+ + - - {app.domain} - - - - - - + {app.typeInfo.label} + - )} - {app.port && ( - - - {/* A port with no domain in front of it is - still reachable — the number alone made - you assemble the URL yourself. */} - {portUrl ? ( + {app.domain && ( + + - {app.port} - + {app.domain} + + + + + - ) : app.port} - - - )} - - - {formatDate(app.created_at, { parts: { - year: 'numeric', month: 'short', day: 'numeric' - } })} - - - {deployConfig && ( - - - {extractRepoDisplay(deployConfig.repo_url)} - {deployConfig.branch || 'main'} - - - )} - {app.environment_type && app.environment_type !== 'standalone' && ( - - - - - - )} - -
- - {/* Resource Usage Card */} -
-

{t('app.overviewTab.resourceUsage', 'Resource usage')}

- {metricsLoading ? ( -
{t('app.overviewTab.loadingMetrics', 'Loading metrics…')}
- ) : isDocker && metrics ? ( -
-
-
- CPU - {metrics.cpu.toFixed(1)}% -
- -
-
-
- {t('common.labels.memory', 'Memory')} - {metrics.memory.toFixed(1)}% -
- - {metrics.memUsage} -
-
-
- {t('app.overviewTab.networkIO', 'Network I/O')} - {metrics.netIO} -
-
- {t('app.overviewTab.processes', 'Processes')} - {metrics.pids} -
-
-
- ) : isPython && metrics ? ( -
-
-
- {t('common.labels.status', 'Status')} - - {metrics.active ? t('app.overviewTab.active', 'Active') : t('app.overviewTab.inactive', 'Inactive')} -
- {metrics.pid && ( -
- PID - {metrics.pid} + + )} + {app.port && ( + + + {/* A port with no domain in front of it is + still reachable — the number alone made + you assemble the URL yourself. */} + {portUrl ? ( + + {app.port} + + + ) : app.port} + + + )} + + + {formatDate(app.created_at, { parts: { + year: 'numeric', month: 'short', day: 'numeric' + } })} + + + {deployConfig && ( + + + {extractRepoDisplay(deployConfig.repo_url)} + {deployConfig.branch || 'main'} + + + )} + {app.environment_type && app.environment_type !== 'standalone' && ( + + + + + + )} + +
+ + + +
+

{t('app.overviewTab.resourceUsage', 'Resource usage')}

+ {metricsLoading ? ( +
{t('app.overviewTab.loadingMetrics', 'Loading metrics…')}
+ ) : isDocker && metrics ? ( +
+
+
+ CPU + {metrics.cpu.toFixed(1)}%
- )} -
- {metrics.memory && ( + +
+
+
+ {t('common.labels.memory', 'Memory')} + {metrics.memory.toFixed(1)}% +
+ + {metrics.memUsage} +
- {t('common.labels.memory', 'Memory')} - {metrics.memory} + {t('app.overviewTab.networkIO', 'Network I/O')} + {metrics.netIO}
- {metrics.workers && ( +
+ {t('app.overviewTab.processes', 'Processes')} + {metrics.pids} +
+
+
+ ) : isPython && metrics ? ( +
+
+
+ {t('common.labels.status', 'Status')} + + {metrics.active ? t('app.overviewTab.active', 'Active') : t('app.overviewTab.inactive', 'Inactive')} + +
+ {metrics.pid && (
- {t('app.overviewTab.workers', 'Workers')} - {metrics.workers} + PID + {metrics.pid}
)}
- )} - {metrics.uptime && ( -
-
- {t('common.labels.uptime', 'Uptime')} - {metrics.uptime} + {metrics.memory && ( +
+
+ {t('common.labels.memory', 'Memory')} + {metrics.memory} +
+ {metrics.workers && ( +
+ {t('app.overviewTab.workers', 'Workers')} + {metrics.workers} +
+ )}
-
- )} -
- ) : ( -
-

{app.isRunning - ? t('app.overviewTab.noMetricsForType', 'No metrics available for this service type.') - : t('app.overviewTab.startToViewMetrics', 'Start the service to view metrics.')}

+ )} + {metrics.uptime && ( +
+
+ {t('common.labels.uptime', 'Uptime')} + {metrics.uptime} +
+
+ )} +
+ ) : ( +
+

{app.isRunning + ? t('app.overviewTab.noMetricsForType', 'No metrics available for this service type.') + : t('app.overviewTab.startToViewMetrics', 'Start the service to view metrics.')}

+
+ )} +
+
+ + {/* Member-visible: domains, DBs, backups, deploys */} + + + + + {/* Read-only cron summary; renders nothing for non-members */} + + + + + {/* Daily nginx rollups; hidden until data exists */} + + {bandwidth?.series?.some(p => p.bytes_sent > 0) && ( +
+
+

{t('app.overviewTab.bandwidth', 'Bandwidth')}

+ + {formatBytes(bandwidth.month_bytes)} {t('app.overviewTab.thisMonth', 'this month')} + +
+ p.bytes_sent)} + width={600} + height={48} + className="bw-spark--wide" + /> + {t('app.overviewTab.last90Days', 'Last 90 days')}
)} -
+ - {/* Related Resources Card (member-visible: domains, DBs, backups, deploys) */} - + {/* Timed access log; hidden until requests exist */} + + + - {/* Scheduled tasks (read-only cron summary; renders nothing for non-members) */} - -
+ {/* Bottleneck hints from the traffic above */} + + + - {/* Bandwidth (daily nginx rollups; hidden until data exists) */} - {bandwidth?.series?.some(p => p.bytes_sent > 0) && ( -
-
-

{t('app.overviewTab.bandwidth', 'Bandwidth')}

- - {formatBytes(bandwidth.month_bytes)} {t('app.overviewTab.thisMonth', 'this month')} - -
- p.bytes_sent)} - width={600} - height={48} - className="bw-spark--wide" - /> - {t('app.overviewTab.last90Days', 'Last 90 days')} -
- )} - - {/* Traffic (timed access log; hidden until requests exist) */} - - - {/* Bottleneck hints from the traffic above */} - - - {/* Short operational cards sit two-up instead of one full-width - row each; a lone or trailing odd card takes the whole row. */} -
{/* Cache / storage / queue this app uses */} - + + + {/* PgBouncer beside an installed PostgreSQL */} - + + + {/* A/B slot deploys: live release, warm standby, switch back */} - -
+ + + - {/* Recent Deployments */} -
-
-

{t('app.overviewTab.recentDeployments', 'Recent deployments')}

- {deployments.length > 0 && ( - - {t('app.overviewTab.deploySummary', '{{total}} total · {{successful}} successful · {{failed}} failed', { - total: deployments.length, - successful: successfulDeploys.length, - failed: failedDeploys.length, - })} - - )} -
- {deploymentsLoading ? ( -
{t('common.loading', 'Loading…')}
- ) : deployments.length === 0 ? ( -
-

{t('app.overviewTab.noDeploymentsYetDeployYourService', 'No deployments yet. Deploy your service to see history here.')}

+ +
+
+

{t('app.overviewTab.recentDeployments', 'Recent deployments')}

+ {deployments.length > 0 && ( + + {t('app.overviewTab.deploySummary', '{{total}} total · {{successful}} successful · {{failed}} failed', { + total: deployments.length, + successful: successfulDeploys.length, + failed: failedDeploys.length, + })} + + )} +
+ {deploymentsLoading ? ( +
{t('common.loading', 'Loading…')}
+ ) : deployments.length === 0 ? ( +
+

{t('app.overviewTab.noDeploymentsYetDeployYourService', 'No deployments yet. Deploy your service to see history here.')}

+
+ ) : ( +
+ {deployments.slice(0, 5).map((deploy, idx) => { + const statusInfo = getDeployStatus(deploy.status); + const tone = statusKind(deploy.status); + const isLatest = idx === 0 && deploy.status === 'success'; + return ( +
+
+
+ + {deploy.commitMessage || deploy.version || t('app.overviewTab.deploymentNumber', 'Deployment #{{number}}', { number: deployments.length - idx })} + + + {deploy.commitSha && ( + {deploy.commitSha.substring(0, 7)} + )} + {deploy.branch && {deploy.branch}} + {deploy.duration && {formatDuration(deploy.duration)}} + {formatRelativeTime(deploy.timestamp)} + +
+ + {isLatest ? t('app.overviewTab.live', 'Live') : statusInfo.label} + +
+ ); + })} +
+ )}
- ) : ( -
- {deployments.slice(0, 5).map((deploy, idx) => { - const statusInfo = getDeployStatus(deploy.status); - const tone = statusKind(deploy.status); - const isLatest = idx === 0 && deploy.status === 'success'; - return ( -
-
-
- - {deploy.commitMessage || deploy.version || t('app.overviewTab.deploymentNumber', 'Deployment #{{number}}', { number: deployments.length - idx })} - - - {deploy.commitSha && ( - {deploy.commitSha.substring(0, 7)} - )} - {deploy.branch && {deploy.branch}} - {deploy.duration && {formatDuration(deploy.duration)}} - {formatRelativeTime(deploy.timestamp)} - -
- - {isLatest ? t('app.overviewTab.live', 'Live') : statusInfo.label} - -
- ); - })} -
- )} -
+ +
); }; diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index 60c83ef8..924466ce 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -4379,6 +4379,17 @@ "vaults": "Vaults", "workspaces": "Workspaces" }, + "overviewBoard": { + "addBlock": "Add block", + "couldNotSave": "Couldn't save the overview layout.", + "discardMessage": "Your saved overview layout stays as it was.", + "discardTitle": "Discard layout changes?", + "editHint": "Drag headers to move · drag the corner to resize · this layout applies to every {{kind}} page for your account", + "editLayout": "Edit overview layout", + "nothingToShow": "Nothing to show here right now.", + "restoreDefault": "Restore default layout", + "saved": "Overview layout saved" + }, "overviewTab": { "active": "Active", "addAlertDeliveryChannelsDiscordSlack": "Add alert delivery channels (Discord, Slack, Telegram) in Settings → Notifications.", @@ -4397,6 +4408,7 @@ "environment": "Environment", "fileIntegrityMonitoringEnabled": "File integrity monitoring enabled", "fixWorking": "Working…", + "hints": "Hints", "inactive": "Inactive", "initializeBaseline": "Initialize baseline", "integrityBaselineInitialized": "Integrity baseline initialized", @@ -4426,6 +4438,7 @@ "serviceInfo": "Service info", "startToViewMetrics": "Start the service to view metrics.", "thisMonth": "this month", + "traffic": "Traffic", "workers": "Workers" }, "packagesTab": { @@ -5652,10 +5665,12 @@ "agentVersion": "Agent version", "architecture": "Architecture", "cantReachAgent": "Couldn't connect to the server agent.", + "connection": "Connection", "dockerVersion": "Docker version", "group": "Group", "hostname": "Hostname", "lastSeen": "Last seen", + "liveStatus": "Live status", "operatingSystem": "Operating system", "serverInformation": "Server information", "serverOffline": "Server offline", @@ -8465,6 +8480,7 @@ "create": "Create", "delete": "Delete", "disable": "Disable", + "discard": "Discard", "dismiss": "Dismiss", "done": "Done", "download": "Download", diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsx index efcebd6d..a14654d2 100644 --- a/frontend/src/pages/ServerDetail.jsx +++ b/frontend/src/pages/ServerDetail.jsx @@ -315,6 +315,9 @@ const ServerDetail = () => { + navigate(`/servers/${id}?layout=edit`)}> + {t('app.overviewBoard.editLayout', 'Edit overview layout')} + {t('app.serverDetail.generateConnectionString', 'Generate connection string')} diff --git a/frontend/src/pages/ServiceDetail.jsx b/frontend/src/pages/ServiceDetail.jsx index 4f6d507d..2d5954d8 100644 --- a/frontend/src/pages/ServiceDetail.jsx +++ b/frontend/src/pages/ServiceDetail.jsx @@ -361,6 +361,12 @@ const ServiceDetail = () => { {showMoreMenu && (
+ {service.isRunning && (