(() => {
const {byId,el,notice,readNotice,request,send,button,setActions,completed,external,directory,closeDialog} = window.gentUI;
const settings = window.gentSettings, dashboards = window.gentDashboards;
const names = ["Dashboard","Status","Chats","Stats","Settings","Permissions","About"];
const tabs = new Map(), reads = new Set(), reread = new Set();
let current = "dashboard", visible = false, lastStatus, enrolled, statusOp = null, queuedAction = null;
let lastStatusRead = null, statusQueued = false, statsOp = null, liveQueued = false;
const nodes = directory("nodes", [["name","Node"],["state","Status"],["role","Role"],["directory","Directory"],["route","Last transport"],["host","Hosted by"],["id","Node ID"]]);
const chats = directory("chats", [["name","Chat"],["node","Node"],["provider","Provider"],["state","Registration"],["id","Chat ID"]]);
for (const [i,title] of names.entries()) {
const id=title.toLowerCase(), tab=button(title,() => select(id));
tab.id = "tab-"+id; tab.setAttribute("role","tab"); tab.setAttribute("aria-controls",id);
const page=byId(id); page.setAttribute("role","tabpanel"); page.setAttribute("aria-labelledby",tab.id);
page.tabIndex=0;
tab.addEventListener("keydown",event => {
const targets={ArrowRight:(i+1)%names.length,ArrowLeft:(i+names.length-1)%names.length,Home:0,End:names.length-1};
if (!(event.key in targets)) return;
event.preventDefault();
const next=names[targets[event.key]].toLowerCase(); select(next); tabs.get(next).focus();
});
byId("tabs").append(tab); tabs.set(id,tab);
}
function displayTabs() {
for (const [id,tab] of tabs) {
const selected=id===current;
tab.setAttribute("aria-selected",String(selected)); tab.tabIndex=selected ? 0 : -1;
byId(id).hidden=!selected;
}
const tab=tabs.get(current), nav=byId("tabs").parentElement;
if (tab.offsetLeft < nav.scrollLeft || tab.offsetLeft+tab.offsetWidth > nav.scrollLeft+nav.clientWidth) {
tab.scrollIntoView({block:"nearest",inline:"nearest"});
}
}
function read(page, afterOperation = false) {
if (reads.has(page)) {
if (afterOperation) reread.add(page);
return;
}
reads.add(page);
request(page).catch(() => {
reads.delete(page);
reread.delete(page);
if (page==="permissions") permissions({error:"Could not load cluster permissions."});
});
}
function service(action="refresh") {
if (statusOp) {
if (action==="refresh") statusQueued=true;
else if (statusOp==="refresh" && !queuedAction) { queuedAction=action; daemonButtons(); }
return;
}
lastStatusRead = Date.now();
statusOp=action; daemonButtons();
send(action).catch(() => snapshot({error:"Could not read daemon status. Refresh to try again."}));
}
function daemonButtons() {
const m=lastStatus || {};
const stop=!!(m.running || m.can_stop);
const busy=!!queuedAction || (statusOp !== null && statusOp !== "refresh");
byId("daemon-toggle").textContent=stop ? "Stop daemon" : "Start daemon";
byId("daemon-toggle").disabled=busy || !(stop ? m.can_stop : m.can_start);
byId("daemon-restart").disabled=busy || !m.can_stop;
}
byId("daemon-toggle").onclick=() => service(lastStatus?.can_stop ? "stop" : "start");
byId("daemon-restart").onclick=() => service("restart");
function loadStats(live) {
if (statsOp) { if (live && statsOp==="stats") liveQueued=true; return; }
statsOp=live ? "refresh_stats" : "stats";
notice("stats-notice",live ? "Requesting current reports from cluster nodes…" : "Loading stats…");
request(statsOp).catch(() => { liveQueued=false; stats({error:"Could not load cluster stats."}); });
}
function load(live=false) {
if (!visible) return;
switch (current) {
case "dashboard": if (live) dashboards?.refresh?.(); break;
case "status": service(); read("cluster"); break;
case "settings": settings.load(); break;
case "stats": loadStats(live); break;
default: read(current);
}
}
function select(id) {
if (!tabs.has(id) || current===id) return;
current=id; displayTabs(); dashboards?.visible(visible && current==="dashboard"); load();
}
function present(message) {
const wasVisible=visible, old=current;
if (message.show) visible=true;
if (typeof message.visible==="boolean") visible=message.visible;
if (message.show && tabs.has(message.tab)) current=message.tab;
if (!visible && lastStatusRead === null) service();
if (wasVisible===visible && old===current) return;
if (!visible) closeDialog();
displayTabs(); dashboards?.visible(visible && current==="dashboard"); load();
if (visible && current!=="status") service();
}
function snapshot(m) {
statusOp=null;
const action=queuedAction; queuedAction=null;
notice("status-error",m.error,!!m.error);
if ("state" in m || m.error) {
lastStatus=m;
if (typeof m.enrolled==="boolean" && enrolled!==m.enrolled) {
enrolled=m.enrolled; settings.enrollment(enrolled); byId("account-card").open=!enrolled;
}
byId("health").hidden=!enrolled; byId("node-directory").hidden=!enrolled;
byId("status-title").textContent=enrolled===false ? "Set up this node" : "Status";
byId("local-node").textContent=m.node ? "Local node · "+m.node : "";
byId("cluster-name").textContent=m.cluster || "Cluster";
byId("daemon-state").textContent="Daemon "+String(m.state || "status unavailable").toLowerCase();
byId("daemon-state").dataset.running=String(!!m.running);
for (const [element,key] of [["sync","sync"],["queue","queue"],["chat-count","chats"]]) byId(element).textContent=m[key] ?? "—";
byId("connection").textContent=m.connection || ""; byId("connection").hidden=!m.connection;
if (m.nodes || m.error) nodes(m.nodes || {rows:[],actions:[]});
}
daemonButtons();
if (action && visible && current==="status" && (action==="start" ? m.can_start : m.can_stop)) {
statusQueued=false;
service(action);
} else if (statusQueued && visible) { statusQueued=false; service(); }
else statusQueued=false;
}
function statsTable(id,caption,columns,rows,emptyText) {
const outer=byId(id);
if (!rows.length) { outer.replaceChildren(el("p",emptyText,"muted")); return; }
const wrap=el("div",null,"table-wrap"), table=el("table");
wrap.setAttribute("role","region"); wrap.setAttribute("aria-label",caption); wrap.tabIndex=0;
table.setAttribute("aria-label",caption);
const header=table.createTHead().insertRow();
for (const [,label] of columns) { const th=el("th",label); th.scope="col"; header.append(th); }
const body=table.createTBody();
for (const data of rows) {
const tr=body.insertRow();
for (const [key] of columns) {
const td=tr.insertCell(); td.textContent=data[key] ?? "—";
if (key==="id" || key==="chat_id") td.className="identifier";
}
}
wrap.append(table); outer.replaceChildren(wrap);
}
function permissions(m) {
byId("permissions-title").textContent=m.title || "Cluster permissions";
byId("permissions-detail").textContent=m.detail || "";
setActions("permissions",m.error ? [] : m.actions);
readNotice("permissions-notice", m.error);
}
function stats(m) {
statsOp=null;
notice("stats-notice",m.error || m.notice,!!m.error); byId("stats-content").hidden=!!m.error;
if (!m.error) {
for (const key of ["coverage","outbound","babysitter"]) byId(key).textContent=m[key] || "";
statsTable("senders","Top sending chats",[["name","Chat"],["messages","Messages"],["bytes","Bytes"],["chat_id","Chat ID"]],m.rows || [],"No sending chats in the reported activity.");
statsTable("reports","Node reports",[["name","Node"],["status","Report"],["messages","Messages"],["bytes","Bytes"],["ordinary","Continuations"],["goals","Goal resumes"],["as_of","As of (UTC)"],["started","Tracking since (UTC)"],["backfill","Earlier activity"],["older_daemon","Older daemon activity"],["id","Node ID"]],m.nodes || [],"No node reports available.");
}
if (liveQueued) { liveQueued=false; loadStats(true); }
}
for (const radio of document.querySelectorAll("input[name=breakdown]")) radio.onchange=() => {
byId("senders").hidden=radio.value!=="senders"; byId("reports").hidden=radio.value!=="reports";
};
let aboutContent;
function about(m) {
setActions("about",m.actions);
readNotice("about-notice", m.error);
const content=JSON.stringify([m.detail,m.version,m.revision,m.revision_url,m.latest_release,m.error]);
if (content === aboutContent) return;
aboutContent=content;
const repo="https://github.com/sam0x17/gent", release=m.error ? {} : m.latest_release || {};
const version=typeof release.version==="string" ? release.version.replace(/^v/,"") : "";
const releaseUrl=/^[0-9][0-9A-Za-z.+-]{0,127}$/.test(version) && release.url===repo+"/releases/tag/v"+version ? release.url : null;
const revision=m.revision || "", short=revision.slice(0,12);
const commitUrl=/^[0-9a-f]{40}$/.test(revision) && (m.revision_url===releaseUrl || m.revision_url===repo+"/commit/"+revision) ? m.revision_url : null;
const detail=byId("about-detail"), raw=m.detail || "";
const prefix="Version "+m.version+" · ";
detail.replaceChildren();
if (m.version && raw.startsWith(prefix)) {
detail.append("Version ", external(m.version,m.version===version ? releaseUrl : null)," · ");
const rest=raw.slice(prefix.length);
if (short && rest.startsWith(short)) detail.append(external(short,commitUrl),rest.slice(short.length));
else detail.append(rest);
} else detail.textContent=raw;
const notes=typeof release.notes==="string" && release.notes.trim() ? release.notes : "";
byId("release").hidden=!notes && !version;
const heading=byId("release-heading"); heading.textContent=notes ? "Release notes" : "Latest release";
if (version) heading.append(" ",external("v"+version,releaseUrl));
byId("release-notes").textContent=notes;
}
byId("gent-site").replaceWith(external("gent.link","https://gent.link"));
function receive(event) {
const m=event.detail;
if (!m || typeof m!=="object") return;
if (m.show || typeof m.visible==="boolean") { present(m); return; }
if (!m.page) { if ("state" in m || m.error) snapshot(m); return; }
if (m.operation) {
completed(m);
if (!m.error) {
if (m.page==="nodes" || m.page==="cluster") service();
if (m.page!=="nodes") read(m.page, true);
}
return;
}
reads.delete(m.page);
switch (m.page) {
case "dashboard": dashboards?.receive(m); break;
case "cluster":
byId("account-title").textContent=m.title==="Set up this node" ? "Account and setup" : m.title || "Account";
byId("account-detail").textContent=m.detail || ""; setActions("cluster",m.actions);
readNotice("cluster-notice", m.error);
break;
case "nodes": nodes(m); break;
case "chats": chats(m); break;
case "settings": settings.receive(m); break;
case "release_channel": settings.receiveChannel(m); break;
case "stats": stats(m); break;
case "permissions": permissions(m); break;
case "about": about(m); break;
}
if (reread.delete(m.page)) read(m.page);
}
byId("refresh").onclick=() => load(true);
displayTabs();
dashboards?.mount(byId("dashboard-content"));
window.addEventListener("gent-message",receive);
setInterval(() => {
if (visible && current==="settings") settings.poll();
if (!statusOp && (visible || (lastStatusRead !== null && Date.now() - lastStatusRead >= 60000))) service();
},15000);
if (window.gent) window.gent.ready().catch(() => notice("bridge-error","Could not connect to Gent Desktop.",true));
else notice("bridge-error","Open this window from Gent Desktop to connect to the supervisor.",true);
})();