feat: complete agent monitoring - hook, UI, and backend filter
- Add event_type and framework filters to events query endpoint - Add /agents SPA route to web-ui server - Add Agents nav link and route in frontend - Add agents page CSS (timeline, VM pills, stats panel) - Build VM status strip, activity timeline, and real-time stats - Add agentmon hook for OpenClaw (HOOK.md + handler.ts) - Add docker-compose, Dockerfile, and supporting infra files Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+744
-105
@@ -1,18 +1,91 @@
|
||||
(function() {
|
||||
const app = document.getElementById('app');
|
||||
|
||||
// Router
|
||||
function route() {
|
||||
const path = window.location.pathname;
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
function route() {
|
||||
cleanupLiveViews();
|
||||
|
||||
const path = window.location.pathname;
|
||||
if (path === '/' || path === '/sessions') {
|
||||
renderSessions();
|
||||
} else if (path.startsWith('/agents')) {
|
||||
renderAgents();
|
||||
} else if (path.startsWith('/openclaw')) {
|
||||
renderOpenClaw();
|
||||
} else if (path.startsWith('/sessions/')) {
|
||||
const sessionID = path.split('/sessions/')[1];
|
||||
renderSession(sessionID);
|
||||
renderSession(path.split('/sessions/')[1]);
|
||||
} else if (path.startsWith('/runs/')) {
|
||||
const runID = path.split('/runs/')[1];
|
||||
renderRun(runID);
|
||||
renderRun(path.split('/runs/')[1]);
|
||||
} else {
|
||||
app.innerHTML = '<p>Page not found</p>';
|
||||
}
|
||||
@@ -25,14 +98,28 @@
|
||||
|
||||
window.addEventListener('popstate', route);
|
||||
|
||||
// API helpers
|
||||
async function api(path) {
|
||||
const resp = await fetch('/api' + path);
|
||||
if (!resp.ok) throw new Error('API error');
|
||||
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, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function relativeTime(ts) {
|
||||
if (!ts) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const then = new Date(ts).getTime();
|
||||
const diff = now - then;
|
||||
@@ -44,23 +131,82 @@
|
||||
}
|
||||
|
||||
function formatDuration(ms) {
|
||||
if (!ms) return '-';
|
||||
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 statusIcon(status) {
|
||||
if (status === 'success') return '<span class="status-success">✓</span>';
|
||||
if (status === 'error') return '<span class="status-error">✗</span>';
|
||||
return '<span class="status-unknown">●</span>';
|
||||
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];
|
||||
}
|
||||
|
||||
// Sessions list
|
||||
let sessionsState = { sessions: [], cursor: null, filters: {} };
|
||||
function statusIcon(status) {
|
||||
if (status === 'success') return '<span class="status-badge status-success"><span class="status-dot"></span>success</span>';
|
||||
if (status === 'error') return '<span class="status-badge status-error"><span class="status-dot"></span>error</span>';
|
||||
return '<span class="status-badge status-unknown"><span class="status-dot"></span>unknown</span>';
|
||||
}
|
||||
|
||||
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 = `
|
||||
<div class="page-header">
|
||||
<h2>Sessions</h2>
|
||||
</div>
|
||||
<div class="filters">
|
||||
<label>From <input type="date" id="filter-from"></label>
|
||||
<label>To <input type="date" id="filter-to"></label>
|
||||
@@ -69,26 +215,28 @@
|
||||
<option value="">All</option>
|
||||
<option value="claude-code">claude-code</option>
|
||||
<option value="opencode">opencode</option>
|
||||
<option value="openclaw">openclaw</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>Host <input type="text" id="filter-host" placeholder="hostname"></label>
|
||||
</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Session</th>
|
||||
<th>Framework</th>
|
||||
<th>Host</th>
|
||||
<th>Runs</th>
|
||||
<th>Time</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="sessions-body"></tbody>
|
||||
</table>
|
||||
<div class="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Session</th>
|
||||
<th>Framework</th>
|
||||
<th>Host</th>
|
||||
<th>Runs</th>
|
||||
<th>Time</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="sessions-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button id="load-more" class="load-more" style="display:none">Load more</button>
|
||||
`;
|
||||
|
||||
// Bind filter events
|
||||
['from', 'to', 'framework', 'host'].forEach(f => {
|
||||
document.getElementById('filter-' + f).addEventListener('change', () => {
|
||||
sessionsState.sessions = [];
|
||||
@@ -122,12 +270,12 @@
|
||||
|
||||
const tbody = document.getElementById('sessions-body');
|
||||
tbody.innerHTML = sessionsState.sessions.map(s => `
|
||||
<tr class="clickable" data-session="${s.session_id}">
|
||||
<td>${s.session_id.substring(0, 12)}...</td>
|
||||
<td>${s.framework || '-'}</td>
|
||||
<td>${s.host || '-'}</td>
|
||||
<tr class="clickable" data-session="${escapeHTML(s.session_id)}">
|
||||
<td class="id-cell">${escapeHTML(s.session_id.substring(0, 12))}...</td>
|
||||
<td>${escapeHTML(s.framework || '-')}</td>
|
||||
<td>${escapeHTML(s.host || '-')}</td>
|
||||
<td>${s.run_count}</td>
|
||||
<td title="${s.started_at}">${relativeTime(s.started_at)}</td>
|
||||
<td title="${escapeHTML(s.started_at)}">${escapeHTML(relativeTime(s.started_at))}</td>
|
||||
</tr>
|
||||
`).join('') || '<tr><td colspan="5" class="empty-state">No sessions found</td></tr>';
|
||||
|
||||
@@ -138,12 +286,10 @@
|
||||
document.getElementById('load-more').style.display = sessionsState.cursor ? 'block' : 'none';
|
||||
}
|
||||
|
||||
// Session detail
|
||||
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';
|
||||
@@ -151,42 +297,44 @@
|
||||
app.innerHTML = `
|
||||
<a href="/sessions" class="back-link">← Back to Sessions</a>
|
||||
<div class="page-header">
|
||||
<h2>Session ${sessionID.substring(0, 16)}...</h2>
|
||||
<p class="meta">
|
||||
Started: ${new Date(s.started_at).toLocaleString()} •
|
||||
Framework: ${s.framework || '-'} •
|
||||
Host: ${s.host || '-'} •
|
||||
Duration: ${duration}
|
||||
</p>
|
||||
<h2>Session <span style="font-family:var(--font-mono);font-size:1.1rem;color:var(--accent)">${escapeHTML(sessionID.substring(0, 16))}...</span></h2>
|
||||
<div class="meta">
|
||||
<span class="meta-item"><span class="meta-label">Started</span> ${escapeHTML(new Date(s.started_at).toLocaleString())}</span>
|
||||
<span class="meta-item"><span class="meta-label">Framework</span> ${escapeHTML(s.framework || '-')}</span>
|
||||
<span class="meta-item"><span class="meta-label">Host</span> ${escapeHTML(s.host || '-')}</span>
|
||||
<span class="meta-item"><span class="meta-label">Duration</span> ${escapeHTML(duration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section-title">Runs <span class="count">${runs.length}</span></div>
|
||||
<div class="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Run ID</th>
|
||||
<th>Status</th>
|
||||
<th>Spans</th>
|
||||
<th>Duration</th>
|
||||
<th>Started</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${runs.map(r => {
|
||||
const runDuration = r.ended_at
|
||||
? formatDuration(new Date(r.ended_at) - new Date(r.started_at))
|
||||
: '-';
|
||||
return `
|
||||
<tr class="clickable" data-run="${escapeHTML(r.run_id)}">
|
||||
<td class="id-cell">${escapeHTML(r.run_id.substring(0, 12))}...</td>
|
||||
<td>${statusIcon(r.status)}</td>
|
||||
<td>${r.span_count}</td>
|
||||
<td>${escapeHTML(runDuration)}</td>
|
||||
<td>${escapeHTML(new Date(r.started_at).toLocaleTimeString())}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('') || '<tr><td colspan="5" class="empty-state">No runs</td></tr>'}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<h3>Runs (${runs.length})</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Run ID</th>
|
||||
<th>Status</th>
|
||||
<th>Spans</th>
|
||||
<th>Duration</th>
|
||||
<th>Started</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${runs.map(r => {
|
||||
const dur = r.ended_at
|
||||
? formatDuration(new Date(r.ended_at) - new Date(r.started_at))
|
||||
: '-';
|
||||
return `
|
||||
<tr class="clickable" data-run="${r.run_id}">
|
||||
<td>${r.run_id.substring(0, 12)}...</td>
|
||||
<td>${statusIcon(r.status)} ${r.status}</td>
|
||||
<td>${r.span_count}</td>
|
||||
<td>${dur}</td>
|
||||
<td>${new Date(r.started_at).toLocaleTimeString()}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('') || '<tr><td colspan="5" class="empty-state">No runs</td></tr>'}
|
||||
</tbody>
|
||||
</table>
|
||||
`;
|
||||
|
||||
document.querySelectorAll('tr.clickable').forEach(row => {
|
||||
@@ -199,51 +347,51 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Run detail
|
||||
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 = `
|
||||
<a href="/sessions/${r.session_id}" class="back-link">← Back to Session</a>
|
||||
<a href="/sessions/${escapeHTML(r.session_id)}" class="back-link">← Back to Session</a>
|
||||
<div class="page-header">
|
||||
<h2>Run ${runID.substring(0, 16)}... ${statusIcon(r.status)}</h2>
|
||||
<p class="meta">
|
||||
Started: ${new Date(r.started_at).toLocaleString()} •
|
||||
Duration: ${duration}
|
||||
</p>
|
||||
<h2>Run <span style="font-family:var(--font-mono);font-size:1.1rem;color:var(--accent)">${escapeHTML(runID.substring(0, 16))}...</span> ${statusIcon(r.status)}</h2>
|
||||
<div class="meta">
|
||||
<span class="meta-item"><span class="meta-label">Started</span> ${escapeHTML(new Date(r.started_at).toLocaleString())}</span>
|
||||
<span class="meta-item"><span class="meta-label">Duration</span> ${escapeHTML(duration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<h3>Spans (${spans.length})</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Kind</th>
|
||||
<th>Status</th>
|
||||
<th>Duration</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="spans-body">
|
||||
${spans.map((sp, i) => `
|
||||
<tr class="expandable" data-index="${i}">
|
||||
<td><span class="expand-icon">▶</span>${sp.name}</td>
|
||||
<td>${sp.kind}</td>
|
||||
<td>${statusIcon(sp.status)}</td>
|
||||
<td>${formatDuration(sp.duration_ms)}</td>
|
||||
<div class="section-title">Spans <span class="count">${spans.length}</span></div>
|
||||
<div class="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Kind</th>
|
||||
<th>Status</th>
|
||||
<th>Duration</th>
|
||||
</tr>
|
||||
<tr class="span-detail-row" data-index="${i}" style="display:none">
|
||||
<td colspan="4">
|
||||
<div class="span-details">${JSON.stringify(sp.payload, null, 2)}</div>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('') || '<tr><td colspan="4" class="empty-state">No spans</td></tr>'}
|
||||
</tbody>
|
||||
</table>
|
||||
</thead>
|
||||
<tbody id="spans-body">
|
||||
${spans.map((sp, i) => `
|
||||
<tr class="expandable" data-index="${i}">
|
||||
<td><span class="expand-icon">▶</span>${escapeHTML(sp.name)}</td>
|
||||
<td>${escapeHTML(sp.kind)}</td>
|
||||
<td>${statusIcon(sp.status)}</td>
|
||||
<td>${escapeHTML(formatDuration(sp.duration_ms))}</td>
|
||||
</tr>
|
||||
<tr class="span-detail-row" data-index="${i}" style="display:none">
|
||||
<td colspan="4">
|
||||
<div class="span-details">${escapeHTML(JSON.stringify(sp.payload, null, 2))}</div>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('') || '<tr><td colspan="4" class="empty-state">No spans</td></tr>'}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.querySelectorAll('tr.expandable').forEach(row => {
|
||||
@@ -267,6 +415,497 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Start
|
||||
async function renderOpenClaw() {
|
||||
app.innerHTML = '<div class="page-header"><h2>OpenClaw</h2></div><p class="empty-state">Loading...</p>';
|
||||
|
||||
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 = `<div class="page-header"><h2>OpenClaw</h2></div><p class="empty-state">Error loading: ${escapeHTML(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 = `
|
||||
<div class="page-header"><h2>OpenClaw</h2></div>
|
||||
<p class="empty-state">No OpenClaw instances found</p>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
app.innerHTML = `
|
||||
<div class="page-header">
|
||||
<h2>OpenClaw <span class="live-indicator"><span class="live-dot"></span>Live</span></h2>
|
||||
</div>
|
||||
<div class="vm-grid">
|
||||
${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 `
|
||||
<div class="vm-card">
|
||||
<div class="vm-card-header">
|
||||
<h3>${escapeHTML(inst.name || name)}</h3>
|
||||
<div class="vm-status ${host.state === 'running' ? 'running' : 'stopped'}">
|
||||
${host.state === 'running' ? 'Running' : 'Stopped'}
|
||||
</div>
|
||||
</div>
|
||||
<div class="vm-updated">Updated ${escapeHTML(relativeTime(getEnvelopeTS(evt)))}</div>
|
||||
<table class="vm-stats">
|
||||
<tr><td>Host</td><td>${escapeHTML(inst.host || '-')}</td></tr>
|
||||
<tr><td>Domain</td><td>${escapeHTML(inst.domain || '-')}</td></tr>
|
||||
<tr><td>vCPUs</td><td>${host.vcpus || '-'}</td></tr>
|
||||
<tr><td>Memory</td><td>${escapeHTML(formatBytes(host.memory_kib ? host.memory_kib * 1024 : 0) || '-')}</td></tr>
|
||||
<tr><td>Disk</td><td>${escapeHTML(formatBytes(host.disk_actual_bytes) || '-')}</td></tr>
|
||||
<tr><td>Autostart</td><td>${host.autostart ? 'Yes' : 'No'}</td></tr>
|
||||
${guest ? `
|
||||
<tr><td>Gateway</td><td class="${guest.service_active ? 'status-success' : 'status-error'}">${guest.service_active ? 'Active' : 'Inactive'}</td></tr>
|
||||
<tr><td>HTTP</td><td class="${guest.http_status === 200 ? 'status-success' : 'status-error'}">${guest.http_status || 'N/A'}</td></tr>
|
||||
<tr><td>Version</td><td>${escapeHTML(guest.version || '-')}</td></tr>
|
||||
<tr><td>Guest Memory</td><td>${guest.memory_percent !== undefined ? guest.memory_percent.toFixed(1) : '-'}%</td></tr>
|
||||
<tr><td>Guest Disk</td><td>${guest.disk_percent !== undefined ? guest.disk_percent.toFixed(1) : '-'}%</td></tr>
|
||||
<tr><td>Load</td><td>${guest.load_average !== undefined ? guest.load_average.toFixed(2) : '-'}</td></tr>
|
||||
<tr><td>Uptime</td><td>${escapeHTML(guest.service_uptime || '-')}</td></tr>
|
||||
` : ''}
|
||||
</table>
|
||||
${issues ? `
|
||||
<div class="vm-issues">
|
||||
${Object.entries(issues).filter(([, value]) => value).map(([key]) => `
|
||||
<span class="issue ${escapeHTML(key)}">${escapeHTML(key.replace(/_/g, ' '))}</span>
|
||||
`).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
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 = `
|
||||
<div class="page-header">
|
||||
<h2>Agents <span class="live-indicator"><span class="live-dot"></span>Live</span></h2>
|
||||
</div>
|
||||
<div class="vm-strip" id="agents-vm-strip"></div>
|
||||
<div class="agents-layout">
|
||||
<div class="timeline" id="agents-timeline">
|
||||
<p class="empty-state">Loading agent activity...</p>
|
||||
</div>
|
||||
<div class="stats-panel">
|
||||
<div class="stat-card">
|
||||
<div class="stat-card-title">Messages</div>
|
||||
<div class="stat-card-value" id="stat-messages">0</div>
|
||||
<div class="stat-card-sub">received and sent</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-card-title">Tool Calls</div>
|
||||
<div class="stat-card-value" id="stat-tools">0</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-card-title">Errors</div>
|
||||
<div class="stat-card-value" id="stat-errors">0</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-card-title">Top Tools</div>
|
||||
<ul class="stat-list" id="stat-top-tools">
|
||||
<li style="color:var(--text-dim);font-size:0.8rem">No data yet</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
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 = `<p class="empty-state">Error loading agent activity: ${escapeHTML(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
agentsUnsubscribe = subscribeWS(handleAgentsWS);
|
||||
}
|
||||
|
||||
function renderAgentVMStrip() {
|
||||
const strip = document.getElementById('agents-vm-strip');
|
||||
if (!strip) {
|
||||
return;
|
||||
}
|
||||
|
||||
const vms = getVMStatus();
|
||||
strip.innerHTML = vms.map(vm => `
|
||||
<div class="vm-pill ${vm.active ? 'active' : 'inactive'}">
|
||||
<span class="vm-pill-dot"></span>
|
||||
<span class="vm-pill-name">${escapeHTML(vm.name)}</span>
|
||||
<span class="vm-pill-label">${vm.active ? 'online' : 'offline'}</span>
|
||||
</div>
|
||||
`).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 '<div class="event-icon message-in">↓</div>';
|
||||
case 'run.end':
|
||||
return '<div class="event-icon message-out">↑</div>';
|
||||
case 'span.start':
|
||||
case 'span.end':
|
||||
return '<div class="event-icon tool">⚙</div>';
|
||||
case 'error':
|
||||
return '<div class="event-icon error">!</div>';
|
||||
case 'session.start':
|
||||
case 'session.end':
|
||||
return '<div class="event-icon session">○</div>';
|
||||
default:
|
||||
return '<div class="event-icon internal">·</div>';
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
? ` <span class="timeline-duration">${escapeHTML(formatDuration(payload.duration_ms))}</span>`
|
||||
: '';
|
||||
return `<div class="timeline-event-body tool-name">${escapeHTML(name)}${duration}</div>`;
|
||||
}
|
||||
|
||||
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 `<div class="timeline-event-body message-preview">"${escapeHTML(trimmed)}"</div>`;
|
||||
}
|
||||
|
||||
if (eventType === 'run.end') {
|
||||
return `<div class="timeline-event-body">${statusIcon(payload.status || 'unknown')}</div>`;
|
||||
}
|
||||
|
||||
if (eventType === 'error') {
|
||||
const errPayload = payload.error || {};
|
||||
const errType = errPayload.type || 'error';
|
||||
const message = errPayload.message || payload.message || 'unknown';
|
||||
return `<div class="timeline-event-body error-message">${escapeHTML(errType + ': ' + message)}</div>`;
|
||||
}
|
||||
|
||||
if (eventType === 'session.start' || eventType === 'session.end') {
|
||||
return correlation.session_id
|
||||
? `<div class="timeline-event-body">session ${escapeHTML(correlation.session_id)}</div>`
|
||||
: '';
|
||||
}
|
||||
|
||||
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 = '<p class="empty-state">Waiting for agent activity...</p>';
|
||||
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 ? `<div class="timeline-detail">${escapeHTML(details)}</div>` : '';
|
||||
const expandHTML = details ? '<button class="timeline-expand-hint" type="button">details</button>' : '';
|
||||
|
||||
return `
|
||||
<div class="timeline-event" data-index="${index}">
|
||||
<div class="timeline-event-header">
|
||||
${getEventIcon(eventType)}
|
||||
<span class="timeline-vm-tag ${vmClass}">${escapeHTML(vmName)}</span>
|
||||
<span class="timeline-event-type">${escapeHTML(getEventLabel(eventType))}</span>
|
||||
<span class="timeline-event-time">${escapeHTML(new Date(getEnvelopeTS(evt)).toLocaleTimeString())}</span>
|
||||
</div>
|
||||
${getEventBody(evt)}
|
||||
${expandHTML}
|
||||
${detailHTML}
|
||||
</div>
|
||||
`;
|
||||
}).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 = '<li style="color:var(--text-dim);font-size:0.8rem">No data yet</li>';
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = topTools.map(([name, count]) => `
|
||||
<li>
|
||||
<span class="stat-list-name">${escapeHTML(name)}</span>
|
||||
<span class="stat-list-count">${count}</span>
|
||||
</li>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
route();
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user