Files

350 lines
21 KiB
HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>CPU &amp; RAM</title>
<!--
conversation.details: a conversation's own CPU and memory, as the hub's
Performance data has it (perf.read's hub/perf/conversation/{sid}) — Now
(while it runs: CPU and RAM over the last 10 minutes), the totals, its
whole life (its prompts as ticks), its heaviest commands (a tap from their
Bash card) and what it left running (Kill / Keep). Polled while it runs
and the drawer is open; folds away (setEmpty + resize(0)) when the hub
never tracked it.
-->
<style>
* { box-sizing: border-box; }
:root { --cpu: #2a78d6; --ram: #eb6834; }
html.dark { --cpu: #3987e5; --ram: #d95926; }
html, body { margin: 0; padding: 0; background: transparent; }
body { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 12px;
line-height: 1.35; color: hsl(var(--foreground)); -webkit-font-smoothing: antialiased; }
#root { display: flex; flex-direction: column; gap: 16px; }
.card { border: 1px solid hsl(var(--border)); border-radius: 12px; background: hsl(var(--card)); padding: 12px; }
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-variant-numeric: tabular-nums; }
.muted { color: hsl(var(--muted-foreground)); }
.trunc { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.head { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; font-size: 10px; font-weight: 600; text-transform: uppercase;
letter-spacing: .04em; color: hsl(var(--muted-foreground)); }
.head svg { color: hsl(var(--primary)); }
.head .r { margin-left: auto; font-weight: 400; text-transform: none; letter-spacing: 0; }
svg.i { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; flex-shrink: 0; }
svg.i.sm { width: 12px; height: 12px; }
.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.cap { font-size: 10px; text-transform: uppercase; letter-spacing: .04em; color: hsl(var(--muted-foreground)); }
.val { font-size: 14px; font-weight: 600; }
.spark + .spark { margin-top: 8px; }
.spark .top { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; margin-bottom: 2px; font-size: 10px; }
.spark .top .v { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; font-weight: 600; }
.plot { position: relative; border-bottom: 1px solid hsl(var(--border)); }
.plot svg { display: block; width: 100%; height: 100%; overflow: visible; }
.h32 { height: 32px; } .h40 { height: 40px; }
.axis { display: flex; justify-content: space-between; margin-top: 2px; font-size: 9px; }
.empty { display: flex; height: 100%; align-items: center; font-size: 10px; }
.cross { position: absolute; top: 0; bottom: 0; width: 1px; background: hsl(var(--foreground) / .4); pointer-events: none; }
.tip { position: absolute; z-index: 20; pointer-events: none; transform: translateY(calc(-100% - 8px)); white-space: nowrap; border-radius: 6px;
border: 1px solid hsl(var(--border)); background: hsl(var(--card)); padding: 3px 6px; font-size: 11px; box-shadow: 0 6px 16px rgb(0 0 0 / .15); }
ul { list-style: none; margin: 0; padding: 0; }
.cmds li + li { margin-top: 6px; }
.cmd { display: block; width: 100%; border: 0; background: none; padding: 0; text-align: left; color: inherit; font: inherit; }
.cmd:enabled { cursor: pointer; }
.cmd:enabled:hover { opacity: .8; }
.cmd .l1 { display: flex; align-items: baseline; gap: 8px; font-size: 11px; }
.cmd .l1 code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-weight: 500; }
.cmd:enabled .l1 code { color: hsl(var(--primary)); }
.cmd .l2 { margin-top: 2px; display: flex; align-items: center; gap: 8px; }
.bar { flex: 1; height: 4px; border-radius: 999px; background: hsl(var(--muted)); overflow: hidden; }
.bar > div { height: 100%; border-radius: 999px; background: var(--cpu); }
.tiny { font-size: 9px; }
.left li { display: flex; align-items: center; gap: 6px; font-size: 11px; }
.left li + li { margin-top: 4px; }
.grow { min-width: 0; flex: 1; }
.pin { display: inline-flex; width: 24px; height: 24px; align-items: center; justify-content: center; border-radius: 6px; border: 0; background: none;
color: hsl(var(--muted-foreground)); cursor: pointer; }
.pin:hover { background: hsl(var(--accent)); }
.pin.on { color: hsl(var(--primary)); }
.kill { display: inline-flex; align-items: center; gap: 4px; height: 24px; padding: 0 6px; flex-shrink: 0; border-radius: 6px; font: inherit; font-size: 11px;
font-weight: 500; border: 1px solid rgb(244 63 94 / .3); color: rgb(225 29 72); background: none; cursor: pointer; }
html.dark .kill { color: rgb(251 113 133); }
.kill:hover { background: rgb(244 63 94 / .1); }
.kill.armed { border-color: rgb(244 63 94); background: rgb(244 63 94); color: #fff; }
.foot { margin-top: 8px; display: flex; align-items: center; justify-content: space-between; }
a.link { display: inline-flex; align-items: center; gap: 4px; font-size: 11px; color: hsl(var(--primary)); text-decoration: none; cursor: pointer; }
a.link:hover { text-decoration: underline; }
</style>
</head>
<body>
<div id="root"></div>
<script>
(function () {
"use strict";
var A = window.aiAgentPlugin || {};
var init = A.init || {};
var root = document.getElementById("root");
var U = {}, data = null, err = null, q = null, timer = null;
// reuseFrame: the host keeps this frame across conversation switches; the
// session comes in init.update / onUpdate (init.sessionId on older hosts).
var sid = String((init.update && init.update.sessionId) || init.sessionId || "");
function el(tag, attrs, kids) {
var n = document.createElement(tag);
for (var k in attrs || {}) {
if (attrs[k] == null || attrs[k] === false) continue;
if (k === "text") n.textContent = attrs[k];
else if (k === "style") n.setAttribute("style", attrs[k]);
else if (k === "onclick") n.addEventListener("click", attrs[k]);
else n.setAttribute(k, attrs[k] === true ? "" : attrs[k]);
}
(kids || []).forEach(function (c) {
if (c == null || c === false) return;
n.appendChild(typeof c === "string" || typeof c === "number" ? document.createTextNode(String(c)) : c);
});
return n;
}
var NS = "http://www.w3.org/2000/svg";
function s(tag, attrs, kids) {
var n = document.createElementNS(NS, tag);
for (var k in attrs || {}) if (attrs[k] != null) n.setAttribute(k, attrs[k]);
(kids || []).forEach(function (c) { if (c) n.appendChild(c); });
return n;
}
var ICONS = {
activity: "M22 12h-4l-3 9L9 3l-3 9H2",
timer: "M10 2h4M12 14l3-3M12 6a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
term: "M4 17l6-6-6-6M12 19h8",
skull: "M9 22v-3M15 22v-3M12 2a8 8 0 0 0-8 8c0 3 1.5 5 3 6v3h10v-3c1.5-1 3-3 3-6a8 8 0 0 0-8-8zM9 12h.01M15 12h.01",
cpu: "M6 6h12v12H6zM9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4",
pin: "M12 17v5M9 10.8V5h6v5.8l2 2.2v2H7v-2z",
pinoff: "M12 17v5M15 9.3V5H9v1M2 2l20 20M7 15h10l-1.7-1.9",
x: "M18 6 6 18M6 6l12 12",
gauge: "M12 14l4-4M3.3 19a10 10 0 1 1 17.4 0",
};
function svg(name, cls) { return s("svg", { viewBox: "0 0 24 24", class: "i" + (cls ? " " + cls : "") }, [s("path", { d: ICONS[name] })]); }
function maxOf(a) { var m = 0; (a || []).forEach(function (v) { if (v != null && v > m) m = v; }); return m; }
function sum(a, f) { return a.reduce(function (n, x) { return n + ((f ? f(x) : x) || 0); }, 0); }
function plural(n, w, ws) { return n + " " + (n === 1 ? w : (ws || w + "s")); }
function now() { return Date.now() / 1000; }
function fmtBytes(n) {
if (n == null) return "—";
var u = ["B", "KB", "MB", "GB", "TB"], v = n, i = 0;
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
return (v >= 100 || i < 2 ? v.toFixed(0) : v.toFixed(1)) + " " + u[i];
}
function fmtPct(p) { return p == null ? "—" : (p >= 10 ? Math.round(p) : p.toFixed(1)) + "%"; }
function fmtCpuTime(x) {
if (x == null) return "—";
if (x < 60) return (x < 10 ? x.toFixed(1) : Math.round(x)) + "s";
if (x < 3600) return (x / 60).toFixed(x < 600 ? 1 : 0) + " min";
return (x / 3600).toFixed(1) + " h";
}
function fmtSpan(x) {
if (x < 60) return Math.max(0, Math.round(x)) + "s";
if (x < 3600) return Math.round(x / 60) + " min";
if (x < 86400 * 2) return (x / 3600).toFixed(x < 36000 ? 1 : 0) + " h";
return Math.round(x / 86400) + " d";
}
function fmtClock(t, withDay) {
var d = new Date(t * 1000);
var hm = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
return withDay ? d.toLocaleDateString([], { day: "numeric", month: "short" }) + " " + hm : hm;
}
function ago(t) { var d = now() - t; return d < 45 ? "just now" : fmtSpan(d) + " ago"; }
function toast(m, tone) { if (A.toast) A.toast(m, tone || "info"); }
/** One measure over time, small: a 2px line over a faint area, gaps left as gaps, ticks as hairlines. */
function spark(t, values, color, fmt, label, right, ticks, axis, hcls) {
t = t || []; values = values || [];
var n = t.length, from = t[0] || 0, span = Math.max(1, (t[n - 1] || 0) - from);
var max = maxOf(values) * 1.1 || 1;
var x = function (tt) { return ((tt - from) / span) * 100; };
var y = function (v) { return 100 - (Math.max(0, v) / max) * 100; };
var plot = el("div", { class: "plot " + hcls });
if (n < 2) plot.appendChild(el("div", { class: "empty muted", text: "Not enough data yet." }));
else {
var g = s("svg", { viewBox: "0 0 100 100", preserveAspectRatio: "none" });
(ticks || []).forEach(function (tt) { if (tt >= from && tt <= from + span) g.appendChild(s("line", { x1: x(tt), x2: x(tt), y1: 0, y2: 100, stroke: "hsl(var(--border))", "stroke-width": "1", "vector-effect": "non-scaling-stroke" })); });
var cur = null, segs = [];
values.forEach(function (v, i) { if (v == null) { cur = null; return; } if (!cur) segs.push(cur = []); cur.push([x(t[i]), y(v)]); });
segs.forEach(function (sg) {
var pts = sg.map(function (p) { return p.join(","); }).join(" ");
if (sg.length > 1) g.appendChild(s("path", { d: "M" + sg[0][0] + ",100 L" + pts.split(" ").join(" L") + " L" + sg[sg.length - 1][0] + ",100 Z", fill: color, "fill-opacity": "0.18" }));
g.appendChild(s("polyline", { points: pts, fill: "none", stroke: color, "stroke-width": "2", "stroke-linejoin": "round", "vector-effect": "non-scaling-stroke" }));
});
plot.appendChild(g);
var cross = el("span", { class: "cross", hidden: true }), tip = null;
plot.appendChild(cross);
plot.addEventListener("mousemove", function (e) {
var r = plot.getBoundingClientRect();
var i = Math.max(0, Math.min(n - 1, Math.round(((e.clientX - r.left) / r.width) * (n - 1))));
cross.hidden = false; cross.style.left = x(t[i]) + "%";
if (!tip) { tip = el("div", { class: "tip" }); plot.appendChild(tip); }
tip.textContent = fmtClock(t[i], span > 86400) + " · " + (values[i] == null ? "not running" : fmt(values[i]));
tip.style.left = Math.max(0, Math.min(e.clientX - r.left - tip.offsetWidth / 2, plot.clientWidth - tip.offsetWidth)) + "px";
tip.style.top = (e.clientY - r.top) + "px";
});
plot.addEventListener("mouseleave", function () { cross.hidden = true; if (tip) { tip.remove(); tip = null; } });
}
return el("div", { class: "spark" }, [
el("div", { class: "top" }, [el("span", { class: "cap", text: label }), right ? el("span", { class: "v", text: right }) : null]),
plot,
axis && n > 1 ? el("div", { class: "axis muted" }, [el("span", { text: fmtClock(from, span > 86400) }), el("span", { text: fmtClock(from + span, span > 86400) })]) : null,
]);
}
function head(icon, text, right) { return el("div", { class: "head" }, [svg(icon), text, right ? el("span", { class: "r" }, [right]) : null]); }
function confirmBtn(label, confirmText, title, onConfirm) {
var armed = false, t = null;
var b = el("button", { type: "button", class: "kill", title: title });
function paint() { b.classList.toggle("armed", armed); b.textContent = ""; if (armed) b.textContent = confirmText; else label.forEach(function (c) { b.appendChild(typeof c === "string" ? document.createTextNode(c) : c); }); }
b.addEventListener("click", function () {
if (armed) { armed = false; clearTimeout(t); paint(); onConfirm(); }
else { armed = true; paint(); t = setTimeout(function () { armed = false; paint(); }, 4000); }
});
paint();
return b;
}
function autoKillNote(p) {
if (p.kept) return el("span", { text: "kept" });
if (p.keptByLabel) return el("span", { title: "Matches a never-auto-killed label", text: "shared" });
if (p.autoKillAt == null) return null;
var left = p.autoKillAt - now();
return el("span", { title: "Auto-kill: leftover for longer than the setting", text: left <= 0 ? "auto-kill soon" : "auto-kill in " + fmtSpan(left) });
}
function kill(t) {
A.action("act", Object.assign({ op: "kill" }, t)).then(function (r) {
var n = (r.killed || []).length;
toast(n ? "Stopped " + plural(n, "process", "processes") : "Nothing to stop", n ? "success" : "info");
refresh();
}).catch(function (e) { toast("Kill failed: " + ((e && e.message) || e), "error"); });
}
function keep(g, p) {
A.action("act", { op: "keep", runner: g.runner, pid: p.pid, startedAt: p.startedAt, kept: !p.kept }).then(refresh)
.catch(function (e) { toast(String((e && e.message) || e), "error"); });
}
function render() {
var perf = data && data.perf, series = (data && data.series) || {};
if (!perf || !perf.tracked) return show([]);
var cards = [];
var ten = series["10m"] || {}, life = series.life || {};
if (perf.live) {
cards.push(el("div", { class: "card", role: "group", "aria-label": "CPU and RAM now" }, [head("activity", "Now", plural(perf.live.procs, "process", "processes")),
spark(ten.t, ten.cpu, "var(--cpu)", fmtPct, "CPU · 10 min", fmtPct(perf.live.cpu), null, false, "h32"),
spark(ten.t, ten.rss, "var(--ram)", fmtBytes, "RAM · 10 min", fmtBytes(perf.live.rss), null, false, "h32")]));
}
cards.push(el("div", { class: "card", role: "group", "aria-label": "Consumption" }, [el("div", { class: "grid" }, [
["CPU time", fmtCpuTime(perf.cpuSeconds), "the whole process tree, children that already exited included"],
["Peak RAM", fmtBytes(perf.peakRss), "the run and everything it had started, at its heaviest"],
["Peak processes", String(perf.peakProcs || 0), "the most processes it had at once"],
["Runs", String(perf.runs || 1), "agent processes: the first run and each resume"],
].map(function (c) { return el("div", { title: c[2] }, [el("div", { class: "cap", text: c[0] }), el("div", { class: "val mono", text: c[1] })]); }))]));
var ticks = Array.isArray(U.prompts) ? U.prompts : [];
cards.push(el("div", { class: "card", role: "group", "aria-label": "CPU and RAM over its life" }, [head("timer", "Over its life"),
spark(life.t, life.cpu, "var(--cpu)", fmtPct, "CPU", "peak " + fmtPct(maxOf(life.cpu)), ticks, false, "h40"),
spark(life.t, life.rss, "var(--ram)", fmtBytes, "RAM", "peak " + fmtBytes(maxOf(life.rss)), ticks, true, "h40"),
ticks.length ? el("div", { class: "muted tiny", style: "margin-top:4px", text: "ticks = your prompts" }) : null]));
var runs = (perf.commands || []).slice(0, 5);
if (runs.length) {
var max = Math.max(1, maxOf(runs.map(function (r) { return r.cpuSeconds; })));
cards.push(el("div", { class: "card", role: "group", "aria-label": "Heaviest commands" }, [head("term", "Heaviest commands"),
el("ul", { class: "cmds" }, runs.map(function (r) {
var id = r.toolUseId || null;
return el("li", null, [el("button", { type: "button", class: "cmd", disabled: id ? null : true,
title: id ? r.cmd + "\n\nJump to this call in the thread" : r.cmd + "\n\n(ran in a subagent, or its call isn't in this thread)",
onclick: function () { if (id && A.scrollTo) A.scrollTo({ toolUseId: id }).catch(function () { toast("That call is further up — scroll the thread to load it"); }); } }, [
el("div", { class: "l1" }, [el("code", { class: "trunc grow", text: r.label }), el("span", { class: "mono muted", style: "flex-shrink:0", text: fmtCpuTime(r.cpuSeconds) + " · " + fmtBytes(r.peakRss) })]),
el("div", { class: "l2" }, [el("div", { class: "bar" }, [el("div", { style: "width:" + (r.cpuSeconds / max) * 100 + "%" })]),
el("span", { class: "tiny muted", style: "flex-shrink:0", text: "~" + fmtSpan(r.duration || 0) + " · " + ago(r.startedAt) })]),
])]);
}))]));
}
var groups = perf.leftovers || [];
var procs = [];
groups.forEach(function (g) { (g.processes || []).forEach(function (p) { procs.push({ g: g, p: p }); }); });
if (procs.length) {
cards.push(el("div", { class: "card", role: "group", "aria-label": "Left running" }, [
head("skull", "Left running (" + procs.length + ")", el("span", { class: "mono", text: fmtBytes(sum(groups, function (g) { return g.rss; })) })),
el("ul", { class: "left" }, procs.map(function (x) {
var g = x.g, p = x.p;
return el("li", null, [
el("div", { class: "grow" }, [el("div", { class: "trunc mono", style: "font-weight:500", title: p.cmd, text: p.label }),
el("div", { class: "tiny muted", style: "display:flex;gap:6px" }, [el("span", { text: fmtBytes(p.rss) }), el("span", { text: "· up " + fmtSpan(now() - p.startedAt) }), autoKillNote(p)])]),
el("button", { type: "button", class: "pin" + (p.kept ? " on" : ""), title: p.kept ? "Let the auto-kill stop it again" : "Keep it: never auto-kill this one",
onclick: function () { keep(g, p); } }, [svg(p.kept ? "pinoff" : "pin", "sm")]),
confirmBtn([svg("x", "sm")], "Kill?", "Stop this process", function () { kill({ runner: g.runner, sessionId: g.sessionId, processes: [{ pid: p.pid, startedAt: p.startedAt }] }); }),
]);
})),
el("div", { class: "foot" }, [
el("a", { class: "link", href: "#", onclick: function (e) { e.preventDefault(); if (A.navigate) A.navigate("/plugins/performance/performance"); } }, [svg("gauge", "sm"), "Performance dashboard"]),
confirmBtn([svg("skull", "sm"), " Kill all"], "Kill all?", "Stop everything it left running (SIGTERM, then SIGKILL)",
function () { groups.forEach(function (g) { kill({ runner: g.runner, sessionId: g.sessionId }); }); }),
]),
]));
}
show(cards);
}
// ── host bridge: empty / resize / live updates ───────────────────────────
var lastH = -1, empty = null;
function fit() {
var h = empty ? 0 : Math.ceil(root.getBoundingClientRect().height);
if (h !== lastH) { lastH = h; if (A.resize) A.resize(h); }
}
function show(nodes) {
var nowEmpty = !nodes.length;
while (root.firstChild) root.removeChild(root.firstChild);
nodes.forEach(function (n) { root.appendChild(n); });
if (nowEmpty !== empty) { empty = nowEmpty; if (A.setEmpty) A.setEmpty(nowEmpty); }
fit();
}
if (window.ResizeObserver) new ResizeObserver(fit).observe(root);
function read(payload, cb) {
if (A.query) return A.query("read", payload, cb);
var live = true;
function run() { return A.action("read", payload).then(function (d) { if (live) cb(d, {}); }, function (e) { if (live) cb(null, { error: String((e && e.message) || e) }); }); }
run();
return { stop: function () { live = false; }, refresh: run };
}
function refresh() { if (q) q.refresh(); }
/** Poll while it runs and the drawer shows it; read once otherwise. */
function schedule() {
clearInterval(timer);
if (U.running && U.drawerOpen !== false) timer = setInterval(function () { if (!document.hidden) refresh(); }, 10000);
}
var wasRunning = null;
function onUpdate(u) {
U = u && typeof u === "object" ? u : {};
if (Object.prototype.hasOwnProperty.call(U, "sessionId") && String(U.sessionId || "") !== sid) {
// Another conversation in the same frame: drop the last one's numbers
// at once, then read the new one's.
sid = String(U.sessionId || "");
data = null; err = null;
wasRunning = null;
show([]);
start();
}
if (wasRunning === true && !U.running) refresh(); // its last numbers
wasRunning = !!U.running;
schedule();
if (data) render();
}
function start() {
if (q) q.stop();
q = null;
if (!sid) { show([]); return; }
q = read({ view: "conversation", sid: sid, series: ["10m", "life"] }, function (d, meta) {
if (d) data = d;
err = (meta && meta.error) || null;
render();
});
}
start();
if (typeof A.onUpdate === "function") A.onUpdate(onUpdate);
onUpdate(init.update || {});
if (typeof A.onTheme === "function") A.onTheme(function () { if (data) render(); });
})();
</script>
</body>
</html>