feat(dashboard): phase C richer panels — host time-series graph + cpu sparklines
CI / lint (push) Successful in 3s
CI / unit (push) Successful in 7s
CI / integration (push) Successful in 2m25s
CI / publish (push) Successful in 56s

Milestone 72 phase C — bring the host-view graphs onto the dashboard:
- host_resource_history widget reworked into a real host-view chart: epoch-ms
  linear axis (no Chart.js date adapter), themed like the host-detail charts,
  maintainAspectRatio:false so it fills the resized panel, unique canvas per
  widget instance (wid), and empty states ("pick a host" / "no metrics yet").
  Was previously unusable — it had a broken time axis and no way to choose a host.
- Add a "host" param type: the edit form renders a live dropdown of hosts
  (dashboard routes now pass the host list to the editor); the chosen host_id is
  stored in config and fed to the widget.
- Hosts-overview widget gains a per-row CPU sparkline (last hour) via the shared
  sparkline_svg helper — the host-view at-a-glance trend, on the main widget.

Charts/sparklines render only in the browser, so CI can't exercise them — needs
an operator visual check.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-17 15:18:50 -04:00
parent 525f6eedbd
commit 988c13d51f
7 changed files with 151 additions and 59 deletions
+35 -25
View File
@@ -387,34 +387,44 @@ async def widget_table():
@host_agent_bp.get("/widget/history")
async def widget_history():
host_id = request.args.get("host_id", "")
hours = int(request.args.get("hours", "6"))
try:
hours = max(1, min(168, int(request.args.get("hours", "6"))))
except ValueError:
hours = 6
# wid (the dashboard widget row id) keeps the <canvas> id unique when several
# history widgets share a page; fall back to the host id.
wid = request.args.get("wid", "") or host_id
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
async with current_app.db_sessionmaker() as session:
host = (await session.execute(
select(Host).where(Host.id == host_id))).scalar_one_or_none()
if host is None:
return _error(404, "not_found")
points = (await session.execute(
select(PluginMetric).where(
PluginMetric.source_module == SOURCE_MODULE,
PluginMetric.recorded_at >= cutoff,
or_(
and_(PluginMetric.resource_name == host.name,
PluginMetric.metric_name.in_(("cpu_pct", "mem_used_pct"))),
and_(PluginMetric.resource_name == host.name + ":/",
PluginMetric.metric_name == "disk_used_pct"),
),
).order_by(PluginMetric.recorded_at)
)).scalars().all()
series: dict[str, list[list]] = {"cpu_pct": [], "mem_used_pct": [], "disk_root": []}
host = None
if host_id:
async with current_app.db_sessionmaker() as session:
host = (await session.execute(
select(Host).where(Host.id == host_id))).scalar_one_or_none()
if host is not None:
points = (await session.execute(
select(PluginMetric).where(
PluginMetric.source_module == SOURCE_MODULE,
PluginMetric.recorded_at >= cutoff,
or_(
and_(PluginMetric.resource_name == host.name,
PluginMetric.metric_name.in_(("cpu_pct", "mem_used_pct"))),
and_(PluginMetric.resource_name == host.name + ":/",
PluginMetric.metric_name == "disk_used_pct"),
),
).order_by(PluginMetric.recorded_at)
)).scalars().all()
# Disk = root (/), consistent with the host panel — not "worst".
# Epoch-ms x values let the chart use a plain linear axis (no
# Chart.js date adapter needed), matching the host-detail charts.
for p in points:
key = "disk_root" if p.resource_name != host.name else p.metric_name
series[key].append([int(p.recorded_at.timestamp() * 1000), round(p.value, 2)])
# Disk = root (/), consistent with the host panel — not the opaque "worst".
series: dict[str, list[dict]] = {"cpu_pct": [], "mem_used_pct": [], "disk_root": []}
for p in points:
key = "disk_root" if p.resource_name != host.name else p.metric_name
series[key].append({"t": p.recorded_at.isoformat(), "v": p.value})
return await render_template("widget_history.html", host=host, series=series, hours=hours)
return await render_template(
"widget_history.html", host=host, series=series, hours=hours, wid=wid,
)
# Host-level metrics charted on the detail page (sub-resources are shown as
@@ -1,24 +1,53 @@
<div class="widget-history">
<h3>{{ host.name }} — last {{ hours }}h</h3>
<canvas id="host-agent-chart-{{ host.id }}" width="600" height="200"></canvas>
<script>
(function() {
const ctx = document.getElementById("host-agent-chart-{{ host.id }}").getContext("2d");
const series = {{ series|tojson }};
new Chart(ctx, {
type: "line",
data: {
datasets: [
{ label: "CPU %", data: series.cpu_pct.map(p => ({x: p.t, y: p.v})) },
{ label: "Mem %", data: series.mem_used_pct.map(p => ({x: p.t, y: p.v})) },
{ label: "Disk / %", data: series.disk_root.map(p => ({x: p.t, y: p.v})) },
],
},
options: {
responsive: true,
scales: { x: { type: "time" }, y: { min: 0, max: 100 } },
},
});
})();
</script>
{# host_agent history-graph widget — the host-view utilization chart, embedded
on a dashboard. Fills the (resizable) panel; epoch-ms linear axis so no
Chart.js date adapter is needed. #}
{% set has_data = host and (series.cpu_pct or series.mem_used_pct or series.disk_root) %}
{% if not host %}
<div style="color:var(--text-muted);font-size:0.85rem;padding:0.75rem 0;">
No host selected. <strong>Edit</strong> this dashboard and pick a host for this graph.
</div>
{% elif not has_data %}
<div style="color:var(--text-muted);font-size:0.85rem;padding:0.75rem 0;">
No agent metrics for <strong>{{ host.name }}</strong> in the last {{ hours }}h yet.
</div>
{% else %}
<div style="height:100%;min-height:180px;position:relative;">
<canvas id="host-hist-{{ wid }}"></canvas>
</div>
<script>
(function () {
var el = document.getElementById("host-hist-{{ wid }}");
if (!el) return;
var series = {{ series|tojson }};
var fmtTime = function (v) {
var d = new Date(v);
return ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
};
var ds = [
{ key: "cpu_pct", label: "CPU %", color: "#c8a840" },
{ key: "mem_used_pct", label: "Mem %", color: "#4aa86a" },
{ key: "disk_root", label: "Disk / %", color: "#c87840" },
];
new Chart(el.getContext("2d"), {
type: "line",
data: { datasets: ds.map(function (d) {
return {
label: d.label,
data: (series[d.key] || []).map(function (p) { return { x: p[0], y: p[1] }; }),
borderColor: d.color, backgroundColor: d.color, borderWidth: 1.5, tension: 0.25,
};
}) },
options: {
responsive: true, maintainAspectRatio: false,
interaction: { mode: "index", intersect: false },
elements: { point: { radius: 0 } },
scales: {
x: { type: "linear", ticks: { callback: function (v) { return fmtTime(v); }, maxTicksLimit: 6, color: "#8a8a92", font: { size: 10 } }, grid: { color: "#30303a" } },
y: { beginAtZero: true, max: 100, ticks: { color: "#8a8a92", font: { size: 10 } }, grid: { color: "#30303a" } },
},
plugins: { legend: { labels: { color: "#b8b8b0", boxWidth: 10, font: { size: 11 } } } },
},
});
})();
</script>
{% endif %}
+10 -3
View File
@@ -279,13 +279,20 @@ WIDGET_REGISTRY: dict[str, dict] = {
},
"host_resource_history": {
"key": "host_resource_history",
"label": "Host Agent — History",
"description": "CPU/memory/disk history for one host",
"label": "Host Agent — History Graph",
"description": "CPU / memory / disk time-series graph for one host (the host-view chart, on your dashboard)",
"hx_url": "/plugins/host_agent/widget/history",
"detail_url": "/plugins/host_agent/fleet/",
"detail_url": "/hosts/",
"plugin": "host_agent",
"poll": True,
"params": [
# type "host" → the edit form renders a live dropdown of hosts.
{
"key": "host_id",
"label": "Host",
"type": "host",
"default": "",
},
{
"key": "hours",
"label": "Time range",
+8 -6
View File
@@ -173,7 +173,7 @@ async def _get_panels_data(db, dashboard_id: int) -> tuple:
result = await db.execute(select(Dashboard).where(Dashboard.id == dashboard_id))
dash = result.scalar_one_or_none()
if dash is None:
return None, [], []
return None, [], [], []
widgets = await _get_widgets(db, dashboard_id)
plugins_cfg = current_app.config.get("PLUGINS", {})
available = get_available_widgets(plugins_cfg)
@@ -182,15 +182,17 @@ async def _get_panels_data(db, dashboard_id: int) -> tuple:
{"db": w, "defn": WIDGET_REGISTRY[w.widget_key], "title": w.title or WIDGET_REGISTRY[w.widget_key]["label"]}
for w in widgets if w.widget_key in WIDGET_REGISTRY
]
return dash, resolved, available
# Hosts feed the "host" param dropdown (e.g. the history-graph widget).
hosts = list((await db.execute(select(Host).order_by(Host.name))).scalars())
return dash, resolved, available, hosts
async def _panels_response(dashboard_id: int):
async with current_app.db_sessionmaker() as db:
dash, resolved, addable = await _get_panels_data(db, dashboard_id)
dash, resolved, addable, hosts = await _get_panels_data(db, dashboard_id)
return await render_template(
"dashboard/_edit_panels.html",
dashboard=dash, widgets=resolved, addable=addable,
dashboard=dash, widgets=resolved, addable=addable, hosts=hosts,
)
@@ -369,12 +371,12 @@ async def edit(dash_id: int):
user_id = current_user_id()
user_role = session.get("user_role", "viewer")
async with current_app.db_sessionmaker() as db:
dash, resolved, addable = await _get_panels_data(db, dash_id)
dash, resolved, addable, hosts = await _get_panels_data(db, dash_id)
if dash is None or not _can_edit(dash, user_id, user_role):
abort(403)
return await render_template(
"dashboard/edit.html",
dashboard=dash, widgets=resolved, addable=addable,
dashboard=dash, widgets=resolved, addable=addable, hosts=hosts,
)
+34 -2
View File
@@ -153,6 +153,36 @@ async def _agent_overview_by_host(db, host_names: list[str]) -> dict[str, dict]:
return out
async def _agent_cpu_sparks_by_host(db, host_names: list[str], hours: int = 1) -> dict[str, str]:
"""{host_name: inline-SVG cpu sparkline} over the last `hours` (core-safe).
A tiny at-a-glance trend in each row — the host-view sparkline, on the widget.
"""
from steward.models.metrics import PluginMetric
from steward.core.status import sparkline_svg
if not host_names:
return {}
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
rows = (await db.execute(
select(PluginMetric.resource_name, PluginMetric.value, PluginMetric.recorded_at)
.where(
PluginMetric.source_module == "host_agent",
PluginMetric.metric_name == "cpu_pct",
PluginMetric.resource_name.in_(host_names),
PluginMetric.recorded_at >= cutoff,
)
.order_by(PluginMetric.recorded_at)
)).all()
by_host: dict[str, list[float]] = {}
for r in rows:
by_host.setdefault(r.resource_name, []).append(r.value)
# Amber line to read as "CPU"; only draw when there are a couple of points.
return {
name: sparkline_svg(vals[-40:], width=64, height=18, stroke="#c8a840")
for name, vals in by_host.items() if len(vals) >= 2
}
@hosts_bp.get("/overview/widget")
@require_role(UserRole.viewer)
async def overview_widget():
@@ -180,12 +210,14 @@ async def overview_widget():
& (DnsResult.resolved_at == latest_dns_subq.c.max_at),
))).scalars()}
uptime = await _compute_uptime(db)
agent = await _agent_overview_by_host(db, [h.name for h in hosts])
host_names = [h.name for h in hosts]
agent = await _agent_overview_by_host(db, host_names)
cpu_sparks = await _agent_cpu_sparks_by_host(db, host_names)
return await render_template(
"hosts/overview_widget.html",
hosts=hosts, latest_pings=latest_pings, latest_dns=latest_dns,
uptime=uptime, agent=agent,
uptime=uptime, agent=agent, cpu_sparks=cpu_sparks,
)
@@ -92,6 +92,16 @@
</option>
{% endfor %}
</select>
{% elif p.type == "host" %}
<select name="param_{{ p.key }}" required
style="width:100%;padding:0.32rem 0.6rem;background:var(--bg);
border:1px solid var(--border-mid);border-radius:4px;
color:var(--text);font-size:0.85rem;">
<option value="">— select a host —</option>
{% for h in hosts %}
<option value="{{ h.id }}">{{ h.name }}</option>
{% endfor %}
</select>
{% endif %}
</div>
{% endfor %}
@@ -17,6 +17,8 @@
{% else %}
<span title="{{ host.name }}" style="{{ name_style }}">{{ host.name }}</span>
{% endif %}
{% set spark = cpu_sparks.get(host.name) %}
{% if spark %}<span title="CPU — last hour" style="flex-shrink:0;line-height:0;opacity:0.85;">{{ spark | safe }}</span>{% endif %}
<span style="display:flex;gap:0.75rem;font-variant-numeric:tabular-nums;color:var(--text-muted);font-size:0.75rem;flex-shrink:0;">
{# Monitors #}
{% if host.ping_enabled and ping and ping.response_time_ms is not none %}