// HarnessWeight — the interface. Served by the plugin's own service, so the
// data is a same-origin fetch away.
import { explainFor, COLS, CARD_SORTS } from "./explain.js"
import { pageLanguage, languageTags, translate } from "./i18n.mjs"
const $ = (id) => document.getElementById(id)
const qs = new URLSearchParams(location.search)
// magpie's window language arrives as ?lang= (page/boot.js); opened directly,
// the browser's own language decides
const LANG = pageLanguage(qs.get("lang") || navigator.language || "")
const LOCALE = languageTags[LANG] || "en"
const T = (key, params) => translate(LANG, key, params)
document.documentElement.lang = LOCALE
document.title = T("app.title")
for (const el of document.querySelectorAll("[data-t]")) el.textContent = T(el.dataset.t)
for (const el of document.querySelectorAll("[aria-label-t]")) el.setAttribute("aria-label", T(el.getAttribute("aria-label-t")))
// sandboxed in magpie's frame the origin is opaque and storage throws
const store = {
get(k) { try { return localStorage.getItem(k) } catch { return null } },
set(k, v) { try { localStorage.setItem(k, v) } catch {} },
}
const state = {
period: store.get("al.period") || "7d",
clients: store.get("al.clients") === "1",
sort: { key: "prompt", dir: -1 },
cardSort: "prompt",
toolSort: "avgBytes",
activeAgents: new Map(),
activityKnown: false,
data: null,
openAgent: null,
}
// the service writes a per-start token into this page's HTML
const TOKEN = document.querySelector('meta[name="harnessweight-token"]')?.content || ""
let reloaded = false
const sessionStorageSafe = () => reloaded || location.hash === "#r"
function markReloaded() { reloaded = true; location.hash = "r" }
// ---------- formatting ----------
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c])
function short(n) {
if (n == null || !Number.isFinite(n)) return "—"
const a = Math.abs(n)
if (a >= 1e9) return `${(n / 1e9).toFixed(2)}B`
if (a >= 1e6) return `${(n / 1e6).toFixed(1)}M`
if (a >= 1e3) return `${(n / 1e3).toFixed(1)}K`
return String(Math.round(n))
}
const int = (n) => (n == null ? "—" : Math.round(n).toLocaleString(LOCALE))
const pct = (x) => (x == null || !Number.isFinite(x) ? "—" : `${(x * 100).toFixed(1)}%`)
function secs(ms) {
if (!ms) return "—"
return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`
}
function dur(ms) {
if (ms == null || !Number.isFinite(ms)) return "—"
const m = ms / 60000
if (m < 1) return `${Math.round(ms / 1000)}${esc(T("dur.second"))}`
if (m < 60) return `${m.toFixed(0)}${esc(T("dur.minute"))}`
const h = m / 60
if (h < 24) return `${h.toFixed(1)}${esc(T("dur.hour"))}`
return `${(h / 24).toFixed(1)}${esc(T("dur.day"))}`
}
function when(at) {
if (!at) return "—"
return new Date(at).toLocaleString(LOCALE, { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" })
}
// ---------- agent mark: magpie's own icon, else the initial ----------
const PALETTE = ["#17A9A2", "#F26B1D", "#6D5DFC", "#2B8AE2", "#C2410C", "#0E7C77", "#8B5CF6", "#64748B"]
function hue(s) { let h = 0; for (const c of String(s)) h = (h * 31 + c.charCodeAt(0)) >>> 0; return PALETTE[h % PALETTE.length] }
function mark(a, size = 20) {
const initial = esc(String(a.name || a.agent || "?").trim().charAt(0).toUpperCase())
const letter = `${initial}`
if (!a.icon) return letter
return ``
}
const label = (a) => esc(a.name || a.agent)
// ---------- explanations ----------
// A small "?" that shows what a number means on hover or keyboard focus. The
// text lives in explain.js; this only renders the marker.
// A label with a small "?" next to it that opens the explanation on hover or
// keyboard focus. The label itself stays plain text; only the marker is a
// button, so a label never gets squeezed by the marker.
function tip(key, label) {
const e = explainFor(key, LANG)
if (!e.title || e.title.startsWith("explain.")) return label ?? ""
return `${label ?? ""}${esc(e.title)}${esc(e.body)}`
}
// Render notes outside scroll containers so table and drawer overflow never clip them.
let activeTip = null
function closeTip() {
if (!activeTip) return
activeTip.trigger.setAttribute('aria-expanded', 'false')
activeTip.bubble.remove()
activeTip = null
}
function wireTips(root) {
for (const t of root.querySelectorAll('.tip:not([data-wired])')) {
t.dataset.wired = '1'
const open = () => {
if (activeTip?.trigger === t) return
closeTip()
const bubble = document.createElement('div')
bubble.className = 'floating-tip'
bubble.setAttribute('aria-hidden', 'true') // trigger already contains the full accessible label
bubble.innerHTML = t.querySelector('.tip-body').innerHTML
document.body.append(bubble)
const r = t.getBoundingClientRect(), b = bubble.getBoundingClientRect()
const left = Math.max(8, Math.min(window.innerWidth - b.width - 8, r.left + r.width / 2 - b.width / 2))
const top = r.top >= b.height + 10 ? r.top - b.height - 8 : Math.min(window.innerHeight - b.height - 8, r.bottom + 8)
bubble.style.left = `${left}px`
bubble.style.top = `${Math.max(8, top)}px`
t.setAttribute('aria-expanded', 'true')
activeTip = {trigger:t, bubble}
}
const close = () => { if (activeTip?.trigger === t) closeTip() }
t.addEventListener('mouseenter', open)
t.addEventListener('mouseleave', close)
t.addEventListener('focus', open)
t.addEventListener('blur', close)
t.addEventListener('click', e => { e.stopPropagation(); open() })
t.addEventListener('keydown', e => {
e.stopPropagation()
if (e.key === 'Escape') { close(); t.blur() }
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); activeTip?.trigger === t ? close() : open() }
})
}
}
document.addEventListener('scroll', closeTip, true)
window.addEventListener('resize', closeTip)
document.addEventListener('pointerdown', e => { if (!e.target.closest('.tip')) closeTip() })
// Only request-start / response-finish hook observations drive activity.
// Completed-request timestamps must never masquerade as in-flight calls.
function isLive(a) {
return state.activityKnown && (state.activeAgents.get(a.agent) || 0) > 0
}
function activityBadge(agent) {
const count = state.activeAgents.get(agent) || 0
return `${tip("live", esc(T("activity.callsInFlight", { n: count })))}`
}
async function refreshActivity() {
if (document.hidden) return
try {
const res = await fetch(`/api/activity?k=${encodeURIComponent(TOKEN)}`, {cache:'no-store', signal:AbortSignal.timeout(4000)})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
state.activeAgents = new Map(data.agents.map(a => [a.agent, a.count]))
state.activityKnown = data.available === true
if (!state.activityKnown) state.activeAgents.clear()
} catch {
state.activityKnown = false
state.activeAgents.clear()
}
$('activityInfo').textContent = state.activityKnown
? T("activity.liveHint")
: T("activity.unavailableHint")
for (const card of document.querySelectorAll('.card[data-agent]')) {
const active = state.activityKnown && (state.activeAgents.get(card.dataset.agent) || 0) > 0
card.classList.toggle('live', active)
const head = card.querySelector('.card-head')
const old = head.querySelector('.live-badge')
const count = state.activeAgents.get(card.dataset.agent) || 0
if (old && old.dataset.count === String(count)) continue
old?.remove()
if (active) {
head.insertAdjacentHTML('beforeend', activityBadge(card.dataset.agent))
const badge = head.querySelector('.live-badge')
badge.dataset.count = String(count)
wireTips(badge)
}
}
}
// ---------- sparkline ----------
function spark(series, key, cls = "") {
if (!series || series.length < 2) return ""
const w = 240, h = cls ? 80 : 34, pad = 2
const vals = series.map((d) => d[key])
const max = Math.max(...vals, 1)
const pts = vals.map((v, i) => [pad + (i * (w - pad * 2)) / (vals.length - 1), h - pad - (v / max) * (h - pad * 2)])
const line = pts.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(" ")
const area = `${line} L${pts.at(-1)[0].toFixed(1)} ${h} L${pts[0][0].toFixed(1)} ${h} Z`
return ``
}
// ---------- paint ----------
function paint() {
const d = state.data
$("state").hidden = true
if (!d.agents.length) {
for (const id of ["insights", "kpis", "cards", "tools"]) $(id).innerHTML = ""
$("table").innerHTML = ""
showState(T("state.noAgents"))
return
}
paintStatus(d)
paintInsights(d)
paintKpis(d)
paintCardSort()
paintCards(d)
paintTable(d)
paintTools(d)
wireTips(document)
const s = d.sources || {}
$("sources").textContent = T("sources.summary", { usageRows: int(s.usageRows), toolRows: int(s.toolRows), time: new Date(d.generatedAt).toLocaleTimeString(LOCALE) })
if (state.openAgent) openDetail(state.openAgent, false)
}
function ago(t) {
if (!t) return T("time.none")
const s = Math.max(0, (Date.now() - t) / 1000)
if (s < 60) return T("time.secondsAgo", { n: Math.round(s) })
if (s < 3600) return T("time.minutesAgo", { n: Math.round(s / 60) })
if (s < 86400) return T("time.hoursAgo", { n: Math.round(s / 3600) })
return T("time.daysAgo", { n: Math.round(s / 86400) })
}
function paintStatus(d) {
const fresh = d.lastTool && Date.now() - d.lastTool < 15 * 60e3
const el = $("status")
el.className = "status " + (fresh ? "live" : d.lastTool ? "idle" : "wait")
el.textContent = fresh ? T("status.collecting", { usage: ago(d.lastUsage), tool: ago(d.lastTool) })
: d.lastTool ? T("status.stale", { tool: ago(d.lastTool) })
: T("status.waiting")
}
function paintInsights(d) {
$("insights").innerHTML = d.insights
.map((i) => `
${esc(T("detail.noRecords"))}
` return items.map(m => `${when(a.first)} — ${when(a.last)} · ${esc(T('detail.selectedPeriod'))}
${esc(T('detail.summaryBody', { avg: short(a.avgPrompt), cache: pct(a.cacheRate), failed: int(a.failed), cancelled: int(a.cancelled) }))}
${esc(T('detail.summaryNote'))}${esc(T('detail.noInput'))}
`}${esc(T('detail.cacheNote'))}
${esc(T('detail.latencyNote'))}
${esc(T('detail.toolsNote'))}
${esc(T('detail.toolsCaveat', { samples: int(a.tools.samples), calls: int(a.calls) }))}
${esc(T('detail.toolInventoryNote'))}
${esc(T('detail.toolsEmpty'))}
`}${esc(T('detail.modelsNote', { count: a.models.length }))}
${distribution(a.models,a.calls)}${modelCount < a.calls ? `${esc(T('detail.remaining', { count: int(a.calls-modelCount) }))}
` : ''}${esc(T('detail.protocolsNote'))}
${distribution(a.protocols.map(p=>({...p,label:protoNames[p.name] || p.name})),a.calls)}${protocolCount < a.calls ? `${esc(T('detail.remaining', { count: int(a.calls-protocolCount) }))}
` : ''}${esc(T('detail.sessionNote', { open: int(a.session.open || 0) }))}
` : `${esc(T('detail.sessionEmpty'))}
${esc(T('detail.trendEmpty'))}
`}${esc(T('detail.trendNote'))}