(function() {
const app = document.getElementById('app');
let ws = null;
let wsReconnectTimeout = null;
const wsCallbacks = new Set();
let sessionsState = { sessions: [], cursor: null };
let openclawState = { instances: {} };
let openclawUnsubscribe = null;
let agentsState = createAgentsState();
let agentsUnsubscribe = null;
let dashboardState = null;
let dashboardUnsubscribe = null;
let dashboardChart = null;
let dashboardResizeObserver = null;
function getWsURL() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
return protocol + '//' + window.location.host + '/api/v1/ws';
}
function connectWS() {
if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
return;
}
try {
ws = new WebSocket(getWsURL());
ws.onopen = () => {
console.log('WebSocket connected');
wsCallbacks.forEach(cb => cb({ type: 'connected' }));
};
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
wsCallbacks.forEach(cb => cb({ type: 'message', data }));
} catch (e) {
console.error('Failed to parse WS message:', e);
}
};
ws.onclose = () => {
console.log('WebSocket disconnected');
wsCallbacks.forEach(cb => cb({ type: 'disconnected' }));
wsReconnectTimeout = setTimeout(connectWS, 5000);
};
ws.onerror = (err) => {
console.error('WebSocket error:', err);
};
} catch (e) {
console.error('Failed to connect WebSocket:', e);
wsReconnectTimeout = setTimeout(connectWS, 5000);
}
}
function subscribeWS(callback) {
wsCallbacks.add(callback);
if (!ws || ws.readyState !== WebSocket.OPEN) {
connectWS();
}
return () => wsCallbacks.delete(callback);
}
function cleanupLiveViews() {
if (openclawUnsubscribe) {
openclawUnsubscribe();
openclawUnsubscribe = null;
}
if (agentsUnsubscribe) {
agentsUnsubscribe();
agentsUnsubscribe = null;
}
if (dashboardUnsubscribe) {
dashboardUnsubscribe();
dashboardUnsubscribe = null;
}
if (dashboardChart) {
dashboardChart.destroy();
dashboardChart = null;
}
if (dashboardResizeObserver) {
dashboardResizeObserver.disconnect();
dashboardResizeObserver = null;
}
}
function route() {
cleanupLiveViews();
const path = window.location.pathname;
if (path === '/') {
renderDashboard();
} else if (path === '/sessions') {
renderSessions();
} else if (path.startsWith('/agents')) {
renderAgents();
} else if (path.startsWith('/openclaw')) {
renderOpenClaw();
} else if (path.startsWith('/sessions/')) {
renderSession(path.split('/sessions/')[1]);
} else if (path.startsWith('/runs/')) {
renderRun(path.split('/runs/')[1]);
} else {
app.innerHTML = '
Page not found
';
}
updateActiveNav();
}
function navigate(path) {
history.pushState(null, '', path);
route();
}
function updateActiveNav() {
const path = window.location.pathname;
document.querySelectorAll('header nav a').forEach(a => {
const href = a.getAttribute('href');
const isActive = href === '/'
? path === '/'
: path.startsWith(href);
a.classList.toggle('active', isActive);
});
}
window.addEventListener('popstate', route);
async function api(path) {
const resp = await fetch('/api' + path);
if (!resp.ok) {
throw new Error('API error');
}
return resp.json();
}
function escapeHTML(value) {
return String(value ?? '')
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function relativeTime(ts) {
if (!ts) {
return '-';
}
const now = Date.now();
const then = new Date(ts).getTime();
const diff = now - then;
if (diff < 60000) return 'just now';
if (diff < 3600000) return Math.floor(diff / 60000) + 'm ago';
if (diff < 86400000) return Math.floor(diff / 3600000) + 'h ago';
return Math.floor(diff / 86400000) + 'd ago';
}
function formatDuration(ms) {
if (ms === undefined || ms === null || ms === '') return '-';
if (ms < 1000) return ms + 'ms';
if (ms < 60000) return (ms / 1000).toFixed(1) + 's';
return (ms / 60000).toFixed(1) + 'm';
}
function formatBytes(bytes) {
if (!bytes) return null;
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let unitIndex = 0;
let value = bytes;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex++;
}
return value.toFixed(1) + ' ' + units[unitIndex];
}
function statusIcon(status) {
if (status === 'success') return 'success';
if (status === 'error') return 'error';
return 'unknown';
}
function extractEnvelope(record) {
if (record && typeof record === 'object' && record.payload && record.payload.event && record.payload.schema) {
return record.payload;
}
return record || {};
}
function getEnvelopeEvent(record) {
const envelope = extractEnvelope(record);
return envelope.event || envelope.Event || {};
}
function getEnvelopeType(record) {
return record?.type || getEnvelopeEvent(record).type || '';
}
function getEnvelopeTS(record) {
return record?.ts || getEnvelopeEvent(record).ts || '';
}
function getEnvelopeSource(record) {
return getEnvelopeEvent(record).source || {};
}
function getEnvelopePayload(record) {
const envelope = extractEnvelope(record);
return envelope.payload || envelope.Payload || {};
}
function getEnvelopeAttributes(record) {
const envelope = extractEnvelope(record);
return envelope.attributes || envelope.Attributes || {};
}
function getEnvelopeCorrelation(record) {
const envelope = extractEnvelope(record);
return envelope.correlation || envelope.Correlation || {};
}
function getRecordID(record) {
return record?.event_id || getEnvelopeEvent(record).id || '';
}
function isCurrentPath(prefix) {
return window.location.pathname.startsWith(prefix);
}
async function renderSessions() {
app.innerHTML = `
| Session |
Framework |
Host |
Runs |
Time |
`;
['from', 'to', 'framework', 'host'].forEach(f => {
document.getElementById('filter-' + f).addEventListener('change', () => {
sessionsState.sessions = [];
sessionsState.cursor = null;
loadSessions();
});
});
document.getElementById('load-more').addEventListener('click', loadSessions);
sessionsState = { sessions: [], cursor: null };
await loadSessions();
}
async function loadSessions() {
const params = new URLSearchParams();
const from = document.getElementById('filter-from').value;
const to = document.getElementById('filter-to').value;
const framework = document.getElementById('filter-framework').value;
const host = document.getElementById('filter-host').value;
if (from) params.set('from', from);
if (to) params.set('to', to);
if (framework) params.set('framework', framework);
if (host) params.set('host', host);
if (sessionsState.cursor) params.set('cursor', sessionsState.cursor);
const data = await api('/v1/sessions?' + params.toString());
sessionsState.sessions = sessionsState.sessions.concat(data.sessions || []);
sessionsState.cursor = data.next_cursor;
const tbody = document.getElementById('sessions-body');
tbody.innerHTML = sessionsState.sessions.map(s => {
const fw = s.framework || 'unknown';
const fwClass = fw.replace(/[^a-z0-9-]/g, '-');
return `
| ${escapeHTML(s.session_id.substring(0, 12))}… |
${escapeHTML(fw)} |
${escapeHTML(s.host || '-')} |
${s.run_count} |
${escapeHTML(relativeTime(s.started_at))} |
`;
}).join('') || '| No sessions found |
';
tbody.querySelectorAll('tr.clickable').forEach(row => {
row.addEventListener('click', () => navigate('/sessions/' + row.dataset.session));
});
document.getElementById('load-more').style.display = sessionsState.cursor ? 'block' : 'none';
}
async function renderSession(sessionID) {
const data = await api('/v1/sessions/' + sessionID);
const s = data.session;
const runs = data.runs || [];
const duration = s.ended_at
? formatDuration(new Date(s.ended_at) - new Date(s.started_at))
: 'ongoing';
app.innerHTML = `
← Back to Sessions
Runs ${runs.length}
| Run ID |
Status |
Spans |
Duration |
Started |
${runs.map(r => {
const runDuration = r.ended_at
? formatDuration(new Date(r.ended_at) - new Date(r.started_at))
: '-';
return `
| ${escapeHTML(r.run_id.substring(0, 12))}... |
${statusIcon(r.status)} |
${r.span_count} |
${escapeHTML(runDuration)} |
${escapeHTML(new Date(r.started_at).toLocaleTimeString())} |
`;
}).join('') || '| No runs |
'}
`;
document.querySelectorAll('tr.clickable').forEach(row => {
row.addEventListener('click', () => navigate('/runs/' + row.dataset.run));
});
document.querySelector('.back-link').addEventListener('click', e => {
e.preventDefault();
navigate('/sessions');
});
}
async function renderRun(runID) {
const data = await api('/v1/runs/' + runID);
const r = data.run;
const spans = data.spans || [];
const duration = r.ended_at
? formatDuration(new Date(r.ended_at) - new Date(r.started_at))
: 'ongoing';
app.innerHTML = `
← Back to Session
Spans ${spans.length}
| Name |
Kind |
Status |
Duration |
${spans.map((sp, i) => `
| ${escapeHTML(sp.name)} |
${escapeHTML(sp.kind)} |
${statusIcon(sp.status)} |
${escapeHTML(formatDuration(sp.duration_ms))} |
|
${escapeHTML(JSON.stringify(sp.payload, null, 2))}
|
`).join('') || '| No spans |
'}
`;
document.querySelectorAll('tr.expandable').forEach(row => {
row.addEventListener('click', () => {
const idx = row.dataset.index;
const detailRow = document.querySelector(`tr.span-detail-row[data-index="${idx}"]`);
const icon = row.querySelector('.expand-icon');
if (detailRow.style.display === 'none') {
detailRow.style.display = 'table-row';
icon.style.transform = 'rotate(45deg)';
} else {
detailRow.style.display = 'none';
icon.style.transform = '';
}
});
});
document.querySelector('.back-link').addEventListener('click', e => {
e.preventDefault();
navigate('/sessions/' + r.session_id);
});
}
async function renderOpenClaw() {
app.innerHTML = 'Loading...
';
openclawUnsubscribe = subscribeWS(handleOpenClawWS);
try {
const data = await api('/v1/events?event_type=openclaw.snapshot&limit=100');
mergeOpenClawEvents(data.events || []);
if (isCurrentPath('/openclaw')) {
renderOpenClawGrid();
}
} catch (e) {
if (isCurrentPath('/openclaw')) {
app.innerHTML = `Error loading: ${escapeHTML(e.message)}
`;
}
}
}
function handleOpenClawWS(msg) {
if (msg.type !== 'message') {
return;
}
if (getEnvelopeType(msg.data) !== 'openclaw.snapshot') {
return;
}
mergeOpenClawEvents([msg.data]);
if (isCurrentPath('/openclaw')) {
renderOpenClawGrid();
}
if (isCurrentPath('/agents')) {
renderAgentVMStrip();
}
}
function mergeOpenClawEvents(events) {
for (const evt of events) {
const payload = getEnvelopePayload(evt);
const instance = payload.instance || {};
if (!instance.name) {
continue;
}
const existing = openclawState.instances[instance.name];
const nextTS = new Date(getEnvelopeTS(evt) || 0).getTime();
const currentTS = existing ? new Date(getEnvelopeTS(existing) || 0).getTime() : 0;
if (!existing || nextTS >= currentTS) {
openclawState.instances[instance.name] = evt;
}
}
}
function renderOpenClawGrid() {
const names = Object.keys(openclawState.instances).sort();
if (names.length === 0) {
app.innerHTML = `
No OpenClaw instances found
`;
return;
}
app.innerHTML = `
${names.map(name => {
const evt = openclawState.instances[name];
const payload = getEnvelopePayload(evt);
const inst = payload.instance || {};
const host = payload.host || {};
const guest = payload.guest;
const issues = payload.issues;
return `
Updated ${escapeHTML(relativeTime(getEnvelopeTS(evt)))}
| Host | ${escapeHTML(inst.host || '-')} |
| Domain | ${escapeHTML(inst.domain || '-')} |
| vCPUs | ${host.vcpus || '-'} |
| Memory | ${escapeHTML(formatBytes(host.memory_kib ? host.memory_kib * 1024 : 0) || '-')} |
| Disk | ${escapeHTML(formatBytes(host.disk_actual_bytes) || '-')} |
| Autostart | ${host.autostart ? 'Yes' : 'No'} |
${guest ? `
| Gateway | ${guest.service_active ? 'Active' : 'Inactive'} |
| HTTP | ${guest.http_status || 'N/A'} |
| Version | ${escapeHTML(guest.version || '-')} |
| Guest Memory | ${guest.memory_percent !== undefined ? guest.memory_percent.toFixed(1) : '-'}% |
| Guest Disk | ${guest.disk_percent !== undefined ? guest.disk_percent.toFixed(1) : '-'}% |
| Load | ${guest.load_average !== undefined ? guest.load_average.toFixed(2) : '-'} |
| Uptime | ${escapeHTML(guest.service_uptime || '-')} |
` : ''}
${issues ? `
${Object.entries(issues).filter(([, value]) => value).map(([key]) => `
${escapeHTML(key.replace(/_/g, ' '))}
`).join('')}
` : ''}
`;
}).join('')}
`;
}
function createAgentsState() {
return {
events: [],
eventIDs: new Set(),
stats: {
messages: 0,
tools: 0,
errors: 0,
toolCounts: {},
},
};
}
function getVMStatus() {
const names = ['zap', 'orb', 'sun'];
return names.map(name => {
const snapshot = openclawState.instances[name];
const payload = snapshot ? getEnvelopePayload(snapshot) : {};
const host = payload.host || {};
return {
name,
active: host.state === 'running',
};
});
}
async function renderAgents() {
agentsState = createAgentsState();
app.innerHTML = `
Loading agent activity...
Messages
0
received and sent
`;
renderAgentVMStrip();
try {
const [snapshots, events] = await Promise.all([
api('/v1/events?event_type=openclaw.snapshot&limit=100').catch(() => ({ events: [] })),
api('/v1/events?framework=openclaw&limit=200'),
]);
if (!isCurrentPath('/agents')) {
return;
}
mergeOpenClawEvents(snapshots.events || []);
renderAgentVMStrip();
addAgentEvents((events.events || []).slice().reverse());
renderAgentTimeline();
renderAgentStats();
} catch (e) {
const timeline = document.getElementById('agents-timeline');
if (timeline) {
timeline.innerHTML = `Error loading agent activity: ${escapeHTML(e.message)}
`;
}
}
agentsUnsubscribe = subscribeWS(handleAgentsWS);
}
function renderAgentVMStrip() {
const strip = document.getElementById('agents-vm-strip');
if (!strip) {
return;
}
const vms = getVMStatus();
strip.innerHTML = vms.map(vm => `
${escapeHTML(vm.name)}
${vm.active ? 'online' : 'offline'}
`).join('');
}
function handleAgentsWS(msg) {
if (msg.type !== 'message') {
return;
}
const eventType = getEnvelopeType(msg.data);
if (eventType === 'openclaw.snapshot') {
mergeOpenClawEvents([msg.data]);
renderAgentVMStrip();
return;
}
const framework = getEnvelopeSource(msg.data).framework || msg.data.source_framework;
if (framework !== 'openclaw') {
return;
}
addAgentEvents([msg.data]);
renderAgentTimeline();
renderAgentStats();
}
function addAgentEvents(events) {
let changed = false;
for (const evt of events) {
const id = getRecordID(evt);
if (!id || agentsState.eventIDs.has(id)) {
continue;
}
agentsState.eventIDs.add(id);
agentsState.events.push(evt);
changed = true;
}
if (!changed) {
return;
}
agentsState.events.sort((a, b) => new Date(getEnvelopeTS(a)).getTime() - new Date(getEnvelopeTS(b)).getTime());
while (agentsState.events.length > 500) {
const removed = agentsState.events.shift();
agentsState.eventIDs.delete(getRecordID(removed));
}
recomputeAgentStats();
}
function recomputeAgentStats() {
const stats = {
messages: 0,
tools: 0,
errors: 0,
toolCounts: {},
};
for (const evt of agentsState.events) {
const eventType = getEnvelopeType(evt);
const attrs = getEnvelopeAttributes(evt);
if (eventType === 'run.start' || eventType === 'run.end') {
stats.messages++;
}
if (eventType === 'span.end' && attrs.span_kind === 'tool') {
stats.tools++;
const toolName = attrs.name || 'unknown';
stats.toolCounts[toolName] = (stats.toolCounts[toolName] || 0) + 1;
}
if (eventType === 'error') {
stats.errors++;
}
}
agentsState.stats = stats;
}
function getEventIcon(eventType) {
switch (eventType) {
case 'run.start':
return '↓
';
case 'run.end':
return '↑
';
case 'span.start':
case 'span.end':
return '⚙
';
case 'error':
return '!
';
case 'session.start':
case 'session.end':
return '○
';
default:
return '·
';
}
}
function getEventLabel(eventType) {
const labels = {
'session.start': 'Session Started',
'session.end': 'Session Ended',
'run.start': 'Message Received',
'run.end': 'Response Sent',
'span.start': 'Span Started',
'span.end': 'Span Completed',
'error': 'Error',
'metric.snapshot': 'Metric',
};
return labels[eventType] || eventType;
}
function getVMName(evt) {
return getEnvelopeSource(evt).client_id || evt.client_id || 'unknown';
}
function getVMClassName(vmName) {
const normalized = String(vmName || 'unknown').toLowerCase();
return ['zap', 'orb', 'sun'].includes(normalized) ? normalized : 'unknown';
}
function getEventBody(evt) {
const eventType = getEnvelopeType(evt);
const payload = getEnvelopePayload(evt);
const attrs = getEnvelopeAttributes(evt);
const correlation = getEnvelopeCorrelation(evt);
if (eventType === 'span.start' || eventType === 'span.end') {
const name = attrs.name || attrs.span_kind || 'unknown span';
const duration = payload.duration_ms !== undefined && payload.duration_ms !== null
? ` ${escapeHTML(formatDuration(payload.duration_ms))}`
: '';
return `${escapeHTML(name)}${duration}
`;
}
if (eventType === 'run.start') {
const preview = payload.message_preview || payload.message || '';
if (!preview) {
return '';
}
const trimmed = preview.length > 140 ? preview.slice(0, 140) + '...' : preview;
return `"${escapeHTML(trimmed)}"
`;
}
if (eventType === 'run.end') {
return `${statusIcon(payload.status || 'unknown')}
`;
}
if (eventType === 'error') {
const errPayload = payload.error || {};
const errType = errPayload.type || 'error';
const message = errPayload.message || payload.message || 'unknown';
return `${escapeHTML(errType + ': ' + message)}
`;
}
if (eventType === 'session.start' || eventType === 'session.end') {
return correlation.session_id
? `session ${escapeHTML(correlation.session_id)}
`
: '';
}
return '';
}
function getEventDetails(evt) {
const details = {};
const correlation = getEnvelopeCorrelation(evt);
const attributes = getEnvelopeAttributes(evt);
const payload = getEnvelopePayload(evt);
if (Object.keys(correlation).length > 0) {
details.correlation = correlation;
}
if (Object.keys(attributes).length > 0) {
details.attributes = attributes;
}
if (Object.keys(payload).length > 0) {
details.payload = payload;
}
if (Object.keys(details).length === 0) {
return '';
}
return JSON.stringify(details, null, 2);
}
function renderAgentTimeline() {
const timeline = document.getElementById('agents-timeline');
if (!timeline) {
return;
}
const recent = agentsState.events.slice(-100).reverse();
if (recent.length === 0) {
timeline.innerHTML = 'Waiting for agent activity...
';
return;
}
timeline.innerHTML = recent.map((evt, index) => {
const eventType = getEnvelopeType(evt);
const vmName = getVMName(evt);
const vmClass = getVMClassName(vmName);
const details = getEventDetails(evt);
const detailHTML = details ? `${escapeHTML(details)}
` : '';
const expandHTML = details ? '' : '';
return `
${getEventBody(evt)}
${expandHTML}
${detailHTML}
`;
}).join('');
timeline.querySelectorAll('.timeline-expand-hint').forEach(button => {
button.addEventListener('click', () => {
button.parentElement.classList.toggle('expanded');
});
});
}
function renderAgentStats() {
const stats = agentsState.stats;
const messagesEl = document.getElementById('stat-messages');
if (messagesEl) {
messagesEl.textContent = String(stats.messages);
}
const toolsEl = document.getElementById('stat-tools');
if (toolsEl) {
toolsEl.textContent = String(stats.tools);
}
const errorsEl = document.getElementById('stat-errors');
if (errorsEl) {
errorsEl.textContent = String(stats.errors);
}
const list = document.getElementById('stat-top-tools');
if (!list) {
return;
}
const topTools = Object.entries(stats.toolCounts)
.sort((a, b) => b[1] - a[1])
.slice(0, 8);
if (topTools.length === 0) {
list.innerHTML = 'No data yet';
return;
}
list.innerHTML = topTools.map(([name, count]) => `
${escapeHTML(name)}
${count}
`).join('');
}
async function renderDashboard() {
dashboardState = {
summary: null,
timeseries: null,
window: '1h',
recentEvents: [],
recentEventIDs: new Set(),
toolCounts: {},
};
app.innerHTML = `
Infrastructure
`;
document.querySelectorAll('.window-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.window-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
dashboardState.window = btn.dataset.w;
loadTimeseries();
});
});
renderDashVMStrip();
try {
const [summaryData, tsData, recentData, snapshots] = await Promise.all([
api('/v1/stats/summary'),
api('/v1/stats/timeseries?window=1h'),
api('/v1/events?limit=20'),
api('/v1/events?event_type=openclaw.snapshot&limit=100').catch(() => ({ events: [] })),
]);
if (!isCurrentPath('/')) return;
mergeOpenClawEvents(snapshots.events || []);
renderDashVMStrip();
dashboardState.summary = summaryData;
dashboardState.timeseries = tsData;
renderSummaryCards();
renderTimeseriesChart();
renderFrameworkBars();
const events = (recentData.events || []).slice().reverse();
for (const evt of events) {
const id = getRecordID(evt);
if (id && !dashboardState.recentEventIDs.has(id)) {
dashboardState.recentEventIDs.add(id);
dashboardState.recentEvents.push(evt);
tallyTool(evt);
}
}
renderDashFeed();
renderDashTopTools();
} catch (e) {
console.error('Dashboard load error:', e);
}
dashboardUnsubscribe = subscribeWS(handleDashboardWS);
}
function renderDashVMStrip() {
const strip = document.getElementById('dash-vm-strip');
if (!strip) return;
const vms = getVMStatus();
strip.innerHTML = vms.map(vm => `
${escapeHTML(vm.name)}
${vm.active ? 'online' : 'offline'}
`).join('');
}
function handleDashboardWS(msg) {
if (msg.type !== 'message') return;
const eventType = getEnvelopeType(msg.data);
if (eventType === 'openclaw.snapshot') {
mergeOpenClawEvents([msg.data]);
renderDashVMStrip();
return;
}
if (dashboardState.summary) {
if (eventType === 'session.start') dashboardState.summary.active_sessions++;
if (eventType === 'session.end') dashboardState.summary.active_sessions = Math.max(0, dashboardState.summary.active_sessions - 1);
if (eventType === 'run.start') dashboardState.summary.runs_today++;
if (eventType === 'error') dashboardState.summary.errors_today++;
if (eventType === 'span.end') {
const attrs = getEnvelopeAttributes(msg.data);
if (attrs.span_kind === 'tool') dashboardState.summary.tool_calls_today++;
}
renderSummaryCards();
}
const id = getRecordID(msg.data);
if (id && !dashboardState.recentEventIDs.has(id)) {
dashboardState.recentEventIDs.add(id);
dashboardState.recentEvents.push(msg.data);
tallyTool(msg.data);
while (dashboardState.recentEvents.length > 50) {
const removed = dashboardState.recentEvents.shift();
dashboardState.recentEventIDs.delete(getRecordID(removed));
}
renderDashFeed();
renderDashTopTools();
}
if (dashboardState.timeseries && dashboardState.window === '1h') {
appendToCurrentBucket(msg.data);
}
}
function tallyTool(evt) {
const eventType = getEnvelopeType(evt);
if (eventType === 'span.end') {
const attrs = getEnvelopeAttributes(evt);
if (attrs.span_kind === 'tool') {
const name = attrs.name || 'unknown';
dashboardState.toolCounts[name] = (dashboardState.toolCounts[name] || 0) + 1;
}
}
}
function renderSummaryCards() {
const s = dashboardState.summary;
if (!s) return;
const el = (id, val) => {
const e = document.getElementById(id);
if (e) e.textContent = String(val);
};
el('dash-active', s.active_sessions);
el('dash-runs', s.runs_today);
el('dash-tools', s.tool_calls_today);
el('dash-errors', s.errors_today);
// Sub-line: framework breakdown for active sessions
const fws = Object.keys(s.by_framework || {});
if (fws.length > 0) {
const sub = document.getElementById('dash-active-sub');
if (sub) sub.textContent = fws.map(f => `${f} ${(s.by_framework[f].runs || 0)}`).join(' · ');
}
const errEl = document.getElementById('dash-errors');
if (errEl) {
errEl.classList.toggle('has-errors', s.errors_today > 0);
}
}
async function loadTimeseries() {
try {
// Destroy chart so it's recreated with new window scale
if (dashboardChart) {
dashboardChart.destroy();
dashboardChart = null;
}
const data = await api('/v1/stats/timeseries?window=' + dashboardState.window);
if (!isCurrentPath('/')) return;
dashboardState.timeseries = data;
renderTimeseriesChart();
} catch (e) {
console.error('Failed to load timeseries:', e);
}
}
function buildChartData() {
const ts = dashboardState.timeseries;
if (!ts || !ts.series || ts.series.length === 0) return null;
// Stacked: errors on bottom, then tools, then runs on top
const errors = ts.series.map(b => b.errors);
const tools = ts.series.map((b, i) => b.tools + errors[i]);
const runs = ts.series.map((b, i) => b.runs + tools[i]);
return [
ts.series.map(b => Math.floor(new Date(b.ts).getTime() / 1000)),
runs,
tools,
errors,
];
}
function renderTimeseriesChart() {
const container = document.getElementById('dash-chart');
if (!container || !dashboardState.timeseries) return;
const data = buildChartData();
if (!data) {
container.innerHTML = 'No data for this window
';
return;
}
// If chart already exists, just update the data
if (dashboardChart) {
dashboardChart.setData(data);
return;
}
container.innerHTML = '';
const width = container.clientWidth || 600;
const height = 200;
const opts = {
width,
height,
cursor: { show: true },
scales: {
x: { time: true },
y: { auto: true, min: 0 },
},
axes: [
{
stroke: '#4e6070',
grid: { stroke: 'rgba(28, 38, 55, 0.6)', width: 1 },
ticks: { stroke: 'rgba(28, 38, 55, 0.6)', width: 1 },
font: '11px Fira Code',
},
{
stroke: '#4e6070',
grid: { stroke: 'rgba(28, 38, 55, 0.6)', width: 1 },
ticks: { stroke: 'rgba(28, 38, 55, 0.6)', width: 1 },
font: '11px Fira Code',
size: 50,
},
],
series: [
{},
{
label: 'Runs',
stroke: '#34d399',
width: 1.5,
fill: 'rgba(52, 211, 153, 0.15)',
},
{
label: 'Tools',
stroke: '#22d3ee',
width: 1.5,
fill: 'rgba(34, 211, 238, 0.15)',
},
{
label: 'Errors',
stroke: '#f87171',
width: 1.5,
fill: 'rgba(248, 113, 113, 0.2)',
},
],
bands: [
{ series: [1, 2], fill: 'rgba(52, 211, 153, 0.15)' },
{ series: [2, 3], fill: 'rgba(34, 211, 238, 0.15)' },
],
};
dashboardChart = new uPlot(opts, data, container);
if (dashboardResizeObserver) {
dashboardResizeObserver.disconnect();
}
dashboardResizeObserver = new ResizeObserver(entries => {
for (const entry of entries) {
if (dashboardChart) {
dashboardChart.setSize({ width: entry.contentRect.width, height: 200 });
}
}
});
dashboardResizeObserver.observe(container);
}
function appendToCurrentBucket(evt) {
const ts = dashboardState.timeseries;
if (!ts || !ts.series || ts.series.length === 0) return;
const now = Math.floor(Date.now() / 60000) * 60000;
const last = ts.series[ts.series.length - 1];
const lastTs = new Date(last.ts).getTime();
let bucket;
if (Math.abs(now - lastTs) < 60000) {
bucket = last;
} else {
bucket = { ts: new Date(now).toISOString(), runs: 0, tools: 0, errors: 0 };
ts.series.push(bucket);
}
const eventType = getEnvelopeType(evt);
if (eventType === 'run.start') bucket.runs++;
if (eventType === 'error') bucket.errors++;
if (eventType === 'span.end') {
const attrs = getEnvelopeAttributes(evt);
if (attrs.span_kind === 'tool') bucket.tools++;
}
renderTimeseriesChart();
}
function renderFrameworkBars() {
const container = document.getElementById('dash-fw-bars');
if (!container || !dashboardState.summary) return;
const byFw = dashboardState.summary.by_framework || {};
const entries = Object.entries(byFw).sort((a, b) => {
const totalA = a[1].runs + a[1].tools + a[1].errors;
const totalB = b[1].runs + b[1].tools + b[1].errors;
return totalB - totalA;
});
if (entries.length === 0) {
container.innerHTML = 'No framework data
';
return;
}
const maxTotal = Math.max(...entries.map(([, s]) => s.runs + s.tools + s.errors));
container.innerHTML = entries.map(([name, stats]) => {
const total = stats.runs + stats.tools + stats.errors;
const pct = maxTotal > 0 ? (total / maxTotal * 100) : 0;
const cssClass = name.toLowerCase().replace(/[^a-z0-9-]/g, '-');
return `
${escapeHTML(name)}
${total} events
`;
}).join('');
}
function renderDashFeed() {
const feed = document.getElementById('dash-feed');
if (!feed) return;
const recent = dashboardState.recentEvents.slice(-20).reverse();
if (recent.length === 0) {
feed.innerHTML = 'Waiting for events...
';
return;
}
feed.innerHTML = recent.map(evt => {
const eventType = getEnvelopeType(evt);
const vmName = getVMName(evt);
const vmClass = getVMClassName(vmName);
const source = getEnvelopeSource(evt);
const framework = source.framework || '';
const tag = framework
? `${escapeHTML(framework)}`
: '';
return `
${getEventBody(evt)}
`;
}).join('');
}
function renderDashTopTools() {
const list = document.getElementById('dash-top-tools');
if (!list) return;
const topTools = Object.entries(dashboardState.toolCounts)
.sort((a, b) => b[1] - a[1])
.slice(0, 10);
if (topTools.length === 0) {
list.innerHTML = 'No tool data yet';
return;
}
const maxCount = topTools[0]?.[1] || 1;
list.innerHTML = topTools.map(([name, count]) => {
const pct = (count / maxCount * 100).toFixed(1);
return `
`;
}).join('');
}
route();
})();