Files

1102 lines
74 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Performance</title>
<style>
* { box-sizing: border-box; }
[hidden] { display: none !important; }
/* the dataviz palette (light, then dark steps): a conversation keeps its slot */
:root {
--s0: #2a78d6; --s1: #eb6834; --s2: #1baf7a; --s3: #eda100; --s4: #e87ba4; --s5: #008300; --s6: #6250d6; --s7: #e34948;
--other: #94a3b8; --good: #1baf7a; --warn: #eda100; --bad: #e34948;
}
html.dark {
--s0: #3987e5; --s1: #d95926; --s2: #199e70; --s3: #c98500; --s4: #d55181; --s5: #008300; --s6: #9085e9; --s7: #e66767;
--other: #64748b; --good: #199e70; --warn: #c98500; --bad: #e66767;
}
html, body { margin: 0; background: hsl(var(--background, 0 0% 100%)); color: hsl(var(--foreground, 222 47% 11%)); }
body { overflow-x: hidden; font-size: 12px; }
.content { display: flex; flex-direction: column; gap: 20px; transition: opacity .15s; }
.content.busy { opacity: .6; }
.mono { font-family: var(--aia-mono, ui-monospace, monospace); font-variant-numeric: tabular-nums; }
.n { font-family: var(--aia-mono, ui-monospace, monospace); font-weight: 600; font-variant-numeric: tabular-nums; }
.muted { color: hsl(var(--muted-foreground, 215 16% 47%)); }
.trunc { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
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; }
.bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; justify-content: flex-end; }
.chips { display: flex; flex-wrap: wrap; gap: 4px; margin-right: auto; }
.kpis { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
@media (min-width: 640px) { .kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
.kpi .lbl { display: flex; align-items: center; gap: 6px; font-size: 11px; text-transform: uppercase; letter-spacing: .04em; }
.kpi .val { margin-top: 4px; font-size: 20px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.kpi .val.bad { color: hsl(var(--destructive, 0 84% 60%)); }
.kpi .sub { font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.machines { display: grid; gap: 12px; grid-template-columns: minmax(0, 1fr); }
@media (min-width: 640px) { .machines { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (min-width: 1000px) { .machines { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
.machine.off { opacity: .7; }
.mhead { display: flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 500; }
.mhead .right { margin-left: auto; font-size: 11px; font-weight: 400; }
.meter { margin-top: 8px; }
.meter .top { display: flex; justify-content: space-between; gap: 8px; font-size: 11px; }
.track { margin-top: 4px; display: flex; gap: 2px; height: 8px; border-radius: 999px; overflow: hidden; background: hsl(var(--muted, 210 40% 96%)); }
.track .a { background: hsl(var(--primary, 24 95% 53%)); }
.track .o { background: hsl(var(--muted-foreground, 215 16% 47%) / .4); }
.mfoot { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: 10px; }
/* panels: one question each, its finding, the evidence (and a table twin) */
.ph { display: flex; align-items: flex-start; gap: 8px; margin-bottom: 12px; }
.ph .t { min-width: 0; flex: 1; }
.ph h2 { margin: 0; font-size: 14px; font-weight: 600; }
.ph p { margin: 2px 0 0; font-size: 11px; }
.finding { margin: 0 0 12px; border-left: 2px solid hsl(var(--primary, 24 95% 53%) / .6); background: hsl(var(--muted, 210 40% 96%) / .4);
border-radius: 8px; padding: 8px 12px; font-size: 12px; line-height: 1.6; }
.tbl { overflow-x: auto; }
.tbl td { white-space: nowrap; }
.tbl td.aia-num { font-family: var(--aia-mono, ui-monospace, monospace); color: hsl(var(--muted-foreground, 215 16% 47%)); }
.sect { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.sect h2 { margin: 0; font-size: 11px; font-weight: 500; text-transform: uppercase; letter-spacing: .04em; color: hsl(var(--muted-foreground, 215 16% 47%)); }
.segrow { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
.seg-r { display: flex; justify-content: flex-end; margin-bottom: 8px; }
/* rows */
ul.rows { list-style: none; margin: 0; padding: 0; }
ul.rows > li + li { border-top: 1px solid hsl(var(--border, 214 32% 91%) / .5); }
.run { border: 1px solid hsl(var(--border, 214 32% 91%) / .6); border-radius: 8px; margin-bottom: 4px; }
.run > button.head { display: flex; width: 100%; align-items: center; gap: 8px; padding: 6px 8px; text-align: left; background: none; border: 0; color: inherit; font: inherit; cursor: pointer; border-radius: 8px; }
.run > button.head:hover { background: hsl(var(--accent, 210 40% 96%) / .4); }
.chev { transition: transform .15s; color: hsl(var(--muted-foreground, 215 16% 47%)); }
.chev.open { transform: rotate(90deg); }
.grow { min-width: 0; flex: 1; }
.line1 { display: flex; align-items: center; gap: 6px; font-size: 13px; min-width: 0; }
.meta { margin-top: 2px; font-size: 10px; }
.minibar { margin-top: 4px; height: 6px; border-radius: 999px; background: hsl(var(--muted, 210 40% 96%)); overflow: hidden; }
.minibar > div { height: 100%; border-radius: 999px; background: hsl(var(--primary, 24 95% 53%) / .7); }
.num { flex-shrink: 0; text-align: right; font-family: var(--aia-mono, ui-monospace, monospace); font-variant-numeric: tabular-nums; }
.w14 { width: 56px; } .w16 { width: 64px; }
.tree { border-top: 1px solid hsl(var(--border, 214 32% 91%) / .6); padding: 0 8px 4px; }
.proc { display: flex; align-items: center; gap: 8px; padding: 4px 0; font-size: 12px; }
.proc .cmd { font-family: var(--aia-mono, ui-monospace, monospace); font-size: 10px; }
.tag { flex-shrink: 0; border-radius: 4px; background: hsl(var(--muted, 210 40% 96%)); padding: 0 4px; font-size: 10px; }
.mchip { flex-shrink: 0; border-radius: 999px; background: hsl(var(--muted, 210 40% 96%)); padding: 1px 6px; font-size: 10px; }
.tool { color: hsl(var(--primary, 24 95% 53%)); }
.group { border: 1px solid hsl(var(--border, 214 32% 91%) / .6); border-radius: 8px; padding: 8px; margin-bottom: 8px; }
.acts { display: flex; flex-shrink: 0; align-items: center; gap: 4px; }
.btn-kill { display: inline-flex; align-items: center; gap: 4px; height: 24px; padding: 0 6px; 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 .btn-kill { color: rgb(251 113 133); }
.btn-kill:hover { background: rgb(244 63 94 / .1); }
.btn-kill.armed { border-color: rgb(244 63 94); background: rgb(244 63 94); color: #fff; }
.btn-kill:disabled { opacity: .5; }
.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, 215 16% 47%)); cursor: pointer; }
.pin:hover { background: hsl(var(--accent, 210 40% 96%)); }
.pin.on { color: hsl(var(--primary, 24 95% 53%)); }
.note10 { font-size: 10px; }
.autokill { margin-top: 12px; border-top: 1px solid hsl(var(--border, 214 32% 91%)); padding-top: 12px; display: flex; flex-direction: column; gap: 8px; font-size: 12px; }
.autokill .r { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.autokill input[type=number] { width: 64px; }
.label-chip { display: inline-flex; align-items: center; gap: 4px; border-radius: 999px; background: hsl(var(--muted, 210 40% 96%)); padding: 2px 8px; font-family: var(--aia-mono, ui-monospace, monospace); font-size: 11px; }
.label-chip button { border: 0; background: none; padding: 0; color: hsl(var(--muted-foreground, 215 16% 47%)); cursor: pointer; display: inline-flex; }
.xs { height: 24px; font-size: 11px; width: 128px; }
a.conv { color: inherit; text-decoration: none; cursor: pointer; }
a.conv:hover { text-decoration: underline; }
code { font-family: var(--aia-mono, ui-monospace, monospace); }
.example { margin: 0 0 8px 20px; border-radius: 6px; background: hsl(var(--muted, 210 40% 96%) / .4); padding: 8px; font-size: 11px; display: flex; flex-direction: column; gap: 6px; }
.example pre { margin: 0; max-height: 128px; overflow: auto; white-space: pre-wrap; word-break: break-all; border-radius: 4px; background: hsl(var(--background, 0 0% 100%)); padding: 6px; font-size: 10px; }
/* charts */
.plot { position: relative; }
.plotrow { display: flex; gap: 6px; }
.yt { flex-shrink: 0; display: flex; flex-direction: column; justify-content: space-between; text-align: right; font-size: 9px; padding: 1px 0; }
.area { position: relative; min-width: 0; flex: 1; border-bottom: 1px solid hsl(var(--border, 214 32% 91%)); }
.area svg { display: block; width: 100%; height: 100%; overflow: visible; }
.cross { position: absolute; top: 0; bottom: 0; width: 1px; background: hsl(var(--foreground, 222 47% 11%) / .4); pointer-events: none; }
.xt { display: flex; justify-content: space-between; margin-top: 4px; font-size: 9px; }
.h160 { height: 160px; } .h80 { height: 80px; } .h64 { height: 64px; }
.chartlbl { margin-bottom: 4px; font-size: 11px; font-weight: 500; }
.legend { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: 11px; }
.legend > span { display: inline-flex; align-items: center; gap: 6px; min-width: 0; max-width: 16rem; }
.sw { display: inline-block; width: 10px; height: 10px; border-radius: 2px; flex-shrink: 0; }
.dash { display: inline-block; width: 12px; border-top: 1.5px dashed hsl(var(--foreground, 222 47% 11%) / .7); }
.tip { position: absolute; z-index: 20; pointer-events: none; transform: translateY(calc(-100% - 10px)); white-space: nowrap;
border-radius: 6px; border: 1px solid hsl(var(--border, 214 32% 91%)); background: hsl(var(--card, 0 0% 100%));
padding: 4px 8px; font-size: 11px; box-shadow: 0 6px 16px rgb(0 0 0 / .15); }
.tip .tr { display: flex; justify-content: space-between; gap: 12px; max-width: 16rem; }
.tip .tr span:first-child { display: inline-flex; align-items: center; gap: 6px; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
/* guests */
.gp { display: inline-flex; flex-shrink: 0; align-items: center; gap: 4px; border-radius: 999px; padding: 1px 6px 1px 1px; font-size: 10px; font-weight: 500;
line-height: 1; cursor: pointer; background: hsl(var(--primary, 24 95% 53%) / .12); color: hsl(var(--foreground, 222 47% 11%)); }
.gp:hover { opacity: .8; }
.gp .nm { max-width: 7rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 2px 0; }
.av { display: inline-flex; width: 14px; height: 14px; border-radius: 999px; align-items: center; justify-content: center; font-size: 7px; font-weight: 700; color: #fff; flex-shrink: 0; }
.stack { display: inline-flex; align-items: center; flex-shrink: 0; }
.stack .av { width: 16px; height: 16px; margin-left: -4px; box-shadow: 0 0 0 1px hsl(var(--card, 0 0% 100%)); cursor: pointer; }
.stack .av:first-child { margin-left: 0; }
/* the hub itself */
.hub { display: flex; flex-direction: column; gap: 12px; }
.route { display: flex; align-items: center; gap: 8px; font-size: 11px; }
.route .m { width: 40px; flex-shrink: 0; font-size: 9px; }
.route .b { margin-top: 2px; height: 6px; border-radius: 0 4px 4px 0; background: hsl(var(--primary, 24 95% 53%) / .8); }
.route .r { width: 80px; flex-shrink: 0; text-align: right; font-size: 10px; line-height: 1.2; }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 999px; }
.vit td, .vit th { padding: 6px 0; }
.linkbtn { margin-top: 8px; border: 0; background: none; padding: 0; font: inherit; font-size: 11px; color: hsl(var(--primary, 24 95% 53%)); cursor: pointer; }
.linkbtn:hover { text-decoration: underline; }
</style>
</head>
<body>
<div class="aia-page">
<div class="aia-stack">
<div class="bar" id="bar" hidden>
<div class="chips" id="guestchips"></div>
<div class="aia-seg" id="scopes" role="group" aria-label="Profile"></div>
</div>
<div class="aia-note" id="note" hidden></div>
<div id="msg" hidden></div>
<div id="content" class="content" hidden>
<div class="kpis" id="kpis"></div>
<div class="machines" id="machines"></div>
<section class="aia-card" id="live"></section>
<section class="aia-card" id="leftovers"></section>
<section class="aia-card" id="history"></section>
<div class="sect"><h2>Totals</h2><div class="aia-seg" id="totalsRange" role="group" aria-label="Range"></div></div>
<section class="aia-card" id="commands"></section>
<section class="aia-card" id="convs"></section>
<div id="bottom"></div>
<div class="sect"><h2>The hub itself</h2><div class="aia-seg" id="hubRange" role="group" aria-label="Range"></div></div>
<div class="hub" id="hub"></div>
</div>
</div>
</div>
<script>
(function () {
"use strict";
var api = window.aiAgentPlugin || null;
var init = (api && api.init) || {};
var KEY = "aia-performance";
var saved = {};
try { saved = JSON.parse(localStorage.getItem(KEY) || "{}") || {}; } catch (e) { saved = {}; }
var HISTORY_RANGES = ["1h", "6h", "24h", "7d", "30d"];
var TOTALS_RANGES = ["24h", "7d", "30d", "all"];
var HUB_RANGES = ["24h", "7d", "30d"];
var state = {
scope: typeof init.scope === "string" && init.scope ? init.scope : (saved.scope || ""),
guests: [],
liveSort: "rss", open: {}, historyRange: saved.historyRange || "24h", runner: null,
totals: TOTALS_RANGES.indexOf(saved.totals) >= 0 ? saved.totals : "7d",
kind: "tool", openCmd: null, convSort: "cpu", hubRange: "24h", routesAll: false,
asTable: {},
};
if (HISTORY_RANGES.indexOf(state.historyRange) < 0) state.historyRange = "24h";
function persist() {
try { localStorage.setItem(KEY, JSON.stringify({ scope: state.scope, historyRange: state.historyRange, totals: state.totals })); } catch (e) {}
}
var D = { live: null, history: null, commands: null, convs: null, hub: null };
var errs = {};
var profiles = [], guestNames = {};
// ── helpers ──────────────────────────────────────────────────────────────
function $(id) { return document.getElementById(id); }
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 = {
bot: "M12 8V4H8M4 12a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v4a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4zM9 13v2M15 13v2",
cpu: "M6 6h12v12H6zM9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4",
mem: "M6 19v-3M10 19v-3M14 19v-3M18 19v-3M8 11V9M16 11V9M12 11V9M2 15h20M2 7a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1.1a2 2 0 0 0 0 3.8V17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5.1a2 2 0 0 0 0-3.8z",
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",
server: "M2 4h20v6H2zM2 14h20v6H2zM6 7h.01M6 17h.01",
laptop: "M4 5h16v10H4zM2 19h20",
chev: "M9 18l6-6-6-6",
term: "M4 17l6-6-6-6M12 19h8",
x: "M18 6 6 18M6 6l12 12",
pin: "M12 17v5M9 10.8V5h6v5.8l2 2.2v2H7v-2z",
pinoff: "M12 17v5M15 9.3V5H9v1M2 2l20 20M7 15h10l-1.7-1.9",
alert: "M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z",
radio: "M4.9 19.1a10 10 0 0 1 0-14.2M7.8 16.2a6 6 0 0 1 0-8.4M12 12h.01M16.2 7.8a6 6 0 0 1 0 8.4M19.1 4.9a10 10 0 0 1 0 14.2",
table: "M3 5h18v14H3zM3 10h18M3 15h18M9 5v14",
chart: "M3 3v18h18M7 15l4-4 3 3 5-6",
timer: "M10 2h4M12 14l3-3M12 6a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
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 sum(a, f) { return a.reduce(function (n, x) { return n + ((f ? f(x) : x) || 0); }, 0); }
function maxOf(a) { var m = 0; a.forEach(function (v) { if (v != null && v > m) m = v; }); return m; }
function plural(n, w, ws) { return n + " " + (n === 1 ? w : (ws || w + "s")); }
function N(v) { return el("span", { class: "n", text: String(v) }); }
var now = function () { return Date.now() / 1000; };
// formats (the app's own: powers of 1024, % of one core)
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 fmtCores(p) { var c = p / 100; return (c >= 10 ? c.toFixed(0) : c.toFixed(1)) + " cores"; }
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 relTime(iso) {
var t = typeof iso === "number" ? iso : Date.parse(iso) / 1000;
if (!isFinite(t)) return "";
var d = now() - t;
if (d < 45) return "just now";
return fmtSpan(d) + " ago";
}
function fmtMs(ms) {
if (ms == null) return "—";
if (ms === 0) return "0";
if (ms < 10) return ms.toFixed(ms < 1 ? 2 : 1) + " ms";
if (ms < 1000) return Math.round(ms) + " ms";
if (ms < 60000) return (ms / 1000).toFixed(ms < 10000 ? 1 : 0) + " s";
return (ms / 60000).toFixed(1) + " min";
}
// ── the bridge ───────────────────────────────────────────────────────────
function read(payload, cb) {
if (api.query) return api.query("read", payload, cb);
var live = true, last = null;
function run() {
return api.action("read", payload).then(
function (d) { last = d; if (live) cb(d, { fromCache: false, fetching: false, at: Date.now() }); },
function (e) { if (live) cb(last, { error: String((e && e.message) || e), fromCache: false, fetching: false, at: Date.now() }); });
}
run();
return { stop: function () { live = false; }, refresh: run };
}
function act(payload) { return api.action("act", payload); }
function toast(msg, tone) { if (api && api.toast) api.toast(msg, tone || "info"); }
var headerJson = "";
function setHeader(h) {
var j = JSON.stringify(h);
if (j === headerJson || !api || !api.setHeader) return;
headerJson = j;
api.setHeader(h);
}
function go(path) { if (api && api.navigate) api.navigate(path); }
// ── shared bits ──────────────────────────────────────────────────────────
function convLink(r, cls) {
var text = r.title || "session " + String(r.sessionId || "").slice(0, 8);
if (!r.conversationId) return el("span", { class: "trunc" + (cls ? " " + cls : ""), text: text });
return el("a", { class: "conv trunc" + (cls ? " " + cls : ""), title: text, text: text, href: "#",
onclick: function (e) { e.preventDefault(); e.stopPropagation(); go("/conversation/" + r.conversationId); } });
}
function hue(uid) { var h = 0; for (var i = 0; i < uid.length; i++) h = (h * 31 + uid.charCodeAt(i)) % 360; return "hsl(" + h + " 55% 45%)"; }
function nameOf(uid) { return guestNames[uid] || uid; }
function avatar(uid) {
var nm = nameOf(uid);
var ini = nm.split(/\s+/).map(function (w) { return w.charAt(0); }).join("").slice(0, 2).toUpperCase();
return el("span", { class: "av", style: "background:" + hue(uid), text: ini || "?" });
}
/** A guest's avatar and name; tap: only theirs (the Guests profile, them picked). */
function guestPill(uid) {
if (!uid) return null;
var nm = nameOf(uid);
return el("span", { class: "gp", role: "button", tabindex: "0", title: nm + "'s — tap to show only " + nm + "'s",
onclick: function (e) { e.preventDefault(); e.stopPropagation(); pickGuest(uid); } }, [avatar(uid), el("span", { class: "nm", text: nm })]);
}
function guestStack(uids, max) {
if (!uids || !uids.length) return null;
max = max || 4;
var box = el("span", { class: "stack", title: uids.map(nameOf).join(", ") });
uids.slice(0, max).forEach(function (u) {
var a = avatar(u);
a.title = nameOf(u) + " — tap to show only " + nameOf(u) + "'s";
a.addEventListener("click", function (e) { e.preventDefault(); e.stopPropagation(); pickGuest(u); });
box.appendChild(a);
});
if (uids.length > max) box.appendChild(el("span", { class: "muted note10", style: "margin-left:4px", text: "+" + (uids.length - max) }));
return box;
}
function pickGuest(uid) {
var again = state.scope === "profile:guests" && state.guests.length === 1 && state.guests[0] === uid;
state.scope = "profile:guests";
state.guests = again ? [] : [uid];
persist(); loadAll();
}
function seg(box, options, value, onPick, label) {
box.textContent = "";
options.forEach(function (o) {
var on = o === value;
box.appendChild(el("button", { type: "button", class: on ? "aia-active" : null, "aria-pressed": on ? "true" : "false",
text: label ? label(o) : o, onclick: function () { if (!on) onPick(o); } }));
});
return box;
}
function segEl(options, value, onPick, label) { return seg(el("div", { class: "aia-seg", role: "group" }), options, value, onPick, label); }
/** One question per panel: the title, its finding, the evidence — or its table twin. */
function panel(box, id, o) {
box.textContent = "";
var asTable = !!state.asTable[id] && !!o.table;
var head = el("div", { class: "ph" }, [
el("div", { class: "t" }, [el("h2", { text: o.title }), o.question ? el("p", { class: "muted", text: o.question }) : null]),
o.table ? el("button", { type: "button", class: "aia-btn aia-btn-ghost aia-btn-sm aia-btn-icon", title: asTable ? "Show the chart" : "Show the numbers as a table",
onclick: function () { state.asTable[id] = !asTable; renderAll(); } }, [svg(asTable ? "chart" : "table")]) : null,
]);
box.appendChild(head);
if (o.finding) box.appendChild(el("p", { class: "finding" }, [].concat(o.finding)));
box.appendChild(asTable ? o.table() : o.body());
}
function dataTable(head, rows) {
return el("div", { class: "tbl" }, [el("table", { class: "aia-table" }, [
el("thead", null, [el("tr", null, head.map(function (h, i) { return el("th", { class: i ? "aia-num" : null, text: h }); }))]),
el("tbody", null, rows.map(function (r) {
return el("tr", null, r.map(function (c, i) { return el("td", { class: i ? "aia-num" : null }, [c == null ? "—" : c]); }));
})),
])]);
}
function confirmBtn(label, confirmText, title, onConfirm, disabled) {
var armed = false, t = null;
var b = el("button", { type: "button", class: "btn-kill", title: title, disabled: disabled ? true : null });
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 (e) {
e.stopPropagation();
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", { class: "muted note10", text: "kept" });
if (p.keptByLabel) return el("span", { class: "muted note10", title: "Matches a never-auto-killed label", text: "shared" });
if (p.autoKillAt == null) return null;
var left = p.autoKillAt - now();
return el("span", { class: "muted note10", title: "Auto-kill: leftover for longer than the setting", text: left <= 0 ? "auto-kill soon" : "auto-kill in " + fmtSpan(left) });
}
function meter(label, agents, used, total, fmt, value) {
var t = total || 0;
var a = t ? Math.min(100, (agents / t) * 100) : 0;
var o = t && used != null ? Math.max(0, Math.min(100 - a, ((used - agents) / t) * 100)) : 0;
var track = el("div", { class: "track", title: "agents " + fmt(agents) + " · rest of the machine " + (used != null ? fmt(Math.max(0, used - agents)) : "—") });
if (a > 0) track.appendChild(el("div", { class: "a", style: "width:" + a + "%" }));
if (o > 0) track.appendChild(el("div", { class: "o", style: "width:" + o + "%" }));
return el("div", { class: "meter" }, [
el("div", { class: "top" }, [el("span", { class: "muted", text: label }),
el("span", { class: "mono" }, value || [used != null ? fmt(used) : "—", el("span", { class: "muted", text: " / " + (t ? fmt(t) : "—") })])]),
track,
]);
}
// ── a pointer read-out for a plot ────────────────────────────────────────
function tipper(plot) {
var tip = null;
return {
show: function (e, kids) {
var r = plot.getBoundingClientRect();
if (!tip) { tip = el("div", { class: "tip" }); plot.appendChild(tip); }
tip.textContent = "";
kids.forEach(function (k) { if (k) tip.appendChild(k); });
var w = tip.offsetWidth;
tip.style.left = Math.max(0, Math.min(e.clientX - r.left - w / 2, plot.clientWidth - w)) + "px";
tip.style.top = (e.clientY - r.top) + "px";
},
hide: function () { if (tip) { tip.remove(); tip = null; } },
};
}
/** Bands stacked bottom-up over t, the machine's own total as a dashed line over them. */
function stackedArea(t, layers, line, yMax, fmtY, hcls) {
var n = t.length;
if (n < 2) return el("div", { class: "muted " + hcls, text: "Not enough data yet." });
var from = t[0], span = Math.max(1, t[n - 1] - from);
var x = function (i) { return ((t[i] - from) / span) * 100; };
var y = function (v) { return 100 - (Math.max(0, Math.min(v, yMax)) / yMax) * 100; };
var base = new Array(n).fill(0);
var g = s("svg", { viewBox: "0 0 100 100", preserveAspectRatio: "none" });
g.appendChild(s("line", { x1: 0, y1: 50, x2: 100, y2: 50, stroke: "hsl(var(--border))", "stroke-width": "0.5", "vector-effect": "non-scaling-stroke" }));
var tops = [];
layers.forEach(function (l) {
var lo = base.slice();
for (var i = 0; i < n; i++) base[i] += l.values[i] || 0;
var top = base.map(function (v, i) { return x(i) + "," + y(v); });
var bottom = lo.map(function (v, i) { return x(i) + "," + y(v); }).reverse();
g.appendChild(s("path", { d: "M" + top.join(" L") + " L" + bottom.join(" L") + " Z", fill: l.color }));
tops.push(top.join(" "));
});
tops.forEach(function (pts) { g.appendChild(s("polyline", { points: pts, fill: "none", stroke: "hsl(var(--card))", "stroke-width": "2", "vector-effect": "non-scaling-stroke" })); });
if (line) {
var cur = null, segs = [];
line.forEach(function (v, i) { if (v == null) { cur = null; return; } if (!cur) segs.push(cur = []); cur.push(x(i) + "," + y(v)); });
segs.forEach(function (sg) { g.appendChild(s("polyline", { points: sg.join(" "), fill: "none", stroke: "hsl(var(--foreground) / .7)", "stroke-width": "1.5", "stroke-dasharray": "4 3", "vector-effect": "non-scaling-stroke" })); });
}
var area = el("div", { class: "area " + hcls }, [g]);
var cross = el("span", { class: "cross", hidden: true });
area.appendChild(cross);
var plot = el("div", { class: "plot" }, [
el("div", { class: "plotrow" }, [el("div", { class: "yt muted " + hcls }, [el("span", { text: fmtY(yMax) }), el("span", { text: fmtY(yMax / 2) }), el("span", { text: fmtY(0) })]), area]),
el("div", { class: "xt muted", style: "padding-left:32px" }, [el("span", { text: fmtClock(from, span > 86400) }), el("span", { text: fmtClock(t[n - 1], span > 86400) })]),
]);
var tip = tipper(plot);
area.addEventListener("mousemove", function (e) {
var r = area.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(i) + "%";
var rows = layers.map(function (l) { return { l: l, v: l.values[i] || 0 }; }).filter(function (r2) { return r2.v > 0; })
.sort(function (a, b) { return b.v - a.v; }).slice(0, 6);
var kids = [el("div", { class: "muted", text: fmtClock(t[i], span > 86400) })];
if (line && line[i] != null) kids.push(el("div", { class: "tr" }, [el("span", { text: "whole machine" }), el("span", { class: "mono", text: fmtY(line[i]) })]));
rows.forEach(function (r2) { kids.push(el("div", { class: "tr" }, [el("span", null, [el("span", { class: "sw", style: "background:" + r2.l.color }), r2.l.label]), el("span", { class: "mono", text: fmtY(r2.v) })])); });
if (!rows.length) kids.push(el("div", { class: "muted", text: "no agent running" }));
tip.show(e, kids);
});
area.addEventListener("mouseleave", function () { cross.hidden = true; tip.hide(); });
return plot;
}
/** One measure over time as a 2px line; gaps longer than gapMs left as gaps. */
function linePlot(points, from, to, yMax, fmtY, color, gapMs, hcls) {
var span = Math.max(1, to - from);
var x = function (t) { return ((t - from) / span) * 100; };
var y = function (v) { return 100 - (Math.max(0, Math.min(v, yMax)) / yMax) * 100; };
var g = s("svg", { viewBox: "0 0 100 100", preserveAspectRatio: "none" });
var cur = null, segs = [], prev = null;
points.forEach(function (p) {
if (!cur || (gapMs && prev && p.t - prev.t > gapMs)) segs.push(cur = []);
cur.push(x(p.t) + "," + y(p.v)); prev = p;
});
segs.forEach(function (sg) {
if (sg.length === 1) { var xy = sg[0].split(","); g.appendChild(s("circle", { cx: xy[0], cy: xy[1], r: "0.8", fill: color })); return; }
g.appendChild(s("polyline", { points: sg.join(" "), fill: "none", stroke: color, "stroke-width": "2", "stroke-linejoin": "round", "vector-effect": "non-scaling-stroke" }));
});
var area = el("div", { class: "area " + hcls }, [g]);
var cross = el("span", { class: "cross", hidden: true });
area.appendChild(cross);
var plot = el("div", { class: "plot" }, [
el("div", { class: "plotrow" }, [el("div", { class: "yt muted " + hcls }, [el("span", { text: fmtY(yMax) }), el("span", { text: fmtY(0) })]), area]),
el("div", { class: "xt muted", style: "padding-left:32px" }, [el("span", { text: fmtClock(from / 1000, true) }), el("span", { text: fmtClock(to / 1000, true) })]),
]);
var tip = tipper(plot);
area.addEventListener("mousemove", function (e) {
if (!points.length) return;
var r = area.getBoundingClientRect();
var at = from + ((e.clientX - r.left) / r.width) * span, best = points[0];
points.forEach(function (p) { if (Math.abs(p.t - at) < Math.abs(best.t - at)) best = p; });
cross.hidden = false; cross.style.left = x(best.t) + "%";
tip.show(e, [el("span", null, [fmtClock(best.t / 1000, true) + " · ", el("span", { class: "mono", text: fmtY(best.v) })])]);
});
area.addEventListener("mouseleave", function () { cross.hidden = true; tip.hide(); });
return plot;
}
// ── scope: the profile switch, the guest chips ───────────────────────────
function scopeSegs() {
var segs = profiles.map(function (p) { return { id: "profile:" + p.id, label: p.label || p.id }; });
if (segs.length) segs.push({ id: "all", label: "All" });
return segs;
}
function scopeWords() {
if (state.scope === "all" || !state.scope) return "All profiles";
var hit = null;
scopeSegs().forEach(function (x) { if (x.id === state.scope) hit = x; });
return hit ? hit.label : "";
}
function renderScope() {
var box = $("scopes");
box.textContent = "";
var segs = scopeSegs();
$("bar").hidden = !segs.length;
segs.forEach(function (x) {
var on = x.id === (state.scope || "all");
box.appendChild(el("button", { type: "button", class: on ? "aia-active" : null, "aria-pressed": on ? "true" : "false", text: x.label,
onclick: function () { if (on) return; state.scope = x.id; if (x.id !== "profile:guests") state.guests = []; persist(); loadAll(); } }));
});
var chips = $("guestchips");
chips.textContent = "";
if (state.scope !== "profile:guests") return;
Object.keys(guestNames).sort(function (a, b) { return nameOf(a).localeCompare(nameOf(b)); }).forEach(function (uid) {
var on = state.guests.indexOf(uid) >= 0;
chips.appendChild(el("button", { type: "button", class: "aia-chip" + (on ? " aia-active" : ""), "aria-pressed": on ? "true" : "false",
onclick: function () {
state.guests = on ? state.guests.filter(function (g) { return g !== uid; }) : state.guests.concat([uid]);
loadAll();
} }, [avatar(uid), " " + nameOf(uid)]));
});
}
// ── the KPIs and the machines ────────────────────────────────────────────
function renderKpis(d) {
var cpu = sum(d.sessions, function (x) { return x.cpu; }), rss = sum(d.sessions, function (x) { return x.rss; });
var procs = sum(d.sessions, function (x) { return x.procs; });
var left = sum(d.leftovers, function (g) { return g.procs; }), leftRss = sum(d.leftovers, function (g) { return g.rss; });
var cores = sum(d.machines, function (m) { return m.host && m.host.cpus; }), mem = sum(d.machines, function (m) { return m.host && m.host.memTotal; });
var box = $("kpis"); box.textContent = "";
[["bot", "Agents", String(d.sessions.length), plural(procs, "process", "processes")],
["cpu", "Agents' CPU", fmtCores(cpu), cores ? "of " + cores + " cores" : ""],
["mem", "Agents' RAM", fmtBytes(rss), mem ? "of " + fmtBytes(mem) : ""],
["skull", "Leftovers", String(left), left ? fmtBytes(leftRss) : "none"]].forEach(function (k) {
box.appendChild(el("div", { class: "kpi aia-card" }, [
el("div", { class: "lbl muted" }, [svg(k[0]), k[1]]),
el("div", { class: "val mono", text: k[2] }),
k[3] ? el("div", { class: "sub muted", text: k[3] }) : null,
]));
});
}
function renderMachines(d) {
var box = $("machines"); box.textContent = "";
d.machines.forEach(function (m) {
var h = m.host, ag = m.agents || { count: 0, cpu: 0, rss: 0 };
var guests = m.owner ? [] : Array.from(new Set(d.sessions.filter(function (x) { return x.runner === m.id && x.guest; }).map(function (x) { return x.guest; })));
var memUsed = h && h.memTotal != null && h.memAvailable != null ? h.memTotal - h.memAvailable : null;
var kids = [el("div", { class: "mhead" }, [svg(m.platform === "darwin" ? "laptop" : "server"), el("span", { class: "trunc", text: m.name }),
guestPill(m.owner), guestStack(guests),
el("span", { class: "right muted", text: h ? plural(ag.count || 0, "agent") : !m.online ? "offline" : "" })])];
if (h) {
kids.push(meter("CPU · " + h.cpus + " cores", ag.cpu, h.cpu != null ? h.cpu : null, h.cpus * 100,
function (v) { return Math.round(v / h.cpus) + "%"; },
[h.cpu != null ? Math.round(h.cpu / h.cpus) + "%" : "—", el("span", { class: "muted", text: " busy" })]));
kids.push(meter("Memory", ag.rss, memUsed, h.memTotal, fmtBytes));
kids.push(el("div", { class: "mfoot muted" }, [
h.load ? el("span", { text: "load " + h.load.map(function (l) { return l.toFixed(1); }).join(" · ") }) : null,
h.swapTotal ? el("span", { text: "swap " + fmtBytes(h.swapUsed || 0) + " / " + fmtBytes(h.swapTotal) }) : null,
]));
} else {
kids.push(el("p", { class: "muted", style: "margin:8px 0 0;font-size:11px", text: m.unsupported
? "Its runner predates the Performance dashboard — it reports once it updates to the hub's commit."
: !m.online ? "Not reachable right now." : (m.error || "Waiting for the first reading…") }));
}
box.appendChild(el("div", { class: "aia-card machine" + (h ? "" : " off") }, kids));
});
}
// ── the process tree ─────────────────────────────────────────────────────
function processRows(rows, extra) {
return el("ul", { class: "rows" }, rows.map(function (p) {
return el("li", { class: "proc" }, [
el("div", { class: "grow", style: "padding-left:" + Math.min(p.depth || 0, 6) * 12 + "px" }, [
el("div", { class: "line1", style: "font-size:12px" }, [
p.kind === "tool" ? el("span", { class: "tool", title: "A Bash command the agent ran — the numbers include everything under it" }, [svg("term", "sm")]) : null,
el("span", { class: "trunc", style: "font-weight:500", text: p.label }),
p.detached ? el("span", { class: "tag muted", title: "Left the run's process tree (setsid / nohup) but still belongs to it", text: "detached" }) : null,
]),
el("div", { class: "cmd trunc muted", title: p.cmd, text: p.cmd }),
]),
el("div", { class: "num w14 muted", title: "CPU now (% of one core)", text: fmtPct(p.cpu) }),
el("div", { class: "num w16", title: p.kind === "tool" ? "this command and everything it started: " + fmtBytes(p.treeRss) + " · " + fmtCpuTime(p.treeCpuSeconds) + " CPU" : "resident memory",
text: fmtBytes(p.kind === "tool" ? p.treeRss : p.rss) }),
el("div", { class: "num w14 muted", style: "font-size:11px", title: "running for", text: fmtSpan(now() - p.startedAt) }),
extra ? extra(p) : null,
]);
}));
}
function machineNames(d) { var o = {}; d.machines.forEach(function (m) { o[m.id] = m.name; }); return o; }
function manyMachines(d) { return d.machines.filter(function (m) { return m.host; }).length > 1; }
// ── running now ──────────────────────────────────────────────────────────
function renderLive(d) {
var names = machineNames(d), many = manyMachines(d);
var rows = d.sessions.slice().sort(function (a, b) { return state.liveSort === "rss" ? b.rss - a.rss : (b.cpu || 0) - (a.cpu || 0); });
var maxRss = Math.max(1, maxOf(rows.map(function (x) { return x.rss; })));
var top = rows[0];
panel($("live"), "live", {
title: "Running now", question: "Which agents are using the machine right now, and on what?",
finding: top ? [N(rows.length), " agent" + (rows.length === 1 ? "" : "s") + " running; " + (top.title ? "“" + top.title + "”" : "the heaviest") + " holds ",
N(fmtBytes(top.rss)), " over ", N(top.procs), " process" + (top.procs === 1 ? "" : "es") + "."] : "No agent is running.",
body: function () {
var wrap = el("div");
if (rows.length) wrap.appendChild(el("div", { class: "seg-r" }, [segEl(["rss", "cpu"], state.liveSort, function (k) { state.liveSort = k; renderLive(D.live); },
function (k) { return k === "rss" ? "by memory" : "by CPU"; })]));
rows.forEach(function (x) {
var k = x.runner + "/" + x.sessionId + "/" + x.rootPid;
var open = !!state.open[k];
var li = el("div", { class: "run" }, [el("button", { type: "button", class: "head",
onclick: function () { state.open[k] = !open; renderLive(D.live); } }, [
svg("chev", "chev" + (open ? " open" : "")),
el("div", { class: "grow" }, [
el("div", { class: "line1" }, [convLink(x, "strong"), guestPill(x.guest), many && names[x.runner] ? el("span", { class: "mchip muted", text: names[x.runner] }) : null]),
el("div", { class: "minibar", title: fmtBytes(x.rss) + " resident" }, [el("div", { style: "width:" + (x.rss / maxRss) * 100 + "%" })]),
el("div", { class: "meta muted", text: x.harness + (x.source === "terminal" ? " · terminal" : "") + " · " + plural(x.procs, "process", "processes") + " · " +
fmtCpuTime(x.cpuSeconds) + " CPU since " + relTime(x.startedAt) }),
]),
el("div", { class: "num w14 muted", title: "CPU now, the whole tree (% of one core)", text: fmtPct(x.cpu) }),
el("div", { class: "num w16", style: "font-weight:500", text: fmtBytes(x.rss) }),
])]);
if (open) li.appendChild(el("div", { class: "tree" }, [processRows(x.processes || [])]));
wrap.appendChild(li);
});
return wrap;
},
});
}
// ── leftovers ────────────────────────────────────────────────────────────
function kill(t) {
return act(Object.assign({ op: "kill" }, t)).then(function (r) {
var n = (r.killed || []).length;
var gone = r.missing && r.missing.length ? " (" + r.missing.length + " had already gone)" : "";
toast(n ? "Stopped " + plural(n, "process", "processes") + gone : "Nothing to stop" + gone, n ? "success" : "info");
refreshLive();
}).catch(function (e) { toast("Kill failed: " + ((e && e.message) || e), "error"); });
}
function keep(runner, p) {
act({ op: "keep", runner: runner, pid: p.pid, startedAt: p.startedAt, kept: !p.kept }).then(refreshLive)
.catch(function (e) { toast(String((e && e.message) || e), "error"); });
}
function saveSettings(patch) {
act(Object.assign({ op: "settings" }, patch)).then(refreshLive).catch(function (e) { toast("Couldn't save: " + ((e && e.message) || e), "error"); });
}
function renderLeftovers(d) {
var box = $("leftovers");
// with something left behind it comes right after the live runs, else at the bottom
var where = d.leftovers.length ? $("history") : $("bottom");
if (box.nextSibling !== where) where.parentNode.insertBefore(box, where);
if (box.contains(document.activeElement) && document.activeElement.tagName === "INPUT") return; // typing in a setting
var names = machineNames(d), many = manyMachines(d), st = d.settings || {};
var total = sum(d.leftovers, function (g) { return g.rss; }), count = sum(d.leftovers, function (g) { return g.procs; });
panel(box, "leftovers", {
title: "Leftover processes", question: "What did ended conversations leave running?",
finding: count ? [N(count), " process" + (count === 1 ? "" : "es") + " from ", N(d.leftovers.length), " ended conversation" + (d.leftovers.length === 1 ? "" : "s") + " still hold ", N(fmtBytes(total)),
st.autoKill ? el("span", null, [" — stopped automatically after ", N(st.autoKillHours + " h"), " unless kept."]) : "."]
: "Nothing left behind — every ended conversation cleaned up after itself.",
body: function () {
var wrap = el("div");
d.leftovers.forEach(function (g) {
wrap.appendChild(el("div", { class: "group" }, [
el("div", { class: "line1" }, [
el("div", { class: "grow" }, [
el("div", { class: "line1" }, [convLink(g, "strong"), guestPill(g.guest), many && names[g.runner] ? el("span", { class: "mchip muted", text: names[g.runner] }) : null]),
el("div", { class: "meta muted", text: (g.endedAt ? "ended " + relTime(g.endedAt) : "ended") + " · " + plural(g.procs, "process", "processes") + " · " + fmtBytes(g.rss) }),
]),
confirmBtn([svg("skull", "sm"), " Kill all"], "Kill all?", "Stop every leftover of this conversation (SIGTERM, then SIGKILL)",
function () { kill({ runner: g.runner, sessionId: g.sessionId }); }),
]),
processRows(g.processes || [], function (p) {
return el("div", { class: "acts" }, [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.runner, 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 }] }); }),
]);
}),
]));
});
wrap.appendChild(autoKillSettings(st));
return wrap;
},
});
}
function autoKillSettings(st) {
var hours = el("input", { type: "number", min: "1", class: "aia-input mono", value: String(st.autoKillHours || 24), disabled: st.autoKill ? null : true });
function commit() {
var h = Math.round(Number(hours.value));
if (isFinite(h) && h >= 1 && h !== st.autoKillHours) saveSettings({ autoKillHours: h });
else hours.value = String(st.autoKillHours);
}
hours.addEventListener("blur", commit);
hours.addEventListener("keydown", function (e) { if (e.key === "Enter") commit(); });
var sw = el("input", { type: "checkbox", checked: st.autoKill ? true : null });
sw.addEventListener("change", function () { saveSettings({ autoKill: sw.checked }); });
var labels = st.keepLabels || [];
var add = el("input", { class: "aia-input xs mono", placeholder: "add a label…" });
function addLabel() {
var l = add.value.trim();
add.value = "";
if (l && labels.indexOf(l) < 0) saveSettings({ keepLabels: labels.concat([l]) });
}
add.addEventListener("keydown", function (e) { if (e.key === "Enter") addLabel(); });
add.addEventListener("blur", addLabel);
return el("div", { class: "autokill" }, [
el("div", { class: "r" }, [el("label", { class: "r" }, [sw, "Auto-kill leftovers after"]), hours, el("span", { class: "muted", text: "hours" })]),
el("div", { class: "r" }, [el("span", { class: "r muted", title: "Shared daemons that inherited a session's environment — opencode serve is started by the first opencode run and serves every later one" },
[svg("alert", "sm"), "Never auto-killed:"])].concat(labels.map(function (l) {
return el("span", { class: "label-chip" }, [l, el("button", { type: "button", title: "Let the auto-kill stop " + l,
onclick: function () { saveSettings({ keepLabels: labels.filter(function (x) { return x !== l; }) }); } }, [svg("x", "sm")])]);
})).concat([add])),
]);
}
// ── over time ────────────────────────────────────────────────────────────
var PALETTE = ["var(--s0)", "var(--s1)", "var(--s2)", "var(--s3)", "var(--s4)", "var(--s5)", "var(--s6)", "var(--s7)"];
/** A band per conversation in order of first appearance (never by rank), past the eighth folded into Other. */
function bandsOf(h, metric) {
var first = function (v) { var i = v.findIndex(function (x) { return x > 0; }); return i < 0 ? Infinity : i; };
var series = h.series.slice().sort(function (a, b) { return first(a.cpu) - first(b.cpu) || first(a.rss) - first(b.rss); });
var own = series.slice(0, PALETTE.length), rest = series.slice(PALETTE.length);
var fold = function (m) { return h.other[m].map(function (v, i) { return v + sum(rest, function (x) { return x[m][i]; }); }); };
var stats = function (cpu, rss) { return { peakRss: maxOf(rss), peakCpu: maxOf(cpu), avgCpu: sum(cpu) / Math.max(1, cpu.length) }; };
var bands = own.map(function (x, i) {
return Object.assign({ key: x.sessionId, label: x.title || "session " + x.sessionId.slice(0, 8), color: PALETTE[i], values: x[metric], guest: x.guest }, stats(x.cpu, x.rss));
});
var other = fold(metric);
if (other.some(function (v) { return v > 0; })) bands.push(Object.assign({ key: "other", label: "Other", color: "var(--other)", values: other }, stats(fold("cpu"), fold("rss"))));
return bands;
}
function renderHistory() {
var lv = D.live, h = D.history;
var machines = lv ? lv.machines : [];
var reporting = machines.filter(function (m) { return m.host || m.id === "lab"; });
var pool = reporting.length ? reporting : machines;
var runner = (pool.filter(function (m) { return m.id === state.runner; })[0] || pool[0] || { id: "lab" }).id;
var machine = h && (h.machines || []).filter(function (m) { return m.id === runner; })[0];
var cpuB = h ? bandsOf(h, "cpu") : [], rssB = h ? bandsOf(h, "rss") : [];
var aCpu = h ? h.t.map(function (_, i) { return sum(cpuB, function (b) { return b.values[i]; }); }) : [];
var aRss = h ? h.t.map(function (_, i) { return sum(rssB, function (b) { return b.values[i]; }); }) : [];
var cpus = (machine && machine.cpus) || 1;
var heaviest = rssB.filter(function (b) { return b.key !== "other"; }).sort(function (a, b) { return b.peakRss - a.peakRss; })[0];
panel($("history"), "history", {
title: "Over time", question: "When were the agents heavy, and which conversation was it?",
finding: h && h.series.length ? ["Agents averaged ", N((sum(aCpu) / Math.max(1, aCpu.length) / 100).toFixed(1) + " cores"), " of ", N(cpus), " and peaked at ", N(fmtBytes(maxOf(aRss))), " of memory",
heaviest ? el("span", null, ["; the heaviest was “" + heaviest.label + "” at ", N(fmtBytes(heaviest.peakRss))]) : null, "."]
: h ? "No agent ran in this window." : (errs.history || null),
table: function () { return dataTable(["Conversation", "Avg CPU", "Peak CPU", "Peak RAM"], rssB.map(function (b) { return [b.label, fmtPct(b.avgCpu), fmtPct(b.peakCpu), fmtBytes(b.peakRss)]; })); },
body: function () {
var wrap = el("div");
var segs = el("div", { class: "segrow" }, [segEl(HISTORY_RANGES, state.historyRange, function (r) { state.historyRange = r; persist(); loadHistory(); })]);
if (pool.length > 1) segs.appendChild(segEl(pool.map(function (m) { return m.id; }), runner, function (id) { state.runner = id; loadHistory(); },
function (id) { var m = machines.filter(function (x) { return x.id === id; })[0]; return m ? m.name : id; }));
wrap.appendChild(segs);
if (!h) return wrap;
var yCpu = Math.max(100, maxOf((machine && machine.cpu) || []), maxOf(aCpu)) * 1.05;
wrap.appendChild(el("div", { class: "chartlbl muted", text: "CPU, in cores" }));
wrap.appendChild(stackedArea(h.t, cpuB, machine && machine.cpu, yCpu, fmtCores, "h160"));
wrap.appendChild(el("div", { class: "chartlbl muted", style: "margin-top:16px", text: "Memory" }));
wrap.appendChild(stackedArea(h.t, rssB, machine && machine.mem, (machine && machine.memTotal) || Math.max(1, maxOf(aRss)), fmtBytes, "h160"));
var lg = el("div", { class: "legend muted" }, [el("span", null, [el("span", { class: "dash" }), "whole machine"])]);
rssB.forEach(function (b) { lg.appendChild(el("span", null, [el("span", { class: "sw", style: "background:" + b.color }), el("span", { class: "trunc", text: b.label }), guestPill(b.guest)])); });
wrap.appendChild(lg);
return wrap;
},
});
}
// ── heaviest commands ────────────────────────────────────────────────────
function renderCommands() {
var d = D.commands, rows = (d && d.rows) || [];
var max = Math.max(1, maxOf(rows.map(function (r) { return r.cpuSeconds; })));
var top = rows[0];
panel($("commands"), "commands", {
title: "Heaviest commands",
question: state.kind === "tool" ? "Which commands the agents run cost the most — what to optimise first?" : "Which programs used the most CPU and memory?",
finding: top ? [el("code", { text: top.label }), " leads: ", N(top.count), " run" + (top.count === 1 ? "" : "s") + " in ", N(top.conversations), " conversation" + (top.conversations === 1 ? "" : "s") + " used ",
N(fmtCpuTime(top.cpuSeconds)), " of CPU (up to ", N(fmtCpuTime(top.maxCpuSeconds)), " a run), peaking at ", N(fmtBytes(top.peakRss)), "."]
: d ? "Nothing recorded yet in this window — commands show up once they have run for a few seconds." : (errs.commands || null),
table: function () {
return dataTable(["Command", "Runs", "CPU total", "Max / run", "Peak RAM", "Avg time"], rows.map(function (r) {
return [r.label, r.count, fmtCpuTime(r.cpuSeconds), fmtCpuTime(r.maxCpuSeconds), fmtBytes(r.peakRss), fmtSpan(r.avgDuration)];
}));
},
body: function () {
var wrap = el("div", null, [el("div", { class: "segrow" }, [segEl(["tool", "program"], state.kind, function (k) { state.kind = k; loadCommands(); },
function (k) { return k === "tool" ? "Bash commands" : "Programs"; })])]);
var ul = el("ul", { class: "rows" });
rows.slice(0, 25).forEach(function (r) {
var open = state.openCmd === r.label;
var li = el("li", null, [el("button", { type: "button", class: "head", style: "display:flex;width:100%;align-items:center;gap:8px;padding:6px 0;background:none;border:0;color:inherit;font:inherit;text-align:left;cursor:pointer",
onclick: function () { state.openCmd = open ? null : r.label; renderCommands(); } }, [
svg("chev", "sm chev" + (open ? " open" : "")),
el("div", { class: "grow" }, [
el("div", { class: "line1", style: "font-size:12px" }, [el("code", { class: "trunc", style: "font-weight:500", text: r.label }),
el("span", { class: "muted note10", style: "flex-shrink:0", text: r.count + "× · " + r.conversations + " conv · ~" + fmtSpan(r.avgDuration) }), guestStack(r.guests || [])]),
el("div", { class: "minibar" }, [el("div", { style: "width:" + (r.cpuSeconds / max) * 100 + "%" })]),
]),
el("div", { class: "num w16", title: "CPU time, all runs", text: fmtCpuTime(r.cpuSeconds) }),
el("div", { class: "num w16 muted", title: "peak memory of one run", text: fmtBytes(r.peakRss) }),
])]);
if (open && r.example) {
var ex = r.example;
li.appendChild(el("div", { class: "example" }, [
el("div", { class: "muted" }, ["Heaviest run (" + fmtCpuTime(ex.cpuSeconds) + " CPU, " + fmtBytes(ex.peakRss) + ", ~" + fmtSpan(ex.duration || 0) + ") in ", convLink(ex), guestPill(ex.guest), ":"]),
el("pre", { text: ex.cmd || "" }),
(r.top || []).length > 1 ? el("div", null, [el("div", { class: "muted", text: "Where it ran most:" })].concat(r.top.map(function (t) {
return el("div", { class: "line1", style: "font-size:11px" }, [convLink(t), guestPill(t.guest), el("span", { class: "grow" }), el("span", { class: "mono muted", text: fmtCpuTime(t.cpuSeconds) })]);
}))) : null,
]));
}
ul.appendChild(li);
});
wrap.appendChild(ul);
return wrap;
},
});
}
// ── per conversation ─────────────────────────────────────────────────────
function renderConvs() {
var d = D.convs, names = D.live ? machineNames(D.live) : {};
var rows = ((d && d.rows) || []).slice().sort(function (a, b) { return state.convSort === "cpu" ? b.cpuSeconds - a.cpuSeconds : b.peakRss - a.peakRss; });
var top = rows[0], total = sum(rows, function (r) { return r.cpuSeconds; });
panel($("convs"), "convs", {
title: "Per conversation", question: "Which conversations were the heaviest overall?",
finding: top ? [N(rows.length), " conversations used ", N(fmtCpuTime(total)), " of CPU; “" + (top.title || top.sessionId.slice(0, 8)) + "”",
state.convSort === "cpu" ? el("span", null, [" alone used ", N(fmtCpuTime(top.cpuSeconds)), " (", N(Math.round((top.cpuSeconds / Math.max(1, total)) * 100) + "%"), ")"])
: el("span", null, [" peaked highest, at ", N(fmtBytes(top.peakRss))]), "."]
: d ? "No conversation recorded in this window yet." : (errs.convs || null),
table: function () {
return dataTable(["Conversation", "CPU time", "Peak RAM", "Peak procs", "Heaviest command"], rows.map(function (r) {
return [r.title || r.sessionId.slice(0, 8), fmtCpuTime(r.cpuSeconds), fmtBytes(r.peakRss), r.peakProcs, r.heaviest ? r.heaviest.label : "—"];
}));
},
body: function () {
var wrap = el("div", null, [el("div", { class: "segrow" }, [segEl(["cpu", "rss"], state.convSort, function (k) { state.convSort = k; renderConvs(); },
function (k) { return k === "cpu" ? "by CPU time" : "by peak memory"; })])]);
wrap.appendChild(el("ul", { class: "rows" }, rows.slice(0, 30).map(function (r) {
return el("li", { class: "proc" }, [
el("div", { class: "grow" }, [
el("div", { class: "line1", style: "font-size:12px" }, [
r.live ? el("span", { title: "Running now", style: "color:var(--good);display:inline-flex" }, [svg("radio", "sm")]) : null,
convLink(r, "strong"), guestPill(r.guest),
r.runner !== "lab" ? el("span", { class: "mchip muted", text: names[r.runner] || r.runner }) : null]),
el("div", { class: "meta muted trunc" }, [r.harness + (r.source === "terminal" ? " · terminal" : "") + " · up to " + r.peakProcs + " processes",
r.heaviest ? el("span", null, [" · heaviest ", el("code", { text: r.heaviest.label }), " (" + fmtCpuTime(r.heaviest.cpuSeconds) + ")"]) : null]),
]),
el("div", { class: "num w16", title: "CPU time, the whole tree", text: fmtCpuTime(r.cpuSeconds) }),
el("div", { class: "num w16 muted", title: "peak memory", text: fmtBytes(r.peakRss) }),
]);
})));
return wrap;
},
});
}
// ── the hub itself (telemetry) ───────────────────────────────────────────
var VITALS = [
{ name: "LCP", label: "Largest paint", good: 2500, poor: 4000 },
{ name: "INP", label: "Tap → response", good: 200, poor: 500 },
{ name: "CLS", label: "Layout shift", good: 0.1, poor: 0.25 },
{ name: "update", label: "New turn → on screen", good: 1000, poor: 3000 },
{ name: "FCP", label: "First paint", good: 1800, poor: 3000 },
{ name: "TTFB", label: "First byte", good: 800, poor: 1800 },
];
function vitalDef(name) { return VITALS.filter(function (v) { return v.name === name; })[0]; }
function rate(name, v) { var t = vitalDef(name); if (!t || v == null) return null; return v <= t.good ? "good" : v <= t.poor ? "needs work" : "poor"; }
var RATING = { good: "var(--good)", "needs work": "var(--warn)", poor: "var(--bad)" };
function fmtVital(name, v) { return v == null ? "—" : name === "CLS" ? v.toFixed(2) : fmtMs(v); }
function vital(web, name, device) { return web.filter(function (w) { return w.name === name && w.device === (device || "all"); })[0]; }
function niceMax(v, floor) {
var x = Math.max(v, floor == null ? 10 : floor), p = Math.pow(10, Math.floor(Math.log10(x)));
var ms = [1, 2, 2.5, 5, 10];
for (var i = 0; i < ms.length; i++) if (x <= ms[i] * p) return ms[i] * p;
return 10 * p;
}
function worst(series, key) { var best = null; series.forEach(function (p) { if (p[key] != null && (!best || p[key] > best[key])) best = p; }); return best; }
function points(series, key) {
return series.filter(function (p) { return p[key] != null && (key.indexOf("lag") === 0 || p.n > 0); }).map(function (p) { return { t: p.t * 1000, v: p[key] }; });
}
function splitRoute(r) { var i = r.indexOf(" "); return i < 0 ? { method: "", path: r } : { method: r.slice(0, i), path: r.slice(i + 1) }; }
function hubPanel(id, o) { var box = el("section", { class: "aia-card" }); panel(box, id, o); return box; }
function renderHub() {
var box = $("hub");
seg($("hubRange"), HUB_RANGES, state.hubRange, function (r) { state.hubRange = r; loadHub(); });
box.textContent = "";
var h = D.hub;
if (!h) { box.appendChild(el("div", { class: "aia-card muted", text: errs.hub || "" })); return; }
var tot = h.totals || {}, rate5 = tot.n ? tot.err / tot.n : 0, series = h.series || [];
var k = el("div", { class: "kpis" });
[["timer", "API p95", fmtMs(tot.p95), "p50 " + fmtMs(tot.p50) + " · " + (tot.n || 0).toLocaleString("en-US") + " calls", (tot.p95 || 0) > 2000],
["alert", "5xx", String(tot.err || 0), tot.n ? (rate5 * 100).toFixed(rate5 < 0.01 ? 2 : 1) + "% of calls" : "no calls", rate5 > 0.01],
["gauge", "Loop lag p95", fmtMs(tot.lagP95), "worst " + fmtMs(tot.lagMax), (tot.lagP95 || 0) > 1000],
["radio", "Live streams", String((h.now && h.now.sse) || 0), "peak " + maxOf(series.map(function (p) { return p.sse || 0; })) + " in range", false]].forEach(function (x) {
k.appendChild(el("div", { class: "kpi aia-card" }, [el("div", { class: "lbl muted" }, [svg(x[0]), x[1]]), el("div", { class: "val mono" + (x[4] ? " bad" : ""), text: x[2] }), el("div", { class: "sub muted", text: x[3] })]));
});
box.appendChild(k);
// speed
var p95 = points(series, "p95"), lag = points(series, "lagP95");
var to = Date.now(), from = to - { "24h": 86400e3, "7d": 7 * 86400e3, "30d": 30 * 86400e3 }[state.hubRange];
var withDay = state.hubRange !== "24h", w = worst(series, "p95"), wl = worst(series, "lagMax");
box.appendChild(hubPanel("speed", {
title: "Is the hub answering fast?", question: "API latency (p95) and how late the event loop ran",
finding: !tot.n ? "No API call counted in this range yet — the history fills a minute at a time."
: [N((tot.n || 0).toLocaleString("en-US")), " calls: half answered under ", N(fmtMs(tot.p50)), ", 95 % under ", N(fmtMs(tot.p95)), ".",
w && w.p95 != null ? el("span", null, [" The slowest stretch reached ", N(fmtMs(w.p95)), " at " + fmtClock(w.t, withDay) + "."]) : null,
wl && wl.lagMax != null && wl.lagMax > 250 ? el("span", null, [" The event loop stalled up to ", N(fmtMs(wl.lagMax)), " (" + fmtClock(wl.t, withDay) + ") — nothing was served meanwhile."])
: " The event loop never stalled past 250 ms."],
table: function () {
return dataTable(["When", "Calls", "5xx", "p50", "p95", "Lag p95", "Lag max"], series.slice().reverse().slice(0, 96).map(function (p) {
return [fmtClock(p.t, withDay), p.n, p.err, fmtMs(p.p50), fmtMs(p.p95), fmtMs(p.lagP95), fmtMs(p.lagMax)];
}));
},
body: function () {
return el("div", { class: "aia-stack" }, [
el("div", null, [el("div", { class: "chartlbl", text: "API p95" }),
linePlot(p95, from, to, niceMax(maxOf(p95.map(function (p) { return p.v; }))), fmtMs, "var(--s0)", (h.step || 60) * 3000, "h80")]),
el("div", null, [el("div", { class: "chartlbl", text: "Event-loop lag (p95)" }),
linePlot(lag, from, to, niceMax(maxOf(lag.map(function (p) { return p.v; })), 50), fmtMs, "var(--s1)", (h.step || 60) * 3000, "h64")]),
]);
},
}));
// routes
var routes = h.routes || [], totalMs = sum(routes, function (r) { return r.sumMs; });
var rows = routes.map(function (r) { return Object.assign({ share: totalMs ? (r.sumMs || 0) / totalMs : 0 }, r); });
if (rows.length) {
var top = rows[0];
box.appendChild(hubPanel("routes", {
title: "Where does the time go?", question: "Routes by total time answering · " + fmtMs(totalMs) + " in all",
finding: [N(splitRoute(top.route).path), " takes ", N(Math.round(top.share * 100) + "%"), " of the time spent answering (" + top.n.toLocaleString("en-US") + " calls, p95 ", N(fmtMs(top.p95)), ")",
rows[1] ? el("span", null, [", then " + splitRoute(rows[1].route).path + " at ", N(Math.round(rows[1].share * 100) + "%")]) : null, "."],
table: function () { return dataTable(["Route", "Calls", "5xx", "p50", "p95", "Max", "Total"], rows.map(function (r) { return [r.route, r.n, r.err, fmtMs(r.p50), fmtMs(r.p95), fmtMs(r.max), fmtMs(r.sumMs)]; })); },
body: function () {
var wrap = el("div", { class: "aia-stack", style: "gap:6px" });
(state.routesAll ? rows : rows.slice(0, 8)).forEach(function (r) {
var sp = splitRoute(r.route);
wrap.appendChild(el("div", { class: "route" }, [el("span", { class: "m mono muted", text: sp.method }),
el("div", { class: "grow" }, [el("div", { class: "mono trunc", title: r.route, text: sp.path }), el("div", { class: "b", style: "width:" + Math.max(r.share * 100, r.share > 0 ? 1.5 : 0) + "%" })]),
el("span", { class: "r mono muted" }, [el("span", { style: "display:block;color:hsl(var(--foreground))", text: "p95 " + fmtMs(r.p95) }), el("span", { style: "display:block", text: r.n.toLocaleString("en-US") + " calls" })])]));
});
if (rows.length > 8) wrap.appendChild(el("button", { type: "button", class: "linkbtn", text: state.routesAll ? "Show fewer" : "Show all " + rows.length,
onclick: function () { state.routesAll = !state.routesAll; renderHub(); } }));
return wrap;
},
}));
}
// the browser
var web = h.web || [], devices = ["phone", "tablet", "desktop"].filter(function (dv) { return web.some(function (x) { return x.device === dv; }); });
var names = VITALS.filter(function (v) { return web.some(function (x) { return x.name === v.name; }); });
if (!names.length) {
box.appendChild(hubPanel("vitals", { title: "How does it feel in the browser?", question: "Web vitals at p75, by device",
finding: "No browser has reported yet — every open tab sends its measures every 30 s and when it hides.", body: function () { return el("div"); } }));
} else {
var poorest = [];
names.forEach(function (v) { devices.forEach(function (dv) { var x = vital(web, v.name, dv); if (x && rate(v.name, x.p75) !== "good") poorest.push({ v: v, d: dv, w: x }); }); });
poorest.sort(function (a, b) { return (rate(b.v.name, b.w.p75) === "poor" ? 1 : 0) - (rate(a.v.name, a.w.p75) === "poor" ? 1 : 0); });
var upd = vital(web, "update");
box.appendChild(hubPanel("vitals", {
title: "How does it feel in the browser?", question: "Web vitals at p75, by device",
finding: [poorest.length ? el("span", null, [poorest[0].v.label + " on " + poorest[0].d + "s is ", N(fmtVital(poorest[0].v.name, poorest[0].w.p75)), " at p75 (" + rate(poorest[0].v.name, poorest[0].w.p75) + ")."])
: "Every vital is in the good band on every device.",
upd && upd.p75 != null ? el("span", null, [" A new turn reaches the open thread in ", N(fmtMs(upd.p75)), " (p75, " + upd.n + " measures)."]) : null],
table: function () { return dataTable(["Measure", "Device", "Measures", "p75", "Rating"], web.map(function (x) { var v = vitalDef(x.name); return [v ? v.label : x.name, x.device, x.n, fmtVital(x.name, x.p75), rate(x.name, x.p75) || "—"]; })); },
body: function () {
return el("div", { class: "tbl" }, [el("table", { class: "aia-table vit" }, [
el("thead", null, [el("tr", null, [el("th", { text: "Measure" })].concat(devices.map(function (dv) { return el("th", { class: "aia-num", text: dv }); })))]),
el("tbody", null, names.map(function (v) {
return el("tr", null, [el("td", null, [el("div", { text: v.label }), el("div", { class: "muted note10", text: "good ≤ " + fmtVital(v.name, v.good) })])].concat(devices.map(function (dv) {
var x = vital(web, v.name, dv), r = rate(v.name, x && x.p75);
return el("td", { class: "aia-num", title: x ? x.n + " measures" : null }, [r ? el("span", { class: "dot", style: "background:" + RATING[r] + ";margin-right:6px", title: r }) : null, fmtVital(v.name, x && x.p75)]);
})));
})),
])]);
},
}));
}
// errors
var errors = h.errors || [], total = sum(errors, function (e) { return e.n; });
box.appendChild(hubPanel("errors", {
title: "What broke in the browser?", question: "Uncaught errors and rejections, most frequent first",
finding: !total ? "No JS error reported in " + state.hubRange + "."
: [N(total), " uncaught error" + (total === 1 ? "" : "s") + " in " + state.hubRange + "; the most frequent, on ", el("code", { text: errors[0].page }), ": “" + String(errors[0].message).slice(0, 80) + "” (", N(errors[0].n + "×"), ")."],
body: function () {
return total ? dataTable(["Message", "Page", "Times", "Last"], errors.map(function (e) { return [String(e.message), e.page, e.n, e.last ? fmtClock(e.last, true) : "—"]; })) : el("div");
},
}));
}
// ── reads ────────────────────────────────────────────────────────────────
var Q = {};
function scopePayload(extra) { return Object.assign({ scope: state.scope, guests: state.guests }, extra || {}); }
function sub(name, payload, every) {
if (Q[name]) Q[name].h.stop();
clearInterval(Q[name] && Q[name].t);
var my = (Q[name] = { h: null, t: null });
my.h = read(payload, function (d, meta) {
if (Q[name] !== my) return;
meta = meta || {};
errs[name] = meta.error || null;
if (d) D[name] = d;
else if (!meta.fromCache) D[name] = D[name] || null;
if (name === "live" && d) {
if (Array.isArray(d.profiles) && d.profiles.length) profiles = d.profiles;
if (d.guestNames) guestNames = d.guestNames;
}
renderAll(name);
});
my.t = setInterval(function () { if (!document.hidden && Q[name] === my) my.h.refresh(); }, every);
}
function refreshLive() { if (Q.live) Q.live.h.refresh(); }
function loadHistory() { sub("history", scopePayload({ view: "history", range: state.historyRange, runner: state.runner || "" }), state.historyRange === "1h" ? 15000 : 60000); renderAll("history"); }
function loadCommands() { sub("commands", scopePayload({ view: "commands", range: state.totals, kind: state.kind }), 60000); renderAll("commands"); }
function loadConvs() { sub("convs", scopePayload({ view: "conversations", range: state.totals }), 60000); renderAll("convs"); }
function loadHub() { sub("hub", { view: "hub", range: state.hubRange }, 60000); }
function loadAll() {
$("content").classList.add("busy");
sub("live", scopePayload({ view: "live" }), 5000);
loadHistory(); loadCommands(); loadConvs();
if (!Q.hub) loadHub();
renderScope();
}
// ── render ───────────────────────────────────────────────────────────────
function showMsg(kind, title, text) {
var box = $("msg");
box.textContent = "";
box.className = kind === "error" ? "aia-error" : "aia-empty";
if (kind === "error") box.textContent = text;
else { box.appendChild(el("strong", { text: title })); if (text) box.appendChild(document.createTextNode(text)); }
box.hidden = false;
$("content").hidden = true;
}
var painted = false;
function renderAll(which) {
var lv = D.live;
if (!api) { showMsg("empty", "Open this page from the ai-agent", ""); return; }
if (!lv) { if (errs.live) showMsg("error", "", errs.live); return; }
if (!painted) { painted = true; which = null; } // the first reading draws every section
$("msg").hidden = true; $("content").hidden = false;
$("content").classList.remove("busy");
var note = $("note");
note.hidden = !errs.live;
note.textContent = errs.live ? "Couldn't refresh (" + errs.live + ") — showing the last reading." : "";
setHeader({ subtitle: (scopeWords() ? scopeWords() + " · " : "") + plural(lv.sessions.length, "agent") + " running · " + fmtBytes(sum(lv.sessions, function (x) { return x.rss; })) });
var y = window.scrollY;
if (!which || which === "live") { renderScope(); renderKpis(lv); renderMachines(lv); renderLive(lv); renderLeftovers(lv); }
if (!which || which === "live" || which === "history") renderHistory();
seg($("totalsRange"), TOTALS_RANGES, state.totals, function (r) { state.totals = r; persist(); loadCommands(); loadConvs(); });
if (!which || which === "commands") renderCommands();
if (!which || which === "convs" || which === "live") renderConvs();
if (!which || which === "hub") renderHub();
window.scrollTo(0, y);
}
document.addEventListener("visibilitychange", function () { if (!document.hidden) Object.keys(Q).forEach(function (k) { Q[k].h.refresh(); }); });
if (api && typeof api.onTheme === "function") api.onTheme(function () { if (D.live) renderAll(); });
// the "running for" and auto-kill clocks tick between readings
setInterval(function () { if (D.live && !document.hidden) renderAll("live"); }, 30000);
if (!api) showMsg("empty", "Open this page from the ai-agent", "");
else loadAll();
})();
</script>
</body>
</html>