Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(dashboard): a grid you arrange, not a list you toggle

Juan Denis8843b860ae75
diff --git a/frontend/src/components/dashboard/grid/DashGrid.jsx b/frontend/src/components/dashboard/grid/DashGrid.jsx
new file mode 100644
index 00000000..0c5879fe
--- /dev/null
+++ b/frontend/src/components/dashboard/grid/DashGrid.jsx
@@ -0,0 +1,196 @@
+import {
+ useCallback, useEffect, useMemo, useRef, useState,
+} from 'react';
+import { LayoutGrid } from 'lucide-react';
+import { getWidgetType, useWidgetTypes } from '../widgets/registry';
+import {
+ GRID_COLS, GRID_GAP, GRID_ROW, pushDown,
+} from './layout';
+import WidgetFrame from './WidgetFrame';
+
+// Shortest board the host will render, so an empty/short dashboard still has a
+// drop target worth aiming at.
+const MIN_ROWS = 6;
+// Breathing room under the last row so the resize grip is never flush with the
+// page edge.
+const HOST_PAD = 8;
+// Fallback minimum span when a widget type declares none.
+const FALLBACK_MIN = [2, 2];
+
+const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
+
+/**
+ * The board host. Measures its own width, derives the cell size from
+ * GRID_COLS/GRID_GAP, absolutely positions every WidgetFrame, and drives
+ * pointer-based move/resize with a live preview of the resulting layout.
+ *
+ * `onWidgetMenu(action, widget)` receives one of: 'config' | 'dup' | 'full' |
+ * 'del' — the host page decides what each one means.
+ */
+export function DashGrid({
+ widgets = [],
+ edit = false,
+ selectedId = null,
+ onSelect,
+ onChange,
+ ctx,
+ onWidgetMenu,
+}) {
+ const hostRef = useRef(null);
+ const [hostWidth, setHostWidth] = useState(0);
+ const [drag, setDrag] = useState(null);
+ // 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();
+
+ useEffect(() => {
+ const element = hostRef.current;
+ if (!element) return undefined;
+ const measure = () => setHostWidth(element.clientWidth);
+ measure();
+ if (typeof ResizeObserver === 'undefined') {
+ window.addEventListener('resize', measure);
+ return () => window.removeEventListener('resize', measure);
+ }
+ const observer = new ResizeObserver(measure);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+
+ useEffect(() => () => {
+ if (detachRef.current) detachRef.current();
+ }, []);
+
+ const cell = hostWidth > 0
+ ? (hostWidth - GRID_GAP * (GRID_COLS - 1)) / GRID_COLS
+ : 0;
+ const stepX = cell + GRID_GAP;
+ const stepY = GRID_ROW + GRID_GAP;
+
+ // While dragging we paint the previewed layout instead of the committed one.
+ const list = drag ? drag.preview : widgets;
+ const rows = Math.max(MIN_ROWS, ...list.map((widget) => widget.y + widget.h));
+
+ const beginGesture = useCallback((event, widget, mode) => {
+ if (!edit || cell <= 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ // A second pointer landing mid-gesture must not orphan the first one's
+ // window listeners.
+ if (detachRef.current) detachRef.current();
+
+ const originX = event.clientX;
+ const originY = event.clientY;
+ const base = { ...widget };
+ const type = getWidgetType(types, widget.type);
+ const [minW, minH] = type?.min || FALLBACK_MIN;
+ const handle = event.currentTarget;
+ const { pointerId } = event;
+ let latest = widgets;
+
+ // Capture so the gesture keeps tracking even when the pointer leaves
+ // the handle; the events still bubble up to our window listeners.
+ try { handle.setPointerCapture?.(pointerId); } catch { /* capture is best-effort */ }
+
+ const handleMove = (moveEvent) => {
+ const dx = Math.round((moveEvent.clientX - originX) / stepX);
+ const dy = Math.round((moveEvent.clientY - originY) / stepY);
+ const next = mode === 'move'
+ ? {
+ ...base,
+ x: clamp(base.x + dx, 0, GRID_COLS - base.w),
+ y: Math.max(0, base.y + dy),
+ }
+ : {
+ ...base,
+ w: Math.max(minW, Math.min(GRID_COLS - base.x, base.w + dx)),
+ h: Math.max(minH, base.h + dy),
+ };
+ latest = pushDown(widgets, next);
+ setDrag({ mode, id: widget.i, preview: latest });
+ };
+
+ const detach = () => {
+ window.removeEventListener('pointermove', handleMove);
+ window.removeEventListener('pointerup', finishGesture);
+ window.removeEventListener('pointercancel', finishGesture);
+ try { handle.releasePointerCapture?.(pointerId); } catch { /* already released */ }
+ detachRef.current = null;
+ };
+
+ function finishGesture() {
+ detach();
+ setDrag(null);
+ if (latest !== widgets) onChange?.(latest);
+ }
+
+ window.addEventListener('pointermove', handleMove);
+ window.addEventListener('pointerup', finishGesture);
+ window.addEventListener('pointercancel', finishGesture);
+ detachRef.current = detach;
+
+ setDrag({ mode, id: widget.i, preview: widgets });
+ onSelect?.(widget.i);
+ }, [edit, cell, stepX, stepY, types, widgets, onChange, onSelect]);
+
+ // Only the cell maths is inline; `position` and the settle transition are
+ // owned by `.skw-grid > .skw-frame` (and killed by `.skw-grid--dragging`).
+ const frameStyle = useCallback((widget) => ({
+ 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,
+ zIndex: drag?.id === widget.i ? 5 : 1,
+ }), [drag, cell, stepX, stepY]);
+
+ const hostClassName = useMemo(() => [
+ 'skw-grid',
+ edit && 'skw-grid--edit',
+ drag && 'skw-grid--dragging',
+ ].filter(Boolean).join(' '), [edit, drag]);
+
+ return (
+ <div
+ ref={hostRef}
+ className={hostClassName}
+ style={{ height: rows * GRID_ROW + (rows - 1) * GRID_GAP + HOST_PAD }}
+ onMouseDown={(event) => {
+ if (edit && event.target === event.currentTarget) onSelect?.(null);
+ }}
+ >
+ {edit && (
+ <div
+ className="skw-grid__ghost"
+ aria-hidden="true"
+ style={{ backgroundSize: `${stepX}px ${stepY}px` }}
+ />
+ )}
+
+ {cell > 0 && list.map((widget) => (
+ <WidgetFrame
+ key={widget.i}
+ widget={widget}
+ type={getWidgetType(types, widget.type)}
+ ctx={ctx}
+ edit={edit}
+ selected={selectedId === widget.i}
+ onSelect={onSelect}
+ onMenu={onWidgetMenu}
+ onDragStart={(event, target) => beginGesture(event, target, 'move')}
+ onResizeStart={(event, target) => beginGesture(event, target, 'resize')}
+ style={frameStyle(widget)}
+ />
+ ))}
+
+ {list.length === 0 && (
+ <div className="skw-grid__empty">
+ <LayoutGrid size={22} aria-hidden="true" />
+ <div>No widgets on this dashboard yet.</div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default DashGrid;
diff --git a/frontend/src/components/dashboard/grid/WidgetFrame.jsx b/frontend/src/components/dashboard/grid/WidgetFrame.jsx
new file mode 100644
index 00000000..a31fa916
--- /dev/null
+++ b/frontend/src/components/dashboard/grid/WidgetFrame.jsx
@@ -0,0 +1,152 @@
+import { useEffect, useRef, useState } from 'react';
+import {
+ Copy, GripVertical, Maximize2, MoreVertical, SlidersHorizontal, Trash2,
+} from 'lucide-react';
+import { WidgetBody } from '../widgets/renderers';
+
+// Chrome around one placed widget: a header (drag handle + title + actions),
+// the renderer body, and — in edit mode — the bottom-right resize grip.
+// Positioning is owned by DashGrid and arrives through `style`.
+export function WidgetFrame({
+ widget,
+ type,
+ ctx,
+ edit = false,
+ selected = false,
+ onSelect,
+ onMenu,
+ onDragStart,
+ onResizeStart,
+ style,
+}) {
+ const [menuOpen, setMenuOpen] = useState(false);
+ const menuRef = useRef(null);
+
+ // Close the overflow menu on any outside pointer press or Escape. Bound
+ // only while the menu is open, and always torn down.
+ useEffect(() => {
+ if (!menuOpen) return undefined;
+ const onPointerDown = (event) => {
+ if (!menuRef.current || !menuRef.current.contains(event.target)) setMenuOpen(false);
+ };
+ const onKeyDown = (event) => { if (event.key === 'Escape') setMenuOpen(false); };
+ window.addEventListener('pointerdown', onPointerDown, true);
+ window.addEventListener('keydown', onKeyDown);
+ return () => {
+ window.removeEventListener('pointerdown', onPointerDown, true);
+ window.removeEventListener('keydown', onKeyDown);
+ };
+ }, [menuOpen]);
+
+ const title = widget.cfg?.title || type?.name || widget.type;
+ const fire = (action) => {
+ setMenuOpen(false);
+ onMenu?.(action, widget);
+ };
+
+ const className = [
+ 'skw-frame',
+ edit && 'skw-frame--edit',
+ selected && 'skw-frame--selected',
+ ].filter(Boolean).join(' ');
+
+ return (
+ <div
+ className={className}
+ style={style}
+ onMouseDown={() => { if (edit) onSelect?.(widget.i); }}
+ >
+ <div
+ className="skw-frame__head"
+ onPointerDown={(event) => {
+ if (edit && !event.target.closest('button')) onDragStart?.(event, widget);
+ }}
+ >
+ {edit && (
+ <span className="skw-frame__grip" aria-hidden="true">
+ <GripVertical size={13} />
+ </span>
+ )}
+ <span className="skw-frame__title" title={title}>{title}</span>
+ {widget.type === 'logs' && <span className="skw-frame__live" aria-hidden="true" />}
+ <div className="skw-frame__actions">
+ {edit && (
+ <button
+ type="button"
+ className="skw-iconbtn skw-iconbtn--bare"
+ title="Configure widget"
+ aria-label="Configure widget"
+ onClick={(event) => { event.stopPropagation(); fire('config'); }}
+ >
+ <SlidersHorizontal size={13} />
+ </button>
+ )}
+ <button
+ type="button"
+ className="skw-iconbtn skw-iconbtn--bare"
+ title="View fullscreen"
+ aria-label="View fullscreen"
+ onClick={(event) => { event.stopPropagation(); fire('full'); }}
+ >
+ <Maximize2 size={13} />
+ </button>
+ <div className="skw-frame__menu-wrap" ref={menuRef}>
+ <button
+ type="button"
+ className="skw-iconbtn skw-iconbtn--bare"
+ title="Widget menu"
+ aria-label="Widget menu"
+ aria-haspopup="menu"
+ aria-expanded={menuOpen}
+ onClick={(event) => { event.stopPropagation(); setMenuOpen((open) => !open); }}
+ >
+ <MoreVertical size={14} />
+ </button>
+ {menuOpen && (
+ <div className="skw-menu" role="menu" onClick={(event) => event.stopPropagation()}>
+ <button type="button" className="skw-menu__item" role="menuitem" onClick={() => fire('config')}>
+ <span className="skw-menu__ic"><SlidersHorizontal size={14} /></span>
+ Configure
+ </button>
+ <button type="button" className="skw-menu__item" role="menuitem" onClick={() => fire('dup')}>
+ <span className="skw-menu__ic"><Copy size={14} /></span>
+ Duplicate
+ </button>
+ <button type="button" className="skw-menu__item" role="menuitem" onClick={() => fire('full')}>
+ <span className="skw-menu__ic"><Maximize2 size={14} /></span>
+ View fullscreen
+ </button>
+ <div className="skw-menu__sep" role="separator" />
+ <button
+ type="button"
+ className="skw-menu__item skw-menu__item--danger"
+ role="menuitem"
+ onClick={() => fire('del')}
+ >
+ <span className="skw-menu__ic"><Trash2 size={14} /></span>
+ Remove
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="skw-frame__body">
+ <WidgetBody widget={widget} ctx={ctx} />
+ </div>
+
+ {edit && (
+ // Pointer-only affordance; the keyboard path to resizing is the
+ // inspector's width/height steppers.
+ <span
+ className="skw-frame__resize"
+ aria-hidden="true"
+ onPointerDown={(event) => onResizeStart?.(event, widget)}
+ />
+ )}
+ </div>
+ );
+}
+
+export default WidgetFrame;
diff --git a/frontend/src/components/dashboard/grid/WidgetFullscreen.jsx b/frontend/src/components/dashboard/grid/WidgetFullscreen.jsx
new file mode 100644
index 00000000..49ef578d
--- /dev/null
+++ b/frontend/src/components/dashboard/grid/WidgetFullscreen.jsx
@@ -0,0 +1,66 @@
+import { useEffect, useRef } from 'react';
+import { X } from 'lucide-react';
+import { getWidgetType, useWidgetTypes } from '../widgets/registry';
+import { WidgetBody } from '../widgets/renderers';
+
+/**
+ * Modal that blows one widget up to a comfortable reading size. Escape or a
+ * click on the scrim closes it; the panel takes focus on open so keyboard users
+ * land inside the dialog rather than back at the top of the board.
+ */
+export function WidgetFullscreen({ widget, type, ctx, onClose }) {
+ const panelRef = useRef(null);
+ const types = useWidgetTypes();
+
+ useEffect(() => {
+ const onKeyDown = (event) => { if (event.key === 'Escape') onClose?.(); };
+ window.addEventListener('keydown', onKeyDown);
+ panelRef.current?.focus();
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [onClose]);
+
+ if (!widget) return null;
+
+ const resolved = type || getWidgetType(types, widget.type);
+ const title = widget.cfg?.title || resolved?.name || widget.type;
+
+ return (
+ <>
+ {/* Escape and the header's close button are the accessible paths;
+ the scrim is a pointer convenience only. */}
+ <div className="skw-full__scrim" aria-hidden="true" onClick={onClose} />
+ <div
+ className="skw-full"
+ ref={panelRef}
+ role="dialog"
+ aria-modal="true"
+ aria-label={title}
+ tabIndex={-1}
+ >
+ {/* Same frame chrome as on the board — `.skw-full .skw-frame`
+ restyles it for the larger surface. */}
+ <div className="skw-frame">
+ <div className="skw-frame__head">
+ <span className="skw-frame__title">{title}</span>
+ <div className="skw-frame__actions">
+ <button
+ type="button"
+ className="skw-iconbtn skw-iconbtn--bare"
+ title="Close"
+ aria-label="Close fullscreen widget"
+ onClick={onClose}
+ >
+ <X size={15} />
+ </button>
+ </div>
+ </div>
+ <div className="skw-frame__body">
+ <WidgetBody widget={widget} ctx={ctx} />
+ </div>
+ </div>
+ </div>
+ </>
+ );
+}
+
+export default WidgetFullscreen;
diff --git a/frontend/src/components/dashboard/grid/WidgetInspector.jsx b/frontend/src/components/dashboard/grid/WidgetInspector.jsx
new file mode 100644
index 00000000..b7029e28
--- /dev/null
+++ b/frontend/src/components/dashboard/grid/WidgetInspector.jsx
@@ -0,0 +1,458 @@
+import { useEffect, useMemo } from 'react';
+import {
+ Copy, LayoutGrid, Minus, Plus, Trash2, X,
+} from 'lucide-react';
+import { SegControl } from '@/components/ds';
+import { Switch } from '@/components/ui/switch';
+import {
+ AGGREGATIONS, getMetric, metricsForResource, metricsForSource,
+} from '../widgets/metrics';
+// Single source of truth for shortcut targets: what a user can pick here is
+// exactly what the renderer can draw.
+import { QUICK_ACTION_OPTIONS } from '../widgets/renderers';
+import { GRID_COLS } from './layout';
+
+// Tallest a widget may be dragged/stepped to. Twelve columns wide is the board;
+// height is only bounded so a stepper can't run away.
+const MAX_ROWS = 20;
+const FALLBACK_MIN = [2, 2];
+// Log widgets count lines, everything else counts rows — different granularity.
+const LINE_STEP = 20;
+const LINE_MIN = 20;
+const ROW_MIN = 2;
+
+
+const TABLE_SOURCES = [
+ ['services', 'Services'],
+ ['servers', 'Servers'],
+ ['containers', 'Containers'],
+ ['deploys', 'Deploys'],
+];
+const TOPN_DIMENSIONS = [['servers', 'Servers'], ['services', 'Services']];
+const LOG_LEVELS = [['all', 'All'], ['out', 'Info'], ['warn', 'Warn'], ['err', 'Error']];
+const SEVERITIES = [['all', 'All'], ['critical', 'Critical'], ['high', 'High'], ['low', 'Low']];
+
+const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
+const toOptions = (pairs) => pairs.map(([value, label]) => ({ value, label }));
+
+// A metric saved before the resource changed is kept in the list, flagged,
+// rather than silently swapped out from under the operator.
+function asOptions(catalog, selected) {
+ const options = catalog.map((metric) => [metric.id, metric.label]);
+ if (selected && !catalog.some((metric) => metric.id === selected)) {
+ options.push([selected, `${getMetric(selected).label} · unavailable here`]);
+ }
+ return options;
+}
+
+/**
+ * Metric dropdown options for a resource. metrics.js is explicit that config
+ * UIs must build this from the resource's own catalog, so a dead option
+ * (network on the local host, load average on an agent) never reaches a user.
+ * The `$server` variable can resolve either way, so it gets the union.
+ */
+function metricOptionsFor(resource, selected) {
+ const catalog = !resource || resource === '$server'
+ ? [...new Set([...metricsForSource('local'), ...metricsForSource('server')])]
+ : metricsForResource(resource);
+ return asOptions(catalog, selected);
+}
+
+/** Top N ranks servers/services, never the panel host. */
+function topnMetricOptions(selected) {
+ return asOptions(metricsForSource('server'), selected);
+}
+
+const iconOf = (type) => {
+ const candidate = type?.icon;
+ const usable = typeof candidate === 'function' || (candidate && typeof candidate === 'object');
+ return usable ? candidate : LayoutGrid;
+};
+
+// The stylesheet targets `.skw-ins__row > label`, so the caption stays a bare
+// <label> element.
+function InspectorRow({ label, hint, children }) {
+ return (
+ <div className="skw-ins__row">
+ <label>{label}</label>
+ {children}
+ {hint && <div className="skw-ins__hint">{hint}</div>}
+ </div>
+ );
+}
+
+function InspectorSelect({ value, onChange, options, label }) {
+ return (
+ <select
+ className="skw-ins__select"
+ value={value}
+ aria-label={label}
+ onChange={(event) => onChange(event.target.value)}
+ >
+ {options.map(([optionValue, optionLabel]) => (
+ <option key={optionValue} value={optionValue}>{optionLabel}</option>
+ ))}
+ </select>
+ );
+}
+
+// `.skw-stepper` styles its `button`/`span` children directly.
+function Stepper({ label, value, onStep, suffix }) {
+ return (
+ <div className="skw-stepper">
+ <button
+ type="button"
+ title={`Decrease ${label}`}
+ aria-label={`Decrease ${label}`}
+ onClick={() => onStep(-1)}
+ >
+ <Minus size={13} />
+ </button>
+ <span className="mono">{value}{suffix ? ` ${suffix}` : ''}</span>
+ <button
+ type="button"
+ title={`Increase ${label}`}
+ aria-label={`Increase ${label}`}
+ onClick={() => onStep(1)}
+ >
+ <Plus size={13} />
+ </button>
+ </div>
+ );
+}
+
+/**
+ * Right-hand configuration panel for the selected widget. Every field writes
+ * straight through `onChange` with a whole new widget instance — the board owns
+ * the list and decides when to persist.
+ */
+export function WidgetInspector({
+ widget,
+ type,
+ resources = [],
+ onChange,
+ onClose,
+ onDuplicate,
+ onRemove,
+}) {
+ useEffect(() => {
+ const onKeyDown = (event) => { if (event.key === 'Escape') onClose?.(); };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [onClose]);
+
+ const resourceOptions = useMemo(() => [
+ ['$server', 'Dashboard variable'],
+ ...resources.map((resource) => [
+ resource.id,
+ resource.kind ? `${resource.label} · ${resource.kind}` : resource.label,
+ ]),
+ ], [resources]);
+
+ if (!widget) return null;
+
+ const cfg = widget.cfg || {};
+ const kind = widget.type;
+ const [minW, minH] = type?.min || FALLBACK_MIN;
+ const Icon = iconOf(type);
+
+ const set = (key, value) => onChange?.({ ...widget, cfg: { ...cfg, [key]: value } });
+ const setSeries = (index, key, value) => set(
+ 'series',
+ (cfg.series || []).map((series, i) => (i === index ? { ...series, [key]: value } : series)),
+ );
+ const stepSize = (key, delta) => {
+ const min = key === 'w' ? minW : minH;
+ const max = key === 'w' ? GRID_COLS : MAX_ROWS;
+ onChange?.({ ...widget, [key]: clamp((widget[key] || min) + delta, min, max) });
+ };
+
+ const countsLines = kind === 'logs';
+ const countKey = countsLines ? 'lines' : 'limit';
+ const countValue = countsLines ? (cfg.lines || 60) : (cfg.limit || 6);
+ const stepCount = (direction) => {
+ const step = countsLines ? LINE_STEP : 1;
+ const floor = countsLines ? LINE_MIN : ROW_MIN;
+ set(countKey, Math.max(floor, countValue + step * direction));
+ };
+
+ return (
+ <aside className="skw-ins" aria-label="Widget settings">
+ <div className="skw-ins__head">
+ <span className="skw-ins__ic"><Icon size={15} aria-hidden="true" /></span>
+ <div className="skw-ins__title">
+ {cfg.title || type?.name || kind}
+ <div className="skw-ins__sub mono">{type?.name || kind} · {widget.w}×{widget.h}</div>
+ </div>
+ <button
+ type="button"
+ className="skw-iconbtn skw-iconbtn--bare"
+ title="Close widget settings"
+ aria-label="Close widget settings"
+ onClick={onClose}
+ >
+ <X size={17} />
+ </button>
+ </div>
+
+ <div className="skw-ins__body">
+ <InspectorRow label="Title">
+ <div className="skw-ins__field">
+ <input
+ type="text"
+ aria-label="Widget title"
+ value={cfg.title || ''}
+ onChange={(event) => set('title', event.target.value)}
+ />
+ </div>
+ </InspectorRow>
+
+ {['stat', 'gauge', 'specs'].includes(kind) && (
+ <InspectorRow label="Resource">
+ <InspectorSelect
+ label="Resource"
+ value={cfg.resource || '$server'}
+ onChange={(value) => set('resource', value)}
+ options={resourceOptions}
+ />
+ </InspectorRow>
+ )}
+
+ {['stat', 'gauge'].includes(kind) && (
+ <InspectorRow label="Metric">
+ <InspectorSelect
+ label="Metric"
+ value={cfg.metric || 'cpu'}
+ onChange={(value) => set('metric', value)}
+ options={metricOptionsFor(cfg.resource, cfg.metric || 'cpu')}
+ />
+ </InspectorRow>
+ )}
+
+ {['stat', 'gauge', 'topn'].includes(kind) && (
+ <InspectorRow label="Aggregation">
+ <SegControl
+ options={toOptions(AGGREGATIONS)}
+ value={cfg.agg || 'last'}
+ onChange={(value) => set('agg', value)}
+ />
+ </InspectorRow>
+ )}
+
+ {['stat', 'gauge'].includes(kind) && (
+ <InspectorRow label="Thresholds" hint="Value colours turn amber, then red.">
+ <div className="skw-ins__pair">
+ {[0, 1].map((index) => (
+ <div className="skw-ins__field" key={index}>
+ <span className="skw-ins__prefix mono">{index ? 'red ≥' : 'amber ≥'}</span>
+ <input
+ type="number"
+ aria-label={index ? 'Red threshold' : 'Amber threshold'}
+ value={(cfg.thresholds || [])[index] ?? ''}
+ onChange={(event) => {
+ const next = [...(cfg.thresholds || [null, null])];
+ next[index] = event.target.value === '' ? null : Number(event.target.value);
+ set('thresholds', next);
+ }}
+ />
+ </div>
+ ))}
+ </div>
+ </InspectorRow>
+ )}
+
+ {kind === 'stat' && (
+ <InspectorRow label="Sparkline">
+ <Switch
+ checked={cfg.spark !== false}
+ aria-label="Show sparkline"
+ onCheckedChange={(checked) => set('spark', checked)}
+ />
+ </InspectorRow>
+ )}
+
+ {kind === 'timeseries' && (
+ <>
+ <InspectorRow label="Series">
+ <div className="skw-ins__series">
+ {(cfg.series || []).map((series, index) => (
+ <div className="skw-ins__ser" key={index}>
+ <InspectorSelect
+ label={`Series ${index + 1} resource`}
+ value={series.resource}
+ onChange={(value) => setSeries(index, 'resource', value)}
+ options={resourceOptions}
+ />
+ <InspectorSelect
+ label={`Series ${index + 1} metric`}
+ value={series.metric}
+ onChange={(value) => setSeries(index, 'metric', value)}
+ options={metricOptionsFor(series.resource, series.metric)}
+ />
+ <button
+ type="button"
+ className="skw-iconbtn skw-iconbtn--bare"
+ title={`Remove series ${index + 1}`}
+ aria-label={`Remove series ${index + 1}`}
+ onClick={() => set('series', (cfg.series || []).filter((_, i) => i !== index))}
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
+ ))}
+ <button
+ type="button"
+ className="skw-ins__add"
+ onClick={() => set('series', [...(cfg.series || []), { resource: '$server', metric: 'cpu' }])}
+ >
+ <Plus size={12} aria-hidden="true" /> Add series
+ </button>
+ </div>
+ </InspectorRow>
+ <InspectorRow label="Legend">
+ <Switch
+ checked={cfg.legend !== false}
+ aria-label="Show legend"
+ onCheckedChange={(checked) => set('legend', checked)}
+ />
+ </InspectorRow>
+ <InspectorRow label="Area fill">
+ <Switch
+ checked={cfg.fill !== false}
+ aria-label="Fill the area under each series"
+ onCheckedChange={(checked) => set('fill', checked)}
+ />
+ </InspectorRow>
+ </>
+ )}
+
+ {kind === 'topn' && (
+ <>
+ <InspectorRow label="Dimension">
+ <SegControl
+ options={toOptions(TOPN_DIMENSIONS)}
+ value={cfg.dim || 'servers'}
+ onChange={(value) => set('dim', value)}
+ />
+ </InspectorRow>
+ {/* Top N always ranks remote resources, so it offers the
+ server-side catalog whatever the board variable is. */}
+ <InspectorRow label="Metric">
+ <InspectorSelect
+ label="Metric"
+ value={cfg.metric || 'cpu'}
+ onChange={(value) => set('metric', value)}
+ options={topnMetricOptions(cfg.metric || 'cpu')}
+ />
+ </InspectorRow>
+ </>
+ )}
+
+ {kind === 'table' && (
+ <InspectorRow label="Source">
+ <InspectorSelect
+ label="Source"
+ value={cfg.source || 'services'}
+ onChange={(value) => set('source', value)}
+ options={TABLE_SOURCES}
+ />
+ </InspectorRow>
+ )}
+
+ {kind === 'logs' && (
+ <>
+ <InspectorRow label="Source">
+ <InspectorSelect
+ label="Log source"
+ value={cfg.source || '$server'}
+ onChange={(value) => set('source', value)}
+ options={resourceOptions}
+ />
+ </InspectorRow>
+ <InspectorRow label="Level">
+ <SegControl
+ options={toOptions(LOG_LEVELS)}
+ value={cfg.level || 'all'}
+ onChange={(value) => set('level', value)}
+ />
+ </InspectorRow>
+ </>
+ )}
+
+ {kind === 'alerts' && (
+ <InspectorRow label="Severity">
+ <SegControl
+ options={toOptions(SEVERITIES)}
+ value={cfg.severity || 'all'}
+ onChange={(value) => set('severity', value)}
+ />
+ </InspectorRow>
+ )}
+
+ {['table', 'logs', 'deploys', 'feed'].includes(kind) && (
+ <InspectorRow label={countsLines ? 'Lines' : 'Rows'}>
+ <Stepper
+ label={countsLines ? 'lines' : 'rows'}
+ value={countValue}
+ onStep={stepCount}
+ />
+ </InspectorRow>
+ )}
+
+ {kind === 'actions' && (
+ <InspectorRow label="Shortcuts">
+ <div className="skw-ins__checks">
+ {QUICK_ACTION_OPTIONS.map(([key, label]) => {
+ const on = (cfg.items || []).includes(key);
+ return (
+ <label className="skw-ins__check" key={key}>
+ <input
+ type="checkbox"
+ checked={on}
+ onChange={() => set(
+ 'items',
+ on
+ ? (cfg.items || []).filter((item) => item !== key)
+ : [...(cfg.items || []), key],
+ )}
+ />
+ {label}
+ </label>
+ );
+ })}
+ </div>
+ </InspectorRow>
+ )}
+
+ {kind === 'note' && (
+ <InspectorRow label="Text" hint="**bold** and `code` are supported.">
+ <textarea
+ className="skw-ins__textarea"
+ aria-label="Note text"
+ value={cfg.text || ''}
+ onChange={(event) => set('text', event.target.value)}
+ />
+ </InspectorRow>
+ )}
+
+ <InspectorRow label="Size">
+ <div className="skw-ins__pair">
+ <Stepper label="width" value={widget.w} suffix="wide" onStep={(d) => stepSize('w', d)} />
+ <Stepper label="height" value={widget.h} suffix="tall" onStep={(d) => stepSize('h', d)} />
+ </div>
+ </InspectorRow>
+ </div>
+
+ <div className="skw-ins__foot">
+ <button type="button" className="btn btn-sm" onClick={onDuplicate}>
+ <Copy size={13} aria-hidden="true" /> Duplicate
+ </button>
+ <button type="button" className="btn btn-sm btn-danger skw-ins__remove" onClick={onRemove}>
+ <Trash2 size={13} aria-hidden="true" /> Remove
+ </button>
+ </div>
+ </aside>
+ );
+}
+
+export default WidgetInspector;
diff --git a/frontend/src/components/dashboard/grid/WidgetLibrary.jsx b/frontend/src/components/dashboard/grid/WidgetLibrary.jsx
new file mode 100644
index 00000000..112d51f0
--- /dev/null
+++ b/frontend/src/components/dashboard/grid/WidgetLibrary.jsx
@@ -0,0 +1,322 @@
+import { useMemo, useState } from 'react';
+import { LayoutGrid, Plus } from 'lucide-react';
+import { Drawer, SearchField } from '@/components/ds';
+
+// Registry entries carry a lucide component in `icon`. Guard against a type
+// that shipped without one (or with a plain string) so the card still renders.
+const iconOf = (type) => {
+ const candidate = type?.icon;
+ const usable = typeof candidate === 'function' || (candidate && typeof candidate === 'object');
+ return usable ? candidate : LayoutGrid;
+};
+
+// Thumbnail palette. These are literal swatch colours inside an inline SVG
+// preview, so they read the same design tokens the real widgets do.
+const T_ACC = 'var(--accent-bright)';
+const T_GRN = 'var(--green)';
+const T_AMB = 'var(--amber)';
+const T_CYN = 'var(--cyan)';
+const T_RED = 'var(--red)';
+const T_LINE = 'var(--border-strong)';
+const T_DIM = 'var(--surface-3)';
+const T_INK = '#0a0c11';
+
+/**
+ * Tiny abstract preview of what a widget type looks like once placed. Purely
+ * decorative — the card's name and description carry the meaning.
+ */
+function WidgetThumb({ type }) {
+ const box = (kids) => (
+ <svg
+ viewBox="0 0 132 68"
+ preserveAspectRatio="xMidYMid meet"
+ className="skw-lib__thumb-svg"
+ aria-hidden="true"
+ focusable="false"
+ >
+ {kids}
+ </svg>
+ );
+ const bars = (values, colour) => values.map((value, i) => (
+ <rect key={i} x="10" y={10 + i * 13} width={value} height="6" rx="3" fill={i ? T_DIM : colour} />
+ ));
+ const lines = (count, y0 = 10, gap = 12) => Array.from({ length: count }, (_, i) => (
+ <rect key={i} x="10" y={y0 + i * gap} width={i % 2 ? 96 : 112} height="5" rx="2.5" fill={T_DIM} />
+ ));
+ const spark = (colour, y = 44, h = 16) => {
+ const points = [0, 6, 3, 11, 7, 14, 9, 17, 12, 20, 8, 25, 14, 28, 11, 33]
+ .map((value, i) => `${10 + i * 7.6},${y + h - (value / 28) * h}`)
+ .join(' ');
+ return <polyline points={points} fill="none" stroke={colour} strokeWidth="2" strokeLinejoin="round" />;
+ };
+
+ switch (type) {
+ case 'stat':
+ return box(
+ <>
+ <rect x="10" y="10" width="46" height="15" rx="3" fill={T_ACC} opacity=".85" />
+ <rect x="10" y="30" width="30" height="5" rx="2.5" fill={T_DIM} />
+ {spark(T_ACC)}
+ </>,
+ );
+ case 'timeseries':
+ return box(
+ <>
+ <path d="M8 52 L28 40 L46 46 L64 26 L84 34 L102 18 L124 26 L124 60 L8 60 Z" fill={T_ACC} opacity=".16" />
+ <path d="M8 52 L28 40 L46 46 L64 26 L84 34 L102 18 L124 26" fill="none" stroke={T_ACC} strokeWidth="2" strokeLinejoin="round" />
+ <path d="M8 58 L28 52 L46 54 L64 44 L84 50 L102 42 L124 46" fill="none" stroke={T_GRN} strokeWidth="2" strokeLinejoin="round" />
+ <g fill={T_DIM}>
+ <rect x="8" y="8" width="20" height="4" rx="2" />
+ <rect x="32" y="8" width="14" height="4" rx="2" />
+ </g>
+ </>,
+ );
+ case 'gauge':
+ return box(
+ <>
+ <path d="M28 52 A38 38 0 0 1 104 52" fill="none" stroke={T_DIM} strokeWidth="9" strokeLinecap="round" />
+ <path d="M28 52 A38 38 0 0 1 96 30" fill="none" stroke={T_GRN} strokeWidth="9" strokeLinecap="round" />
+ <rect x="52" y="42" width="28" height="9" rx="3" fill={T_GRN} opacity=".8" />
+ </>,
+ );
+ case 'topn':
+ return box(
+ <>
+ {bars([84, 66, 50, 34], T_CYN)}
+ <rect x="10" y="10" width="84" height="6" rx="3" fill={T_CYN} />
+ </>,
+ );
+ case 'table':
+ return box(
+ <>
+ <rect x="0" y="0" width="132" height="14" fill={T_DIM} opacity=".7" />
+ {[0, 1, 2].map((i) => (
+ <g key={i}>
+ <rect x="10" y={22 + i * 14} width="34" height="5" rx="2.5" fill={i ? T_DIM : T_LINE} />
+ <rect x="52" y={22 + i * 14} width="26" height="5" rx="2.5" fill={T_DIM} />
+ <rect x="86" y={22 + i * 14} width="18" height="5" rx="2.5" fill={i === 1 ? T_GRN : T_DIM} />
+ </g>
+ ))}
+ </>,
+ );
+ case 'logs':
+ return box(
+ <>
+ <rect x="0" y="0" width="132" height="68" fill={T_INK} />
+ {[112, 92, 120, 74, 104, 86].map((width, i) => (
+ <g key={i}>
+ <rect x="8" y={9 + i * 10} width="14" height="4" rx="2" fill={T_LINE} />
+ <rect x="26" y={9 + i * 10} width={width - 26} height="4" rx="2" fill={i === 3 ? T_RED : i === 4 ? T_AMB : T_DIM} />
+ </g>
+ ))}
+ </>,
+ );
+ case 'deploys':
+ return box(
+ <>
+ {[0, 1, 2].map((i) => (
+ <g key={i}>
+ <rect x="10" y={10 + i * 20} width="40" height="5" rx="2.5" fill={T_LINE} />
+ {[0, 1, 2, 3, 4, 5].map((j) => (
+ <rect
+ key={j}
+ x={10 + j * 20}
+ y={19 + i * 20}
+ width="16"
+ height="4"
+ rx="2"
+ fill={j < 4 - i ? (i === 1 ? T_RED : T_GRN) : T_DIM}
+ />
+ ))}
+ </g>
+ ))}
+ </>,
+ );
+ case 'alerts':
+ return box(
+ <>
+ {[T_RED, T_AMB, T_CYN].map((colour, i) => (
+ <g key={i}>
+ <circle cx="14" cy={16 + i * 18} r="4" fill={colour} />
+ <rect x="24" y={13 + i * 18} width="70" height="5" rx="2.5" fill={T_LINE} />
+ <rect x="100" y={13 + i * 18} width="22" height="5" rx="2.5" fill={T_DIM} />
+ </g>
+ ))}
+ </>,
+ );
+ case 'status':
+ return box(
+ <>
+ {Array.from({ length: 8 }, (_, i) => {
+ const colour = i === 3 ? T_AMB : i === 6 ? T_RED : T_GRN;
+ return (
+ <g key={i}>
+ <rect x={8 + (i % 4) * 32} y={10 + Math.floor(i / 4) * 28} width="28" height="22" rx="4" fill={T_DIM} />
+ <circle cx={15 + (i % 4) * 32} cy={18 + Math.floor(i / 4) * 28} r="3" fill={colour} />
+ <rect x={12 + (i % 4) * 32} y={25 + Math.floor(i / 4) * 28} width="18" height="3" rx="1.5" fill={T_LINE} />
+ </g>
+ );
+ })}
+ </>,
+ );
+ case 'feed':
+ return box(
+ <>
+ {[0, 1, 2].map((i) => (
+ <g key={i}>
+ <circle cx="15" cy={16 + i * 19} r="6" fill={T_DIM} />
+ <rect x="28" y={11 + i * 19} width="94" height="5" rx="2.5" fill={T_LINE} />
+ <rect x="28" y={20 + i * 19} width="40" height="4" rx="2" fill={T_DIM} />
+ </g>
+ ))}
+ </>,
+ );
+ case 'actions':
+ return box(
+ <>
+ {[0, 1, 2].map((i) => (
+ <g key={i}>
+ <rect x="10" y={9 + i * 19} width="112" height="15" rx="5" fill={T_DIM} />
+ <rect x="18" y={14 + i * 19} width="46" height="5" rx="2.5" fill={T_LINE} />
+ <rect x="104" y={13 + i * 19} width="10" height="7" rx="2" fill={T_ACC} opacity=".7" />
+ </g>
+ ))}
+ </>,
+ );
+ case 'specs':
+ return box(
+ <>
+ {[0, 1, 2, 3].map((i) => (
+ <g key={i}>
+ <rect x="10" y={11 + i * 15} width="34" height="5" rx="2.5" fill={T_DIM} />
+ <rect x="70" y={11 + i * 15} width="52" height="5" rx="2.5" fill={T_LINE} />
+ </g>
+ ))}
+ </>,
+ );
+ case 'note':
+ return box(
+ <>
+ {lines(4, 12, 14)}
+ <rect x="10" y="12" width="42" height="5" rx="2.5" fill={T_ACC} opacity=".7" />
+ </>,
+ );
+ default:
+ return box(<rect x="10" y="10" width="112" height="48" rx="6" fill={T_DIM} />);
+ }
+}
+
+/**
+ * "Add a widget" drawer: search + category chips over a grid of preview cards.
+ * Picking a card hands the widget type back to the board, which decides where
+ * to place it.
+ */
+export function WidgetLibrary({ types = [], onAdd, onClose }) {
+ const [query, setQuery] = useState('');
+ const [category, setCategory] = useState(null);
+
+ // Derived from the live type list so plugin-contributed categories show up
+ // without a second source of truth.
+ const categories = useMemo(
+ () => [...new Set(types.map((type) => type.cat).filter(Boolean))],
+ [types],
+ );
+
+ const visible = useMemo(() => {
+ const needle = query.trim().toLowerCase();
+ return types.filter((type) => {
+ if (category && type.cat !== category) return false;
+ if (!needle) return true;
+ return `${type.name} ${type.desc || ''}`.toLowerCase().includes(needle);
+ });
+ }, [types, query, category]);
+
+ return (
+ <Drawer
+ open
+ onOpenChange={(next) => { if (!next) onClose?.(); }}
+ title="Add a widget"
+ subtitle={`${types.length} types · drag to reposition after adding`}
+ icon={<LayoutGrid size={18} />}
+ width={700}
+ className="skw-lib"
+ >
+ <div className="skw-lib__filters">
+ <SearchField
+ className="skw-lib__search"
+ value={query}
+ onSearch={setQuery}
+ placeholder="Search widgets…"
+ />
+ <div className="skw-lib__chips">
+ <button
+ type="button"
+ className={`skw-lib__chip${category ? '' : ' skw-lib__chip--on'}`}
+ aria-pressed={!category}
+ onClick={() => setCategory(null)}
+ >
+ All
+ </button>
+ {categories.map((name) => (
+ <button
+ key={name}
+ type="button"
+ className={`skw-lib__chip${category === name ? ' skw-lib__chip--on' : ''}`}
+ aria-pressed={category === name}
+ onClick={() => setCategory(category === name ? null : name)}
+ >
+ {name}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="skw-lib__grid">
+ {visible.map((type) => {
+ const Icon = iconOf(type);
+ const add = () => onAdd?.(type);
+ return (
+ // Kept as a div (not a <button>) so the ported card CSS,
+ // which nests block-level rows, still applies; role +
+ // key handling give it the same keyboard behaviour.
+ <div
+ className="skw-lib__card"
+ key={type.id}
+ role="button"
+ tabIndex={0}
+ aria-label={`Add ${type.name} widget`}
+ onClick={add}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ add();
+ }
+ }}
+ >
+ <div className="skw-lib__thumb">
+ <WidgetThumb type={type.id} />
+ <span className="skw-lib__add">
+ <Plus size={14} aria-hidden="true" />
+ Add
+ </span>
+ </div>
+ <div className="skw-lib__meta">
+ <div className="skw-lib__name">
+ <span className="skw-lib__icon"><Icon size={13} aria-hidden="true" /></span>
+ {type.name}
+ <span className="skw-lib__size mono">{type.w}×{type.h}</span>
+ </div>
+ <div className="skw-lib__desc">{type.desc}</div>
+ </div>
+ </div>
+ );
+ })}
+ {visible.length === 0 && (
+ <div className="skw-lib__empty">No widgets match.</div>
+ )}
+ </div>
+ </Drawer>
+ );
+}
+
+export default WidgetLibrary;
diff --git a/frontend/src/components/dashboard/grid/layout.js b/frontend/src/components/dashboard/grid/layout.js
new file mode 100644
index 00000000..80ef3a81
--- /dev/null
+++ b/frontend/src/components/dashboard/grid/layout.js
@@ -0,0 +1,91 @@
+// Pure geometry helpers for the dashboard widget grid.
+//
+// The board is a fixed 12-column grid. A widget instance is
+// `{ i, type, x, y, w, h, cfg }` where x/y are cell coordinates and w/h are
+// spans in cells. Everything in here is side-effect free and returns new
+// arrays, so callers can drive React state straight from the result.
+
+/** Columns in the board grid. */
+export const GRID_COLS = 12;
+/** Gutter between cells, in px. */
+export const GRID_GAP = 12;
+/** Height of one row unit, in px. */
+export const GRID_ROW = 88;
+
+// findFreeSpot gives up after this many rows rather than looping forever on a
+// pathological board.
+const MAX_SCAN_ROWS = 200;
+
+/**
+ * True when two widget rectangles intersect. A widget never overlaps itself,
+ * so the same `i` short-circuits to false.
+ */
+export function overlaps(a, b) {
+ return (
+ a.i !== b.i
+ && a.x < b.x + b.w
+ && a.x + a.w > b.x
+ && a.y < b.y + b.h
+ && a.y + a.h > b.y
+ );
+}
+
+/**
+ * Gravity-up compaction: walk the widgets top-to-bottom, left-to-right and
+ * float each one as far up as it can go without hitting an already-placed
+ * neighbour. Returns a new array of new objects.
+ */
+export function compact(list) {
+ const out = [...list]
+ .sort((a, b) => a.y - b.y || a.x - b.x)
+ .map((widget) => ({ ...widget }));
+ const placed = [];
+ out.forEach((widget) => {
+ let y = widget.y;
+ while (y > 0 && !placed.some((other) => overlaps(other, { ...widget, y: y - 1 }))) y -= 1;
+ widget.y = y;
+ placed.push(widget);
+ });
+ return out;
+}
+
+/**
+ * Apply `moved` to the board, push anything it lands on straight down (and
+ * anything those hit, recursively), then re-compact. Returns a new array.
+ */
+export function pushDown(list, moved) {
+ const out = list.map((widget) => (widget.i === moved.i ? { ...moved } : { ...widget }));
+ const seen = new Set();
+ const walk = (target) => {
+ if (!target || seen.has(target.i)) return;
+ seen.add(target.i);
+ out.filter((widget) => overlaps(widget, target)).forEach((widget) => {
+ widget.y = target.y + target.h;
+ walk(widget);
+ });
+ };
+ walk(out.find((widget) => widget.i === moved.i));
+ return compact(out);
+}
+
+/** Lowest unused `w<N>` id for this board. */
+export function nextWidgetId(list) {
+ let n = 1;
+ while (list.some((widget) => widget.i === `w${n}`)) n += 1;
+ return `w${n}`;
+}
+
+/**
+ * First cell (scanning row by row, left to right) where a `w`×`h` widget fits
+ * without overlapping anything. Falls back to the origin — compaction will
+ * sort out the collision.
+ */
+export function findFreeSpot(list, w, h) {
+ for (let y = 0; y < MAX_SCAN_ROWS; y += 1) {
+ for (let x = 0; x <= GRID_COLS - w; x += 1) {
+ const candidate = { i: '__new', x, y, w, h };
+ if (!list.some((other) => overlaps(other, candidate))) return { x, y };
+ }
+ }
+ return { x: 0, y: 0 };
+}
diff --git a/frontend/src/components/dashboard/widgets/metrics.js b/frontend/src/components/dashboard/widgets/metrics.js
new file mode 100644
index 00000000..95ad6472
--- /dev/null
+++ b/frontend/src/components/dashboard/widgets/metrics.js
@@ -0,0 +1,281 @@
+/**
+ * Metric catalog for the dashboard widget grid (plan 62).
+ *
+ * Every entry here is backed by a REAL field on a real payload — there is no
+ * synthetic data anywhere in the widget stack. Two history payloads exist and
+ * they are shaped differently, so each metric carries the candidate paths for
+ * both:
+ *
+ * local host GET /api/v1/metrics/history?period=…
+ * → MetricsHistory.to_dict() (backend/app/models/metrics_history.py)
+ * { timestamp, level, cpu:{percent,min,max},
+ * memory:{percent,used_bytes,total_bytes,…},
+ * disk:{percent,used_bytes,total_bytes,…},
+ * load:{'1m','5m','15m'}, sample_count }
+ * NOTE: no network fields at all.
+ *
+ * remote agent GET /api/v1/servers/<id>/metrics/history?period=…
+ * → ServerMetrics.to_dict() (backend/app/models/server.py)
+ * { timestamp, cpu_percent, memory_percent, memory_used,
+ * disk_percent, disk_used, network_rx, network_tx,
+ * network_rx_rate, network_tx_rate, container_count,
+ * container_running, extra }
+ * NOTE: no load average.
+ *
+ * The live socket/poll payload (GET /api/v1/system/metrics, and the same shape
+ * for /servers/<id>/system/metrics) nests differently again — `live` holds its
+ * path. Network there is a cumulative byte counter, not a rate, so it cannot
+ * stand in for net_in/net_out and is deliberately left null.
+ */
+
+// The agent reports network rates in bytes/sec; the catalog presents MB/s.
+const BYTES_PER_MB = 1024 * 1024;
+
+export const METRICS = [
+ {
+ id: 'cpu',
+ label: 'CPU usage',
+ unit: '%',
+ color: 'var(--accent-bright)',
+ max: 100,
+ field: 'cpu.percent',
+ paths: ['cpu.percent', 'cpu_percent'],
+ live: 'cpu.percent',
+ sources: ['local', 'server'],
+ },
+ {
+ id: 'ram',
+ label: 'Memory usage',
+ unit: '%',
+ color: 'var(--green)',
+ max: 100,
+ field: 'memory.percent',
+ paths: ['memory.percent', 'memory_percent'],
+ live: 'memory.percent',
+ sources: ['local', 'server'],
+ },
+ {
+ id: 'disk',
+ label: 'Disk usage',
+ unit: '%',
+ color: 'var(--amber)',
+ max: 100,
+ field: 'disk.percent',
+ paths: ['disk.percent', 'disk_percent'],
+ live: 'disk.percent',
+ sources: ['local', 'server'],
+ },
+ {
+ id: 'net_in',
+ label: 'Network in',
+ unit: 'MB/s',
+ color: 'var(--cyan)',
+ max: null,
+ // ServerMetrics.network_rx_rate (bytes/sec) is a real, populated column
+ // — but ONLY on the agent-server history. The local-host history table
+ // has no network columns at all, so this metric is server-scoped and is
+ // never offered for `local`. See metricsForSource().
+ field: 'network_rx_rate',
+ paths: ['network_rx_rate'],
+ scale: 1 / BYTES_PER_MB,
+ live: null,
+ sources: ['server'],
+ },
+ {
+ id: 'net_out',
+ label: 'Network out',
+ unit: 'MB/s',
+ color: 'var(--violet)',
+ max: null,
+ field: 'network_tx_rate',
+ paths: ['network_tx_rate'],
+ scale: 1 / BYTES_PER_MB,
+ live: null,
+ sources: ['server'],
+ },
+ {
+ id: 'load',
+ label: 'Load average',
+ unit: '',
+ color: 'var(--accent-bright)',
+ max: null,
+ // MetricsHistory column load_1m is serialised as load['1m'].
+ // ServerMetrics has no load column, so this is local-host only.
+ field: 'load.1m',
+ paths: ['load.1m'],
+ live: 'load_average.1min',
+ sources: ['local'],
+ },
+];
+
+export const AGGREGATIONS = [
+ ['last', 'Last'],
+ ['avg', 'Average'],
+ ['max', 'Max'],
+ ['p95', 'p95'],
+ ['min', 'Min'],
+];
+
+export const RANGES = [
+ ['1h', '1h'],
+ ['6h', '6h'],
+ ['24h', '24h'],
+ ['7d', '7d'],
+ ['30d', '30d'],
+];
+
+export const RANGE_IDS = RANGES.map(([id]) => id);
+
+/** Look a metric up by id. Falls back to the first entry so callers never
+ * have to null-check a stale saved config. */
+export function getMetric(id) {
+ return METRICS.find((m) => m.id === id) || METRICS[0];
+}
+
+/** Which history source a resource id maps to: 'local' or 'server'. */
+export function sourceOf(resource) {
+ return !resource || resource === 'local' ? 'local' : 'server';
+}
+
+/** True when this metric actually has a backing column on that source. */
+export function metricSupports(metric, source) {
+ if (!metric) return false;
+ return (metric.sources || []).includes(source);
+}
+
+/**
+ * The metrics a given resource can actually answer for. Config UIs MUST build
+ * their metric dropdown from this, not from METRICS — that is what keeps a dead
+ * option (network on the local host, load average on an agent server) from ever
+ * reaching a user.
+ *
+ * metricsForSource('local') -> cpu, ram, disk, load
+ * metricsForSource('server') -> cpu, ram, disk, net_in, net_out
+ */
+export function metricsForSource(source) {
+ const key = source === 'server' ? 'server' : 'local';
+ return METRICS.filter((m) => metricSupports(m, key));
+}
+
+/** Same, but resolving a resource id rather than a source name. */
+export function metricsForResource(resource) {
+ return metricsForSource(sourceOf(resource));
+}
+
+/** Read a dotted path off a plain object without throwing on gaps. */
+export function readAt(obj, path) {
+ if (!obj || !path) return undefined;
+ let cur = obj;
+ for (const key of String(path).split('.')) {
+ if (cur === null || cur === undefined) return undefined;
+ cur = cur[key];
+ }
+ return cur;
+}
+
+/** Pull one metric's value out of a single history point. Returns null when
+ * the point does not carry that field (e.g. load on an agent server). */
+export function readPoint(point, metric) {
+ if (!point || !metric) return null;
+ for (const path of metric.paths || []) {
+ const raw = readAt(point, path);
+ if (typeof raw === 'number' && Number.isFinite(raw)) {
+ return metric.scale ? raw * metric.scale : raw;
+ }
+ }
+ return null;
+}
+
+/** Pull one metric's value out of the live /system/metrics payload. */
+export function readLive(liveMetrics, metric) {
+ if (!liveMetrics || !metric || !metric.live) return null;
+ const raw = readAt(liveMetrics, metric.live);
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return null;
+ return metric.scale ? raw * metric.scale : raw;
+}
+
+/**
+ * Turn a history payload ({ data: [...] } from either endpoint) into a plain
+ * number[] for one metric. Points missing the field are skipped, so a metric
+ * with no backing column yields an empty series rather than a row of zeroes.
+ */
+export function seriesFrom(payload, metricId) {
+ const metric = getMetric(metricId);
+ const points = Array.isArray(payload?.data) ? payload.data : [];
+ const out = [];
+ for (const point of points) {
+ const value = readPoint(point, metric);
+ if (value !== null) out.push(value);
+ }
+ return out;
+}
+
+/** Timestamps that line up 1:1 with seriesFrom() for the same metric. */
+export function stampsFrom(payload, metricId) {
+ const metric = getMetric(metricId);
+ const points = Array.isArray(payload?.data) ? payload.data : [];
+ const out = [];
+ for (const point of points) {
+ if (readPoint(point, metric) !== null) out.push(point.timestamp || null);
+ }
+ return out;
+}
+
+/** Reduce a series to one number. Unknown aggregations behave as 'last'. */
+export function aggregate(series, agg) {
+ const values = (series || []).filter((v) => typeof v === 'number' && Number.isFinite(v));
+ if (!values.length) return null;
+ const sorted = [...values].sort((a, b) => a - b);
+ switch (agg) {
+ case 'avg':
+ return values.reduce((a, b) => a + b, 0) / values.length;
+ case 'max':
+ return sorted[sorted.length - 1];
+ case 'min':
+ return sorted[0];
+ case 'p95':
+ return sorted[Math.max(0, Math.ceil(sorted.length * 0.95) - 1)];
+ default:
+ return values[values.length - 1];
+ }
+}
+
+/**
+ * Percentage change of the aggregate between the older 60% of the window and
+ * the whole window — the same "vs earlier in this range" delta the stat tile
+ * shows. Returns null when there is not enough history to be honest about it.
+ */
+export function deltaPercent(series, agg) {
+ const values = (series || []).filter((v) => typeof v === 'number' && Number.isFinite(v));
+ if (values.length < 4) return null;
+ const head = values.slice(0, Math.floor(values.length * 0.6));
+ if (!head.length) return null;
+ const now = aggregate(values, agg);
+ const before = aggregate(head, agg);
+ if (now === null || !before) return null;
+ return ((now - before) / Math.abs(before)) * 100;
+}
+
+/** Human-readable value + unit. `null`/NaN render as an em dash. */
+export function formatValue(value, unit) {
+ if (value === null || value === undefined || !Number.isFinite(value)) return '—';
+ if (unit === '%') return `${Math.round(value * 10) / 10}%`;
+ const num = Math.abs(value) >= 1000
+ ? `${(value / 1000).toFixed(1)}k`
+ : `${Math.round(value * 100) / 100}`;
+ return unit ? `${num} ${unit}` : num;
+}
+
+/**
+ * Threshold colour for a value. `thresholds` is [amber, red]; anything below
+ * amber is green. Returns null when no thresholds are configured so callers
+ * can fall back to the metric's own colour.
+ */
+export function thresholdColor(value, thresholds) {
+ if (!Array.isArray(thresholds) || thresholds.length === 0) return null;
+ if (value === null || value === undefined || !Number.isFinite(value)) return null;
+ const [amber, red] = thresholds;
+ if (Number.isFinite(red) && value >= red) return 'var(--red)';
+ if (Number.isFinite(amber) && value >= amber) return 'var(--amber)';
+ return 'var(--green)';
+}
diff --git a/frontend/src/components/dashboard/widgets/registry.js b/frontend/src/components/dashboard/widgets/registry.js
new file mode 100644
index 00000000..02e13743
--- /dev/null
+++ b/frontend/src/components/dashboard/widgets/registry.js
@@ -0,0 +1,320 @@
+/**
+ * Widget type registry for the dashboard grid (plan 62).
+ *
+ * A widget TYPE describes a placeable kind of widget:
+ * { id, name, icon, cat, desc, w, h, min: [w,h], defaultCfg, component?, plugin? }
+ *
+ * Core types render through `WidgetBody` in ./renderers.jsx. Plugin-contributed
+ * types carry their own `component`, resolved from the plugin's frontend module.
+ */
+import { useMemo } from 'react';
+import {
+ Activity,
+ BarChart3,
+ CheckCircle2,
+ CircleDashed,
+ Cpu,
+ FileText,
+ History,
+ LayoutGrid,
+ Rocket,
+ Rows3,
+ ShieldAlert,
+ Terminal,
+ Zap,
+} from 'lucide-react';
+import { useContributions, resolveComponent } from '@/plugins/contributions';
+
+export const WIDGET_CATEGORIES = ['Metrics', 'Inventory', 'Operations', 'Utility'];
+
+export const CORE_WIDGET_TYPES = [
+ {
+ id: 'stat',
+ name: 'Stat',
+ icon: BarChart3,
+ cat: 'Metrics',
+ desc: 'Single value with sparkline and threshold colouring',
+ w: 3,
+ h: 2,
+ min: [2, 2],
+ defaultCfg: {
+ title: 'CPU usage',
+ resource: '$server',
+ metric: 'cpu',
+ agg: 'last',
+ spark: true,
+ thresholds: [70, 90],
+ color: '',
+ },
+ },
+ {
+ id: 'timeseries',
+ name: 'Time series',
+ icon: Activity,
+ cat: 'Metrics',
+ desc: 'Multi-series area chart with legend',
+ w: 8,
+ h: 4,
+ min: [3, 3],
+ defaultCfg: {
+ title: 'Real-time performance',
+ series: [
+ { resource: '$server', metric: 'cpu' },
+ { resource: '$server', metric: 'ram' },
+ ],
+ legend: true,
+ fill: true,
+ },
+ },
+ {
+ id: 'gauge',
+ name: 'Gauge',
+ icon: CircleDashed,
+ cat: 'Metrics',
+ desc: 'Radial gauge against a maximum',
+ w: 3,
+ h: 3,
+ min: [2, 3],
+ defaultCfg: {
+ title: 'Disk usage',
+ resource: '$server',
+ metric: 'disk',
+ agg: 'last',
+ thresholds: [70, 88],
+ },
+ },
+ {
+ id: 'topn',
+ name: 'Top N',
+ icon: Rows3,
+ cat: 'Metrics',
+ desc: 'Ranked bars across the server fleet',
+ w: 4,
+ h: 4,
+ min: [3, 3],
+ defaultCfg: {
+ title: 'Busiest servers',
+ dim: 'servers',
+ metric: 'cpu',
+ limit: 5,
+ },
+ },
+ {
+ id: 'table',
+ name: 'Resource table',
+ icon: LayoutGrid,
+ cat: 'Inventory',
+ desc: 'Services, servers, containers or deployments',
+ w: 8,
+ h: 4,
+ min: [4, 3],
+ defaultCfg: {
+ title: 'Applications',
+ source: 'services',
+ limit: 6,
+ },
+ },
+ {
+ id: 'logs',
+ name: 'Log stream',
+ icon: Terminal,
+ cat: 'Operations',
+ desc: 'Tailing log lines with a level filter',
+ w: 6,
+ h: 4,
+ min: [3, 3],
+ defaultCfg: {
+ title: 'Live logs',
+ source: 'file',
+ path: '',
+ containerId: '',
+ level: 'all',
+ lines: 60,
+ },
+ },
+ {
+ id: 'deploys',
+ name: 'Deploy activity',
+ icon: Rocket,
+ cat: 'Operations',
+ desc: 'Recent deployment jobs with step progress',
+ w: 4,
+ h: 4,
+ min: [3, 3],
+ defaultCfg: {
+ title: 'Deploy activity',
+ limit: 5,
+ },
+ },
+ {
+ id: 'alerts',
+ name: 'Alerts',
+ icon: ShieldAlert,
+ cat: 'Operations',
+ desc: 'Open threshold alerts across the fleet and this host',
+ w: 4,
+ h: 3,
+ min: [3, 2],
+ defaultCfg: {
+ title: 'Open alerts',
+ severity: 'all',
+ limit: 8,
+ },
+ },
+ {
+ id: 'status',
+ name: 'Status grid',
+ icon: CheckCircle2,
+ cat: 'Operations',
+ desc: 'Up/down matrix for servers or services',
+ w: 4,
+ h: 3,
+ min: [3, 2],
+ defaultCfg: {
+ title: 'Status grid',
+ source: 'servers',
+ limit: 12,
+ },
+ },
+ {
+ id: 'feed',
+ name: 'Activity feed',
+ icon: History,
+ cat: 'Operations',
+ desc: 'Audit trail of recent changes (admin only)',
+ w: 4,
+ h: 4,
+ min: [3, 3],
+ defaultCfg: {
+ title: 'Recent activity',
+ limit: 6,
+ },
+ },
+ {
+ id: 'actions',
+ name: 'Quick actions',
+ icon: Zap,
+ cat: 'Utility',
+ desc: 'Shortcut buttons into other sections',
+ w: 3,
+ h: 3,
+ min: [2, 2],
+ defaultCfg: {
+ title: 'Quick actions',
+ items: ['servers', 'docker', 'terminal'],
+ },
+ },
+ {
+ id: 'specs',
+ name: 'Host details',
+ icon: Cpu,
+ cat: 'Utility',
+ desc: 'Key/value hardware and OS facts',
+ w: 3,
+ h: 3,
+ min: [2, 2],
+ defaultCfg: {
+ title: 'Host details',
+ resource: '$server',
+ },
+ },
+ {
+ id: 'note',
+ name: 'Text note',
+ icon: FileText,
+ cat: 'Utility',
+ desc: 'Markdown-ish note for runbooks and context',
+ w: 3,
+ h: 2,
+ min: [2, 2],
+ defaultCfg: {
+ title: 'Note',
+ text: 'On-call: check **deploy activity** before restarting anything.',
+ },
+ },
+];
+
+// Clamp a contributed size to something the grid can actually place.
+function clampSpan(value, fallback, max) {
+ const n = Number(value);
+ if (!Number.isFinite(n) || n < 1) return fallback;
+ return Math.min(Math.round(n), max);
+}
+
+/**
+ * Namespaced type id for a contributed widget: `<plugin-slug>:<id>`.
+ *
+ * Without this, two extensions both shipping an `activity` widget would
+ * collide and one would vanish. The namespace is also what a saved board
+ * stores in `widget.type`, so a board keeps pointing at the right plugin's
+ * widget even if another plugin later claims the same bare id.
+ */
+export function contributedTypeId(plugin, id) {
+ return `${plugin}:${id}`;
+}
+
+// Manifest fields are snake_case like the rest of `contributions` (see
+// docs/EXTENSIONS.md). The camelCase spellings are tolerated as aliases so an
+// extension author who guessed the JS convention isn't silently ignored.
+function normalizeContributed(decl, component) {
+ const w = clampSpan(decl.w, 4, 12);
+ const h = clampSpan(decl.h, 3, 12);
+ const min = Array.isArray(decl.min) ? decl.min : [];
+ const category = decl.category || decl.cat;
+ const defaultCfg = decl.default_cfg || decl.defaultCfg;
+ return {
+ id: contributedTypeId(decl.plugin, decl.id),
+ name: decl.name || decl.id,
+ icon: LayoutGrid,
+ cat: WIDGET_CATEGORIES.includes(category) ? category : 'Utility',
+ desc: decl.description || decl.desc || '',
+ w,
+ h,
+ min: [clampSpan(min[0], 2, w), clampSpan(min[1], 2, h)],
+ defaultCfg: defaultCfg && typeof defaultCfg === 'object' ? defaultCfg : {},
+ component,
+ plugin: decl.plugin,
+ };
+}
+
+/**
+ * Core types plus anything plugins contribute under
+ * `contributions.dashboard_widgets`.
+ *
+ * That contribution surface does not exist in the backend envelope yet — the
+ * `|| []` below is what keeps this working today and lights it up the moment
+ * the backend starts emitting it. A contributed entry is skipped (silently,
+ * not fatally) when its component cannot be resolved, which is the normal
+ * state for a plugin whose frontend bundle has not been built.
+ */
+export function useWidgetTypes() {
+ const contributions = useContributions();
+
+ return useMemo(() => {
+ const declared = Array.isArray(contributions?.dashboard_widgets)
+ ? contributions.dashboard_widgets
+ : [];
+
+ const types = [...CORE_WIDGET_TYPES];
+ const seen = new Set(types.map((t) => t.id));
+
+ for (const decl of declared) {
+ if (!decl || typeof decl !== 'object' || !decl.id || !decl.plugin) continue;
+ const typeId = contributedTypeId(decl.plugin, decl.id);
+ if (seen.has(typeId)) continue;
+ const component = resolveComponent(decl.plugin, decl.component);
+ if (!component) continue;
+ seen.add(typeId);
+ types.push(normalizeContributed(decl, component));
+ }
+
+ return types;
+ }, [contributions]);
+}
+
+/** Pure lookup. Returns null for an unknown id so callers can render a
+ * "this widget type is gone" placeholder instead of crashing. */
+export function getWidgetType(types, id) {
+ if (!Array.isArray(types) || !id) return null;
+ return types.find((t) => t && t.id === id) || null;
+}
diff --git a/frontend/src/components/dashboard/widgets/renderers.jsx b/frontend/src/components/dashboard/widgets/renderers.jsx
new file mode 100644
index 00000000..a77b9ae5
--- /dev/null
+++ b/frontend/src/components/dashboard/widgets/renderers.jsx
@@ -0,0 +1,822 @@
+/**
+ * The 13 core dashboard widget renderers (plan 62).
+ *
+ * Every renderer is presentational — all fetching lives in ./useWidgetData.
+ * Every renderer handles three states: loading, empty and error. Nothing here
+ * may throw: `WidgetBody` wraps each one in a boundary so one bad widget can
+ * never take the grid down with it.
+ */
+import { Component, useEffect, useId, useMemo, useRef } from 'react';
+import {
+ Activity,
+ Archive,
+ ArrowDown,
+ ArrowUp,
+ Boxes,
+ Container,
+ Database,
+ FolderOpen,
+ Globe,
+ ListChecks,
+ Rocket,
+ Server,
+ ShieldCheck,
+ Terminal,
+} from 'lucide-react';
+import { Gauge, Pill, Sparkline } from '@/components/ds';
+import { getWidgetType } from './registry';
+import {
+ aggregate,
+ deltaPercent,
+ formatValue,
+ getMetric,
+ sourceOf,
+ thresholdColor,
+} from './metrics';
+import {
+ useActivity,
+ useDeployJobs,
+ useFleetHeatmap,
+ useLogTail,
+ useMetricSeries,
+ useMetricSeriesSet,
+ useOpenAlerts,
+ useResourceLabel,
+ useResourceRows,
+ useStatusCells,
+ useSystemSpecs,
+} from './useWidgetData';
+
+/* ------------------------------------------------------------ shared bits */
+
+// A widget's `cfg.resource` may be the literal '$server' dashboard variable.
+function resolveResource(resource, ctx) {
+ if (resource === '$server') return ctx?.serverVar || 'local';
+ return resource || 'local';
+}
+
+function Loading({ label = 'Loading…' }) {
+ return <div className="skw-empty skw-empty--loading">{label}</div>;
+}
+
+function Empty({ children }) {
+ return <div className="skw-empty">{children}</div>;
+}
+
+// Muted one-liner. A 403 is phrased as a permission note, not a failure.
+function Failed({ error, subject = 'data' }) {
+ if (error?.forbidden) {
+ return <div className="skw-empty skw-empty--error">Your role cannot read {subject}.</div>;
+ }
+ return (
+ <div className="skw-empty skw-empty--error">
+ Could not load {subject}
+ {error?.message ? ` — ${error.message}` : '.'}
+ </div>
+ );
+}
+
+function relTime(value) {
+ if (!value) return '';
+ const stamp = new Date(value).getTime();
+ if (Number.isNaN(stamp)) return '';
+ const minutes = Math.floor(Math.max(0, Date.now() - stamp) / 60000);
+ if (minutes < 1) return 'just now';
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ return `${Math.floor(hours / 24)}d ago`;
+}
+
+const OK_STATE = /^(running|healthy|online|succeeded|success|completed|up|active)$/i;
+const BAD_STATE = /^(failed|error|down|exited|stopped|offline|cancelled)$/i;
+
+function pillKind(state) {
+ const value = String(state || '');
+ if (OK_STATE.test(value)) return 'green';
+ if (BAD_STATE.test(value)) return 'red';
+ return 'amber';
+}
+
+/**
+ * Multi-series area chart. Hand-rolled rather than reusing ds/AreaChart
+ * because a widget needs the fill toggle and a height that tracks its cell.
+ * Gradient ids are per-instance (useId) so two charts on one board cannot
+ * capture each other's fills.
+ */
+function WidgetChart({ series, colors, fill = true, grid = true, height = '100%' }) {
+ const uid = useId().replace(/:/g, '');
+ const data = (series || []).filter((s) => Array.isArray(s) && s.length > 0);
+ const all = data.flat();
+ if (!all.length) return null;
+
+ const w = 100;
+ const h = 100;
+ const max = Math.max(...all) * 1.12;
+ const min = Math.min(...all) * 0.7;
+ const span = max - min || 1;
+ const toX = (i, len) => (i / (len - 1 || 1)) * w;
+ const toY = (v) => h - ((v - min) / span) * h;
+ const line = (s) => s.map((v, i) => `${i ? 'L' : 'M'}${toX(i, s.length).toFixed(2)} ${toY(v).toFixed(2)}`).join(' ');
+
+ return (
+ <svg
+ viewBox={`0 0 ${w} ${h}`}
+ preserveAspectRatio="none"
+ style={{ width: '100%', height, display: 'block' }}
+ aria-hidden="true"
+ >
+ <defs>
+ {colors.map((color, i) => (
+ <linearGradient key={i} id={`skw-${uid}-${i}`} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor={color} stopOpacity="0.26" />
+ <stop offset="100%" stopColor={color} stopOpacity="0" />
+ </linearGradient>
+ ))}
+ </defs>
+ {grid && [0, 25, 50, 75, 100].map((y) => (
+ <line
+ key={y}
+ x1="0"
+ y1={y}
+ x2={w}
+ y2={y}
+ stroke="var(--border-soft)"
+ strokeWidth="0.4"
+ vectorEffect="non-scaling-stroke"
+ />
+ ))}
+ {fill && data.map((s, i) => (
+ <path key={`a${i}`} d={`${line(s)} L ${w} ${h} L 0 ${h} Z`} fill={`url(#skw-${uid}-${i % colors.length})`} />
+ ))}
+ {data.map((s, i) => (
+ <path
+ key={`l${i}`}
+ d={line(s)}
+ fill="none"
+ stroke={colors[i % colors.length]}
+ strokeWidth="1.6"
+ vectorEffect="non-scaling-stroke"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ />
+ ))}
+ </svg>
+ );
+}
+
+// Phrase why a metric has no series on this resource, using real reasons.
+function unsupportedNote(metric, resource) {
+ const where = sourceOf(resource) === 'local' ? 'the local host' : 'agent servers';
+ return `${metric.label} is not collected for ${where}.`;
+}
+
+/* -------------------------------------------------------------------- stat */
+
+function WStat({ cfg, ctx }) {
+ const resource = resolveResource(cfg.resource, ctx);
+ const label = useResourceLabel(resource);
+ const agg = cfg.agg || 'last';
+ const { series, loading, error, supported, metric } = useMetricSeries(resource, cfg.metric, ctx.range, ctx.tick);
+
+ if (loading && !series.length) return <Loading />;
+ if (error) return <Failed error={error} subject="metrics" />;
+ if (!supported) return <Empty>{unsupportedNote(metric, resource)}</Empty>;
+ if (!series.length) return <Empty>No samples recorded in this range yet.</Empty>;
+
+ const value = aggregate(series, agg);
+ const delta = deltaPercent(series, agg);
+ const color = cfg.color || thresholdColor(value, cfg.thresholds) || metric.color;
+
+ return (
+ <div className="skw-stat">
+ <div className="skw-stat-v" style={{ color }}>{formatValue(value, metric.unit)}</div>
+ <div className="skw-stat-meta mono">
+ {delta === null ? (
+ <span className="faint">no trend yet</span>
+ ) : (
+ <span className={delta >= 0 ? 'up' : 'dn'}>
+ {delta >= 0 ? <ArrowUp size={11} /> : <ArrowDown size={11} />}
+ {Math.abs(delta).toFixed(1)}%
+ </span>
+ )}
+ <span className="faint">{agg} · {label}</span>
+ </div>
+ {cfg.spark !== false && (
+ <div className="skw-stat-spark">
+ <Sparkline data={series} color={color} width={220} height={40} />
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* -------------------------------------------------------------- timeseries */
+
+// A board should not be able to ask for an unreadable number of lines.
+const MAX_SERIES = 6;
+
+function WTimeseries({ cfg, ctx }) {
+ const serverVar = ctx.serverVar;
+ const entries = useMemo(() => {
+ const configured = Array.isArray(cfg.series) && cfg.series.length
+ ? cfg.series
+ : [{ resource: '$server', metric: 'cpu' }];
+ return configured.slice(0, MAX_SERIES).map((entry) => ({
+ resource: entry?.resource === '$server' ? (serverVar || 'local') : (entry?.resource || 'local'),
+ metric: entry?.metric,
+ color: entry?.color || '',
+ }));
+ }, [cfg.series, serverVar]);
+
+ const { rows, loading, error } = useMetricSeriesSet(entries, ctx.range, ctx.tick);
+ const withData = rows.filter((r) => r.supported && r.series.length > 0);
+
+ if (error) return <Failed error={error} subject="metrics" />;
+ if (loading && !withData.length) return <Loading />;
+ if (!withData.length) {
+ const blocked = rows.find((r) => !r.supported);
+ return (
+ <Empty>
+ {blocked
+ ? unsupportedNote(blocked.metric, blocked.resource)
+ : 'No samples recorded in this range yet.'}
+ </Empty>
+ );
+ }
+
+ const colors = withData.map((row) => row.color || row.metric.color);
+
+ return (
+ <div className="skw-ts">
+ <div className="skw-ts-chart">
+ <WidgetChart
+ series={withData.map((r) => r.series)}
+ colors={colors}
+ fill={cfg.fill !== false}
+ />
+ </div>
+ {cfg.legend !== false && (
+ <div className="skw-legend">
+ {withData.map((row, i) => {
+ const last = row.series[row.series.length - 1];
+ return (
+ <span className="skw-lg" key={`${row.resource}-${row.metric.id}-${i}`}>
+ <span className="sw" style={{ background: colors[i] }} />
+ {row.metric.label}
+ <b>{formatValue(last, row.metric.unit)}</b>
+ </span>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------- gauge */
+
+// Half-circle radial. No ds primitive covers this shape (ds/Gauge is a linear
+// meter), so the arc is hand-rolled.
+const GAUGE_RADIUS = 54;
+const GAUGE_ARC = Math.PI * GAUGE_RADIUS;
+const GAUGE_PATH = 'M16 72 A54 54 0 0 1 124 72';
+
+function WGauge({ cfg, ctx }) {
+ const resource = resolveResource(cfg.resource, ctx);
+ const label = useResourceLabel(resource);
+ const { series, loading, error, supported, metric } = useMetricSeries(resource, cfg.metric, ctx.range, ctx.tick);
+
+ if (loading && !series.length) return <Loading />;
+ if (error) return <Failed error={error} subject="metrics" />;
+ if (!supported) return <Empty>{unsupportedNote(metric, resource)}</Empty>;
+ if (!series.length) return <Empty>No samples recorded in this range yet.</Empty>;
+
+ const value = aggregate(series, cfg.agg || 'last');
+ // Percentage metrics have a real ceiling; rates do not, so scale to the
+ // observed peak rather than inventing a maximum.
+ const ceiling = metric.max || Math.max(...series) * 1.15 || 1;
+ const ratio = Math.max(0, Math.min(1, (value ?? 0) / ceiling));
+ const color = thresholdColor(value, cfg.thresholds) || metric.color;
+
+ return (
+ <div className="skw-gauge">
+ <svg viewBox="0 0 140 82" style={{ width: '100%', maxWidth: 200 }} role="img" aria-label={`${metric.label} ${formatValue(value, metric.unit)}`}>
+ <path d={GAUGE_PATH} fill="none" stroke="var(--surface-3)" strokeWidth="12" strokeLinecap="round" />
+ <path
+ d={GAUGE_PATH}
+ fill="none"
+ stroke={color}
+ strokeWidth="12"
+ strokeLinecap="round"
+ strokeDasharray={`${(GAUGE_ARC * ratio).toFixed(1)} ${GAUGE_ARC.toFixed(1)}`}
+ />
+ <text x="70" y="63" textAnchor="middle" fill={color} style={{ font: '600 24px var(--sans)' }}>
+ {formatValue(value, metric.unit)}
+ </text>
+ </svg>
+ <div className="skw-gauge-sub mono">
+ {label}{metric.max ? ` · max ${metric.max}${metric.unit}` : ''}
+ </div>
+ </div>
+ );
+}
+
+/* -------------------------------------------------------------------- topn */
+
+// The fleet heatmap exposes exactly these three per-server metrics.
+const HEATMAP_KEY = { cpu: 'cpu', ram: 'memory', disk: 'disk' };
+
+function WTopN({ cfg, ctx }) {
+ const { servers, loading, error } = useFleetHeatmap(ctx.tick);
+ const metric = getMetric(cfg.metric);
+ const key = HEATMAP_KEY[metric.id];
+
+ if (loading && !servers.length) return <Loading />;
+ if (error) return <Failed error={error} subject="fleet metrics" />;
+ if (!key) {
+ return <Empty>{metric.label} cannot be ranked across servers — pick CPU, memory or disk.</Empty>;
+ }
+
+ const rows = servers
+ .map((s) => ({ id: s.id, label: s.name, value: s[key] }))
+ .filter((r) => typeof r.value === 'number' && Number.isFinite(r.value))
+ .sort((a, b) => b.value - a.value)
+ .slice(0, Math.max(1, Number(cfg.limit) || 5));
+
+ if (!rows.length) return <Empty>No fleet servers are reporting metrics yet.</Empty>;
+
+ const peak = Math.max(...rows.map((r) => r.value), 1);
+
+ return (
+ <div className="skw-topn">
+ {rows.map((row) => (
+ <div className="skw-bar-row" key={row.id}>
+ <span className="skw-bar-l">{row.label}</span>
+ <Gauge
+ className="skw-bar-t"
+ value={(row.value / peak) * 100}
+ color={metric.color}
+ />
+ <span className="skw-bar-v mono">{formatValue(row.value, metric.unit)}</span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------- table */
+
+const TABLE_DEFS = {
+ services: {
+ empty: 'No applications yet.',
+ cols: [['Name', 'name'], ['Type', 'app_type'], ['Status', 'status'], ['Server', 'server_name']],
+ href: (row) => `/services/${row.id}`,
+ },
+ servers: {
+ empty: 'No servers connected.',
+ cols: [['Name', 'name'], ['Status', 'status'], ['Group', 'group_name'], ['OS', 'os_type']],
+ href: (row) => (row.is_local ? '/servers' : `/servers/${row.id}`),
+ },
+ containers: {
+ empty: 'No containers on this host.',
+ cols: [['Name', 'name'], ['Image', 'image'], ['Status', 'state'], ['Ports', 'ports']],
+ href: () => '/docker',
+ },
+ deploys: {
+ empty: 'No deployments recorded.',
+ cols: [['App', 'app_name'], ['Trigger', 'trigger'], ['Status', 'status'], ['When', 'created_at']],
+ href: (row) => `/deployments/${row.id}`,
+ },
+};
+
+function WTable({ cfg, ctx }) {
+ const limit = Math.max(1, Number(cfg.limit) || 6);
+ const { rows, loading, error, source } = useResourceRows(cfg.source, limit, ctx.tick);
+ const def = TABLE_DEFS[source] || TABLE_DEFS.services;
+
+ if (loading && !rows.length) return <Loading />;
+ if (error) return <Failed error={error} subject={source} />;
+ if (!rows.length) return <Empty>{def.empty}</Empty>;
+
+ return (
+ <div className="skw-table-wrap">
+ <table className="skw-table">
+ <thead>
+ <tr>{def.cols.map(([label]) => <th key={label}>{label}</th>)}</tr>
+ </thead>
+ <tbody>
+ {rows.map((row, i) => (
+ <tr key={row.id ?? i} onClick={() => ctx.navigate?.(def.href(row))}>
+ {def.cols.map(([label, key]) => {
+ const value = row[key];
+ if (key === 'status' || key === 'state') {
+ return (
+ <td key={label}>
+ <Pill kind={pillKind(value)}>{value || 'unknown'}</Pill>
+ </td>
+ );
+ }
+ const isName = key === 'name' || key === 'app_name';
+ const text = key === 'created_at' ? relTime(value) : value;
+ return (
+ <td key={label} className={isName ? 'nm' : 'mono'}>
+ {text === null || text === undefined || text === '' ? '—' : String(text)}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+/* -------------------------------------------------------------------- logs */
+
+function WLogs({ cfg, ctx }) {
+ const bodyRef = useRef(null);
+ const { lines, label, loading, error } = useLogTail(cfg, ctx.tick);
+
+ const shown = cfg.level && cfg.level !== 'all'
+ ? lines.filter((l) => l.lvl === cfg.level)
+ : lines;
+
+ useEffect(() => {
+ if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
+ }, [shown.length]);
+
+ if (loading && !lines.length) return <Loading />;
+ if (error) return <Failed error={error} subject="logs" />;
+ if (!lines.length) return <Empty>No log lines available.</Empty>;
+
+ const counts = lines.reduce((acc, l) => ({ ...acc, [l.lvl]: (acc[l.lvl] || 0) + 1 }), {});
+
+ return (
+ <div className="skw-logs">
+ <div className="skw-logs-bar mono">
+ <span>{label || 'log'}</span>
+ <span className="faint">{lines.length} lines</span>
+ {counts.err ? <span className="lv-err">{counts.err} errors</span> : null}
+ {counts.warn ? <span className="lv-warn">{counts.warn} warnings</span> : null}
+ </div>
+ <div className="skw-logs-body" ref={bodyRef}>
+ {shown.length === 0 ? (
+ <Empty>No lines at this level.</Empty>
+ ) : shown.map((l, i) => (
+ <div className={`skw-log-line lv-${l.lvl}`} key={i}>
+ {l.t ? <span className="t">{l.t}</span> : null}
+ {l.txt}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/* ----------------------------------------------------------------- deploys */
+
+const DEPLOY_COLOR = {
+ succeeded: 'var(--green)',
+ completed: 'var(--green)',
+ failed: 'var(--red)',
+ running: 'var(--amber)',
+};
+
+// A job reports total_steps + current_step; derive each dot's state from those
+// rather than inventing per-step records the API does not return.
+function stepState(index, job) {
+ if (index < job.current_step) return 'done';
+ if (index > job.current_step) return '';
+ if (job.status === 'failed') return 'failed';
+ if (job.status === 'running') return 'running';
+ return job.status === 'succeeded' || job.status === 'completed' ? 'done' : '';
+}
+
+function WDeploys({ cfg, ctx }) {
+ const { jobs, loading, error } = useDeployJobs(cfg.limit, ctx.tick);
+
+ if (loading && !jobs.length) return <Loading />;
+ if (error) return <Failed error={error} subject="deployments" />;
+ if (!jobs.length) return <Empty>No deployments yet.</Empty>;
+
+ return (
+ <div className="skw-list">
+ {jobs.map((job) => (
+ <div
+ className="skw-dep"
+ key={job.id}
+ onClick={() => ctx.navigate?.(`/deployments/${job.id}`)}
+ >
+ <div className="skw-dep-top">
+ <span className="skw-dep-n">{job.app_name || job.kind || 'deployment'}</span>
+ <span className="skw-dep-s mono" style={{ color: DEPLOY_COLOR[job.status] || 'var(--text-faint)' }}>
+ {job.status}
+ </span>
+ </div>
+ {job.total_steps > 0 && (
+ <div className="skw-dep-steps">
+ {Array.from({ length: job.total_steps }, (_, i) => (
+ <i key={i} className={`st ${stepState(i, job)}`} />
+ ))}
+ </div>
+ )}
+ <div className="skw-dep-meta mono">
+ {job.trigger || 'manual'} · {job.target_server_name || 'local'} · {relTime(job.created_at) || '—'}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------ alerts */
+
+const SEVERITY_COLOR = { critical: 'var(--red)', warning: 'var(--amber)' };
+
+function WAlerts({ cfg, ctx }) {
+ const { alerts, loading, error } = useOpenAlerts(cfg.limit, ctx.tick);
+
+ if (loading && !alerts.length) return <Loading />;
+ if (error) return <Failed error={error} subject="alerts" />;
+
+ const shown = cfg.severity && cfg.severity !== 'all'
+ ? alerts.filter((a) => a.severity === cfg.severity)
+ : alerts;
+
+ if (!shown.length) return <Empty>No alerts firing.</Empty>;
+
+ return (
+ <div className="skw-list">
+ {shown.map((alert) => {
+ const color = SEVERITY_COLOR[alert.severity] || 'var(--cyan)';
+ return (
+ <div className="skw-alert" key={alert.id} onClick={() => ctx.navigate?.('/monitoring')}>
+ <span className="skw-al-sev" style={{ background: color, boxShadow: `0 0 7px ${color}` }} />
+ <div className="skw-al-body">
+ <div className="skw-al-t">{alert.title}</div>
+ <div className="skw-al-m mono">
+ {alert.target}{alert.time ? ` · ${relTime(alert.time)}` : ''}
+ </div>
+ </div>
+ <Pill kind={alert.state === 'firing' ? 'red' : 'amber'}>{alert.state}</Pill>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------ status */
+
+const STATE_COLOR = { up: 'var(--green)', down: 'var(--red)', unknown: 'var(--amber)' };
+
+function WStatus({ cfg, ctx }) {
+ const { cells, loading, error, source } = useStatusCells(cfg.source, cfg.limit, ctx.tick);
+
+ if (loading && !cells.length) return <Loading />;
+ if (error) return <Failed error={error} subject={source} />;
+ if (!cells.length) return <Empty>Nothing to monitor yet.</Empty>;
+
+ const target = source === 'services' ? '/services' : '/servers';
+
+ return (
+ <div className="skw-status">
+ {cells.map((cell) => {
+ const color = STATE_COLOR[cell.state] || 'var(--amber)';
+ return (
+ <div
+ className="skw-st-cell"
+ key={cell.id}
+ onClick={() => ctx.navigate?.(target)}
+ title={`${cell.name} · ${cell.state}`}
+ >
+ <span className="skw-st-dot" style={{ background: color, boxShadow: `0 0 8px ${color}` }} />
+ <div className="skw-st-n">{cell.name}</div>
+ <div className="skw-st-m mono">{cell.meta || cell.state}</div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+/* -------------------------------------------------------------------- feed */
+
+// Turn an audit action ('app.deploy', 'user.login') into something readable
+// without pretending we know more than the row carries.
+function describeLog(entry) {
+ const action = String(entry.action || 'change').replace(/[._]/g, ' ');
+ const who = entry.username || 'system';
+ const what = entry.target_type
+ ? `${entry.target_type}${entry.target_id ? ` #${entry.target_id}` : ''}`
+ : '';
+ return what ? `${who} · ${action} · ${what}` : `${who} · ${action}`;
+}
+
+function WFeed({ cfg, ctx }) {
+ const isAdmin = Boolean(ctx.isAdmin);
+ const { items, loading, error } = useActivity(cfg.limit, isAdmin, ctx.tick);
+
+ // The audit trail lives behind /admin/activity/feed. Say so instead of
+ // firing a request that can only come back 403.
+ if (!isAdmin) return <Empty>Requires admin.</Empty>;
+ if (loading && !items.length) return <Loading />;
+ if (error) return <Failed error={error} subject="the activity feed" />;
+ if (!items.length) return <Empty>No recorded activity yet.</Empty>;
+
+ return (
+ <div className="skw-list">
+ {items.map((entry) => (
+ <div className="skw-feed-item" key={entry.id} onClick={() => ctx.navigate?.('/security')}>
+ <div className="skw-feed-body">
+ <div className="skw-feed-txt">{describeLog(entry)}</div>
+ <div className="skw-feed-time mono">{relTime(entry.created_at)}</div>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/* ----------------------------------------------------------------- actions */
+
+// Every destination is a real route registered in App.jsx.
+const ACTIONS = {
+ servers: ['Manage servers', Server, '/servers'],
+ services: ['Services', Boxes, '/services'],
+ docker: ['Docker containers', Container, '/docker'],
+ terminal: ['Open terminal', Terminal, '/terminal'],
+ deploys: ['Deploy activity', Rocket, '/deployments'],
+ databases: ['Databases', Database, '/databases'],
+ backups: ['Backups', Archive, '/backups'],
+ monitoring: ['Monitoring', Activity, '/monitoring'],
+ domains: ['Domains', Globe, '/domains'],
+ files: ['File manager', FolderOpen, '/files'],
+ security: ['Security', ShieldCheck, '/security'],
+ jobs: ['Jobs', ListChecks, '/jobs'],
+};
+
+export const QUICK_ACTION_KEYS = Object.keys(ACTIONS);
+
+// [key, label] pairs for the inspector's shortcut picker. Derived from ACTIONS
+// so the list of shortcuts a user can *choose* can never drift from the list
+// this widget can actually *render* — they did drift once already.
+export const QUICK_ACTION_OPTIONS = Object.entries(ACTIONS).map(([key, [label]]) => [key, label]);
+
+function WActions({ cfg, ctx }) {
+ const items = (Array.isArray(cfg.items) ? cfg.items : []).filter((key) => ACTIONS[key]);
+ if (!items.length) return <Empty>No actions selected.</Empty>;
+
+ return (
+ <div className="skw-actions">
+ {items.map((key) => {
+ const [label, Icon, href] = ACTIONS[key];
+ return (
+ <button type="button" className="skw-qa-row" key={key} onClick={() => ctx.navigate?.(href)}>
+ <span className="skw-qa-n">{label}</span>
+ <span className="skw-qa-ic"><Icon size={15} /></span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------- specs */
+
+function WSpecs({ cfg, ctx }) {
+ const resource = resolveResource(cfg.resource, ctx);
+ const { rows, loading, error } = useSystemSpecs(resource, ctx.tick);
+
+ if (loading && !rows.length) return <Loading />;
+ if (error) return <Failed error={error} subject="host details" />;
+ if (!rows.length) return <Empty>This host reported no details.</Empty>;
+
+ return (
+ <div className="skw-kv">
+ {rows.map(([key, value]) => (
+ <div className="skw-kv-row" key={key}>
+ <span className="k">{key}</span>
+ <span className="v">{value}</span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/* -------------------------------------------------------------------- note */
+
+// Minimal inline markdown rendered as React nodes. Deliberately NOT an HTML
+// string: no dangerouslySetInnerHTML means no sink to sanitize.
+function renderInline(text, keyPrefix) {
+ const nodes = [];
+ const pattern = /\*\*([^*]+)\*\*|`([^`]+)`/g;
+ let cursor = 0;
+ let match = pattern.exec(text);
+ let n = 0;
+
+ while (match) {
+ if (match.index > cursor) nodes.push(text.slice(cursor, match.index));
+ if (match[1] !== undefined) {
+ nodes.push(<b key={`${keyPrefix}-b${n}`}>{match[1]}</b>);
+ } else {
+ nodes.push(<code className="mono" key={`${keyPrefix}-c${n}`}>{match[2]}</code>);
+ }
+ cursor = match.index + match[0].length;
+ n += 1;
+ match = pattern.exec(text);
+ }
+ if (cursor < text.length) nodes.push(text.slice(cursor));
+ return nodes;
+}
+
+function WNote({ cfg }) {
+ const text = typeof cfg.text === 'string' ? cfg.text : '';
+ if (!text.trim()) return <Empty>Empty note — add text in the widget settings.</Empty>;
+
+ return (
+ <div className="skw-note">
+ {text.split('\n').map((line, i) => (
+ <p key={i}>{line ? renderInline(line, `l${i}`) : ' '}</p>
+ ))}
+ </div>
+ );
+}
+
+/* --------------------------------------------------------------- dispatch */
+
+const CORE_RENDERERS = {
+ stat: WStat,
+ timeseries: WTimeseries,
+ gauge: WGauge,
+ topn: WTopN,
+ table: WTable,
+ logs: WLogs,
+ deploys: WDeploys,
+ alerts: WAlerts,
+ status: WStatus,
+ feed: WFeed,
+ actions: WActions,
+ specs: WSpecs,
+ note: WNote,
+};
+
+/**
+ * Last line of defence. A renderer that throws (a plugin widget, or a core one
+ * fed a malformed saved cfg) degrades to a muted note instead of unmounting
+ * the whole grid.
+ */
+class WidgetBoundary extends Component {
+ constructor(props) {
+ super(props);
+ this.state = { failed: false };
+ }
+
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+
+ componentDidCatch(error) {
+ console.error(`Dashboard widget "${this.props.widgetType}" crashed:`, error);
+ }
+
+ render() {
+ if (this.state.failed) {
+ return <div className="skw-empty skw-empty--error">This widget failed to render.</div>;
+ }
+ return this.props.children;
+ }
+}
+
+/**
+ * Render one widget's body.
+ *
+ * `ctx` carries { range, tick, serverVar, isAdmin, navigate } and may also
+ * carry `types` (the merged registry from useWidgetTypes) — when present,
+ * plugin-contributed widget types render through their own component.
+ * An unknown type renders a `.skw-empty` notice and never throws.
+ */
+export function WidgetBody({ widget, ctx }) {
+ const safeCtx = ctx || {};
+ const type = widget?.type;
+
+ const Core = type ? CORE_RENDERERS[type] : null;
+ const contributed = !Core && type
+ ? getWidgetType(safeCtx.types, type)?.component || null
+ : null;
+ const Renderer = Core || contributed;
+
+ if (!Renderer) {
+ return <div className="skw-empty">Unknown widget type “{String(type ?? '')}”.</div>;
+ }
+
+ return (
+ <WidgetBoundary key={`${widget?.i ?? ''}:${type}`} widgetType={type}>
+ <Renderer cfg={widget?.cfg || {}} ctx={safeCtx} widget={widget} />
+ </WidgetBoundary>
+ );
+}
+
+export default WidgetBody;
diff --git a/frontend/src/components/dashboard/widgets/useWidgetData.js b/frontend/src/components/dashboard/widgets/useWidgetData.js
new file mode 100644
index 00000000..19d1dadb
--- /dev/null
+++ b/frontend/src/components/dashboard/widgets/useWidgetData.js
@@ -0,0 +1,483 @@
+/**
+ * Data hooks shared by the dashboard widget renderers (plan 62).
+ *
+ * Renderers stay presentational: everything that talks to the API lives here.
+ *
+ * De-duplication: a board can easily hold ten stat widgets pointed at the same
+ * server and range. Each one asks for the SAME history payload, so requests are
+ * collapsed through a tiny module-level promise cache keyed by
+ * `<kind>|<resource>|<metric>|<range>|<tick>`. Ten widgets on one tick produce
+ * one HTTP request; the next tick makes a new key and refetches.
+ */
+import { useEffect, useMemo, useRef, useState } from 'react';
+import api from '@/services/api';
+import {
+ RANGE_IDS,
+ getMetric,
+ metricSupports,
+ readAt,
+ seriesFrom,
+ sourceOf,
+ stampsFrom,
+} from './metrics';
+
+// Requests for the same key inside this window share one in-flight promise.
+const CACHE_TTL_MS = 4000;
+const CACHE_MAX_ENTRIES = 96;
+
+const cache = new Map();
+
+function prune(now) {
+ if (cache.size <= CACHE_MAX_ENTRIES) return;
+ for (const [key, entry] of cache) {
+ if (now - entry.at > CACHE_TTL_MS) cache.delete(key);
+ }
+ // Still oversized (a burst of distinct keys) — drop oldest-first.
+ while (cache.size > CACHE_MAX_ENTRIES) {
+ const oldest = cache.keys().next();
+ if (oldest.done) break;
+ cache.delete(oldest.value);
+ }
+}
+
+/** Share one in-flight promise per key. Exported for tests and for the
+ * fullscreen view, which mounts a second copy of the same widget. */
+export function fetchShared(key, loader) {
+ const now = Date.now();
+ const hit = cache.get(key);
+ if (hit && now - hit.at < CACHE_TTL_MS) return hit.promise;
+
+ const promise = Promise.resolve().then(loader);
+ cache.set(key, { at: now, promise });
+ // A failure must not be replayed to a later mount, and must not surface as
+ // an unhandled rejection when no consumer is attached yet.
+ promise.catch(() => {
+ const current = cache.get(key);
+ if (current && current.promise === promise) cache.delete(key);
+ });
+ prune(now);
+ return promise;
+}
+
+/**
+ * Normalise a thrown API error into what a widget needs to render.
+ * ApiClient attaches `status`, so a permission problem (403 from
+ * @admin_required / @viewer_required routes) can be shown as a calm
+ * "not permitted" note rather than a red error tile.
+ */
+function toWidgetError(err) {
+ const status = err?.status ?? null;
+ return {
+ message: err?.message || (err ? String(err) : 'Request failed'),
+ status,
+ forbidden: status === 403,
+ };
+}
+
+/**
+ * Generic "load this key once, share it, report loading/error" hook.
+ * `loader` is read through a ref so an inline arrow does not re-trigger the
+ * effect — the key is the identity.
+ */
+function useShared(key, loader, enabled = true) {
+ const loaderRef = useRef(loader);
+ loaderRef.current = loader;
+
+ const [state, setState] = useState({ data: null, loading: Boolean(enabled), error: null });
+
+ useEffect(() => {
+ if (!enabled) {
+ setState({ data: null, loading: false, error: null });
+ return undefined;
+ }
+ let cancelled = false;
+ setState((prev) => ({ data: prev.data, loading: true, error: null }));
+
+ fetchShared(key, () => loaderRef.current())
+ .then((data) => {
+ if (!cancelled) setState({ data, loading: false, error: null });
+ })
+ .catch((err) => {
+ if (!cancelled) setState({ data: null, loading: false, error: toWidgetError(err) });
+ });
+
+ return () => { cancelled = true; };
+ }, [key, enabled]);
+
+ return state;
+}
+
+function safeRange(range) {
+ return RANGE_IDS.includes(range) ? range : '1h';
+}
+
+/* ------------------------------------------------------------------ metrics */
+
+/**
+ * Raw history payload for one resource + range.
+ * local -> GET /api/v1/metrics/history?period=…
+ * agent server -> GET /api/v1/servers/<id>/metrics/history?period=…
+ * Both answer `{ period, points, data: [...], summary }`.
+ */
+export function useMetricHistory(resource, range, tick) {
+ const target = resource || 'local';
+ const period = safeRange(range);
+ const key = `history|${target}|${period}|${tick ?? 0}`;
+
+ return useShared(key, () => (
+ sourceOf(target) === 'local'
+ ? api.getMetricsHistory(period)
+ : api.getServerMetricsHistory(target, period)
+ ));
+}
+
+/**
+ * One metric's series for one resource.
+ * `supported` is false when the metric has no backing column on that source
+ * (e.g. load average on an agent server, network rate on the local host) —
+ * renderers use it to say so instead of drawing a flat zero line.
+ */
+export function useMetricSeries(resource, metric, range, tick) {
+ const metricId = typeof metric === 'string' ? metric : metric?.id;
+ const { data, loading, error } = useMetricHistory(resource, range, tick);
+ const meta = getMetric(metricId);
+ const supported = metricSupports(meta, sourceOf(resource || 'local'));
+
+ const series = useMemo(
+ () => (supported ? seriesFrom(data, metricId) : []),
+ [data, metricId, supported],
+ );
+ const stamps = useMemo(
+ () => (supported ? stampsFrom(data, metricId) : []),
+ [data, metricId, supported],
+ );
+
+ return { series, stamps, loading, error, supported, metric: meta };
+}
+
+/**
+ * Several (resource, metric) pairs at once — what the time-series widget needs.
+ *
+ * One effect, not one per line: the histories are fetched through the SAME
+ * `history|…` cache keys `useMetricHistory` uses, so a chart and the stat tiles
+ * beside it pointed at one server share a single request.
+ *
+ * `entries` is [{ resource, metric }] with `$server` already resolved.
+ */
+export function useMetricSeriesSet(entries, range, tick) {
+ const period = safeRange(range);
+ const list = Array.isArray(entries) ? entries : [];
+ const signature = list.map((e) => `${e?.resource || 'local'}:${e?.metric || ''}`).join(',');
+ const key = `multi|${signature}|${period}|${tick ?? 0}`;
+
+ const listRef = useRef(list);
+ listRef.current = list;
+
+ const { data, loading, error } = useShared(key, async () => {
+ const current = listRef.current || [];
+ const resources = [...new Set(current.map((e) => e?.resource || 'local'))];
+
+ const payloads = new Map();
+ await Promise.all(resources.map(async (resource) => {
+ const payload = await fetchShared(
+ `history|${resource}|${period}|${tick ?? 0}`,
+ () => (sourceOf(resource) === 'local'
+ ? api.getMetricsHistory(period)
+ : api.getServerMetricsHistory(resource, period)),
+ );
+ payloads.set(resource, payload);
+ }));
+
+ return current.map((entry) => {
+ const resource = entry?.resource || 'local';
+ const meta = getMetric(entry?.metric);
+ const supported = metricSupports(meta, sourceOf(resource));
+ return {
+ resource,
+ metric: meta,
+ supported,
+ color: entry?.color || '',
+ series: supported ? seriesFrom(payloads.get(resource), meta.id) : [],
+ };
+ });
+ });
+
+ return {
+ rows: useMemo(() => (Array.isArray(data) ? data : []), [data]),
+ loading,
+ error,
+ };
+}
+
+/* -------------------------------------------------------------- inventories */
+
+const ROW_LOADERS = {
+ services: (limit) => api.getApps().then((d) => (Array.isArray(d?.apps) ? d.apps : [])).then((r) => r.slice(0, limit)),
+ servers: () => api.getAvailableServers().then((d) => (Array.isArray(d) ? d : [])),
+ containers: (limit) => api.getContainers(true).then((d) => (Array.isArray(d?.containers) ? d.containers : [])).then((r) => r.slice(0, limit)),
+ deploys: (limit) => api.getDeploymentJobs({ limit }).then((d) => (Array.isArray(d?.jobs) ? d.jobs : [])),
+};
+
+/** Rows for the resource table. `source` is services | servers | containers | deploys. */
+export function useResourceRows(source, limit = 6, tick) {
+ const kind = ROW_LOADERS[source] ? source : 'services';
+ const size = Math.max(1, Math.min(Number(limit) || 6, 50));
+ const key = `rows|${kind}|${size}|${tick ?? 0}`;
+
+ const { data, loading, error } = useShared(key, () => ROW_LOADERS[kind](size));
+ const rows = useMemo(() => (Array.isArray(data) ? data.slice(0, size) : []), [data, size]);
+ return { rows, loading, error, source: kind };
+}
+
+/** The servers the panel can address, used for display names and status. */
+export function useServerDirectory() {
+ // Deliberately tick-free: names change far more slowly than metrics, and
+ // every stat/gauge/legend wants this list.
+ const { data, loading, error } = useShared('servers|available', () => (
+ api.getAvailableServers().then((d) => (Array.isArray(d) ? d : []))
+ ));
+ const servers = useMemo(() => (Array.isArray(data) ? data : []), [data]);
+ const byId = useMemo(() => {
+ const map = new Map();
+ for (const s of servers) if (s && s.id) map.set(s.id, s);
+ return map;
+ }, [servers]);
+ return { servers, byId, loading, error };
+}
+
+/** Display name for a resource id ('local', a server id, or the '$server' var). */
+export function useResourceLabel(resource) {
+ const { byId } = useServerDirectory();
+ if (!resource || resource === 'local') return 'Local (this server)';
+ if (resource === '$server') return 'dashboard variable';
+ return byId.get(resource)?.name || resource;
+}
+
+/* -------------------------------------------------------------- fleet views */
+
+/** Latest metric snapshot per fleet server — the ranking + status source. */
+export function useFleetHeatmap(tick) {
+ const { data, loading, error } = useShared(`fleet|heatmap|${tick ?? 0}`, () => (
+ api.getFleetHeatmap().then((d) => (Array.isArray(d) ? d : []))
+ ));
+ return { servers: useMemo(() => (Array.isArray(data) ? data : []), [data]), loading, error };
+}
+
+const SEVERITY_RANK = { critical: 0, warning: 1, info: 2 };
+
+function normalizeFleetAlert(alert) {
+ const metric = alert.metric || 'metric';
+ const value = Number.isFinite(alert.value) ? Math.round(alert.value * 10) / 10 : null;
+ const threshold = Number.isFinite(alert.threshold) ? alert.threshold : null;
+ return {
+ id: `fleet:${alert.id}`,
+ title: value !== null && threshold !== null
+ ? `${metric} at ${value} (threshold ${threshold})`
+ : `${metric} threshold exceeded`,
+ target: alert.server_name || alert.server_id || 'unknown server',
+ severity: alert.severity === 'critical' ? 'critical' : 'warning',
+ state: alert.status === 'acknowledged' ? 'acknowledged' : 'firing',
+ time: alert.created_at || null,
+ };
+}
+
+function normalizeLocalAlert(alert, index) {
+ return {
+ id: `local:${alert.type || index}`,
+ title: alert.message || `${alert.type || 'threshold'} exceeded`,
+ target: 'Local (this server)',
+ severity: alert.severity === 'critical' ? 'critical' : 'warning',
+ state: 'firing',
+ time: null,
+ };
+}
+
+/**
+ * Open alerts, merged from the two real sources:
+ * - GET /api/v1/fleet-monitor/alerts?status=active (MetricAlert rows)
+ * - GET /api/v1/monitoring/alerts/check (live host thresholds)
+ * One source being unavailable is tolerated; both failing is a real error.
+ */
+export function useOpenAlerts(limit = 8, tick) {
+ const size = Math.max(1, Math.min(Number(limit) || 8, 50));
+ const key = `alerts|open|${size}|${tick ?? 0}`;
+
+ const { data, loading, error } = useShared(key, async () => {
+ const [fleet, local] = await Promise.all([
+ api.getFleetAlerts({ status: 'active', limit: size })
+ .then((r) => (Array.isArray(r) ? r : []))
+ .catch(() => null),
+ api.checkAlerts()
+ .then((r) => (Array.isArray(r?.alerts) ? r.alerts : []))
+ .catch(() => null),
+ ]);
+ if (fleet === null && local === null) throw new Error('Alert sources unavailable');
+ return [
+ ...(fleet || []).map(normalizeFleetAlert),
+ ...(local || []).map(normalizeLocalAlert),
+ ].sort((a, b) => (SEVERITY_RANK[a.severity] ?? 9) - (SEVERITY_RANK[b.severity] ?? 9));
+ });
+
+ return { alerts: useMemo(() => (Array.isArray(data) ? data : []), [data]), loading, error };
+}
+
+/** Up/down cells for the status grid. `source` is servers | services. */
+export function useStatusCells(source, limit = 12, tick) {
+ const kind = source === 'services' ? 'services' : 'servers';
+ const size = Math.max(1, Math.min(Number(limit) || 12, 60));
+ const key = `status|${kind}|${size}|${tick ?? 0}`;
+
+ const { data, loading, error } = useShared(key, async () => {
+ if (kind === 'services') {
+ const apps = await api.getApps().then((d) => (Array.isArray(d?.apps) ? d.apps : []));
+ return apps.map((app) => ({
+ id: `app:${app.id}`,
+ name: app.name,
+ state: app.status === 'running' ? 'up' : app.status === 'stopped' ? 'down' : 'unknown',
+ meta: app.app_type || '',
+ }));
+ }
+ const servers = await api.getAvailableServers().then((d) => (Array.isArray(d) ? d : []));
+ return servers.map((server) => ({
+ id: server.id,
+ name: server.name,
+ state: server.status === 'online' ? 'up' : server.status === 'connecting' ? 'unknown' : 'down',
+ meta: server.group_name || (server.is_local ? 'local' : server.os_type || ''),
+ }));
+ });
+
+ const cells = useMemo(() => (Array.isArray(data) ? data.slice(0, size) : []), [data, size]);
+ return { cells, loading, error, source: kind };
+}
+
+/* -------------------------------------------------------------- operations */
+
+/** Recent deployment jobs (DeploymentJob.to_dict()). */
+export function useDeployJobs(limit = 5, tick) {
+ const size = Math.max(1, Math.min(Number(limit) || 5, 25));
+ const key = `deploys|${size}|${tick ?? 0}`;
+ const { data, loading, error } = useShared(key, () => (
+ api.getDeploymentJobs({ limit: size }).then((d) => (Array.isArray(d?.jobs) ? d.jobs : []))
+ ));
+ return { jobs: useMemo(() => (Array.isArray(data) ? data : []), [data]), loading, error };
+}
+
+/** Audit trail. Admin-only endpoint — pass `enabled: false` for everyone else. */
+export function useActivity(limit = 6, enabled = true, tick) {
+ const size = Math.max(1, Math.min(Number(limit) || 6, 50));
+ const key = `activity|${size}|${tick ?? 0}`;
+ const { data, loading, error } = useShared(key, () => (
+ api.getActivityFeed({ per_page: size }).then((d) => (Array.isArray(d?.logs) ? d.logs : []))
+ ), enabled);
+ return { items: useMemo(() => (Array.isArray(data) ? data : []), [data]), loading, error };
+}
+
+const LEVEL_ERROR = /\b(error|errors|err|fatal|critical|panic|exception|traceback|failed|failure)\b/i;
+const LEVEL_WARN = /\b(warn|warning|deprecated|retry|retrying|slow)\b/i;
+// Docker's `logs -t` prefixes an RFC3339 stamp; syslog-style files start HH:MM:SS.
+const LEADING_STAMP = /^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?)\s+/;
+
+function classify(text) {
+ if (LEVEL_ERROR.test(text)) return 'err';
+ if (LEVEL_WARN.test(text)) return 'warn';
+ return 'out';
+}
+
+function toLogLine(raw) {
+ const text = String(raw ?? '');
+ const match = text.match(LEADING_STAMP);
+ let time = null;
+ let body = text;
+ if (match) {
+ const parsed = new Date(match[1]);
+ if (!Number.isNaN(parsed.getTime())) time = parsed.toISOString().slice(11, 19);
+ body = text.slice(match[0].length);
+ }
+ return { lvl: classify(body), txt: body, t: time };
+}
+
+/**
+ * Tail of a log source.
+ * cfg.source === 'container' + cfg.containerId -> GET /docker/containers/<id>/logs
+ * otherwise -> GET /logs/read?path=…
+ * With no path configured the first entry from GET /logs is used, so the
+ * widget shows something real out of the box. Both endpoints are admin-only.
+ */
+export function useLogTail(cfg = {}, tick) {
+ const mode = cfg.source === 'container' && cfg.containerId ? 'container' : 'file';
+ const lineCount = Math.max(10, Math.min(Number(cfg.lines) || 60, 500));
+ const target = mode === 'container' ? cfg.containerId : (cfg.path || '');
+ const key = `logs|${mode}|${target}|${lineCount}|${tick ?? 0}`;
+
+ const { data, loading, error } = useShared(key, async () => {
+ if (mode === 'container') {
+ const result = await api.getContainerLogs(target, lineCount);
+ if (result && result.success === false) throw new Error(result.error || 'Could not read container logs');
+ const text = typeof result?.logs === 'string' ? result.logs : '';
+ return { label: target, lines: text.split('\n') };
+ }
+
+ let path = target;
+ if (!path) {
+ const files = await api.getLogFiles().then((d) => (Array.isArray(d?.logs) ? d.logs : []));
+ if (!files.length) return { label: '', lines: [] };
+ path = files[0].path;
+ }
+ const result = await api.readLog(path, lineCount);
+ if (result && result.success === false) throw new Error(result.error || 'Could not read log file');
+ return { label: path, lines: Array.isArray(result?.lines) ? result.lines : [] };
+ });
+
+ const lines = useMemo(() => (
+ (data?.lines || [])
+ .filter((l) => String(l ?? '').trim().length > 0)
+ .map(toLogLine)
+ ), [data]);
+
+ return { lines, label: data?.label || '', loading, error };
+}
+
+/* ------------------------------------------------------------------- specs */
+
+const SPEC_FIELDS = [
+ ['Hostname', ['hostname', 'host', 'name']],
+ ['Processor', ['cpu.model', 'processor', 'cpu_model']],
+ ['Architecture', ['architecture', 'cpu.architecture', 'arch']],
+ ['Platform', ['platform', 'os', 'os_name', 'distro']],
+ ['Kernel', ['kernel', 'platform_release', 'kernel_version']],
+ ['IP address', ['ip_address', 'ip']],
+ ['Uptime', ['uptime_human', 'uptime']],
+];
+
+/**
+ * Key/value host facts.
+ * local -> GET /api/v1/system/info (SystemService.get_system_info)
+ * agent server -> GET /api/v1/servers/<id>/system/info
+ * The agent payload is not shaped by a model in this repo, so each row tries a
+ * few candidate keys and drops out when none of them resolve.
+ */
+export function useSystemSpecs(resource, tick) {
+ const target = resource || 'local';
+ const key = `specs|${target}|${tick ?? 0}`;
+
+ const { data, loading, error } = useShared(key, () => (
+ sourceOf(target) === 'local' ? api.getSystemInfo() : api.getRemoteSystemInfo(target)
+ ));
+
+ const rows = useMemo(() => {
+ if (!data || typeof data !== 'object') return [];
+ const out = [];
+ for (const [label, paths] of SPEC_FIELDS) {
+ for (const path of paths) {
+ const value = readAt(data, path);
+ if (value !== undefined && value !== null && value !== '') {
+ out.push([label, String(value)]);
+ break;
+ }
+ }
+ }
+ return out;
+ }, [data]);
+
+ return { rows, loading, error };
+}
diff --git a/frontend/src/components/settings/AppearanceTab.jsx b/frontend/src/components/settings/AppearanceTab.jsx
index fd1ae12e..f78fc47b 100644
--- a/frontend/src/components/settings/AppearanceTab.jsx
+++ b/frontend/src/components/settings/AppearanceTab.jsx
@@ -2,8 +2,8 @@ import { useRef, useState } from 'react';
import { useTheme } from '../../contexts/ThemeContext';
import { useAuth } from '../../contexts/AuthContext';
import { useToast } from '../../contexts/ToastContext';
-import useDashboardLayout from '../../hooks/useDashboardLayout';
-import { ChevronDown, ChevronUp, RotateCcw, Upload, Store, Sparkles } from 'lucide-react';
+import { Link } from 'react-router-dom';
+import { RotateCcw, Upload, Store, Sparkles, LayoutGrid } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import useSettingFocus from '../../hooks/useSettingFocus';
@@ -30,7 +30,6 @@ const AppearanceTab = () => {
} = useTheme();
const { user } = useAuth();
const toast = useToast();
- const { widgets, toggleWidget, moveWidget, resetLayout } = useDashboardLayout();
const register = useSettingFocus();
const fileInputRef = useRef(null);
const [browseOpen, setBrowseOpen] = useState(false);
@@ -182,41 +181,15 @@ const AppearanceTab = () => {
<div {...register('appearance-widgets', 'settings-card')}>
<h3>Dashboard Widgets</h3>
- <p>Toggle visibility and reorder widgets on the dashboard</p>
- <div className="widget-list">
- {widgets.map((widget, idx) => (
- <div key={widget.id} className={`widget-item${!widget.visible ? ' widget-item--hidden' : ''}`}>
- <div className="widget-item__info">
- <Switch
- checked={widget.visible}
- onCheckedChange={() => toggleWidget(widget.id)}
- />
- <span className="widget-item__label">{widget.label}</span>
- </div>
- <div className="widget-item__controls">
- <button type="button"
- className="widget-move-btn"
- onClick={() => moveWidget(widget.id, 'up')}
- disabled={idx === 0}
- title="Move up"
- >
- <ChevronUp size={14} />
- </button>
- <button type="button"
- className="widget-move-btn"
- onClick={() => moveWidget(widget.id, 'down')}
- disabled={idx === widgets.length - 1}
- title="Move down"
- >
- <ChevronDown size={14} />
- </button>
- </div>
- </div>
- ))}
- </div>
- <Button variant="outline" size="sm" onClick={resetLayout} style={{ marginTop: '12px' }}>
- <RotateCcw size={14} />
- Reset to defaults
+ <p>
+ Widgets are arranged on the dashboard itself now — add, move, resize and
+ configure them in place, across as many boards as you need.
+ </p>
+ <Button variant="outline" size="sm" asChild>
+ <Link to="/">
+ <LayoutGrid size={14} />
+ Edit dashboards
+ </Link>
</Button>
</div>
diff --git a/frontend/src/hooks/useDashboardBoards.js b/frontend/src/hooks/useDashboardBoards.js
new file mode 100644
index 00000000..33d0f1bc
--- /dev/null
+++ b/frontend/src/hooks/useDashboardBoards.js
@@ -0,0 +1,133 @@
+/**
+ * Dashboard boards — load, edit and persist a user's widget layouts (plan 62).
+ *
+ * Supersedes `useDashboardLayout`, which kept a visibility list in
+ * localStorage. Boards live server-side (`/api/v1/dashboards`) so a layout
+ * follows the user to another browser, and they carry real geometry
+ * (x/y/w/h/cfg per widget) rather than just an on/off flag.
+ *
+ * Editing is deliberately local-until-saved: `setWidgets` mutates in memory
+ * only, `saveActive` writes. That is what lets the page offer Discard — the
+ * snapshot taken when edit mode opens is restored verbatim, with nothing
+ * having reached the server in between.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import api from '../services/api';
+
+export default function useDashboardBoards() {
+ const [boards, setBoards] = useState([]);
+ const [activeBoardId, setActiveBoardId] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const snapshotRef = useRef(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ api.getDashboards()
+ .then((data) => {
+ if (cancelled) return;
+ const list = Array.isArray(data?.boards) ? data.boards : [];
+ setBoards(list);
+ setActiveBoardId((current) => (
+ current && list.some((b) => b.id === current) ? current : (list[0]?.id ?? null)
+ ));
+ })
+ .catch((err) => {
+ if (!cancelled) setError(err?.message || 'Could not load dashboards');
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => { cancelled = true; };
+ }, []);
+
+ const activeBoard = boards.find((b) => b.id === activeBoardId) || boards[0] || null;
+
+ // Local-only widget edit on the active board.
+ const setWidgets = useCallback((next) => {
+ setBoards((list) => list.map((b) => (
+ b.id !== (activeBoard?.id) ? b : {
+ ...b,
+ widgets: typeof next === 'function' ? next(b.widgets || []) : next,
+ }
+ )));
+ }, [activeBoard?.id]);
+
+ const takeSnapshot = useCallback(() => {
+ snapshotRef.current = JSON.parse(JSON.stringify(boards));
+ }, [boards]);
+
+ const restoreSnapshot = useCallback(() => {
+ if (snapshotRef.current) setBoards(snapshotRef.current);
+ snapshotRef.current = null;
+ }, []);
+
+ const dropSnapshot = useCallback(() => { snapshotRef.current = null; }, []);
+
+ const saveActive = useCallback(async () => {
+ if (!activeBoard) return;
+ setError(null);
+ try {
+ await api.updateDashboard(activeBoard.id, { widgets: activeBoard.widgets || [] });
+ snapshotRef.current = null;
+ } catch (err) {
+ // Keep the edited state on screen — losing someone's layout to a
+ // failed request would be worse than showing a stale error.
+ setError(err?.message || 'Could not save this dashboard');
+ throw err;
+ }
+ }, [activeBoard]);
+
+ const createBoard = useCallback(async (name = 'New dashboard') => {
+ const board = await api.createDashboard({ name, icon: 'grid', widgets: [] });
+ setBoards((list) => [...list, board]);
+ setActiveBoardId(board.id);
+ return board;
+ }, []);
+
+ const renameBoard = useCallback(async (id, name) => {
+ setBoards((list) => list.map((b) => (b.id === id ? { ...b, name } : b)));
+ try {
+ await api.updateDashboard(id, { name });
+ } catch (err) {
+ setError(err?.message || 'Could not rename this dashboard');
+ }
+ }, []);
+
+ const removeBoard = useCallback(async (id) => {
+ const remaining = boards.filter((b) => b.id !== id);
+ if (!remaining.length) return; // never leave the user with none
+ setBoards(remaining);
+ setActiveBoardId((current) => (current === id ? remaining[0].id : current));
+ try {
+ await api.deleteDashboard(id);
+ } catch (err) {
+ setError(err?.message || 'Could not delete this dashboard');
+ }
+ }, [boards]);
+
+ const resetActiveBoard = useCallback(async () => {
+ if (!activeBoard) return;
+ const board = await api.resetDashboard(activeBoard.id);
+ setBoards((list) => list.map((b) => (b.id === board.id ? board : b)));
+ return board;
+ }, [activeBoard]);
+
+ return {
+ boards,
+ activeBoard,
+ activeBoardId: activeBoard?.id ?? null,
+ setActiveBoardId,
+ loading,
+ error,
+ setWidgets,
+ saveActive,
+ createBoard,
+ renameBoard,
+ removeBoard,
+ resetActiveBoard,
+ takeSnapshot,
+ restoreSnapshot,
+ dropSnapshot,
+ };
+}
diff --git a/frontend/src/hooks/useDashboardLayout.js b/frontend/src/hooks/useDashboardLayout.js
deleted file mode 100644
index 107bacff..00000000
--- a/frontend/src/hooks/useDashboardLayout.js
+++ /dev/null
@@ -1,87 +0,0 @@
-import { useState, useCallback } from 'react';
-
-const STORAGE_KEY = 'dashboard_layout';
-
-const DEFAULT_WIDGETS = [
- // Admin-only: renders nothing for non-admins (see Dashboard WIDGET_RENDERERS).
- { id: 'setup-health', label: 'Setup Health', visible: true },
- { id: 'cpu', label: 'CPU', visible: true },
- { id: 'ram', label: 'RAM', visible: true },
- { id: 'network', label: 'Network', visible: true },
- { id: 'disk', label: 'Disk', visible: true },
- { id: 'chart', label: 'Metrics Chart', visible: true },
- { id: 'specs', label: 'Quick Actions & Specs', visible: true },
- { id: 'processes', label: 'Processes / Containers', visible: true },
-];
-
-function loadWidgets() {
- try {
- const stored = JSON.parse(localStorage.getItem(STORAGE_KEY));
- if (!Array.isArray(stored)) return DEFAULT_WIDGETS.map(w => ({ ...w }));
-
- // Merge with defaults to handle new widgets added in future versions
- const storedMap = new Map(stored.map(w => [w.id, w]));
- const merged = [];
-
- // Keep stored order for known widgets
- for (const sw of stored) {
- const def = DEFAULT_WIDGETS.find(d => d.id === sw.id);
- if (def) {
- merged.push({ ...def, visible: sw.visible });
- }
- }
-
- // Append any new defaults not in stored
- for (const dw of DEFAULT_WIDGETS) {
- if (!storedMap.has(dw.id)) {
- merged.push({ ...dw });
- }
- }
-
- return merged;
- } catch {
- return DEFAULT_WIDGETS.map(w => ({ ...w }));
- }
-}
-
-function saveWidgets(widgets) {
- localStorage.setItem(STORAGE_KEY, JSON.stringify(widgets.map(({ id, visible }) => ({ id, visible }))));
-}
-
-export default function useDashboardLayout() {
- const [widgets, setWidgets] = useState(loadWidgets);
-
- const toggleWidget = useCallback((id) => {
- setWidgets(prev => {
- const next = prev.map(w => w.id === id ? { ...w, visible: !w.visible } : w);
- saveWidgets(next);
- return next;
- });
- }, []);
-
- const moveWidget = useCallback((id, direction) => {
- setWidgets(prev => {
- const idx = prev.findIndex(w => w.id === id);
- if (idx < 0) return prev;
- const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
- if (swapIdx < 0 || swapIdx >= prev.length) return prev;
- const next = [...prev];
- [next[idx], next[swapIdx]] = [next[swapIdx], next[idx]];
- saveWidgets(next);
- return next;
- });
- }, []);
-
- const resetLayout = useCallback(() => {
- const fresh = DEFAULT_WIDGETS.map(w => ({ ...w }));
- saveWidgets(fresh);
- setWidgets(fresh);
- }, []);
-
- const isVisible = useCallback((id) => {
- const w = widgets.find(w => w.id === id);
- return w ? w.visible : true;
- }, [widgets]);
-
- return { widgets, toggleWidget, moveWidget, resetLayout, isVisible };
-}
diff --git a/frontend/src/pages/Dashboard.jsx b/frontend/src/pages/Dashboard.jsx
index 3d2b6250..c2d3eb56 100644
--- a/frontend/src/pages/Dashboard.jsx
+++ b/frontend/src/pages/Dashboard.jsx
@@ -1,51 +1,29 @@
-import React, { useState, useEffect, useCallback } from 'react';
-import { useNavigate, Link } from 'react-router-dom';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
import {
- HardDrive, Activity,
- RefreshCw, Zap,
- Database, Container, Globe, Code, Layers, Server, Terminal,
- ChevronDown, Check, ChevronRight,
- Plus, Trash2, Pencil, LogIn, Power, Shield, AlertTriangle, History
+ Check, ChevronDown, Grid2x2, History, Maximize2, Plus,
+ RefreshCw, SlidersHorizontal, X,
} from 'lucide-react';
import api from '../services/api';
import { useAuth } from '../contexts/AuthContext';
+import { useToast } from '../contexts/ToastContext';
import { useMetrics } from '../hooks/useMetrics';
-import MetricsGraph from '../components/MetricsGraph';
-import useDashboardLayout from '../hooks/useDashboardLayout';
-import { Button } from '@/components/ui/button';
+import useDashboardBoards from '../hooks/useDashboardBoards';
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover';
-import { MetricCard, Pill, Feed, FeedItem } from '@/components/ds';
-import { formatRelativeTime } from '@/utils/time';
+import { SegControl } from '@/components/ds';
import EmptyState from '../components/EmptyState';
import PluginSlot from '../components/PluginSlot';
+import { DashGrid } from '../components/dashboard/grid/DashGrid';
+import { WidgetLibrary } from '../components/dashboard/grid/WidgetLibrary';
+import { WidgetInspector } from '../components/dashboard/grid/WidgetInspector';
+import { WidgetFullscreen } from '../components/dashboard/grid/WidgetFullscreen';
+import {
+ compact, findFreeSpot, nextWidgetId, pushDown,
+} from '../components/dashboard/grid/layout';
+import { useWidgetTypes, getWidgetType } from '../components/dashboard/widgets/registry';
+import { RANGES } from '../components/dashboard/widgets/metrics';
-// Map an audit action verb to a tinted icon + semantic tone token.
-// Falls back to a neutral history icon for unrecognised actions.
-function getActivityVisual(action = '') {
- const a = action.toLowerCase();
- if (a.includes('login_failed')) return { tone: 'red', icon: <AlertTriangle size={15} /> };
- if (a.includes('login') || a.includes('logout') || a.includes('auth')) return { tone: 'cyan', icon: <LogIn size={15} /> };
- if (a.includes('delete') || a.includes('remove') || a.includes('disable')) return { tone: 'red', icon: <Trash2 size={15} /> };
- if (a.includes('create') || a.includes('add') || a.includes('enable')) return { tone: 'green', icon: <Plus size={15} /> };
- if (a.includes('update') || a.includes('edit') || a.includes('permission')) return { tone: 'amber', icon: <Pencil size={15} /> };
- if (a.includes('start') || a.includes('restart') || a.includes('stop')) return { tone: 'violet', icon: <Power size={15} /> };
- if (a.includes('security') || a.includes('firewall') || a.includes('ssl') || a.includes('cert')) return { tone: 'accent', icon: <Shield size={15} /> };
- return { tone: 'accent', icon: <History size={15} /> };
-}
-
-// Build a readable "actor verb target" sentence from an audit-log item.
-// action is dotted (e.g. "user.create"); we humanise the verb and append the
-// target_type/id when present.
-function describeActivity(item) {
- const actor = item.username || (item.user_id ? `user #${item.user_id}` : 'System');
- const verb = (item.action || '').split('.').slice(1).join(' ').replace(/_/g, ' ') || (item.action || 'activity');
- const target = item.target_type
- ? `${item.target_type}${item.target_id ? ` #${item.target_id}` : ''}`
- : '';
- return { actor, verb, target };
-}
-
-// Refresh interval options in seconds
+// Auto-refresh choices, in seconds. 0 means "don't".
const REFRESH_OPTIONS = [
{ label: 'Off', value: 0 },
{ label: '5s', value: 5 },
@@ -54,236 +32,318 @@ const REFRESH_OPTIONS = [
{ label: '1m', value: 60 },
];
+function formatUptime(seconds) {
+ if (!seconds) return { days: 0, hours: 0, minutes: 0 };
+ return {
+ days: Math.floor(seconds / 86400),
+ hours: Math.floor((seconds % 86400) / 3600),
+ minutes: Math.floor((seconds % 3600) / 60),
+ };
+}
+
const Dashboard = () => {
const navigate = useNavigate();
const { isAdmin } = useAuth();
- const { metrics: localMetrics, loading: metricsLoading, connected, refresh: refreshMetrics } = useMetrics(true);
- const { widgets } = useDashboardLayout();
- const [apps, setApps] = useState([]);
- const [systemInfo, setSystemInfo] = useState(null);
- const [loading, setLoading] = useState(true);
-
- // Recent activity feed (admin-only — endpoint is /admin/activity/feed)
- const [activity, setActivity] = useState([]);
- const [activityLoading, setActivityLoading] = useState(true);
+ const toast = useToast();
+ const widgetTypes = useWidgetTypes();
+
+ const {
+ boards, activeBoard, activeBoardId, setActiveBoardId,
+ loading: boardsLoading, error: boardsError,
+ setWidgets, saveActive, createBoard, renameBoard, removeBoard, resetActiveBoard,
+ takeSnapshot, restoreSnapshot,
+ } = useDashboardBoards();
+
+ // ---- board editing UI state -------------------------------------------
+ const [edit, setEdit] = useState(false);
+ const [selectedId, setSelectedId] = useState(null);
+ const [libraryOpen, setLibraryOpen] = useState(false);
+ const [fullscreen, setFullscreen] = useState(null);
+ const [renamingId, setRenamingId] = useState(null);
+ const [tvMode, setTvMode] = useState(false);
+
+ // ---- board-wide variables ---------------------------------------------
+ const [range, setRange] = useState('1h');
+ const [tick, setTick] = useState(0);
const [refreshInterval, setRefreshInterval] = useState(() => {
const saved = localStorage.getItem('dashboard_refresh_interval');
return saved ? parseInt(saved, 10) : 10;
});
- const [localUptime, setLocalUptime] = useState(null);
- const [localTime, setLocalTime] = useState(null);
- const lastServerUptime = React.useRef(null);
- const lastServerTime = React.useRef(null);
- // Server selector state
+ // ---- host identity strip ----------------------------------------------
+ const { metrics: localMetrics, loading: metricsLoading, connected, refresh: refreshMetrics } = useMetrics(true);
+ const [systemInfo, setSystemInfo] = useState(null);
const [servers, setServers] = useState([]);
const [selectedServer, setSelectedServer] = useState({ id: 'local', name: 'Local (this server)' });
const [serverMenuOpen, setServerMenuOpen] = useState(false);
- const isRemote = selectedServer.id !== 'local';
-
- // Remote metrics (when a non-local server is selected)
const [remoteMetrics, setRemoteMetrics] = useState(null);
const [remoteSystemInfo, setRemoteSystemInfo] = useState(null);
- const [remoteLoading, setRemoteLoading] = useState(false);
-
- // Active metrics: remote when a remote server is selected, local otherwise
+ const isRemote = selectedServer.id !== 'local';
const metrics = isRemote ? remoteMetrics : localMetrics;
+ // Uptime and clock tick locally between server samples so they don't freeze
+ // between polls; the refs stop a repeated sample from resetting the drift.
+ const [localUptime, setLocalUptime] = useState(null);
+ const [localTime, setLocalTime] = useState(null);
+ const lastServerUptime = useRef(null);
+ const lastServerTime = useRef(null);
+
+ const widgets = useMemo(() => activeBoard?.widgets || [], [activeBoard]);
+ const selectedWidget = widgets.find((w) => w.i === selectedId) || null;
+ const selectedType = getWidgetType(widgetTypes, selectedWidget?.type);
+
+ const resources = useMemo(() => ([
+ { id: 'local', label: 'Local (this server)', kind: 'panel host' },
+ ...servers
+ .filter((s) => s && s.id && s.id !== 'local')
+ .map((s) => ({ id: s.id, label: s.name || s.id, kind: 'server' })),
+ ]), [servers]);
+
+ const ctx = useMemo(() => ({
+ range,
+ tick,
+ serverVar: selectedServer.id,
+ isAdmin,
+ navigate,
+ types: widgetTypes,
+ }), [range, tick, selectedServer.id, isAdmin, navigate, widgetTypes]);
+
+ // ---- data loading ------------------------------------------------------
+ useEffect(() => {
+ api.getAvailableServers()
+ .then((data) => setServers(Array.isArray(data) ? data : []))
+ .catch(() => setServers([]));
+ api.getSystemInfo()
+ .then(setSystemInfo)
+ .catch(() => setSystemInfo(null));
+ }, []);
+
const fetchRemote = useCallback(async () => {
if (!isRemote) return;
- setRemoteLoading(true);
try {
- const [metricsData, sysInfo] = await Promise.all([
+ const [m, info] = await Promise.all([
api.getRemoteSystemMetrics(selectedServer.id),
- api.getRemoteSystemInfo(selectedServer.id).catch(() => null)
+ api.getRemoteSystemInfo(selectedServer.id).catch(() => null),
]);
- setRemoteMetrics(metricsData);
- setRemoteSystemInfo(sysInfo);
- } catch (err) {
- console.error('Failed to load remote metrics:', err);
- } finally {
- setRemoteLoading(false);
+ setRemoteMetrics(m);
+ setRemoteSystemInfo(info);
+ } catch {
+ // The identity strip degrades to placeholders; widgets report their
+ // own failures individually.
}
- }, [selectedServer.id, isRemote]);
-
- // Load servers list on mount
- useEffect(() => {
- api.getAvailableServers()
- .then(data => setServers(Array.isArray(data) ? data : []))
- .catch(() => setServers([{ id: 'local', name: 'Local (this server)', status: 'online' }]));
- }, []);
+ }, [isRemote, selectedServer.id]);
- // Fetch remote metrics when a remote server is selected
useEffect(() => {
if (!isRemote) {
setRemoteMetrics(null);
setRemoteSystemInfo(null);
- return;
+ return undefined;
}
-
fetchRemote();
- const interval = refreshInterval > 0
- ? setInterval(fetchRemote, refreshInterval * 1000)
- : null;
+ const id = refreshInterval > 0 ? setInterval(fetchRemote, refreshInterval * 1000) : null;
+ return () => { if (id) clearInterval(id); };
+ }, [fetchRemote, isRemote, refreshInterval]);
- return () => { if (interval) clearInterval(interval); };
- }, [fetchRemote, refreshInterval, isRemote]);
+ // Board-wide refresh pulse: every widget watches ctx.tick.
+ useEffect(() => {
+ if (!refreshInterval) return undefined;
+ const id = setInterval(() => setTick((k) => k + 1), refreshInterval * 1000);
+ return () => clearInterval(id);
+ }, [refreshInterval]);
- // Sync local counters when server data arrives
+ // HTTP polling fallback for live metrics when the socket is down.
useEffect(() => {
- const serverUptime = metrics?.system?.uptime_seconds;
- const serverTimeStr = metrics?.time?.current_time_formatted;
+ if (!refreshInterval || connected || isRemote) return undefined;
+ const id = setInterval(() => refreshMetrics(), refreshInterval * 1000);
+ return () => clearInterval(id);
+ }, [refreshInterval, connected, refreshMetrics, isRemote]);
- if (serverUptime && serverUptime !== lastServerUptime.current) {
- lastServerUptime.current = serverUptime;
- setLocalUptime(serverUptime);
+ useEffect(() => {
+ const uptime = metrics?.system?.uptime_seconds;
+ const stamp = metrics?.time?.current_time_formatted;
+ if (uptime && uptime !== lastServerUptime.current) {
+ lastServerUptime.current = uptime;
+ setLocalUptime(uptime);
}
-
- if (serverTimeStr && serverTimeStr !== lastServerTime.current) {
- lastServerTime.current = serverTimeStr;
- try {
- const parsed = new Date(serverTimeStr);
- if (!isNaN(parsed)) {
- setLocalTime(parsed);
- }
- } catch {
- // If parsing fails, skip
- }
+ if (stamp && stamp !== lastServerTime.current) {
+ lastServerTime.current = stamp;
+ const parsed = new Date(stamp);
+ if (!Number.isNaN(parsed.getTime())) setLocalTime(parsed);
}
}, [metrics?.system?.uptime_seconds, metrics?.time?.current_time_formatted]);
- // Tick every second - increment uptime and time locally
+ const hasUptime = localUptime !== null;
+ const hasClock = localTime !== null;
useEffect(() => {
- const tick = setInterval(() => {
- if (localUptime !== null) {
- setLocalUptime(prev => prev + 1);
- }
- if (localTime !== null) {
- setLocalTime(prev => new Date(prev.getTime() + 1000));
- }
+ if (!hasUptime && !hasClock) return undefined;
+ const id = setInterval(() => {
+ if (hasUptime) setLocalUptime((prev) => prev + 1);
+ if (hasClock) setLocalTime((prev) => new Date(prev.getTime() + 1000));
}, 1000);
-
- return () => clearInterval(tick);
- }, [localUptime !== null, localTime !== null]);
-
- // Load initial data
+ return () => clearInterval(id);
+ }, [hasUptime, hasClock]);
+
+ // ---- widget operations -------------------------------------------------
+ const addWidget = useCallback((type) => {
+ const spot = findFreeSpot(widgets, type.w, type.h);
+ const widget = {
+ i: nextWidgetId(widgets),
+ type: type.id,
+ ...spot,
+ w: type.w,
+ h: type.h,
+ cfg: JSON.parse(JSON.stringify(type.defaultCfg || {})),
+ };
+ setWidgets((list) => compact([...list, widget]));
+ setSelectedId(widget.i);
+ setLibraryOpen(false);
+ if (!edit) setEdit(true);
+ }, [widgets, setWidgets, edit]);
+
+ const duplicateWidget = useCallback((widget) => {
+ const spot = findFreeSpot(widgets, widget.w, widget.h);
+ const copy = { ...JSON.parse(JSON.stringify(widget)), i: nextWidgetId(widgets), ...spot };
+ setWidgets((list) => compact([...list, copy]));
+ setSelectedId(copy.i);
+ }, [widgets, setWidgets]);
+
+ const removeWidget = useCallback((id) => {
+ setWidgets((list) => compact(list.filter((w) => w.i !== id)));
+ setSelectedId(null);
+ }, [setWidgets]);
+
+ // The inspector can change w/h, which may overlap neighbours — re-settle.
+ const updateWidget = useCallback((next) => {
+ setWidgets((list) => pushDown(list.map((w) => (w.i === next.i ? next : w)), next));
+ }, [setWidgets]);
+
+ const onWidgetMenu = useCallback((action, widget) => {
+ if (action === 'config') { setEdit(true); setSelectedId(widget.i); }
+ else if (action === 'dup') duplicateWidget(widget);
+ else if (action === 'del') removeWidget(widget.i);
+ else if (action === 'full') setFullscreen(widget);
+ }, [duplicateWidget, removeWidget]);
+
+ // Escape backs out of TV mode, then out of a selection. Delete removes the
+ // selected widget, but only while editing and never while typing into the
+ // inspector — otherwise backspacing a title would delete the widget.
useEffect(() => {
- loadData();
- }, []);
-
- // Load the recent-activity feed — admins only (avoids a 403 for others)
- useEffect(() => {
- if (!isAdmin) {
- setActivityLoading(false);
- return;
- }
- let cancelled = false;
- setActivityLoading(true);
- api.getActivityFeed({ per_page: 8 })
- .then(data => {
- if (!cancelled) setActivity(data?.logs || []);
- })
- .catch(err => {
- if (!cancelled) console.error('Failed to load activity feed:', err);
- })
- .finally(() => {
- if (!cancelled) setActivityLoading(false);
+ const onKeyDown = (event) => {
+ if (event.key === 'Escape') {
+ if (tvMode) setTvMode(false);
+ else if (selectedId) setSelectedId(null);
+ return;
+ }
+ if (!edit || !selectedId) return;
+ if (event.key !== 'Delete' && event.key !== 'Backspace') return;
+ if (/input|textarea|select/i.test(document.activeElement?.tagName || '')) return;
+ event.preventDefault();
+ removeWidget(selectedId);
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [edit, selectedId, tvMode, removeWidget]);
+
+ // ---- edit session ------------------------------------------------------
+ const startEdit = () => { takeSnapshot(); setEdit(true); };
+
+ const discardEdit = () => {
+ restoreSnapshot();
+ setEdit(false);
+ setSelectedId(null);
+ };
+
+ const finishEdit = async () => {
+ try {
+ await saveActive();
+ setEdit(false);
+ setSelectedId(null);
+ toast.success('Dashboard saved', {
+ description: `${widgets.length} widget${widgets.length === 1 ? '' : 's'} · ${activeBoard?.name}`,
});
- return () => { cancelled = true; };
- }, [isAdmin]);
-
- // Polling fallback when WebSocket is not connected (local only)
- useEffect(() => {
- if (refreshInterval > 0 && !connected && !isRemote) {
- const interval = setInterval(() => {
- refreshMetrics();
- }, refreshInterval * 1000);
- return () => clearInterval(interval);
+ } catch {
+ // useDashboardBoards keeps the edited layout on screen and surfaces
+ // the reason; staying in edit mode means the work isn't lost.
+ toast.error('Could not save', { description: 'Your layout is still here — try again.' });
}
- }, [refreshInterval, connected, refreshMetrics, isRemote]);
+ };
- // Save refresh interval preference
- const handleRefreshIntervalChange = useCallback((value) => {
- setRefreshInterval(value);
- localStorage.setItem('dashboard_refresh_interval', value.toString());
- }, []);
+ const handleReset = async () => {
+ try {
+ await resetActiveBoard();
+ toast.info('Reset to the shipped layout', { description: activeBoard?.name });
+ } catch {
+ toast.error('Could not reset', { description: 'This board has no shipped default.' });
+ }
+ };
- function handleServerChange(serverId) {
- const server = servers.find(s => s.id === serverId) || { id: 'local', name: 'Local (this server)' };
+ const handleServerChange = (serverId) => {
+ const server = servers.find((s) => s.id === serverId) || { id: 'local', name: 'Local (this server)' };
setSelectedServer(server);
- // Reset ticking counters when switching servers
lastServerUptime.current = null;
lastServerTime.current = null;
setLocalUptime(null);
setLocalTime(null);
- }
+ };
- async function loadData() {
- try {
- const [appsData, sysInfoData] = await Promise.all([
- api.getApps(),
- api.getSystemInfo().catch(() => null)
- ]);
- setApps(appsData.apps || []);
- setSystemInfo(sysInfoData);
- } catch (err) {
- console.error('Failed to load data:', err);
- } finally {
- setLoading(false);
- }
- }
-
- function handleRefreshAll() {
- if (isRemote) {
- fetchRemote();
- } else {
- refreshMetrics();
- }
- loadData();
- }
-
- function formatUptime(seconds) {
- if (!seconds) return { days: 0, hours: 0, minutes: 0 };
- const days = Math.floor(seconds / 86400);
- const hours = Math.floor((seconds % 86400) / 3600);
- const minutes = Math.floor((seconds % 3600) / 60);
- return { days, hours, minutes };
- }
-
- function getStackIcon(type) {
- switch (type) {
- case 'docker': return <Container size={16} />;
- case 'wordpress':
- case 'php': return <Code size={16} />;
- case 'flask':
- case 'django': return <Layers size={16} />;
- default: return <Globe size={16} />;
- }
- }
+ const handleRefreshIntervalChange = (value) => {
+ setRefreshInterval(value);
+ localStorage.setItem('dashboard_refresh_interval', String(value));
+ };
- // Get uptime from local ticking counter (synced with server)
- const uptimeFormatted = formatUptime(localUptime ?? metrics?.system?.uptime_seconds);
+ // ---- derived display ---------------------------------------------------
const activeSysInfo = isRemote ? remoteSystemInfo : systemInfo;
const hostname = metrics?.system?.hostname || activeSysInfo?.hostname || 'server';
const kernelVersion = metrics?.system?.kernel || activeSysInfo?.kernel || '-';
const ipAddress = metrics?.system?.ip_address || activeSysInfo?.ip_address || '-';
- const serverTime = metrics?.time;
-
- // Format the local ticking clock
+ const uptime = formatUptime(localUptime ?? metrics?.system?.uptime_seconds);
+ const isConnected = isRemote ? !!remoteMetrics : !!localMetrics;
const displayTime = localTime
- ? localTime.toLocaleTimeString('en-US', { hour12: false })
- : serverTime?.current_time_formatted?.split(' ')[1] || '--:--:--';
-
- // Show green if we have metrics data (regardless of transport — WS or HTTP poll)
- const isConnected = isRemote ? !remoteLoading && !!remoteMetrics : !!localMetrics;
+ ? localTime.toLocaleTimeString('en-GB', { hour12: false })
+ : metrics?.time?.current_time_formatted?.split(' ')[1] || '--:--:--';
- if (loading && metricsLoading) {
+ if (boardsLoading && metricsLoading) {
return <EmptyState loading loadingVariant="chart" title="Loading dashboard..." />;
}
+ const grid = (
+ <DashGrid
+ widgets={widgets}
+ edit={edit}
+ selectedId={selectedId}
+ onSelect={setSelectedId}
+ onChange={(next) => setWidgets(next)}
+ ctx={ctx}
+ onWidgetMenu={onWidgetMenu}
+ />
+ );
+
+ // TV mode: the board, a clock and nothing else — for a wall display.
+ if (tvMode) {
+ return (
+ <div className="skw-tv">
+ <div className="skw-tv__bar">
+ <span className="skw-tv__name">{activeBoard?.name}</span>
+ <span className={`conn-status conn-status--${isConnected ? 'live' : 'down'}`} role="status">
+ <span className="conn-status__dot" aria-hidden="true"></span>
+ {isConnected ? 'Live' : 'Reconnecting'}
+ </span>
+ <span className="skw-tv__meta mono">
+ {selectedServer.name} · {range} · refresh {refreshInterval ? `${refreshInterval}s` : 'off'}
+ </span>
+ <span className="skw-tv__clock mono">{displayTime}</span>
+ <button type="button" className="btn btn-outline btn-sm" onClick={() => setTvMode(false)}>
+ <X size={14} /> Exit
+ </button>
+ </div>
+ <div className="skw-tv__body">{grid}</div>
+ </div>
+ );
+ }
+
return (
- <div className="page-container dashboard-page">
- {/* Top Bar */}
+ <div className={`page-container dashboard-page${edit && selectedWidget ? ' skw-ins-open' : ''}`}>
+ {/* Host identity — which machine the board's $server variable points at */}
<div className="top-bar">
<div className="server-identity">
<Popover open={serverMenuOpen} onOpenChange={setServerMenuOpen}>
@@ -297,15 +357,10 @@ const Dashboard = () => {
<ChevronDown size={18} className="srv-switch__chev" aria-hidden="true" />
</button>
</PopoverTrigger>
- <PopoverContent
- align="start"
- sideOffset={7}
- className="env-menu"
- >
+ <PopoverContent align="start" sideOffset={7} className="env-menu">
<div className="env-menu__head">Connected servers · {servers.length}</div>
- {servers.map(server => {
+ {servers.map((server) => {
const online = server.status === 'online';
- const active = server.id === selectedServer.id;
return (
<button
type="button"
@@ -325,10 +380,8 @@ const Dashboard = () => {
{online ? 'online' : 'offline'}
</span>
</span>
- {active && (
- <span className="env-opt__check" aria-hidden="true">
- <Check size={15} />
- </span>
+ {server.id === selectedServer.id && (
+ <span className="env-opt__check" aria-hidden="true"><Check size={15} /></span>
)}
</button>
);
@@ -336,10 +389,7 @@ const Dashboard = () => {
</PopoverContent>
</Popover>
<div className="server-details">
- <span
- className={`conn-status conn-status--${isConnected ? 'live' : 'down'}`}
- role="status"
- >
+ <span className={`conn-status conn-status--${isConnected ? 'live' : 'down'}`} role="status">
<span className="conn-status__dot" aria-hidden="true"></span>
{isConnected ? 'Live' : 'Reconnecting'}
</span>
@@ -348,32 +398,16 @@ const Dashboard = () => {
<span className="detail-separator">·</span>
<span>KERNEL: {kernelVersion}</span>
<span className="detail-separator">·</span>
- <span>UPTIME: {uptimeFormatted.days}d {String(uptimeFormatted.hours).padStart(2, '0')}h {String(uptimeFormatted.minutes).padStart(2, '0')}m</span>
+ <span>
+ UPTIME: {uptime.days}d {String(uptime.hours).padStart(2, '0')}h{' '}
+ {String(uptime.minutes).padStart(2, '0')}m
+ </span>
</div>
</div>
<div className="top-bar-right">
<div className="clock-widget">
<span className="clock-time">{displayTime}</span>
- <span className="clock-zone">{serverTime?.timezone_id || 'UTC'}</span>
- </div>
- <div className="refresh-control">
- <button type="button"
- className="btn-refresh"
- onClick={handleRefreshAll}
- title="Refresh now"
- >
- <RefreshCw size={14} />
- </button>
- <select
- value={refreshInterval}
- onChange={(e) => handleRefreshIntervalChange(parseInt(e.target.value, 10))}
- className="refresh-select"
- title="Auto-refresh interval"
- >
- {REFRESH_OPTIONS.map(opt => (
- <option key={opt.value} value={opt.value}>{opt.label}</option>
- ))}
- </select>
+ <span className="clock-zone">{metrics?.time?.timezone_id || 'UTC'}</span>
</div>
</div>
</div>
@@ -381,202 +415,182 @@ const Dashboard = () => {
{/* Extension slot: widgets contributed to the top of the dashboard */}
<PluginSlot name="dashboard.top" />
- {/* Grid Container */}
- <div className="grid-container">
- {widgets.filter(w => w.visible).map(w => {
- const WIDGET_RENDERERS = {
- cpu: () => (
- <MetricCard
- key="cpu"
- className="dash-kpi"
- tone="accent"
- icon={<Zap size={16} />}
- value={(metrics?.cpu?.percent || 0).toFixed(1)}
- unit="%"
- label="CPU"
- >
- <div className="sk-kpi__sub">
- <span>Cores {metrics?.cpu?.count_logical || 0}</span>
- </div>
- </MetricCard>
- ),
- ram: () => (
- <MetricCard
- key="ram"
- className="dash-kpi"
- tone="green"
- icon={<Database size={16} />}
- value={metrics?.memory?.ram?.used_human || '0 GB'}
- label="RAM"
- >
- <div className="sk-kpi__sub">
- <span>Total {metrics?.memory?.ram?.total_human || '0 GB'}</span>
- <span>Cached {metrics?.memory?.ram?.cached_human || '0 GB'}</span>
- </div>
- </MetricCard>
- ),
- network: () => (
- <MetricCard
- key="network"
- className="dash-kpi"
- tone="cyan"
- icon={<Activity size={16} />}
- value={metrics?.network?.io?.bytes_sent_human || '0 B'}
- unit="sent"
- label="Network"
- >
- <div className="sk-kpi__sub">
- <span>In {metrics?.network?.io?.bytes_recv_human || '0 B'}</span>
- <span>Out {metrics?.network?.io?.bytes_sent_human || '0 B'}</span>
- </div>
- </MetricCard>
- ),
- disk: () => (
- <MetricCard
- key="disk"
- className="dash-kpi"
- tone="amber"
- icon={<HardDrive size={16} />}
- value={(metrics?.disk?.partitions?.[0]?.percent || 0).toFixed(1)}
- unit="%"
- label="Disk"
- >
- <div className="sk-kpi__sub">
- <span>Used {metrics?.disk?.partitions?.[0]?.used_human || '0 GB'}</span>
- <span>Free {metrics?.disk?.partitions?.[0]?.free_human || '0 GB'}</span>
- </div>
- </MetricCard>
- ),
- chart: () => (
- <div key="chart" className="chart-panel">
- <MetricsGraph timezone={serverTime?.timezone_id} />
- </div>
- ),
- specs: () => (
- <div key="specs" className="spec-panel">
- <h3 className="spec-panel-title">Quick Actions</h3>
- <button type="button" className="btn-action" onClick={() => navigate('/servers')}>
- <span>Manage Servers</span>
- <span><Server size={14} /></span>
- </button>
- <button type="button" className="btn-action" onClick={() => navigate('/docker')}>
- <span>Docker Containers</span>
- <span><Container size={14} /></span>
- </button>
- <button type="button" className="btn-action" onClick={() => navigate('/terminal')}>
- <span>Open Terminal</span>
- <span><Terminal size={14} /></span>
+ {/* Board tabs + board-wide controls */}
+ <div className="skw-bar">
+ <div className="skw-tabs">
+ {boards.map((board) => (
+ <div
+ key={board.id}
+ className={`skw-tab${board.id === activeBoardId ? ' is-on' : ''}`}
+ onClick={() => { setActiveBoardId(board.id); setSelectedId(null); }}
+ onDoubleClick={() => edit && setRenamingId(board.id)}
+ role="button"
+ tabIndex={0}
+ onKeyDown={(e) => { if (e.key === 'Enter') { setActiveBoardId(board.id); setSelectedId(null); } }}
+ >
+ <Grid2x2 size={14} aria-hidden="true" />
+ {renamingId === board.id ? (
+ <input
+ className="skw-rename"
+ autoFocus
+ defaultValue={board.name}
+ onBlur={(e) => {
+ renameBoard(board.id, e.target.value.trim() || board.name);
+ setRenamingId(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') e.target.blur();
+ if (e.key === 'Escape') setRenamingId(null);
+ }}
+ />
+ ) : (
+ <span>{board.name}</span>
+ )}
+ <span className="skw-tab__count mono">{(board.widgets || []).length}</span>
+ {edit && boards.length > 1 && board.id === activeBoardId && (
+ <button
+ type="button"
+ className="skw-iconbtn skw-iconbtn--bare"
+ aria-label={`Delete ${board.name}`}
+ onClick={(e) => { e.stopPropagation(); removeBoard(board.id); }}
+ >
+ <X size={12} />
</button>
-
- <h3 className="spec-panel-title mt-6">Hardware Specs</h3>
- <div className="spec-row">
- <span className="spec-label">Processor</span>
- <span className="spec-data">{activeSysInfo?.cpu?.model || 'N/A'}</span>
- </div>
- <div className="spec-row">
- <span className="spec-label">Architecture</span>
- <span className="spec-data">{activeSysInfo?.cpu?.architecture || 'N/A'}</span>
- </div>
- <div className="spec-row">
- <span className="spec-label">Swap Memory</span>
- <span className="spec-data">{metrics?.memory?.swap?.total_human || 'N/A'}</span>
- </div>
- </div>
- ),
- processes: () => (
- <div key="processes" className="table-panel">
- <div className="table-header">
- <span>Applications</span>
- <Button variant="outline" size="sm" onClick={loadData}>
- <RefreshCw size={14} />
- </Button>
- </div>
- <table className="data-table">
- <thead>
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Type</th>
- <th>Status</th>
- <th>Domain</th>
- </tr>
- </thead>
- <tbody>
- {apps.length === 0 ? (
- <tr>
- <td colSpan="5" className="text-center text-gray-400">
- No applications found
- </td>
- </tr>
- ) : (
- apps.slice(0, 6).map(app => (
- <tr key={app.id} onClick={() => navigate(`/apps/${app.id}`)} className="cursor-pointer">
- <td>{app.id}</td>
- <td>
- <div className="app-name-cell">
- <span className="app-icon-mini" aria-hidden="true">{getStackIcon(app.app_type)}</span>
- <Link
- to={`/apps/${app.id}`}
- className="app-name-link"
- onClick={(e) => e.stopPropagation()}
- >
- {app.name}
- </Link>
- </div>
- </td>
- <td>{app.app_type}</td>
- <td>
- <Pill kind={app.status === 'running' ? 'green' : 'amber'}>
- {app.status?.toUpperCase()}
- </Pill>
- </td>
- <td>{app.domains?.[0]?.name || '-'}</td>
- </tr>
- ))
- )}
- </tbody>
- </table>
- </div>
- ),
- };
- return WIDGET_RENDERERS[w.id]?.();
- })}
-
- {/* Recent activity — admin-only audit feed, paired with Applications */}
- {isAdmin && (
- <div className="activity-panel">
- <div className="activity-panel__head">
- <h3 className="activity-panel__title">Recent Activity</h3>
- <Link to="/security/audit" className="activity-panel__link">
- Audit log <ChevronRight size={14} aria-hidden="true" />
- </Link>
+ )}
</div>
- {activityLoading ? (
- <div className="activity-panel__empty">Loading activity…</div>
- ) : activity.length === 0 ? (
- <div className="activity-panel__empty">No recent activity</div>
- ) : (
- <Feed>
- {activity.map(item => {
- const { tone, icon } = getActivityVisual(item.action);
- const { actor, verb, target } = describeActivity(item);
- return (
- <FeedItem
- key={item.id}
- icon={icon}
- tone={tone}
- time={formatRelativeTime(item.created_at)}
- >
- <b>{actor}</b> {verb}
- {target && <> · {target}</>}
- </FeedItem>
- );
- })}
- </Feed>
+ ))}
+ <button
+ type="button"
+ className="skw-tab skw-tab--add"
+ onClick={() => createBoard().then((b) => setRenamingId(b.id))}
+ aria-label="New dashboard"
+ title="New dashboard"
+ >
+ <Plus size={14} />
+ </button>
+ </div>
+
+ <div className="skw-bar__ctl">
+ <SegControl
+ options={RANGES.map(([value, label]) => ({ value, label }))}
+ value={range}
+ onChange={setRange}
+ aria-label="Time range"
+ />
+ <select
+ value={refreshInterval}
+ onChange={(e) => handleRefreshIntervalChange(parseInt(e.target.value, 10))}
+ className="refresh-select"
+ title="Auto-refresh interval"
+ aria-label="Auto-refresh interval"
+ >
+ {REFRESH_OPTIONS.map((opt) => (
+ <option key={opt.value} value={opt.value}>↻ {opt.label}</option>
+ ))}
+ </select>
+ <button
+ type="button"
+ className="skw-iconbtn"
+ title="Refresh now"
+ aria-label="Refresh now"
+ onClick={() => { setTick((k) => k + 1); if (isRemote) fetchRemote(); else refreshMetrics(); }}
+ >
+ <RefreshCw size={15} />
+ </button>
+ <button
+ type="button"
+ className="skw-iconbtn"
+ title="TV mode"
+ aria-label="TV mode"
+ onClick={() => setTvMode(true)}
+ >
+ <Maximize2 size={15} />
+ </button>
+ {edit ? (
+ <>
+ <button type="button" className="btn btn-outline btn-sm" onClick={() => setLibraryOpen(true)}>
+ <Plus size={14} /> Add widget
+ </button>
+ <button
+ type="button"
+ className="btn btn-sm"
+ onClick={handleReset}
+ title="Restore the shipped layout"
+ aria-label="Restore the shipped layout"
+ >
+ <History size={14} />
+ </button>
+ <button type="button" className="btn btn-sm" onClick={discardEdit}>Discard</button>
+ <button type="button" className="btn btn-primary btn-sm" onClick={finishEdit}>
+ <Check size={14} /> Done
+ </button>
+ </>
+ ) : (
+ <button type="button" className="btn btn-outline btn-sm" onClick={startEdit}>
+ <SlidersHorizontal size={14} /> Edit
+ </button>
+ )}
+ </div>
+ </div>
+
+ {boardsError && <div className="skw-hint skw-hint--error">{boardsError}</div>}
+
+ {edit && (
+ <div className="skw-hint mono">
+ <Grid2x2 size={13} aria-hidden="true" /> Drag headers to move · drag the corner to resize ·
+ click a widget to configure it{selectedId ? ' · Delete removes it' : ''}
+ </div>
+ )}
+
+ {widgets.length === 0 ? (
+ <div className="skw-empty-board">
+ <div className="skw-empty-board__title">Build “{activeBoard?.name || 'this dashboard'}”</div>
+ <div className="skw-empty-board__desc">
+ This board has no widgets yet. Add one to get started, or restore the layout it shipped with.
+ </div>
+ <div className="skw-empty-board__acts">
+ <button
+ type="button"
+ className="btn btn-primary btn-sm"
+ onClick={() => { setEdit(true); setLibraryOpen(true); }}
+ >
+ <Plus size={14} /> Add a widget
+ </button>
+ {activeBoard?.slug && (
+ <button type="button" className="btn btn-outline btn-sm" onClick={handleReset}>
+ <History size={14} /> Restore default layout
+ </button>
)}
</div>
- )}
- </div>
+ </div>
+ ) : grid}
+
+ {libraryOpen && (
+ <WidgetLibrary
+ types={widgetTypes}
+ onAdd={addWidget}
+ onClose={() => setLibraryOpen(false)}
+ />
+ )}
+ {edit && selectedWidget && (
+ <WidgetInspector
+ widget={selectedWidget}
+ type={selectedType}
+ resources={resources}
+ onChange={updateWidget}
+ onClose={() => setSelectedId(null)}
+ onDuplicate={() => duplicateWidget(selectedWidget)}
+ onRemove={() => removeWidget(selectedWidget.i)}
+ />
+ )}
+ {fullscreen && (
+ <WidgetFullscreen
+ widget={fullscreen}
+ type={getWidgetType(widgetTypes, fullscreen.type)}
+ ctx={ctx}
+ onClose={() => setFullscreen(null)}
+ />
+ )}
</div>
);
};
diff --git a/frontend/src/styles/components/_dashboard-widgets.scss b/frontend/src/styles/components/_dashboard-widgets.scss
new file mode 100644
index 00000000..378d0ddc
--- /dev/null
+++ b/frontend/src/styles/components/_dashboard-widgets.scss
@@ -0,0 +1,1727 @@
+// ============================================================
+// DASHBOARD WIDGET GRID (plan 62)
+// ============================================================
+// Everything the configurable dashboard needs: the board bar, the placement
+// grid, one widget's chrome, the 13 core widget bodies, the "add a widget"
+// drawer, the right-hand inspector, fullscreen + TV mode, and the empty-board
+// template picker.
+//
+// Namespaced `skw-` (ServerKit Widget) so NOTHING here can reach a page that
+// did not opt in. That matters more than usual for this file: widget bodies
+// render arbitrary app content (tables, logs, lists) whose generic names
+// (.table/.list/.alert/.status) already exist elsewhere in the app.
+//
+// Ported from the design mock (`w-*` / `dash-*` / `wl-*` / `ins-*`), not
+// copied: the mock is dark-only and hardcodes surface hexes, so every colour
+// here comes from a var() token in _theme-variables.scss and reads correctly
+// in both themes. Substitutions made while porting are called out inline.
+//
+// State classes are published in BOTH forms — the BEM modifier
+// (`.skw-frame--selected`) and the repo's `is-` convention
+// (`.skw-frame.is-selected`) — because the frame is driven by JSX written
+// against the mock's vocabulary. Pick one at the call site; both resolve here.
+// ============================================================
+
+// Row height / gap mirror grid/layout.js (GRID_ROW 88, GRID_GAP 12). They are
+// duplicated rather than imported because the JS owns the placement maths and
+// SCSS only needs them for the responsive stack-down below.
+$skw-grid-gap: 12px;
+$skw-stack-row-h: 260px;
+
+// Inspector panel width + the gutter the page reserves for it while open.
+$skw-ins-w: 340px;
+$skw-ins-gutter: 352px;
+
+// The overlay layers sit deliberately ABOVE the app's $z-* scale (which tops
+// out at $z-tooltip: 60): a fullscreen widget must cover the page chrome, and
+// TV mode must cover everything including toasts.
+$skw-z-inspector: 90;
+$skw-z-fullscreen: 101;
+$skw-z-tv: 200;
+
+// ------------------------------------------------------------
+// Dashboard bar — board tabs on the left, board-wide controls on the right.
+// ------------------------------------------------------------
+.skw-bar {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ flex-wrap: wrap;
+ margin-bottom: 14px;
+
+ // Range / refresh / variable pickers + edit toggle. `margin-left:auto`
+ // rather than a spacer element so the tabs keep their natural width.
+ &__ctl {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-left: auto;
+ flex-wrap: wrap;
+ }
+}
+
+.skw-tabs {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex-wrap: wrap;
+}
+
+.skw-tab {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 7px 11px;
+ border: 1px solid transparent;
+ border-radius: 9px;
+ background: none;
+ color: var(--text-faint);
+ font-family: inherit;
+ font-size: 13px;
+ cursor: pointer;
+ transition: 0.13s;
+
+ &:hover {
+ color: var(--text);
+ background: var(--surface-2);
+ }
+
+ // Active board. Set apart by fill + border, never by weight, so switching
+ // boards cannot re-flow the row (same rule as .sk-topbar__tab).
+ &--on,
+ &.is-on,
+ &.is-active {
+ color: var(--text);
+ background: var(--surface-2);
+ border-color: var(--border-strong);
+
+ svg { color: var(--accent-bright); }
+ }
+
+ // Widget count on the tab.
+ &__count {
+ padding: 1px 5px;
+ border-radius: 5px;
+ background: var(--surface-3);
+ color: var(--text-ghost);
+ font-family: var(--mono);
+ font-size: 10px;
+ }
+
+ // "+" new-board affordance — icon only, so it drops the label padding.
+ &--add {
+ padding: 8px;
+ color: var(--text-faint);
+ }
+}
+
+// Inline board rename. Accent border rather than a focus ring: the input
+// replaces the tab in place and has to read as "editing" without growing.
+.skw-rename {
+ width: 130px;
+ padding: 2px 6px;
+ border: 1px solid var(--accent);
+ border-radius: 6px;
+ background: var(--surface-3);
+ color: var(--text);
+ font-family: var(--sans);
+ font-size: 13px;
+ outline: none;
+}
+
+// Variable picker ($server / $env) — a labelled value, not a select.
+.skw-varpick {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ height: 32px;
+ padding: 0 10px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--surface-2);
+ color: var(--text);
+ font-family: inherit;
+ font-size: 12.5px;
+ cursor: pointer;
+ transition: 0.13s;
+
+ &:hover,
+ &--open,
+ &.is-open {
+ border-color: var(--accent-dim);
+ background: var(--surface-3);
+ }
+
+ &__k {
+ color: var(--text-ghost);
+ font-size: 10px;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ }
+ &__v {
+ font-family: var(--mono);
+ font-size: 12px;
+ }
+}
+
+// Refresh-interval select. Sizing only — the select chrome comes from the
+// shared form styles.
+.skw-refresh {
+ select {
+ height: 32px;
+ padding: 0 26px 0 10px;
+ font-family: var(--mono);
+ font-size: 11.5px;
+ }
+}
+
+// Square icon button used across the bar and the widget head.
+.skw-iconbtn {
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--surface-2);
+ color: var(--text-faint);
+ cursor: pointer;
+ transition: 0.13s;
+
+ &:hover {
+ color: var(--text);
+ border-color: var(--border-strong);
+ background: var(--surface-3);
+ }
+
+ // Head actions are smaller and borderless — they live inside a 30px row.
+ &--bare {
+ width: 24px;
+ height: 24px;
+ border-color: transparent;
+ background: none;
+
+ &:hover { background: var(--surface-2); }
+ }
+}
+
+// Edit-mode banner ("drag to move, drag the corner to resize").
+.skw-hint {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 12px;
+ padding: 8px 12px;
+ border: 1px solid var(--accent-dim);
+ border-radius: 8px;
+ background: var(--accent-bg);
+ color: var(--accent-bright);
+ font-size: 11.5px;
+}
+
+// ------------------------------------------------------------
+// Grid host + ghost overlay
+// ------------------------------------------------------------
+.skw-grid {
+ position: relative;
+ width: 100%;
+
+ // Placed widgets are absolutely positioned by DashGrid from the cell
+ // maths (inline left/top/width/height). Both shapes are supported — a
+ // frame dropped straight into the host, or wrapped in an __item
+ // positioner — so the grid does not dictate the JSX's element count.
+ > .skw-frame,
+ &__item {
+ position: absolute;
+ // Animate settling into a new cell, but only when the pointer is up;
+ // during a drag the inline coords must track the cursor exactly.
+ transition: left 0.16s ease, top 0.16s ease, width 0.16s ease, height 0.16s ease;
+ }
+
+ &--dragging,
+ &.is-dragging {
+ cursor: grabbing;
+
+ > .skw-frame,
+ .skw-grid__item { transition: none; }
+ }
+
+ // Column/row guides, shown only while editing. Drawn as two 1px gradients
+ // rather than a repeating element so the overlay costs no DOM and no
+ // hit-testing. `--accent-bg` replaces the mock's rgba(109,124,255,.09):
+ // it is the same periwinkle wash, follows a runtime accent override, and
+ // it exists in the light theme.
+ &__ghost {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ border-radius: 8px;
+ background-image:
+ linear-gradient(to right, var(--accent-bg) 1px, transparent 1px),
+ linear-gradient(to bottom, var(--accent-bg) 1px, transparent 1px);
+ }
+
+ // Drop placeholder / "this board has no widgets yet" panel that fills the
+ // host itself (distinct from .skw-empty, which lives inside one widget).
+ &__empty {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ border: 1.5px dashed var(--border-strong);
+ border-radius: var(--radius);
+ color: var(--text-faint);
+ font-size: 13px;
+ }
+}
+
+// Page/host modifier: reserve the gutter the open inspector occupies so the
+// panel never covers the widget being configured.
+.skw-ins-open {
+ padding-right: $skw-ins-gutter;
+ transition: padding-right 0.18s ease;
+}
+
+// ------------------------------------------------------------
+// Widget frame — the chrome every widget type shares.
+// ------------------------------------------------------------
+.skw-frame {
+ // `relative` so __resize anchors to the frame even outside the grid
+ // (fullscreen, TV mode). Inside .skw-grid this is overridden to absolute.
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ overflow: hidden;
+
+ // Edit mode: the frame reads as movable, and the head becomes the handle.
+ &--edit,
+ &.is-edit,
+ &.is-editing {
+ border-color: var(--border-strong);
+
+ .skw-frame__head { cursor: grab; }
+ }
+
+ // The widget the inspector is currently bound to.
+ &--selected,
+ &.is-selected,
+ &.is-sel {
+ border-color: var(--accent-bright);
+ box-shadow: 0 0 0 3px var(--accent-bg);
+ }
+
+ &__head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-shrink: 0;
+ padding: 9px 11px 8px;
+ border-bottom: 1px solid var(--border-soft);
+ }
+
+ // Drag grip. Rotated because lucide's GripVertical reads as horizontal
+ // rails at this size; the quarter turn makes it a grab target.
+ &__grip {
+ display: grid;
+ place-items: center;
+ color: var(--text-ghost);
+ transform: rotate(90deg);
+ }
+
+ &__title {
+ flex: 1;
+ min-width: 0;
+ font-size: 12.5px;
+ font-weight: 550;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ // "Tailing" indicator on the logs widget head. Sits between the title and
+ // the actions, and unlike them it stays visible at rest: whether a stream
+ // is still live is state, not an affordance, so hover must not gate it.
+ // Shares skw-tick-pulse with the deploy step ribbon, run slower.
+ &__live {
+ width: 6px;
+ height: 6px;
+ flex-shrink: 0;
+ border-radius: 50%;
+ background: var(--green);
+ box-shadow: 0 0 6px var(--green);
+ animation: skw-tick-pulse 1.6s ease-in-out infinite;
+
+ // A paused / disconnected stream keeps the dot but drops the pulse,
+ // so "stopped" is never mistaken for "quiet".
+ &--off {
+ background: var(--text-ghost);
+ box-shadow: none;
+ animation: none;
+ }
+ }
+
+ // Head actions stay hidden until the widget is hovered or selected — a
+ // board of 12 widgets otherwise shows 36 buttons at rest.
+ &__actions {
+ display: flex;
+ align-items: center;
+ gap: 1px;
+ flex-shrink: 0;
+ opacity: 0;
+ transition: opacity 0.13s;
+ }
+
+ &:hover &__actions,
+ &--selected &__actions,
+ &.is-selected &__actions { opacity: 1; }
+
+ // Anchor for the overflow menu. The frame itself clips (overflow:hidden,
+ // for the rounded corners), so the menu cannot anchor to it — it anchors
+ // to this wrapper around the trigger button instead.
+ &__menu-wrap {
+ position: relative;
+ display: inline-flex;
+ flex-shrink: 0;
+ }
+
+ // Every renderer fills this box; it never scrolls itself, the body's own
+ // scroll region does.
+ &__body {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ }
+
+ // A menu anchored inside the head would be sliced off by the frame's own
+ // corner clip, so the clip is lifted for exactly as long as a menu is
+ // mounted. Safe to do: __body clips itself, and neither head nor body
+ // paints a background that could spill past the radius.
+ &:has(.skw-menu),
+ &--menu-open,
+ &.is-menu-open { overflow: visible; }
+
+ // Corner resize grip — two diagonal rules drawn with a gradient so the
+ // handle needs no extra markup and no icon payload.
+ &__resize {
+ position: absolute;
+ right: 2px;
+ bottom: 2px;
+ width: 16px;
+ height: 16px;
+ cursor: nwse-resize;
+ background: linear-gradient(
+ 135deg,
+ transparent 46%,
+ var(--border-strong) 46%,
+ var(--border-strong) 56%,
+ transparent 56%,
+ transparent 70%,
+ var(--border-strong) 70%,
+ var(--border-strong) 80%,
+ transparent 80%
+ );
+ }
+}
+
+// Widget overflow menu (configure / duplicate / fullscreen / remove).
+// A plain absolutely-positioned popover rather than a Radix dropdown: it is
+// anchored by .skw-frame__menu-wrap around its own trigger, so it needs no
+// portal and stays inside the frame it belongs to. Surface treatment matches
+// .ui-dropdown-content so the app has one menu look.
+.skw-menu {
+ position: absolute;
+ top: calc(100% + 5px);
+ // Right-anchored — the trigger is the last control in the head, and a
+ // 196px menu opening leftward would hang off a 3-column widget.
+ right: 0;
+ z-index: $z-tooltip;
+ width: 196px;
+ padding: 4px;
+ background: var(--surface-2);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ box-shadow: var(--shadow-md);
+
+ &__item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 7px 10px;
+ border: none;
+ border-radius: 6px;
+ background: none;
+ color: var(--text-dim);
+ font-family: inherit;
+ font-size: 12.5px;
+ text-align: left;
+ cursor: pointer;
+ transition: 0.12s;
+
+ &:hover {
+ background: var(--surface-3);
+ color: var(--text);
+ }
+
+ &[disabled] { opacity: 0.45; pointer-events: none; }
+
+ &--danger {
+ color: var(--red);
+ &:hover { background: var(--red-bg); color: var(--red); }
+ }
+ }
+
+ // Leading icon slot. Fixed box so the labels line up whether or not a
+ // given row has an icon.
+ &__ic {
+ display: grid;
+ place-items: center;
+ width: 16px;
+ height: 16px;
+ flex-shrink: 0;
+ color: var(--text-faint);
+ }
+
+ &__item:hover &__ic { color: var(--text-dim); }
+ &__item--danger:hover &__ic { color: var(--red); }
+
+ // Negative margins pull the rule to the panel edges, past the 4px pad.
+ &__sep {
+ height: 1px;
+ margin: 4px -4px;
+ background: var(--border-soft);
+ }
+}
+
+// Unknown widget type / no data. Deliberately plain: an unrecognised type is
+// a config problem, not an error, and the frame around it already names it.
+.skw-empty {
+ padding: 16px;
+ color: var(--text-faint);
+ font-size: 12.5px;
+}
+
+// ============================================================
+// WIDGET INTERNALS — one block per core type.
+// ============================================================
+
+// ---- stat: big number + delta + bottom-bled sparkline -------
+.skw-stat {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ padding: 12px 13px;
+
+ &__value {
+ color: var(--text);
+ font-size: 28px;
+ font-weight: 700;
+ line-height: 1.1;
+ letter-spacing: -0.01em;
+ // Even digit columns, and an ellipsis instead of a burst tile when a
+ // metric returns something unexpectedly long.
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &__meta {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ margin-top: 5px;
+ color: var(--text-faint);
+ font-size: 11px;
+ }
+
+ &__delta {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+
+ &--up,
+ .up { color: var(--green); }
+ &--down,
+ .dn { color: var(--red); }
+ }
+
+ // Negative side margins cancel the padding so the series bleeds to the
+ // frame edge rather than floating in a box (same trick as .sk-kpi__spark).
+ &__spark {
+ margin-top: auto;
+ margin-left: -2px;
+ margin-right: -2px;
+ line-height: 0;
+ }
+}
+
+// ---- timeseries: area chart + legend ------------------------
+.skw-ts {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ padding: 8px 10px 6px;
+
+ &__chart {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+
+ // The chart component ships a fixed height attribute; the widget's
+ // cell span decides the real one, so the flex box wins.
+ svg {
+ flex: 1;
+ height: 100% !important;
+ }
+ }
+}
+
+.skw-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ padding-top: 8px;
+ color: var(--text-faint);
+ font-family: var(--mono);
+ font-size: 10.5px;
+
+ &__item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+
+ b { color: var(--text); font-weight: 600; }
+ }
+
+ // Series swatch — colour comes inline from the metric catalog.
+ &__swatch,
+ .sw {
+ width: 8px;
+ height: 8px;
+ border-radius: 2px;
+ flex-shrink: 0;
+ }
+}
+
+// ---- gauge: half-circle radial ------------------------------
+.skw-gauge {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: 10px;
+
+ &__sub {
+ color: var(--text-faint);
+ font-size: 10.5px;
+ }
+}
+
+// ---- topn: ranked bars --------------------------------------
+.skw-topn {
+ display: flex;
+ flex-direction: column;
+ gap: 9px;
+ padding: 12px 13px;
+ overflow: auto;
+ @include custom-scrollbar;
+
+ // label | track | value. The 1fr/2fr split keeps the bar the dominant
+ // element while long names still truncate instead of squeezing it.
+ &__row {
+ display: grid;
+ grid-template-columns: 1fr 2fr auto;
+ align-items: center;
+ gap: 9px;
+ }
+
+ &__label {
+ font-size: 12px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &__track {
+ height: 7px;
+ border-radius: 4px;
+ background: var(--surface-3);
+ overflow: hidden;
+ }
+
+ // Fill width + colour are the only inline values here.
+ &__fill,
+ &__track i {
+ display: block;
+ height: 100%;
+ border-radius: 4px;
+ transition: width 0.4s ease;
+ }
+
+ &__value {
+ color: var(--text-dim);
+ font-size: 11px;
+ }
+}
+
+// ---- table: apps / servers / containers / deploys -----------
+.skw-table-wrap {
+ flex: 1;
+ overflow: auto;
+ @include custom-scrollbar;
+}
+
+.skw-table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 12px;
+
+ // Sticky head so a widget only 3 rows tall still shows its columns.
+ th {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ padding: 7px 12px;
+ border-bottom: 1px solid var(--border-soft);
+ background: var(--surface-2);
+ color: var(--text-ghost);
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.05em;
+ text-align: left;
+ text-transform: uppercase;
+ }
+
+ td {
+ max-width: 180px;
+ padding: 7px 12px;
+ border-bottom: 1px solid var(--border-soft);
+ color: var(--text-dim);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+
+ &.nm { color: var(--text); font-weight: 500; }
+ &.mono { font-family: var(--mono); font-size: 11px; }
+ }
+
+ tbody tr {
+ cursor: pointer;
+ transition: background 0.1s;
+
+ &:hover { background: var(--surface-2); }
+ }
+}
+
+// Mono status chip used by the table and list widgets. Kept local rather than
+// @extend-ing %sk-state: this one is lowercase and sized for a 12px row.
+.skw-pill {
+ padding: 2px 7px;
+ border-radius: 5px;
+ background: var(--surface-3);
+ color: var(--text-faint);
+ font-family: var(--mono);
+ font-size: 10px;
+
+ &--ok,
+ &.ok { color: var(--green); background: var(--green-bg); }
+ &--bad,
+ &.bad { color: var(--red); background: var(--red-bg); }
+ &--warn,
+ &.warn { color: var(--amber); background: var(--amber-bg); }
+}
+
+// ---- logs: tailing lines ------------------------------------
+.skw-logs {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+
+ &__bar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-shrink: 0;
+ padding: 6px 11px;
+ border-bottom: 1px solid var(--border-soft);
+ color: var(--text-faint);
+ font-size: 10.5px;
+
+ .lv-err { color: var(--red); }
+ .lv-warn { color: var(--amber); }
+ }
+
+ // `--bg-code` replaces the mock's hardcoded #0a0c11. It is the app's
+ // terminal/code surface token and is defined in both themes, so the log
+ // pane stays an inset "console" without being a black slab on light.
+ &__body {
+ flex: 1;
+ overflow: auto;
+ padding: 6px 0;
+ background: var(--bg-code);
+ font-family: var(--mono);
+ font-size: 11px;
+ line-height: 1.65;
+ @include custom-scrollbar;
+ }
+
+ &__line {
+ display: flex;
+ gap: 9px;
+ padding: 0 11px;
+ color: var(--text-dim);
+ white-space: pre-wrap;
+ word-break: break-all;
+
+ // Timestamp gutter.
+ .t {
+ flex-shrink: 0;
+ color: var(--text-ghost);
+ }
+
+ &.lv-dim { color: var(--text-faint); }
+ &.lv-warn { color: var(--amber); }
+ &.lv-err {
+ color: var(--red);
+ // Compile-time rgba of the raw hex: the semantic reds are
+ // theme-independent, and --red-bg (0.12) is too loud behind a
+ // whole line of text.
+ background: rgba($danger-raw, 0.06);
+ }
+ }
+}
+
+// ---- shared scroll list (deploys / alerts / feed) -----------
+.skw-list {
+ flex: 1;
+ overflow: auto;
+ padding: 6px 0;
+ @include custom-scrollbar;
+}
+
+// ---- deploys: recent deployment jobs ------------------------
+.skw-dep {
+ padding: 9px 13px;
+ border-bottom: 1px solid var(--border-soft);
+ cursor: pointer;
+ transition: background 0.12s;
+
+ &:hover { background: var(--surface-2); }
+
+ &__top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ }
+
+ &__name { font-size: 12.5px; font-weight: 550; }
+ &__state { font-size: 10.5px; }
+
+ // Step ribbon: one segment per pipeline stage, so progress reads at a
+ // glance without a percentage.
+ &__steps {
+ display: flex;
+ gap: 3px;
+ margin: 7px 0 5px;
+
+ .st {
+ flex: 1;
+ height: 4px;
+ border-radius: 2px;
+ background: var(--surface-3);
+
+ &.done { background: var(--green); }
+ &.failed { background: var(--red); }
+ &.running {
+ background: var(--amber);
+ animation: skw-tick-pulse 1.2s ease-in-out infinite;
+ }
+ }
+ }
+
+ &__meta {
+ color: var(--text-ghost);
+ font-size: 10.5px;
+ }
+}
+
+// ---- alerts: open monitoring alerts -------------------------
+.skw-alert {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 13px;
+ border-bottom: 1px solid var(--border-soft);
+ cursor: pointer;
+ transition: background 0.12s;
+
+ &:hover { background: var(--surface-2); }
+
+ // Severity dot — colour set inline from the alert's severity.
+ &__sev {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ flex-shrink: 0;
+ }
+
+ &__title {
+ font-size: 12.5px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &__meta {
+ margin-top: 2px;
+ color: var(--text-faint);
+ font-size: 10.5px;
+ }
+}
+
+// ---- status: monitor up/down matrix -------------------------
+.skw-status {
+ flex: 1;
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(104px, 1fr));
+ align-content: start;
+ gap: 8px;
+ padding: 12px 13px;
+ overflow: auto;
+ @include custom-scrollbar;
+
+ &__cell {
+ padding: 9px 10px;
+ border: 1px solid var(--border-soft);
+ border-radius: 8px;
+ background: var(--surface-2);
+ cursor: pointer;
+ transition: 0.12s;
+
+ &:hover { border-color: var(--border-strong); }
+ }
+
+ &__dot {
+ display: block;
+ width: 7px;
+ height: 7px;
+ margin-bottom: 6px;
+ border-radius: 50%;
+ }
+
+ &__name {
+ font-size: 11.5px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &__meta {
+ margin-top: 2px;
+ color: var(--text-faint);
+ font-size: 10px;
+ }
+}
+
+// ---- actions: shortcut buttons ------------------------------
+.skw-actions {
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ padding: 12px 13px;
+ overflow: auto;
+ @include custom-scrollbar;
+}
+
+// ---- specs: key/value host details --------------------------
+.skw-kv {
+ padding: 4px 13px 8px;
+ overflow: auto;
+ @include custom-scrollbar;
+
+ // Own rows…
+ &__row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ min-height: 0;
+ padding: 6px 0;
+ border-top: 1px solid var(--border-soft);
+
+ &:first-child { border-top: none; }
+ }
+ &__k { color: var(--text-faint); font-family: var(--mono); font-size: 11.5px; }
+ &__v { color: var(--text); font-family: var(--mono); font-size: 12px; text-align: right; overflow-wrap: anywhere; }
+
+ // …and a density override when the renderer reuses the shared
+ // .sk-info-row primitive instead, which is spaced for a drawer.
+ .sk-info-row {
+ padding: 6px 0;
+ min-height: 0;
+
+ .k { font-size: 11.5px; }
+ }
+}
+
+// ---- note: markdown-ish text --------------------------------
+.skw-note {
+ padding: 13px;
+ overflow: auto;
+ color: var(--text-dim);
+ font-size: 12.5px;
+ line-height: 1.6;
+ @include custom-scrollbar;
+
+ code {
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: var(--surface-3);
+ font-family: var(--mono);
+ font-size: 11.5px;
+ }
+}
+
+// ============================================================
+// WIDGET LIBRARY — "add a widget" drawer, thumbnail-first.
+// ============================================================
+// A name and a description do not tell you what a widget looks like, so each
+// card leads with a miniature SVG of the real thing.
+.skw-lib {
+ // The library owns its own padding rather than leaning on the drawer's:
+ // .sk-drawer__body deliberately has none (it is the scroll region), and
+ // the sticky filter bar below cancels this padding with negative margins
+ // to span the panel edge to edge. Both numbers therefore live here.
+ padding: 14px 16px 18px;
+
+ // Search + category chips. The library renders inside the shared
+ // ds/Drawer, whose .sk-drawer__body owns the scroll — so this bar has to
+ // stick to the top of THAT scroller or the search box leaves the screen
+ // as soon as you scroll to the widget you were searching for. Sticky
+ // demands an opaque background (it scrolls over the cards) and the
+ // negative top/side margins let it span the drawer's padding edge to edge.
+ &__filters {
+ position: sticky;
+ top: 0;
+ z-index: 2;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ margin: -14px -16px 14px;
+ padding: 14px 16px 12px;
+ background: var(--surface);
+ border-bottom: 1px solid var(--border-soft);
+ }
+
+ &__search {
+ // The shared .sk-searchfield caps itself at 420px and sits inline;
+ // in a 380px drawer it should simply fill the row.
+ display: flex;
+
+ .sk-searchfield {
+ flex: 1 1 auto;
+ max-width: none;
+ min-width: 0;
+ }
+ }
+
+ &__chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+
+ &__chip {
+ padding: 4px 11px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: var(--surface-2);
+ color: var(--text-dim);
+ font-family: inherit;
+ font-size: 11.5px;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: 0.13s;
+
+ &:hover {
+ color: var(--text);
+ border-color: var(--border-strong);
+ }
+
+ &--on,
+ &.is-on {
+ color: var(--accent-bright);
+ background: var(--accent-bg);
+ border-color: var(--accent-dim);
+ font-weight: 550;
+ }
+ }
+
+ // "No widget matches that search."
+ &__empty {
+ padding: 40px 16px;
+ color: var(--text-faint);
+ font-size: 12.5px;
+ text-align: center;
+ }
+
+ &__grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(196px, 1fr));
+ gap: 12px;
+ }
+
+ &__card {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ background: var(--surface-2);
+ cursor: pointer;
+ overflow: hidden;
+ transition: 0.14s;
+
+ &:hover {
+ border-color: var(--accent-dim);
+ background: var(--surface-3);
+ transform: translateY(-1px);
+ }
+ }
+
+ // `--bg-sidebar` replaces the mock's #0d0f14: it is within a hair of that
+ // value in dark, and in light it is one step darker than the card, so the
+ // preview still reads as an inset well instead of a black rectangle.
+ &__thumb {
+ position: relative;
+ height: 88px;
+ display: flex;
+ align-items: stretch;
+ padding: 6px;
+ border-bottom: 1px solid var(--border-soft);
+ background: var(--bg-sidebar);
+ }
+
+ &__thumb-svg {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+
+ // Hover scrim over the thumbnail. Built from --surface at full opacity and
+ // faded in as a whole, rather than the mock's rgba(13,15,20,.74) + #fff
+ // text — that pairing is a black slab with white text on a light board.
+ &__add {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ background: var(--surface);
+ color: var(--accent-bright);
+ font-size: 12px;
+ font-weight: 550;
+ opacity: 0;
+ transition: opacity 0.14s;
+ }
+
+ &__card:hover &__add { opacity: 0.94; }
+
+ &__meta { padding: 10px 11px 12px; }
+
+ &__icon {
+ display: inline-grid;
+ place-items: center;
+ flex-shrink: 0;
+ color: var(--accent-bright);
+ }
+
+ &__name {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12.5px;
+ font-weight: 550;
+ }
+
+ // Default cell span ("3×2"), pushed to the right edge of the name row.
+ &__size {
+ margin-left: auto;
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: var(--surface-3);
+ color: var(--text-ghost);
+ font-family: var(--mono);
+ font-size: 9.5px;
+ }
+
+ &__desc {
+ margin-top: 5px;
+ color: var(--text-faint);
+ font-size: 11px;
+ line-height: 1.45;
+ }
+}
+
+// ============================================================
+// INSPECTOR — right-hand config panel for the selected widget.
+// ============================================================
+// Fixed rather than a modal: you change a setting and watch the live widget
+// react beside it, which is why the host reserves .skw-ins-open's gutter.
+.skw-ins {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ z-index: $skw-z-inspector;
+ width: $skw-ins-w;
+ display: flex;
+ flex-direction: column;
+ background: var(--surface);
+ border-left: 1px solid var(--border-strong);
+ box-shadow: var(--shadow-lg);
+ animation: skw-ins-in 0.18s cubic-bezier(0.2, 0.7, 0.3, 1);
+
+ &__head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-shrink: 0;
+ padding: 14px;
+ border-bottom: 1px solid var(--border-soft);
+ }
+
+ // Widget-type glyph in the panel header — same 32px tinted box as
+ // .sk-kpi__icon / .sk-drawer__ico, so the inspector reads as a drawer.
+ &__ic {
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ flex-shrink: 0;
+ border-radius: 9px;
+ background: var(--accent-bg);
+ color: var(--accent-bright);
+ }
+
+ &__title { flex: 1; min-width: 0; font-size: 13.5px; font-weight: 600; }
+
+ // Type name / instance id under the title. Mono, because it is an
+ // identifier rather than prose.
+ &__sub {
+ margin-top: 1px;
+ color: var(--text-faint);
+ font-family: var(--mono);
+ font-size: 11px;
+ }
+
+ &__body {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ padding: 16px 16px 26px;
+ @include custom-scrollbar;
+ }
+
+ &__row {
+ margin-bottom: 15px;
+
+ > label {
+ display: block;
+ margin-bottom: 7px;
+ color: var(--text-ghost);
+ font-size: 11px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ }
+
+ // Segmented controls fill the panel width instead of hugging content;
+ // a 340px column has no room for a control that floats left.
+ .sk-seg {
+ display: flex;
+ width: 100%;
+
+ &__btn { flex: 1; justify-content: center; }
+ }
+ }
+
+ &__select {
+ width: 100%;
+ padding: 7px 24px 7px 9px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--surface-2);
+ color: var(--text);
+ font-family: inherit;
+ font-size: 12.5px;
+ cursor: pointer;
+
+ &:focus {
+ outline: none;
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px var(--accent-bg);
+ }
+ }
+
+ // Single-line text input (widget title, unit, link target). Matched to
+ // __select's metrics so a row of mixed controls sits on one baseline —
+ // the app's global .form-input is sized for a full-width page form and
+ // reads oversized in a 340px column.
+ &__field {
+ width: 100%;
+ padding: 7px 9px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--surface-2);
+ color: var(--text);
+ font-family: inherit;
+ font-size: 12.5px;
+ transition: border-color 0.14s, box-shadow 0.14s;
+
+ &::placeholder { color: var(--text-ghost); }
+
+ &:focus {
+ outline: none;
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px var(--accent-bg);
+ }
+
+ // Numeric fields (thresholds, top-N) read as values, not prose.
+ &--mono {
+ font-family: var(--mono);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ }
+ }
+
+ // Free text: note body, custom query. Resizable vertically only — a
+ // horizontal drag would push it out of a fixed-width panel.
+ &__textarea {
+ @extend .skw-ins__field;
+
+ min-height: 96px;
+ line-height: 1.55;
+ resize: vertical;
+ }
+
+ // Leading unit/sigil glued to a field ("$", "%", "≥"). Rendered as a
+ // sibling inside __pair rather than inside the input, so it never eats a
+ // click meant for the text cursor.
+ &__prefix {
+ flex-shrink: 0;
+ padding: 0 2px;
+ color: var(--text-faint);
+ font-family: var(--mono);
+ font-size: 11.5px;
+ }
+
+ // Two controls sharing one row (amber + red thresholds, min + max).
+ &__pair {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+
+ > .skw-ins__field,
+ > .skw-ins__select { flex: 1; min-width: 0; }
+ }
+
+ // Explanatory line under a control. Deliberately quieter than the label
+ // above it, so a row still reads label → control → aside.
+ &__hint {
+ display: block;
+ margin-top: 6px;
+ color: var(--text-faint);
+ font-size: 11px;
+ line-height: 1.45;
+
+ code {
+ padding: 1px 4px;
+ border-radius: 4px;
+ background: var(--surface-3);
+ font-family: var(--mono);
+ font-size: 10.5px;
+ }
+ }
+
+ // "Add series" / "Add threshold" — a full-width dashed slot rather than a
+ // button, so it reads as the next empty row of the list above it.
+ &__add {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ width: 100%;
+ margin-top: 7px;
+ padding: 6px 10px;
+ border: 1px dashed var(--border-strong);
+ border-radius: 7px;
+ background: none;
+ color: var(--text-faint);
+ font-family: inherit;
+ font-size: 11.5px;
+ cursor: pointer;
+ transition: 0.13s;
+
+ &:hover {
+ border-color: var(--accent-dim);
+ color: var(--accent-bright);
+ background: var(--accent-bg);
+ }
+ }
+
+ // Row delete — the 24px third column of __ser. Stays neutral until
+ // hovered; a column of red X's would shout over the settings themselves.
+ &__remove {
+ width: 24px;
+ height: 24px;
+ display: grid;
+ place-items: center;
+ border: none;
+ border-radius: 6px;
+ background: none;
+ color: var(--text-ghost);
+ cursor: pointer;
+ transition: 0.12s;
+
+ &:hover { color: var(--red); background: var(--red-bg); }
+ }
+
+ // Series editor: metric | aggregation | remove.
+ &__series {
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ }
+
+ &__ser {
+ display: grid;
+ grid-template-columns: 1fr 1fr 24px;
+ align-items: center;
+ gap: 5px;
+
+ select,
+ .skw-ins__select {
+ padding: 6px 22px 6px 8px;
+ font-size: 11.5px;
+ }
+ }
+
+ // Column / resource pickers. Capped and scrollable so a long list cannot
+ // push the rest of the form out of reach.
+ &__checks {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ max-height: 190px;
+ overflow: auto;
+ @include custom-scrollbar;
+ }
+
+ &__check {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 3px 2px;
+ color: var(--text-dim);
+ font-size: 12.5px;
+ cursor: pointer;
+
+ &:hover { color: var(--text); }
+
+ input[type='checkbox'] {
+ width: 15px;
+ height: 15px;
+ flex-shrink: 0;
+ accent-color: var(--accent);
+ cursor: pointer;
+ }
+ }
+
+ &__foot {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-shrink: 0;
+ padding: 12px 14px;
+ border-top: 1px solid var(--border-soft);
+ }
+}
+
+// Numeric stepper (widget span, top-N count, refresh seconds).
+.skw-stepper {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding: 2px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--surface-2);
+
+ button {
+ width: 26px;
+ height: 26px;
+ display: grid;
+ place-items: center;
+ border: none;
+ border-radius: 6px;
+ background: none;
+ color: var(--text-faint);
+ cursor: pointer;
+ transition: 0.12s;
+
+ &:hover { color: #fff; background: var(--accent); }
+ &:disabled { opacity: 0.4; cursor: default; background: none; color: var(--text-ghost); }
+ }
+
+ span {
+ min-width: 58px;
+ padding: 0 8px;
+ color: var(--text-dim);
+ font-size: 11.5px;
+ text-align: center;
+ }
+}
+
+// ============================================================
+// FULLSCREEN WIDGET + TV MODE
+// ============================================================
+// One widget, blown up, still driven by the same renderer — so "expand" costs
+// no second implementation.
+.skw-full {
+ position: fixed;
+ top: 5vh;
+ left: 50%;
+ z-index: $skw-z-fullscreen;
+ width: min(1280px, 92vw);
+ height: min(760px, 86vh);
+ transform: translateX(-50%);
+ display: flex;
+ flex-direction: column;
+ background: var(--surface);
+ border: 1px solid var(--border-strong);
+ border-radius: var(--radius-lg);
+ box-shadow: var(--shadow-lg);
+ overflow: hidden;
+ animation: skw-modal-in 0.18s cubic-bezier(0.2, 0.7, 0.3, 1);
+
+ // Backdrop behind the expanded widget. Same treatment as .modal-overlay /
+ // .ui-dialog-overlay so a fullscreened widget dims the page exactly like
+ // every other modal surface — a neutral scrim, not a themed one, because
+ // it must read as "the board is still there, just behind this".
+ // Sits one layer under .skw-full and above everything the board draws.
+ &__scrim {
+ position: fixed;
+ inset: 0;
+ z-index: $skw-z-fullscreen - 1;
+ background: rgba(0, 0, 0, 0.7);
+ backdrop-filter: blur(4px);
+ animation: skw-scrim-in 0.18s ease;
+ }
+
+ // The frame inside gets a roomier head and always-visible actions: there
+ // is no hover-to-reveal affordance when the widget IS the page.
+ .skw-frame {
+ position: static;
+ flex: 1;
+ min-height: 0;
+ border: none;
+ border-radius: 0;
+ background: none;
+ }
+ .skw-frame__head { padding: 13px 16px; }
+ .skw-frame__actions { opacity: 1; }
+ .skw-frame__resize { display: none; }
+}
+
+// TV mode: the board on a wall display. `--bg-body` replaces the mock's
+// var(--bg,#0a0c11) — same intent (the app's page background), real token.
+.skw-tv {
+ position: fixed;
+ inset: 0;
+ z-index: $skw-z-tv;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ background: var(--bg-body);
+
+ &__bar {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ flex-shrink: 0;
+ padding: 12px 20px;
+ border-bottom: 1px solid var(--border-soft);
+ }
+
+ &__body {
+ flex: 1;
+ overflow: auto;
+ padding: 18px 20px;
+ @include custom-scrollbar;
+ }
+}
+
+// ============================================================
+// EMPTY BOARD — template picker
+// ============================================================
+// A blank 12-column grid is not a starting point, so a new board offers
+// ready-made layouts before it offers an "add widget" button.
+.skw-empty-board {
+ padding: 70px 20px;
+ border: 1.5px dashed var(--border-strong);
+ border-radius: var(--radius-lg);
+ text-align: center;
+
+ &__title { margin: 0 0 6px; color: var(--text); font-size: 15px; font-weight: 600; }
+ &__desc { margin: 0 auto 24px; max-width: 460px; color: var(--text-dim); font-size: 13px; }
+}
+
+.skw-tpl {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
+ gap: 12px;
+ max-width: 900px;
+ margin: 0 auto;
+ text-align: left;
+
+ &__card {
+ padding: 15px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ background: var(--surface-2);
+ cursor: pointer;
+ transition: 0.14s;
+
+ &:hover {
+ border-color: var(--accent-dim);
+ background: var(--surface-3);
+ transform: translateY(-1px);
+ }
+ }
+
+ &__icon {
+ width: 34px;
+ height: 34px;
+ margin-bottom: 11px;
+ display: grid;
+ place-items: center;
+ border-radius: 9px;
+ background: var(--surface-3);
+ color: var(--accent-bright);
+ }
+
+ &__name { font-size: 13.5px; font-weight: 600; }
+ &__desc { margin-top: 4px; color: var(--text-faint); font-size: 11.5px; line-height: 1.5; }
+}
+
+// ============================================================
+// ANIMATIONS (prefixed — the mock's insIn/modalIn/tickPulse are global)
+// ============================================================
+@keyframes skw-ins-in {
+ from { transform: translateX(18px); opacity: 0; }
+ to { transform: none; opacity: 1; }
+}
+
+@keyframes skw-modal-in {
+ from { transform: translateX(-50%) translateY(10px); opacity: 0; }
+ to { transform: translateX(-50%); opacity: 1; }
+}
+
+@keyframes skw-tick-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.4; }
+}
+
+@keyframes skw-scrim-in {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+
+// ============================================================
+// RESPONSIVE
+// ============================================================
+// The inspector's reserved gutter is 352px. Below $breakpoint-xl the content
+// column is already narrow enough that giving a third of it to the panel
+// leaves the board unreadable, so the panel starts overlaying instead.
+@include respond-to($breakpoint-xl) {
+ .skw-ins-open { padding-right: 0; }
+}
+
+@include respond-to($breakpoint-lg) {
+ // Board controls wrap under the tabs rather than fighting them for width.
+ .skw-bar__ctl {
+ margin-left: 0;
+ width: 100%;
+ }
+
+ .skw-lib__grid { grid-template-columns: repeat(auto-fill, minmax(168px, 1fr)); }
+}
+
+@include respond-to($breakpoint-md) {
+ // Below tablet the 12-column cell maths produces columns too narrow to
+ // read anything in, so absolute placement is dropped and widgets stack in
+ // document order at a fixed height. DashGrid writes left/top/width/height
+ // as inline styles, so these overrides need !important — the collapse
+ // point lives here, in CSS, rather than being duplicated in JS.
+ .skw-grid {
+ height: auto !important;
+ min-height: 0 !important;
+ display: flex;
+ flex-direction: column;
+ gap: $skw-grid-gap;
+
+ &__ghost { display: none; }
+
+ > .skw-frame,
+ &__item {
+ position: relative !important;
+ left: auto !important;
+ top: auto !important;
+ width: 100% !important;
+ height: $skw-stack-row-h !important;
+ transition: none;
+ }
+ }
+
+ // Dragging and resizing are pointer-precision gestures; neither survives
+ // a stacked column, and both are meaningless once placement is implicit.
+ .skw-frame__resize,
+ .skw-frame__grip { display: none; }
+
+ .skw-frame--edit .skw-frame__head,
+ .skw-frame.is-edit .skw-frame__head { cursor: default; }
+
+ // Inspector becomes a full-width sheet.
+ .skw-ins {
+ width: 100vw;
+ border-left: none;
+ }
+
+ .skw-full {
+ top: 0;
+ width: 100vw;
+ height: 100vh;
+ border: none;
+ border-radius: 0;
+ }
+
+ .skw-empty-board { padding: 40px 16px; }
+ .skw-tpl { grid-template-columns: 1fr; }
+}
diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scss
index a876da26..cfe2fb7c 100644
--- a/frontend/src/styles/main.scss
+++ b/frontend/src/styles/main.scss
@@ -71,6 +71,7 @@
@import 'components/_ui';
@import 'components/_staging-banner';
@import 'components/_design-system'; // redesign shared primitives (sk-* namespace)
+@import 'components/_dashboard-widgets'; // configurable dashboard grid (skw-* namespace)
@import 'components/_system-notices';
@import 'components/container-status';
@import 'components/api-key-scopes';