Files
beads/examples/monitor-webui/web/static/js/app.js
Markus Flür e7f532db93 Implementing an RPC monitoring solution with a web-ui as implementation example. (#244)
* bd sync: 2025-10-30 12:12:27

* Working on frontend

* bd sync: 2025-11-06 16:55:55

* feat: finish bd monitor human viewer

* Merge conflicts resolved and added tests

* bd sync: 2025-11-06 17:23:41

* bd sync: 2025-11-06 17:34:52

* feat: Add reload button and multiselect status filter to monitor

- Changed status filter from single select to multiselect with 'Open' selected by default
- Added reload button with visual feedback (hover/active states)
- Updated filterIssues() to handle multiple selected statuses
- Added reloadData() function that reloads both stats and issues
- Improved responsive design for mobile devices
- Filter controls now use flexbox layout with better spacing

* fix: Update monitor statistics to show Total, In Progress, Open, Closed

- Replaced 'Ready to Work' stat with 'In Progress' stat
- Reordered stats to show logical progression: Total -> In Progress -> Open -> Closed
- Updated loadStats() to fetch in-progress count from stats API
- Removed unnecessary separate API call for ready count

* fix: Correct API field names in monitor stats JavaScript

The JavaScript was using incorrect field names (stats.total, stats.by_status)
that don't match the actual types.Statistics struct which uses flat fields
with underscores (total_issues, in_progress_issues, etc).

Fixed by updating loadStats() to use correct field names:
- stats.total -> stats.total_issues
- stats.by_status?.['in-progress'] -> stats.in_progress_issues
- stats.by_status?.open -> stats.open_issues
- stats.by_status?.closed -> stats.closed_issues

Fixes beads-9

* bd sync: 2025-11-06 17:51:24

* bd sync: 2025-11-06 17:56:09

* fix: Make monitor require daemon to prevent SQLite locking

Implemented Option 1 from beads-eel: monitor now requires daemon and never
opens direct SQLite connection.

Changes:
- Added 'monitor' to noDbCommands list in main.go to skip normal DB initialization
- Added validateDaemonForMonitor() PreRun function that:
  - Finds database path using beads.FindDatabasePath()
  - Validates daemon is running and healthy
  - Fails gracefully with clear error message if no daemon
  - Only uses RPC connection, never opens SQLite directly

Benefits:
- Eliminates SQLite locking conflicts between monitor and daemon
- Users can now close/update issues via CLI while monitor runs
- Clear error messages guide users to start daemon first

Fixes beads-eel

* bd sync: 2025-11-06 18:03:50

* docs: Add bd daemons restart subcommand documentation

Added documentation for the 'bd daemons restart' subcommand across all documentation files:

- commands/daemons.md: Added full restart subcommand section with synopsis, description, arguments, flags, and examples
- README.md: Added restart examples to daemon management section
- AGENTS.md: Added restart examples with --json flag for agents

The restart command gracefully stops and starts a specific daemon by workspace path or PID,
useful after upgrading bd or when a daemon needs refreshing.

Fixes beads-11

* bd sync: 2025-11-06 18:13:16

* Separated the web ui from the general monitoring functionality

---------

Co-authored-by: Steve Yegge <stevey@sourcegraph.com>
2025-11-07 09:49:12 -08:00

249 lines
9.6 KiB
JavaScript

let allIssues = [];
let ws = null;
let wsConnected = false;
// WebSocket connection
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = protocol + '//' + window.location.host + '/ws';
ws = new WebSocket(wsUrl);
ws.onopen = function() {
console.log('WebSocket connected');
wsConnected = true;
updateConnectionStatus(true);
};
ws.onmessage = function(event) {
console.log('WebSocket message:', event.data);
const mutation = JSON.parse(event.data);
handleMutation(mutation);
};
ws.onerror = function(error) {
console.error('WebSocket error:', error);
wsConnected = false;
updateConnectionStatus(false);
};
ws.onclose = function() {
console.log('WebSocket disconnected');
wsConnected = false;
updateConnectionStatus(false);
// Reconnect after 5 seconds
setTimeout(connectWebSocket, 5000);
};
}
// Update connection status indicator
function updateConnectionStatus(connected) {
const statusEl = document.getElementById('connection-status');
const dotEl = document.getElementById('connection-dot');
const textEl = document.getElementById('connection-text');
if (connected) {
statusEl.className = 'connection-status connected';
dotEl.className = 'connection-dot connected';
textEl.textContent = 'Connected';
} else {
statusEl.className = 'connection-status disconnected';
dotEl.className = 'connection-dot disconnected';
textEl.textContent = 'Disconnected';
}
}
// Show/hide loading overlay
function setLoading(isLoading) {
const overlay = document.getElementById('loading-overlay');
if (isLoading) {
overlay.classList.add('active');
} else {
overlay.classList.remove('active');
}
}
// Show error message
function showError(message) {
const errorEl = document.getElementById('error-message');
errorEl.textContent = message;
errorEl.classList.add('active');
setTimeout(() => {
errorEl.classList.remove('active');
}, 5000);
}
// Handle mutation event
function handleMutation(mutation) {
console.log('Mutation:', mutation.type, mutation.issue_id);
// Refresh data on mutation
loadStats();
loadIssues();
}
// Load statistics
async function loadStats() {
try {
const response = await fetch('/api/stats');
if (!response.ok) throw new Error('Failed to load statistics');
const stats = await response.json();
document.getElementById('stat-total').textContent = stats.total_issues || 0;
document.getElementById('stat-in-progress').textContent = stats.in_progress_issues || 0;
document.getElementById('stat-open').textContent = stats.open_issues || 0;
document.getElementById('stat-closed').textContent = stats.closed_issues || 0;
} catch (error) {
console.error('Error loading statistics:', error);
showError('Failed to load statistics: ' + error.message);
}
}
// Load all issues
async function loadIssues() {
try {
const response = await fetch('/api/issues');
if (!response.ok) throw new Error('Failed to load issues');
allIssues = await response.json();
renderIssues(allIssues);
} catch (error) {
console.error('Error loading issues:', error);
showError('Failed to load issues: ' + error.message);
document.getElementById('issues-tbody').innerHTML = '<tr><td colspan="6" style="text-align: center; color: #721c24;">Error loading issues</td></tr>';
document.getElementById('issues-card-view').innerHTML = '<div class="empty-state"><div class="empty-state-icon">⚠️</div><p>Error loading issues</p></div>';
}
}
// Render issues table
function renderIssues(issues) {
const tbody = document.getElementById('issues-tbody');
const cardView = document.getElementById('issues-card-view');
if (!issues || issues.length === 0) {
const emptyState = '<div class="empty-state"><div class="empty-state-icon">📋</div><h3>No issues found</h3><p>Create your first issue to get started!</p></div>';
tbody.innerHTML = '<tr><td colspan="6">' + emptyState + '</td></tr>';
cardView.innerHTML = emptyState;
return;
}
// Render table view
tbody.innerHTML = issues.map(issue => {
const statusClass = 'status-' + (issue.status || 'open').toLowerCase().replace('_', '-');
const priorityClass = 'priority-' + (issue.priority || 2);
return '<tr onclick="showIssueDetail(\'' + issue.id + '\')"><td>' + issue.id + '</td><td>' + issue.title + '</td><td class="' + statusClass + '">' + (issue.status || 'open') + '</td><td class="' + priorityClass + '">P' + (issue.priority || 2) + '</td><td>' + (issue.issue_type || 'task') + '</td><td>' + (issue.assignee || '-') + '</td></tr>';
}).join('');
// Render card view for mobile
cardView.innerHTML = issues.map(issue => {
const statusClass = 'status-' + (issue.status || 'open').toLowerCase().replace('_', '-');
const priorityClass = 'priority-' + (issue.priority || 2);
let html = '<div class="issue-card" onclick="showIssueDetail(\'' + issue.id + '\')">';
html += '<div class="issue-card-header">';
html += '<span class="issue-card-id">' + issue.id + '</span>';
html += '<span class="' + priorityClass + '">P' + (issue.priority || 2) + '</span>';
html += '</div>';
html += '<h3 class="issue-card-title">' + issue.title + '</h3>';
html += '<div class="issue-card-meta">';
html += '<span class="' + statusClass + '">● ' + (issue.status || 'open') + '</span>';
html += '<span>Type: ' + (issue.issue_type || 'task') + '</span>';
if (issue.assignee) html += '<span>👤 ' + issue.assignee + '</span>';
html += '</div>';
html += '</div>';
return html;
}).join('');
}
// Filter issues
function filterIssues() {
const statusSelect = document.getElementById('filter-status');
const selectedStatuses = Array.from(statusSelect.selectedOptions).map(opt => opt.value);
const priorityFilter = document.getElementById('filter-priority').value;
const filtered = allIssues.filter(issue => {
// If statuses are selected, check if issue status is in the selected list
if (selectedStatuses.length > 0 && !selectedStatuses.includes(issue.status)) return false;
if (priorityFilter && issue.priority !== parseInt(priorityFilter)) return false;
return true;
});
renderIssues(filtered);
}
// Reload all data
function reloadData() {
setLoading(true);
Promise.all([loadStats(), loadIssues()])
.then(() => {
setLoading(false);
})
.catch(error => {
console.error('Error reloading data:', error);
setLoading(false);
showError('Failed to reload data: ' + error.message);
});
}
// Show issue detail modal
async function showIssueDetail(issueId) {
const modal = document.getElementById('issue-modal');
const modalTitle = document.getElementById('modal-title');
const modalBody = document.getElementById('modal-body');
modal.style.display = 'block';
modalTitle.textContent = 'Loading...';
modalBody.innerHTML = '<div class="spinner"></div>';
try {
const response = await fetch('/api/issues/' + issueId);
if (!response.ok) throw new Error('Issue not found');
const issue = await response.json();
modalTitle.textContent = issue.id + ': ' + issue.title;
let html = '<p><strong>Status:</strong> ' + issue.status + '</p>';
html += '<p><strong>Priority:</strong> P' + issue.priority + '</p>';
html += '<p><strong>Type:</strong> ' + issue.issue_type + '</p>';
html += '<p><strong>Assignee:</strong> ' + (issue.assignee || 'Unassigned') + '</p>';
html += '<p><strong>Created:</strong> ' + new Date(issue.created_at).toLocaleString() + '</p>';
html += '<p><strong>Updated:</strong> ' + new Date(issue.updated_at).toLocaleString() + '</p>';
if (issue.description) html += '<h3>Description</h3><pre>' + issue.description + '</pre>';
if (issue.design) html += '<h3>Design</h3><pre>' + issue.design + '</pre>';
if (issue.notes) html += '<h3>Notes</h3><pre>' + issue.notes + '</pre>';
if (issue.labels && issue.labels.length > 0) html += '<p><strong>Labels:</strong> ' + issue.labels.join(', ') + '</p>';
modalBody.innerHTML = html;
} catch (error) {
console.error('Error loading issue details:', error);
showError('Failed to load issue details: ' + error.message);
modalBody.innerHTML = '<div class="empty-state"><div class="empty-state-icon">⚠️</div><p>Error loading issue details</p></div>';
}
}
// Close modal
document.querySelector('.close').onclick = function() {
document.getElementById('issue-modal').style.display = 'none';
};
window.onclick = function(event) {
const modal = document.getElementById('issue-modal');
if (event.target == modal) {
modal.style.display = 'none';
}
};
// Filter event listeners
document.getElementById('filter-status').addEventListener('change', filterIssues);
document.getElementById('filter-priority').addEventListener('change', filterIssues);
// Reload button listener
document.getElementById('reload-button').addEventListener('click', reloadData);
// Initial load
connectWebSocket();
loadStats();
loadIssues();
// Fallback: Refresh every 30 seconds (WebSocket should handle real-time updates)
setInterval(() => {
if (!wsConnected) {
loadStats();
loadIssues();
}
}, 30000);