Compare commits
9 Commits
049edc0238
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2840d8b58e | |||
| 1a3740cdad | |||
| 147c2eb30d | |||
| 5839bc47ce | |||
| 3f086b7849 | |||
| 9788abb8ce | |||
| ca1cb63f65 | |||
| 54af25d2da | |||
| 0dc5a2db2f |
@@ -1,20 +1,43 @@
|
||||
# Hermes Command Center
|
||||
|
||||
Mobile-friendly web dashboard for managing Hermes agents, configs, and network infrastructure.
|
||||
Mobile-friendly web dashboard for managing Hermes agents, configs, tasks, services, and network infrastructure.
|
||||
|
||||
## Features
|
||||
|
||||
- **Agent Chat Interface** - Talk to all Hermes profiles (kanban, coder, assistant, artist)
|
||||
- **Config Editor** - Edit .env and YAML config files
|
||||
- **Obsidian Vault Reader** - Browse markdown notes and wiki
|
||||
- **Network Status** - Live host and service monitoring
|
||||
- **📊 Dashboard** — At-a-glance overview of agents, hosts, config files, chat messages, and kanban tasks
|
||||
- **💬 Agent Chat** — Talk to all Hermes profiles (kanban, coder, assistant, artist) with online/offline status
|
||||
- **⚙️ Config Editor** — Edit .env, config.yaml, and profile configs with YAML validation and auto-backup
|
||||
- **📋 Kanban Viewer** — Browse all 19 kanban boards and view task status (done/blocked/ready/todo)
|
||||
- **📚 Vault Reader** — Browse Obsidian markdown notes with wiki-link support and full-text search
|
||||
- **🔧 Service Control** — View and manage Hermes systemd services (start/stop/restart)
|
||||
- **🌐 Network Status** — Live host ping monitoring, service health checks, and local port scanning
|
||||
|
||||
## Panels
|
||||
|
||||
| Panel | Description |
|
||||
|---|---|
|
||||
| Dashboard | 6-card overview with quick action buttons |
|
||||
| Chat | Real-time agent messaging with history |
|
||||
| Config | 7 whitelisted config files with line-numbered editor |
|
||||
| Kanban | 19-board viewer with status summary |
|
||||
| Vault | File tree, markdown renderer, wiki-links, grep search |
|
||||
| Services | 11 Hermes systemd services with start/stop/restart |
|
||||
| Network | 5 hosts, 17 services, 36 local ports with auto-refresh |
|
||||
|
||||
## Mobile
|
||||
|
||||
- Bottom navigation bar on mobile (≤768px)
|
||||
- Full-width panels with touch-friendly 44px+ tap targets
|
||||
- Sidebar on desktop, bottom tabs on mobile
|
||||
- Safe-area-inset support for notched devices
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- FastAPI backend
|
||||
- Vanilla HTML/CSS/JS frontend
|
||||
- Vanilla HTML/CSS/JS frontend (no frameworks)
|
||||
- SQLite for conversation and kanban storage
|
||||
- Mobile-first responsive design
|
||||
- Port: 8888
|
||||
- Port: 8888 (public via command.ourpad.casa:443)
|
||||
|
||||
## Development
|
||||
|
||||
@@ -25,4 +48,4 @@ pip install -r requirements.txt
|
||||
python3 main.py
|
||||
```
|
||||
|
||||
Access at: http://localhost:8888
|
||||
Access at: http://localhost:8888 (Basic auth: shawn / your-password)
|
||||
|
||||
+760
-6
@@ -1,17 +1,771 @@
|
||||
// Command Center SPA Router
|
||||
// ── Command Center SPA Router ───────────────────────────────────────
|
||||
const sections = document.querySelectorAll('.panel');
|
||||
const links = document.querySelectorAll('.nav-links a');
|
||||
const navLinks = document.querySelectorAll('.nav-links a');
|
||||
const bottomNavItems = document.querySelectorAll('.bottom-nav .nav-item');
|
||||
|
||||
function navigate(hash) {
|
||||
const target = hash.replace('#', '') || 'agents';
|
||||
const target = hash.replace('#', '') || 'dashboard';
|
||||
sections.forEach(s => s.hidden = s.id !== target);
|
||||
links.forEach(l => l.classList.toggle('active', l.getAttribute('href') === '#' + target));
|
||||
// Desktop sidebar
|
||||
navLinks.forEach(l => l.classList.toggle('active', l.getAttribute('href') === '#' + target));
|
||||
// Mobile bottom nav
|
||||
bottomNavItems.forEach(item => item.classList.toggle('active', item.dataset.tab === target));
|
||||
|
||||
// Init panels on first visit
|
||||
if (target === 'config') initConfigPanel();
|
||||
if (target === 'kanban') initKanban();
|
||||
if (target === 'dashboard') loadDashboard();
|
||||
if (target === 'agents') setTimeout(loadAgentProfiles, 100);
|
||||
if (target === 'network') { if (!window._networkInited) { window._networkInited = true; initNetworkDashboard(); } }
|
||||
if (target === 'services') loadServices();
|
||||
}
|
||||
|
||||
links.forEach(l => l.addEventListener('click', e => {
|
||||
// Desktop sidebar clicks
|
||||
navLinks.forEach(l => l.addEventListener('click', e => {
|
||||
e.preventDefault();
|
||||
window.location.hash = l.getAttribute('href');
|
||||
}));
|
||||
// Mobile bottom nav clicks
|
||||
bottomNavItems.forEach(item => item.addEventListener('click', e => {
|
||||
e.preventDefault();
|
||||
window.location.hash = '#' + item.dataset.tab;
|
||||
}));
|
||||
|
||||
window.addEventListener('hashchange', () => navigate(window.location.hash));
|
||||
navigate(window.location.hash || '#agents');
|
||||
navigate(window.location.hash || '#dashboard');
|
||||
|
||||
// ── Utility ─────────────────────────────────────────────────────────
|
||||
function escapeHtml(text) {
|
||||
if (text == null) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// ── Dashboard Panel ─────────────────────────────────────────────────
|
||||
async function loadDashboard() {
|
||||
try {
|
||||
const res = await fetch('/api/dashboard');
|
||||
const data = await res.json();
|
||||
document.getElementById('dash-agents-val').textContent = data.agents?.online + '/' + data.agents?.total;
|
||||
document.getElementById('dash-hosts-val').textContent = data.network?.hosts ?? '—';
|
||||
document.getElementById('dash-files-val').textContent = data.config?.editable_files ?? '—';
|
||||
document.getElementById('dash-msgs-val').textContent = data.chat?.total_messages ?? '—';
|
||||
document.getElementById('dash-tasks-val').textContent = data.kanban?.done_tasks ?? '—';
|
||||
document.getElementById('dash-boards-val').textContent = data.kanban?.total_boards ?? '—';
|
||||
} catch (err) {
|
||||
console.error('Dashboard load failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshDashboard() {
|
||||
document.querySelectorAll('.dash-card-value').forEach(el => el.textContent = '…');
|
||||
loadDashboard();
|
||||
}
|
||||
|
||||
// ── Config File Editor ──────────────────────────────────────────────
|
||||
let configState = {
|
||||
files: [],
|
||||
currentFile: null,
|
||||
currentContent: '',
|
||||
currentPath: '',
|
||||
dirty: false,
|
||||
lastSaved: null,
|
||||
};
|
||||
|
||||
function initConfigPanel() {
|
||||
if (configState.files.length === 0) loadFileList();
|
||||
}
|
||||
|
||||
async function loadFileList() {
|
||||
const container = document.getElementById('config-files-container');
|
||||
container.innerHTML = '<p class="loading-text">Loading files...</p>';
|
||||
try {
|
||||
const res = await fetch('/api/config/list');
|
||||
if (!res.ok) throw new Error('HTTP ' + res.status);
|
||||
const data = await res.json();
|
||||
configState.files = data.files;
|
||||
renderFileList(data.files);
|
||||
} catch (err) {
|
||||
container.innerHTML = '<p class="error-text">Failed to load files: ' + escapeHtml(err.message) + '</p>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderFileList(files) {
|
||||
const container = document.getElementById('config-files-container');
|
||||
const countEl = document.getElementById('config-count');
|
||||
countEl.textContent = files.length + ' file' + (files.length !== 1 ? 's' : '');
|
||||
if (files.length === 0) {
|
||||
container.innerHTML = '<p class="empty-text">No config files found.</p>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = '';
|
||||
files.forEach(f => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'config-file-item';
|
||||
if (configState.currentPath === f.path) item.classList.add('selected');
|
||||
item.dataset.path = f.path;
|
||||
const nameSpan = document.createElement('span');
|
||||
nameSpan.className = 'file-item-name';
|
||||
nameSpan.textContent = f.label || f.filename;
|
||||
const metaSpan = document.createElement('span');
|
||||
metaSpan.className = 'file-item-meta';
|
||||
if (f.missing) {
|
||||
metaSpan.textContent = 'missing';
|
||||
metaSpan.style.color = 'var(--text-muted)';
|
||||
} else {
|
||||
metaSpan.textContent = formatFileSize(f.size) + ' · ' + f.line_count + ' lines';
|
||||
}
|
||||
item.appendChild(nameSpan);
|
||||
item.appendChild(metaSpan);
|
||||
item.addEventListener('click', () => openFile(f.path));
|
||||
container.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
function formatFileSize(bytes) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const units = ['B', 'KB', 'MB'];
|
||||
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), 2);
|
||||
return (bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1) + ' ' + units[i];
|
||||
}
|
||||
|
||||
async function openFile(path) {
|
||||
configState.dirty = false;
|
||||
configState.currentPath = path;
|
||||
configState.lastSaved = null;
|
||||
document.getElementById('config-file-list').hidden = true;
|
||||
document.getElementById('config-editor').hidden = false;
|
||||
document.getElementById('config-editor-textarea').disabled = true;
|
||||
document.getElementById('config-editor-textarea').value = 'Loading...';
|
||||
document.getElementById('editor-line-numbers').innerHTML = '';
|
||||
document.getElementById('editor-filename').textContent = '';
|
||||
document.getElementById('status-path').textContent = 'Loading...';
|
||||
document.getElementById('status-meta').textContent = '';
|
||||
document.getElementById('status-saved').textContent = '';
|
||||
try {
|
||||
const res = await fetch('/api/config/read?path=' + encodeURIComponent(path));
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new Error(err.error || 'HTTP ' + res.status);
|
||||
}
|
||||
const data = await res.json();
|
||||
configState.currentFile = data;
|
||||
configState.currentContent = data.content;
|
||||
const filename = data.label || data.filename;
|
||||
document.getElementById('editor-filename').textContent = filename;
|
||||
document.getElementById('config-editor-textarea').value = data.content;
|
||||
document.getElementById('config-editor-textarea').disabled = false;
|
||||
document.getElementById('config-editor-textarea').focus();
|
||||
document.getElementById('status-path').textContent = data.path;
|
||||
document.getElementById('status-meta').textContent = formatFileSize(data.size) + ' · ' + data.line_count + ' lines';
|
||||
document.getElementById('status-saved').textContent = data.last_modified
|
||||
? 'Last modified: ' + formatTimestamp(data.last_modified) : '';
|
||||
updateLineNumbers();
|
||||
document.getElementById('config-editor-textarea').addEventListener('input', onEditorChange);
|
||||
document.getElementById('config-editor-textarea').addEventListener('scroll', syncScroll);
|
||||
document.getElementById('config-editor-textarea').addEventListener('keydown', handleEditorKeydown);
|
||||
renderFileList(configState.files);
|
||||
} catch (err) {
|
||||
showToast('Error loading file: ' + err.message, 'error');
|
||||
document.getElementById('config-editor-textarea').value = '';
|
||||
document.getElementById('config-editor-textarea').disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
function onEditorChange() { configState.dirty = true; updateLineNumbers(); updateSaveButton(); }
|
||||
|
||||
function updateSaveButton() {
|
||||
const btn = document.getElementById('config-save-btn');
|
||||
if (configState.dirty) { btn.textContent = 'Save'; btn.style.background = 'var(--accent)'; }
|
||||
else { btn.textContent = 'Saved ✓'; btn.style.background = 'var(--success)'; }
|
||||
}
|
||||
|
||||
function syncScroll() {
|
||||
const textarea = document.getElementById('config-editor-textarea');
|
||||
document.getElementById('editor-line-numbers').scrollTop = textarea.scrollTop;
|
||||
}
|
||||
|
||||
function handleEditorKeydown(e) {
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
const textarea = document.getElementById('config-editor-textarea');
|
||||
const start = textarea.selectionStart, end = textarea.selectionEnd;
|
||||
const val = textarea.value;
|
||||
textarea.value = val.substring(0, start) + ' ' + val.substring(end);
|
||||
textarea.selectionStart = textarea.selectionEnd = start + 4;
|
||||
onEditorChange();
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); saveFile(); }
|
||||
}
|
||||
|
||||
function updateLineNumbers() {
|
||||
const textarea = document.getElementById('config-editor-textarea');
|
||||
const lines = textarea.value.split('\n');
|
||||
let html = '';
|
||||
for (let i = 1; i <= lines.length; i++) html += '<div class="ln">' + i + '</div>';
|
||||
document.getElementById('editor-line-numbers').innerHTML = html;
|
||||
}
|
||||
|
||||
function goBackToList() {
|
||||
if (configState.dirty && !confirm('Unsaved changes. Discard?')) return;
|
||||
document.getElementById('config-file-list').hidden = false;
|
||||
document.getElementById('config-editor').hidden = true;
|
||||
configState.currentFile = null;
|
||||
configState.currentContent = '';
|
||||
configState.currentPath = '';
|
||||
configState.dirty = false;
|
||||
renderFileList(configState.files);
|
||||
}
|
||||
|
||||
async function saveFile() {
|
||||
if (!configState.dirty) return;
|
||||
const textarea = document.getElementById('config-editor-textarea');
|
||||
const content = textarea.value;
|
||||
const path = configState.currentPath;
|
||||
if (!confirm('Save changes to ' + (configState.currentFile?.label || path) + '?')) return;
|
||||
const btn = document.getElementById('config-save-btn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Saving...';
|
||||
try {
|
||||
const res = await fetch('/api/config/save', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ path, content }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'HTTP ' + res.status);
|
||||
configState.dirty = false;
|
||||
configState.lastSaved = new Date();
|
||||
configState.currentContent = content;
|
||||
document.getElementById('status-meta').textContent = formatFileSize(data.size) + ' · ' + data.line_count + ' lines';
|
||||
document.getElementById('status-saved').textContent = 'Saved: ' + formatTimestamp(new Date().toISOString());
|
||||
showToast('File saved. Backup: ' + data.backup_path, 'success');
|
||||
updateSaveButton();
|
||||
loadFileList();
|
||||
} catch (err) {
|
||||
showToast('Save failed: ' + err.message, 'error');
|
||||
} finally { btn.disabled = false; }
|
||||
}
|
||||
|
||||
function formatTimestamp(iso) {
|
||||
try {
|
||||
const d = new Date(iso);
|
||||
return d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
} catch { return iso; }
|
||||
}
|
||||
|
||||
function showToast(message, type) {
|
||||
const toast = document.getElementById('config-toast');
|
||||
toast.textContent = message;
|
||||
toast.className = 'config-toast toast-' + (type || 'info');
|
||||
toast.hidden = false;
|
||||
const editor = document.querySelector('.config-editor');
|
||||
if (!editor.hidden) {
|
||||
const rect = editor.getBoundingClientRect();
|
||||
toast.style.top = (rect.top + 20) + 'px';
|
||||
toast.style.left = '50%';
|
||||
toast.style.transform = 'translateX(-50%)';
|
||||
}
|
||||
clearTimeout(toast._timeout);
|
||||
toast._timeout = setTimeout(() => { toast.hidden = true; }, 4000);
|
||||
}
|
||||
|
||||
// ── Agent Chat ────────────────────────────────────────────────────
|
||||
let chatState = {
|
||||
profiles: [],
|
||||
activeProfile: null,
|
||||
messages: {},
|
||||
sending: false,
|
||||
};
|
||||
|
||||
const PROFILE_ICONS = { coder: '💻', assistant: '🤖', artist: '🎨', kanban: '📋', watchdog: '🛡️' };
|
||||
|
||||
async function loadAgentProfiles() {
|
||||
try {
|
||||
const res = await fetch('/api/agents');
|
||||
if (!res.ok) throw new Error('HTTP ' + res.status);
|
||||
const data = await res.json();
|
||||
chatState.profiles = data.agents || [];
|
||||
renderProfileTabs();
|
||||
if (chatState.activeProfile) {
|
||||
selectProfile(chatState.activeProfile);
|
||||
} else if (chatState.profiles.length > 0) {
|
||||
const online = chatState.profiles.find(p => p.status === 'online');
|
||||
selectProfile(online || chatState.profiles[0]);
|
||||
}
|
||||
} catch (err) { console.error('Failed to load profiles:', err); }
|
||||
}
|
||||
|
||||
function renderProfileTabs() {
|
||||
const container = document.getElementById('chat-profile-tabs');
|
||||
container.innerHTML = '';
|
||||
chatState.profiles.forEach(p => {
|
||||
const tab = document.createElement('button');
|
||||
tab.className = 'chat-profile-tab';
|
||||
if (p.profile === chatState.activeProfile?.profile) tab.classList.add('active');
|
||||
const icon = PROFILE_ICONS[p.profile] || '🤖';
|
||||
tab.innerHTML = '<span class="status-dot ' + p.status + '"></span> ' + icon + ' ' + (p.label || p.profile);
|
||||
tab.title = p.status === 'online' ? 'Online' : 'Offline';
|
||||
tab.addEventListener('click', () => selectProfile(p));
|
||||
container.appendChild(tab);
|
||||
});
|
||||
}
|
||||
|
||||
function selectProfile(profile) {
|
||||
chatState.activeProfile = profile;
|
||||
document.querySelectorAll('.chat-profile-tab').forEach(tab => {
|
||||
const txt = tab.textContent.trim();
|
||||
tab.classList.toggle('active', txt.includes(profile.label || profile.profile));
|
||||
});
|
||||
const msgArea = document.getElementById('chat-messages');
|
||||
msgArea.innerHTML = '';
|
||||
if (!chatState.messages[profile.profile]) showWelcome(profile);
|
||||
document.getElementById('chat-input').disabled = false;
|
||||
document.getElementById('chat-input').focus();
|
||||
updateSendButton();
|
||||
loadConversationHistory(profile.profile);
|
||||
}
|
||||
|
||||
function showWelcome(profile) {
|
||||
const msgArea = document.getElementById('chat-messages');
|
||||
const icon = PROFILE_ICONS[profile.profile] || '🤖';
|
||||
msgArea.innerHTML = '<div class="chat-welcome"><div class="chat-welcome-icon">' + icon + '</div><h3>' + (profile.label || profile.profile) + '</h3><p>' + (profile.status === 'online' ? 'This agent is online. Type a message to start a conversation.' : 'This agent is offline. Start the gateway to chat.') + '</p></div>';
|
||||
}
|
||||
|
||||
async function loadConversationHistory(profileName) {
|
||||
try {
|
||||
const res = await fetch('/api/agents/' + encodeURIComponent(profileName) + '/history?limit=50');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const messages = data.messages || [];
|
||||
chatState.messages[profileName] = messages;
|
||||
if (chatState.activeProfile?.profile === profileName) renderMessages(messages);
|
||||
} catch (err) { console.error('Failed to load history:', err); }
|
||||
}
|
||||
|
||||
function renderMessages(messages) {
|
||||
const msgArea = document.getElementById('chat-messages');
|
||||
msgArea.innerHTML = '';
|
||||
if (!messages || messages.length === 0) { if (chatState.activeProfile) showWelcome(chatState.activeProfile); return; }
|
||||
messages.forEach(msg => appendMessageBubble(msg, false));
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function appendMessageBubble(msg, animate) {
|
||||
const msgArea = document.getElementById('chat-messages');
|
||||
const isUser = msg.role === 'user';
|
||||
const div = document.createElement('div');
|
||||
div.className = 'chat-message ' + (isUser ? 'user' : 'agent');
|
||||
if (!animate) div.style.animation = 'none';
|
||||
const icon = chatState.activeProfile ? (PROFILE_ICONS[chatState.activeProfile.profile] || '🤖') : '🤖';
|
||||
const time = msg.created_at ? new Date(msg.created_at * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '';
|
||||
div.innerHTML = '<div class="bubble">' + escapeHtml(msg.content) + '</div><div class="msg-meta">' + (isUser ? '' : '<span class="msg-profile-icon">' + icon + '</span>') + '<span>' + (isUser ? 'You' : (chatState.activeProfile?.label || 'Agent')) + '</span>' + (time ? ' <span>· ' + time + '</span>' : '') + '</div>';
|
||||
msgArea.appendChild(div);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function scrollToBottom() { document.getElementById('chat-messages').scrollTop = document.getElementById('chat-messages').scrollHeight; }
|
||||
|
||||
function showTypingIndicator(show) { document.getElementById('chat-typing').hidden = !show; }
|
||||
|
||||
async function sendMessage() {
|
||||
if (chatState.sending) return;
|
||||
const input = document.getElementById('chat-input');
|
||||
const message = input.value.trim();
|
||||
if (!message || !chatState.activeProfile) return;
|
||||
chatState.sending = true;
|
||||
input.disabled = true;
|
||||
document.getElementById('chat-send-btn').disabled = true;
|
||||
document.getElementById('chat-send-btn').textContent = '...';
|
||||
appendMessageBubble({ role: 'user', content: message, created_at: Date.now() / 1000 });
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
showTypingIndicator(true);
|
||||
try {
|
||||
const res = await fetch('/api/agents/' + encodeURIComponent(chatState.activeProfile.profile) + '/send', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
appendMessageBubble({ role: 'agent', content: '⚠️ Error: ' + (data.error || 'HTTP ' + res.status), created_at: Date.now() / 1000 });
|
||||
} else {
|
||||
appendMessageBubble({ role: 'agent', content: data.response, created_at: Date.now() / 1000 });
|
||||
}
|
||||
} catch (err) {
|
||||
appendMessageBubble({ role: 'agent', content: '⚠️ Network error: ' + err.message, created_at: Date.now() / 1000 });
|
||||
} finally {
|
||||
chatState.sending = false;
|
||||
showTypingIndicator(false);
|
||||
input.disabled = false;
|
||||
document.getElementById('chat-send-btn').disabled = false;
|
||||
document.getElementById('chat-send-btn').textContent = 'Send';
|
||||
input.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function updateSendButton() {
|
||||
const input = document.getElementById('chat-input');
|
||||
const btn = document.getElementById('chat-send-btn');
|
||||
btn.disabled = !input.value.trim() || !chatState.activeProfile || chatState.sending;
|
||||
}
|
||||
|
||||
// ── Event Listeners (shared) ───────────────────────────────────────
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Config editor listeners
|
||||
const configSaveBtn = document.getElementById('config-save-btn');
|
||||
const configBackBtn = document.getElementById('config-back-btn');
|
||||
if (configSaveBtn) configSaveBtn.addEventListener('click', saveFile);
|
||||
if (configBackBtn) configBackBtn.addEventListener('click', goBackToList);
|
||||
|
||||
// Chat input
|
||||
const chatInput = document.getElementById('chat-input');
|
||||
const sendBtn = document.getElementById('chat-send-btn');
|
||||
if (chatInput) {
|
||||
chatInput.addEventListener('input', () => {
|
||||
updateSendButton();
|
||||
chatInput.style.height = 'auto';
|
||||
chatInput.style.height = Math.min(chatInput.scrollHeight, 120) + 'px';
|
||||
});
|
||||
chatInput.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
|
||||
});
|
||||
}
|
||||
if (sendBtn) sendBtn.addEventListener('click', sendMessage);
|
||||
});
|
||||
|
||||
// ── Kanban Panel ──────────────────────────────────────────────────
|
||||
let kanbanState = { boards: [], currentSlug: '' };
|
||||
|
||||
async function initKanban() {
|
||||
try {
|
||||
const res = await fetch('/api/kanban/boards');
|
||||
const data = await res.json();
|
||||
kanbanState.boards = data.boards || [];
|
||||
const select = document.getElementById('kanban-board-select');
|
||||
select.innerHTML = '<option value="">Select a board...</option>';
|
||||
data.boards.forEach(b => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = b.slug;
|
||||
opt.textContent = b.name + ' (' + b.task_count + ' tasks)';
|
||||
select.appendChild(opt);
|
||||
});
|
||||
// Restore selection if previously set
|
||||
if (kanbanState.currentSlug) {
|
||||
select.value = kanbanState.currentSlug;
|
||||
loadKanbanBoard();
|
||||
}
|
||||
} catch (err) { console.error('Kanban init failed:', err); }
|
||||
}
|
||||
|
||||
async function loadKanbanBoard() {
|
||||
const select = document.getElementById('kanban-board-select');
|
||||
const slug = select.value;
|
||||
if (!slug) {
|
||||
document.getElementById('kanban-task-list').innerHTML = '<p class="loading-text">Select a board to view tasks...</p>';
|
||||
document.getElementById('ks-done').textContent = '0';
|
||||
document.getElementById('ks-blocked').textContent = '0';
|
||||
document.getElementById('ks-ready').textContent = '0';
|
||||
document.getElementById('ks-todo').textContent = '0';
|
||||
document.getElementById('ks-total').textContent = '0';
|
||||
return;
|
||||
}
|
||||
kanbanState.currentSlug = slug;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/kanban/board/' + encodeURIComponent(slug));
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'HTTP ' + res.status);
|
||||
renderKanbanTasks(data.tasks || []);
|
||||
} catch (err) {
|
||||
document.getElementById('kanban-task-list').innerHTML = '<p class="error-text">' + escapeHtml(err.message) + '</p>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderKanbanTasks(tasks) {
|
||||
const list = document.getElementById('kanban-task-list');
|
||||
if (!tasks || tasks.length === 0) {
|
||||
list.innerHTML = '<p class="empty-text">No tasks in this board.</p>';
|
||||
document.getElementById('ks-done').textContent = '0';
|
||||
document.getElementById('ks-blocked').textContent = '0';
|
||||
document.getElementById('ks-ready').textContent = '0';
|
||||
document.getElementById('ks-todo').textContent = '0';
|
||||
document.getElementById('ks-total').textContent = '0';
|
||||
return;
|
||||
}
|
||||
|
||||
// Summary
|
||||
const counts = { done: 0, blocked: 0, ready: 0, todo: 0, total: tasks.length };
|
||||
tasks.forEach(t => { if (counts[t.status] !== undefined) counts[t.status]++; });
|
||||
document.getElementById('ks-done').textContent = counts.done;
|
||||
document.getElementById('ks-blocked').textContent = counts.blocked;
|
||||
document.getElementById('ks-ready').textContent = counts.ready;
|
||||
document.getElementById('ks-todo').textContent = counts.todo;
|
||||
document.getElementById('ks-total').textContent = counts.total;
|
||||
|
||||
// Task cards
|
||||
const statusIcons = { done: '✅', blocked: '🚫', ready: '🟡', todo: '⬜' };
|
||||
list.innerHTML = '';
|
||||
tasks.forEach(t => {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'kanban-task-card';
|
||||
const icon = statusIcons[t.status] || '⬜';
|
||||
const statusLabel = t.status || 'todo';
|
||||
card.innerHTML = '<div class="kanban-task-status status-' + statusLabel + '">' + icon + '</div>' +
|
||||
'<div class="kanban-task-info">' +
|
||||
'<div class="kanban-task-title">' + escapeHtml(t.title) + '</div>' +
|
||||
'<div class="kanban-task-meta">' +
|
||||
(t.assignee ? '<span>👤 ' + escapeHtml(t.assignee) + '</span>' : '') +
|
||||
'<span class="status-badge status-' + statusLabel + '">' + statusLabel + '</span>' +
|
||||
'</div>' +
|
||||
(t.body ? '<div class="kanban-task-body">' + escapeHtml(t.body) + '</div>' : '') +
|
||||
'</div>';
|
||||
card.title = 'Click to view details (ID: ' + t.id + ')';
|
||||
card.addEventListener('click', () => {
|
||||
// Show task details in a simple way
|
||||
showToast(t.id + ': ' + t.title + ' [' + t.status + ']', 'info');
|
||||
});
|
||||
list.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Services Panel ─────────────────────────────────────────────────
|
||||
async function loadServices() {
|
||||
const tbody = document.getElementById('services-tbody-svc');
|
||||
tbody.innerHTML = '<tr><td colspan="4" class="loading-text">Loading services...</td></tr>';
|
||||
try {
|
||||
const res = await fetch('/api/services');
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || 'HTTP ' + res.status);
|
||||
renderServicesList(data.services || []);
|
||||
} catch (err) {
|
||||
tbody.innerHTML = '<tr><td colspan="4" class="error-text">' + escapeHtml(err.message) + '</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderServicesList(services) {
|
||||
const tbody = document.getElementById('services-tbody-svc');
|
||||
if (!services || services.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="4" class="empty-text">No Hermes services found.</td></tr>';
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = '';
|
||||
services.forEach(s => {
|
||||
const tr = document.createElement('tr');
|
||||
const isActive = s.active === 'active';
|
||||
const badgeClass = 'svc-active-' + s.active;
|
||||
const statusLabel = s.active + '/' + s.sub;
|
||||
tr.innerHTML = '<td class="svc-name">' + escapeHtml(s.name) + '</td>' +
|
||||
'<td><span class="svc-status-badge ' + badgeClass + '">' + escapeHtml(statusLabel) + '</span></td>' +
|
||||
'<td>' + escapeHtml(s.sub || '—') + '</td>' +
|
||||
'<td class="service-actions">' +
|
||||
(!isActive ? '<button class="service-action-btn start" onclick="serviceAction(\'' + escapeHtml(s.name) + "','start'" + ')">▶ Start</button>' : '') +
|
||||
(isActive ? '<button class="service-action-btn restart" onclick="serviceAction(\'' + escapeHtml(s.name) + "','restart'" + ')">↻ Restart</button>' : '') +
|
||||
(isActive ? '<button class="service-action-btn stop" onclick="serviceAction(\'' + escapeHtml(s.name) + "','stop'" + ')">⏹ Stop</button>' : '') +
|
||||
'</td>';
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
}
|
||||
|
||||
async function serviceAction(serviceName, action) {
|
||||
if (!confirm(action + ' ' + serviceName + '?')) return;
|
||||
try {
|
||||
const res = await fetch('/api/services/' + encodeURIComponent(serviceName) + '/action', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { alert('Failed: ' + (data.error || 'HTTP ' + res.status)); return; }
|
||||
showToast(action + ' ' + serviceName + ' — done', 'success');
|
||||
setTimeout(loadServices, 1500);
|
||||
} catch (err) { alert('Error: ' + err.message); }
|
||||
}
|
||||
|
||||
// ── Network Dashboard ────────────────────────────────────────────────
|
||||
let networkState = {
|
||||
autoRefresh: true,
|
||||
refreshInterval: 30000,
|
||||
countdownInterval: null,
|
||||
refreshTimer: null,
|
||||
countdownRemaining: 0,
|
||||
data: null,
|
||||
};
|
||||
|
||||
function initNetworkDashboard() {
|
||||
document.querySelectorAll('.tab-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
|
||||
const tab = document.getElementById('tab-' + btn.dataset.tab);
|
||||
if (tab) tab.classList.add('active');
|
||||
});
|
||||
});
|
||||
document.getElementById('network-refresh-btn').addEventListener('click', forceRefresh);
|
||||
document.getElementById('auto-refresh-toggle').addEventListener('click', () => {
|
||||
networkState.autoRefresh = document.getElementById('auto-refresh-toggle').checked;
|
||||
if (networkState.autoRefresh) startAutoRefresh(); else stopAutoRefresh();
|
||||
});
|
||||
fetchNetworkData();
|
||||
}
|
||||
|
||||
async function fetchNetworkData() {
|
||||
try {
|
||||
const res = await fetch('/api/network/refresh');
|
||||
if (!res.ok) throw new Error('HTTP ' + res.status);
|
||||
const data = await res.json();
|
||||
networkState.data = data;
|
||||
renderNetwork(data);
|
||||
updateFooter(data);
|
||||
if (networkState.autoRefresh) startAutoRefresh();
|
||||
} catch (err) { showNetworkError('Failed: ' + err.message); }
|
||||
}
|
||||
|
||||
function forceRefresh() {
|
||||
networkState.data = null;
|
||||
if (networkState.refreshTimer) { clearTimeout(networkState.refreshTimer); networkState.refreshTimer = null; }
|
||||
if (networkState.countdownInterval) { clearInterval(networkState.countdownInterval); networkState.countdownInterval = null; }
|
||||
document.getElementById('hosts-grid').innerHTML = '<div class="loading-text">Refreshing...</div>';
|
||||
document.getElementById('services-tbody').innerHTML = '<tr><td colspan="5" class="loading-text">Refreshing...</td></tr>';
|
||||
document.getElementById('local-services-tbody').innerHTML = '<tr><td colspan="3" class="loading-text">Refreshing...</td></tr>';
|
||||
fetchNetworkData();
|
||||
}
|
||||
|
||||
function startAutoRefresh() {
|
||||
stopAutoRefresh();
|
||||
networkState.countdownRemaining = 30;
|
||||
updateCountdownBar();
|
||||
networkState.countdownInterval = setInterval(() => {
|
||||
networkState.countdownRemaining--;
|
||||
if (networkState.countdownRemaining <= 0) { networkState.countdownRemaining = 30; fetchNetworkData(); }
|
||||
updateCountdownBar();
|
||||
}, 1000);
|
||||
networkState.refreshTimer = setTimeout(() => { fetchNetworkData(); }, networkState.refreshInterval + 1000);
|
||||
}
|
||||
|
||||
function stopAutoRefresh() {
|
||||
if (networkState.countdownInterval) { clearInterval(networkState.countdownInterval); networkState.countdownInterval = null; }
|
||||
if (networkState.refreshTimer) { clearTimeout(networkState.refreshTimer); networkState.refreshTimer = null; }
|
||||
document.getElementById('countdown-fill').style.width = '0%';
|
||||
}
|
||||
|
||||
function updateCountdownBar() {
|
||||
const pct = (networkState.countdownRemaining / 30) * 100;
|
||||
document.getElementById('countdown-fill').style.width = pct + '%';
|
||||
}
|
||||
|
||||
function renderNetwork(data) {
|
||||
renderHosts(data.hosts || []);
|
||||
renderServices(data.services || []);
|
||||
renderLocalServices(data.local_services || []);
|
||||
renderSummary(data.hosts || []);
|
||||
}
|
||||
|
||||
function renderSummary(hosts) {
|
||||
let online = 0, offline = 0, degraded = 0;
|
||||
hosts.forEach(h => {
|
||||
if (h.status === 'online') online++;
|
||||
else if (h.status === 'offline') offline++;
|
||||
else if (h.status === 'degraded') degraded++;
|
||||
else offline++;
|
||||
});
|
||||
document.getElementById('hosts-online').textContent = online;
|
||||
document.getElementById('hosts-offline').textContent = offline;
|
||||
document.getElementById('hosts-degraded').textContent = degraded;
|
||||
document.getElementById('hosts-total').textContent = hosts.length;
|
||||
}
|
||||
|
||||
function renderHosts(hosts) {
|
||||
const grid = document.getElementById('hosts-grid');
|
||||
if (!hosts || hosts.length === 0) { grid.innerHTML = '<div class="empty-text">No hosts configured.</div>'; return; }
|
||||
grid.innerHTML = '';
|
||||
hosts.forEach(host => {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'host-card status-' + (host.status || 'unknown');
|
||||
card.dataset.host = host.name;
|
||||
const statusLabel = host.status === 'online' ? 'Online' : host.status === 'offline' ? 'Offline' : host.status === 'degraded' ? 'Degraded' : 'Unknown';
|
||||
let latencyDisplay = host.latency_ms != null ? host.latency_ms.toFixed(1) + 'ms' : '—';
|
||||
let osDisplay = host.os || '';
|
||||
card.innerHTML = '<div class="host-card-header"><div class="host-name-row"><span class="host-name">' + escapeHtml(host.name) + '</span><span class="status-badge status-' + (host.status || 'unknown') + '">' + statusLabel + '</span></div><div class="host-meta"><span class="host-ip">' + escapeHtml(host.ip || '—') + '</span>' + (osDisplay ? '<span class="host-os">' + escapeHtml(osDisplay) + '</span>' : '') + '<span class="host-latency">' + latencyDisplay + '</span></div></div>' +
|
||||
'<div class="host-card-body">' + (host.role ? '<div class="host-role">' + escapeHtml(host.role) + '</div>' : '') + (host.ports && host.ports.length > 0 ? renderPorts(host.ports) : '') +
|
||||
'<button class="btn btn-sm host-expand-btn" data-host="' + escapeHtml(host.name) + '">Details</button></div>' +
|
||||
'<div class="host-details hidden" id="host-details-' + escapeHtml(host.name).replace(/\s/g, '_') + '"><div class="host-details-content">' + renderHostDetails(host) + '</div></div>';
|
||||
const expandBtn = card.querySelector('.host-expand-btn');
|
||||
expandBtn.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const detailsId = 'host-details-' + escapeHtml(host.name).replace(/\s/g, '_');
|
||||
const details = document.getElementById(detailsId);
|
||||
if (details) { details.classList.toggle('hidden'); expandBtn.textContent = details.classList.contains('hidden') ? 'Details' : 'Hide'; }
|
||||
});
|
||||
grid.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
function renderPorts(ports) {
|
||||
if (!ports || ports.length === 0) return '';
|
||||
let html = '<div class="host-ports"><span class="ports-label">Ports:</span>';
|
||||
ports.forEach(p => { html += '<span class="port-badge ' + (p.open ? 'port-open' : 'port-closed') + '" title="' + escapeHtml(p.name) + ':' + p.port + '">' + escapeHtml(p.name) + ':' + p.port + '</span>'; });
|
||||
html += '</div>';
|
||||
return html;
|
||||
}
|
||||
|
||||
function renderHostDetails(host) {
|
||||
let html = '<table class="details-table">';
|
||||
const fields = [
|
||||
['Hostname', host.hostname], ['OS', host.os], ['Role', host.role],
|
||||
['Local IP', host.local_ip], ['Tailscale IP', host.tailscale_ip],
|
||||
['Public IP', host.public_ip], ['Status', host.status],
|
||||
['Latency', host.latency_ms != null ? host.latency_ms.toFixed(1) + 'ms' : '—']
|
||||
];
|
||||
fields.forEach(([label, val]) => { if (val) html += '<tr><td class="dt-label">' + escapeHtml(label) + '</td><td class="dt-value">' + escapeHtml(String(val)) + '</td></tr>'; });
|
||||
if (host.ports && host.ports.length > 0) {
|
||||
html += '<tr><td class="dt-label">Ports</td><td class="dt-value">';
|
||||
host.ports.forEach(p => { html += '<span class="port-badge ' + (p.open ? 'port-open' : 'port-closed') + '">' + (p.open ? '✓' : '✗') + ' ' + escapeHtml(p.name) + ':' + p.port + '</span> '; });
|
||||
html += '</td></tr>';
|
||||
}
|
||||
html += '</table>';
|
||||
return html;
|
||||
}
|
||||
|
||||
function renderServices(services) {
|
||||
const tbody = document.getElementById('services-tbody');
|
||||
if (!services || services.length === 0) { tbody.innerHTML = '<tr><td colspan="5" class="empty-text">No services configured.</td></tr>'; return; }
|
||||
tbody.innerHTML = '';
|
||||
services.forEach(svc => {
|
||||
const tr = document.createElement('tr');
|
||||
const status = svc.status || 'unknown';
|
||||
const statusLabel = status === 'online' ? 'Online' : status === 'offline' ? 'Offline' : 'Unknown';
|
||||
const latency = svc.latency_ms != null ? svc.latency_ms.toFixed(1) + 'ms' : '—';
|
||||
const url = svc.url || (svc.port ? ':' + svc.port : '—');
|
||||
const category = svc.category || '—';
|
||||
tr.innerHTML = '<td class="svc-name">' + escapeHtml(svc.name || '—') + '</td><td><span class="svc-category">' + escapeHtml(category) + '</span></td><td class="svc-url">' + escapeHtml(url) + '</td><td><span class="status-badge status-' + status + '">' + statusLabel + '</span></td><td class="svc-latency">' + latency + '</td>';
|
||||
if (svc.error) tr.innerHTML += '<td class="svc-error" colspan="5"><small>' + escapeHtml(svc.error) + '</small></td>';
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
}
|
||||
|
||||
function renderLocalServices(services) {
|
||||
const tbody = document.getElementById('local-services-tbody');
|
||||
if (!services || services.length === 0) { tbody.innerHTML = '<tr><td colspan="3" class="empty-text">No local services detected.</td></tr>'; return; }
|
||||
tbody.innerHTML = '';
|
||||
services.forEach(svc => {
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = '<td>' + escapeHtml(svc.local_address || '—') + '</td><td>' + escapeHtml(svc.port || '—') + '</td><td>' + escapeHtml(svc.process || '—') + '</td>';
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
}
|
||||
|
||||
function updateFooter(data) {
|
||||
const cached = data.cached_at ? new Date(data.cached_at * 1000) : null;
|
||||
document.getElementById('last-updated').textContent = cached ? 'Last updated: ' + cached.toLocaleTimeString() : 'Last updated: —';
|
||||
document.getElementById('cache-info').textContent = data.cache_ttl ? 'Cache: ' + data.cache_ttl + 's' : '';
|
||||
}
|
||||
|
||||
function showNetworkError(msg) {
|
||||
document.getElementById('hosts-grid').innerHTML = '<div class="error-text">' + escapeHtml(msg) + '</div>';
|
||||
document.getElementById('services-tbody').innerHTML = '<tr><td colspan="5" class="error-text">' + escapeHtml(msg) + '</td></tr>';
|
||||
document.getElementById('local-services-tbody').innerHTML = '<tr><td colspan="3" class="error-text">' + escapeHtml(msg) + '</td></tr>';
|
||||
}
|
||||
|
||||
+269
-18
@@ -2,40 +2,291 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<meta name="theme-color" content="#0d1117">
|
||||
<title>Hermes Command Center</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<link rel="stylesheet" href="/static/style.css?v=16">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<nav class="sidebar">
|
||||
<!-- Desktop Sidebar -->
|
||||
<nav class="sidebar" id="sidebar">
|
||||
<div class="logo">🎛️ Command Center</div>
|
||||
<ul class="nav-links">
|
||||
<li><a href="#agents" class="active">💬 Agents</a></li>
|
||||
<li><a href="#dashboard" class="active">📊 Dashboard</a></li>
|
||||
<li><a href="#agents">💬 Chat</a></li>
|
||||
<li><a href="#config">⚙️ Config</a></li>
|
||||
<li><a href="#kanban">📋 Kanban</a></li>
|
||||
<li><a href="#vault">📚 Vault</a></li>
|
||||
<li><a href="#services">🔧 Services</a></li>
|
||||
<li><a href="#network">🌐 Network</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<main class="content">
|
||||
<section id="agents" class="panel">
|
||||
<h2>Agent Chat</h2>
|
||||
<p>Coming soon...</p>
|
||||
|
||||
<!-- Mobile Bottom Nav -->
|
||||
<nav class="bottom-nav" id="bottom-nav">
|
||||
<a href="#dashboard" class="nav-item active" data-tab="dashboard">📊<span>Home</span></a>
|
||||
<a href="#agents" class="nav-item" data-tab="agents">💬<span>Chat</span></a>
|
||||
<a href="#config" class="nav-item" data-tab="config">⚙️<span>Config</span></a>
|
||||
<a href="#kanban" class="nav-item" data-tab="kanban">📋<span>Tasks</span></a>
|
||||
<a href="#vault" class="nav-item" data-tab="vault">📚<span>Vault</span></a>
|
||||
<a href="#network" class="nav-item" data-tab="network">🌐<span>Net</span></a>
|
||||
</nav>
|
||||
|
||||
<main class="content" id="content">
|
||||
|
||||
<!-- ════════════ Dashboard Panel ════════════ -->
|
||||
<section id="dashboard" class="panel">
|
||||
<h2 class="panel-title">📊 Dashboard</h2>
|
||||
<div class="dash-grid" id="dash-grid">
|
||||
<div class="dash-card" id="dash-agents">
|
||||
<div class="dash-card-icon">💬</div>
|
||||
<div class="dash-card-body">
|
||||
<div class="dash-card-value" id="dash-agents-val">—</div>
|
||||
<div class="dash-card-label">Agents Online</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dash-card" id="dash-hosts">
|
||||
<div class="dash-card-icon">🖥️</div>
|
||||
<div class="dash-card-body">
|
||||
<div class="dash-card-value" id="dash-hosts-val">—</div>
|
||||
<div class="dash-card-label">Hosts</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dash-card" id="dash-files">
|
||||
<div class="dash-card-icon">⚙️</div>
|
||||
<div class="dash-card-body">
|
||||
<div class="dash-card-value" id="dash-files-val">—</div>
|
||||
<div class="dash-card-label">Config Files</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dash-card" id="dash-msgs">
|
||||
<div class="dash-card-icon">💭</div>
|
||||
<div class="dash-card-body">
|
||||
<div class="dash-card-value" id="dash-msgs-val">—</div>
|
||||
<div class="dash-card-label">Chat Messages</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dash-card" id="dash-tasks">
|
||||
<div class="dash-card-icon">✅</div>
|
||||
<div class="dash-card-body">
|
||||
<div class="dash-card-value" id="dash-tasks-val">—</div>
|
||||
<div class="dash-card-label">Tasks Done</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dash-card" id="dash-boards">
|
||||
<div class="dash-card-icon">📋</div>
|
||||
<div class="dash-card-body">
|
||||
<div class="dash-card-value" id="dash-boards-val">—</div>
|
||||
<div class="dash-card-label">Kanban Boards</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dash-section">
|
||||
<h3>Quick Actions</h3>
|
||||
<div class="dash-actions">
|
||||
<button class="btn btn-sm" onclick="window.location.hash='#agents'">💬 Open Chat</button>
|
||||
<button class="btn btn-sm" onclick="window.location.hash='#kanban'">📋 View Tasks</button>
|
||||
<button class="btn btn-sm" onclick="window.location.hash='#network'">🌐 Check Network</button>
|
||||
<button class="btn btn-sm" onclick="refreshDashboard()">🔄 Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="config" class="panel" hidden>
|
||||
<h2>Config Editor</h2>
|
||||
<p>Coming soon...</p>
|
||||
|
||||
<!-- ════════════ Agent Chat Panel ════════════ -->
|
||||
<section id="agents" class="panel" hidden>
|
||||
<div id="chat-app">
|
||||
<div class="chat-header">
|
||||
<div class="chat-profile-strip">
|
||||
<span class="chat-profiles-label">Agent:</span>
|
||||
<div id="chat-profile-tabs" class="chat-profile-tabs"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="chat-messages" class="chat-messages">
|
||||
<div class="chat-welcome">
|
||||
<div class="chat-welcome-icon">💬</div>
|
||||
<h3>Agent Chat</h3>
|
||||
<p>Select an agent profile above and type a message to start a conversation.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div id="chat-typing" class="chat-typing" hidden>
|
||||
<span class="typing-dot"></span>
|
||||
<span class="typing-dot"></span>
|
||||
<span class="typing-dot"></span>
|
||||
<span class="typing-label">Agent is typing...</span>
|
||||
</div>
|
||||
<div class="chat-input-area">
|
||||
<textarea id="chat-input" rows="1" placeholder="Type a message..." maxlength="2000"></textarea>
|
||||
<button id="chat-send-btn" class="btn btn-primary" disabled>Send</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ════════════ Config Editor Panel ════════════ -->
|
||||
<section id="config" class="panel config-panel" hidden>
|
||||
<div class="config-file-list" id="config-file-list">
|
||||
<div class="config-header">
|
||||
<h2 class="panel-title">⚙️ Config Editor</h2>
|
||||
<span class="config-count" id="config-count">0 files</span>
|
||||
</div>
|
||||
<div class="config-files-container" id="config-files-container">
|
||||
<p class="loading-text">Select a panel to open...</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-editor" id="config-editor" hidden>
|
||||
<div class="editor-header">
|
||||
<button id="config-back-btn" class="btn btn-sm" title="Back to file list">← Back</button>
|
||||
<span class="editor-filename" id="editor-filename"></span>
|
||||
<div class="editor-actions">
|
||||
<button id="config-save-btn" class="btn btn-primary btn-sm" disabled>Saved ✓</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor-body">
|
||||
<div class="editor-line-numbers" id="editor-line-numbers"></div>
|
||||
<textarea class="editor-textarea" id="config-editor-textarea"
|
||||
spellcheck="false" wrap="off" disabled
|
||||
placeholder="Select a file to edit..."></textarea>
|
||||
</div>
|
||||
<div class="editor-status-bar">
|
||||
<span id="status-path"></span>
|
||||
<span id="status-meta"></span>
|
||||
<span id="status-saved" class="status-saved"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="config-toast" class="config-toast" hidden></div>
|
||||
</section>
|
||||
|
||||
<!-- ════════════ Kanban Panel ════════════ -->
|
||||
<section id="kanban" class="panel" hidden>
|
||||
<div class="kanban-header">
|
||||
<h2 class="panel-title">📋 Kanban Boards</h2>
|
||||
<div class="kanban-controls">
|
||||
<select id="kanban-board-select" class="kanban-select" onchange="loadKanbanBoard()">
|
||||
<option value="">Select a board...</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div id="kanban-summary" class="kanban-summary">
|
||||
<div class="kanban-summary-item"><span class="ks-num" id="ks-done">0</span> Done</div>
|
||||
<div class="kanban-summary-item"><span class="ks-num" id="ks-blocked">0</span> Blocked</div>
|
||||
<div class="kanban-summary-item"><span class="ks-num" id="ks-ready">0</span> Ready</div>
|
||||
<div class="kanban-summary-item"><span class="ks-num" id="ks-todo">0</span> Todo</div>
|
||||
<div class="kanban-summary-item"><span class="ks-num" id="ks-total">0</span> Total</div>
|
||||
</div>
|
||||
<div id="kanban-task-list" class="kanban-task-list">
|
||||
<p class="loading-text">Select a board to view tasks...</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ════════════ Vault Reader Panel ════════════ -->
|
||||
<section id="vault" class="panel" hidden>
|
||||
<h2>Obsidian Vault</h2>
|
||||
<p>Coming soon...</p>
|
||||
<div id="vault-app">
|
||||
<div class="vault-toolbar">
|
||||
<button id="vault-toggle-tree" class="vault-btn" title="Toggle file tree">📂</button>
|
||||
<div class="vault-search-box">
|
||||
<input type="text" id="vault-search-input" placeholder="Search vault..." />
|
||||
<div id="vault-search-results" class="vault-search-dropdown" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="vault-body">
|
||||
<div id="vault-tree" class="vault-tree-panel"></div>
|
||||
<div id="vault-content" class="vault-content-panel">
|
||||
<div class="vault-welcome">
|
||||
<h2>Obsidian Vault</h2>
|
||||
<p>Select a file from the tree or search to get started.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="network" class="panel" hidden>
|
||||
<h2>Network Status</h2>
|
||||
<p>Coming soon...</p>
|
||||
|
||||
<!-- ════════════ Services Panel ════════════ -->
|
||||
<section id="services" class="panel" hidden>
|
||||
<div class="services-panel-header">
|
||||
<h2 class="panel-title">🔧 System Services</h2>
|
||||
<button class="btn btn-sm" onclick="loadServices()">🔄 Refresh</button>
|
||||
</div>
|
||||
<div class="services-table-wrap">
|
||||
<table class="services-table" id="services-table-svc">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Service</th>
|
||||
<th>Status</th>
|
||||
<th>Sub</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="services-tbody-svc">
|
||||
<tr><td colspan="4" class="loading-text">Loading services...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ════════════ Network Dashboard Panel ════════════ -->
|
||||
<section id="network" class="panel network-panel" hidden>
|
||||
<div class="network-header">
|
||||
<h2>🌐 Network Status</h2>
|
||||
<div class="network-controls">
|
||||
<div class="countdown-bar" id="countdown-bar">
|
||||
<div class="countdown-fill" id="countdown-fill"></div>
|
||||
</div>
|
||||
<button class="btn btn-sm btn-refresh" id="network-refresh-btn" title="Refresh now">⟳</button>
|
||||
<label class="auto-refresh-toggle" title="Toggle auto-refresh">
|
||||
<input type="checkbox" id="auto-refresh-toggle" checked>
|
||||
<span>Auto</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="network-summary" id="network-summary">
|
||||
<div class="summary-item online"><span class="summary-count" id="hosts-online">0</span> Online</div>
|
||||
<div class="summary-item degraded"><span class="summary-count" id="hosts-degraded">0</span> Degraded</div>
|
||||
<div class="summary-item offline"><span class="summary-count" id="hosts-offline">0</span> Offline</div>
|
||||
<div class="summary-item total"><span class="summary-count" id="hosts-total">0</span> Total</div>
|
||||
</div>
|
||||
<div class="network-tabs">
|
||||
<button class="tab-btn active" data-tab="hosts">Hosts</button>
|
||||
<button class="tab-btn" data-tab="services">Services</button>
|
||||
<button class="tab-btn" data-tab="local">Local</button>
|
||||
</div>
|
||||
<div class="tab-content active" id="tab-hosts">
|
||||
<div class="hosts-grid" id="hosts-grid">
|
||||
<div class="loading-text">Loading hosts...</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-content" id="tab-services">
|
||||
<div class="services-table-wrap">
|
||||
<table class="services-table" id="services-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Service</th><th>Category</th><th>URL / Port</th><th>Status</th><th>Latency</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="services-tbody">
|
||||
<tr><td colspan="5" class="loading-text">Loading services...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-content" id="tab-local">
|
||||
<div class="services-table-wrap">
|
||||
<table class="services-table" id="local-services-table">
|
||||
<thead><tr><th>Address</th><th>Port</th><th>Process</th></tr></thead>
|
||||
<tbody id="local-services-tbody">
|
||||
<tr><td colspan="3" class="loading-text">Loading local services...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="network-footer">
|
||||
<span class="last-updated" id="last-updated">Last updated: —</span>
|
||||
<span class="cache-info" id="cache-info"></span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</main>
|
||||
</div>
|
||||
<script src="/static/app.js"></script>
|
||||
<script src="/static/app.js?v=3"></script>
|
||||
<script src="/static/vault.js?v=2"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1491
File diff suppressed because it is too large
Load Diff
+428
@@ -0,0 +1,428 @@
|
||||
/* ── Obsidian Vault Reader ─────────────────────────────────────────────
|
||||
* File tree navigation, markdown rendering, wiki-links, search.
|
||||
* Relies on server.py's /api/vault/* endpoints.
|
||||
*/
|
||||
|
||||
const VAULT_API = '/api/vault';
|
||||
|
||||
// ── Markdown Renderer ────────────────────────────────────────────────
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.appendChild(document.createTextNode(text));
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function renderMarkdown(md) {
|
||||
// Normalise line endings
|
||||
let text = md.replace(/\r\n?/g, '\n');
|
||||
|
||||
// Extract code blocks first so they're not mangled by inline rules
|
||||
const blocks = [];
|
||||
text = text.replace(/```(\w*)\n?([\s\S]*?)```/g, (_, lang, code) => {
|
||||
const idx = blocks.length;
|
||||
blocks.push(`<pre><code class="lang-${escapeHtml(lang || '')}">${escapeHtml(code.trimEnd())}</code></pre>`);
|
||||
return `\x00CODEBLOCK${idx}\x00`;
|
||||
});
|
||||
|
||||
// Inline code
|
||||
text = text.replace(/`([^`]+)`/g, '<code>$1</code>');
|
||||
|
||||
// Wiki-links [[Page Name]] → clickable links
|
||||
text = text.replace(/\[\[([^\]]+)\]\]/g, (_, page) => {
|
||||
const label = page.includes('|') ? page.split('|')[1] : page;
|
||||
const target = page.split('|')[0];
|
||||
const href = '#' + target.replace(/\s+/g, '-').toLowerCase();
|
||||
return `<a href="#" class="wiki-link" data-wiki-link="${escapeHtml(target)}">${escapeHtml(label)}</a>`;
|
||||
});
|
||||
|
||||
// Images 
|
||||
text = text.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" loading="lazy">');
|
||||
|
||||
// Links [text](url)
|
||||
text = text.replace(/(?<!!)\[([^\]]*)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
|
||||
|
||||
// Bold/italic: ***bold italic***, **bold**, *italic*
|
||||
text = text.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
|
||||
text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
||||
text = text.replace(/(?<!\*)\*([^*\n]+)\*(?!\*)/g, '<em>$1</em>');
|
||||
|
||||
// Strikethrough
|
||||
text = text.replace(/~~(.+?)~~/g, '<del>$1</del>');
|
||||
|
||||
// Blockquotes
|
||||
text = text.replace(/^>(.*)$/gm, '<blockquote>$1</blockquote>');
|
||||
text = text.replace(/^>(.*)$/gm, '<blockquote>$1</blockquote>');
|
||||
|
||||
// Horizontal rules
|
||||
text = text.replace(/^(---|\*\*\*|___)\s*$/gm, '<hr>');
|
||||
|
||||
// Headings (must be at start of line)
|
||||
text = text.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>');
|
||||
text = text.replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>');
|
||||
text = text.replace(/^####\s+(.+)$/gm, '<h4>$1</h4>');
|
||||
text = text.replace(/^###\s+(.+)$/gm, '<h3>$1</h3>');
|
||||
text = text.replace(/^##\s+(.+)$/gm, '<h2>$1</h2>');
|
||||
text = text.replace(/^#\s+(.+)$/gm, function (_, title) {
|
||||
const id = title.replace(/\s+/g, '-').replace(/[^\w-]/g, '').toLowerCase();
|
||||
return `<h1 id="${id}">${title}</h1>`;
|
||||
});
|
||||
|
||||
// Ordered lists
|
||||
text = text.replace(/^(?:\d+\.\s.*(?:\n|$))+/gm, function (match) {
|
||||
const items = match.trim().split('\n').map(l => l.replace(/^\d+\.\s+/, '').trim());
|
||||
return '<ol>' + items.map(i => `<li>${i}</li>`).join('') + '</ol>\n';
|
||||
});
|
||||
|
||||
// Unordered lists
|
||||
text = text.replace(/^(?:[-*+]\s.*(?:\n|$))+/gm, function (match) {
|
||||
const items = match.trim().split('\n').map(l => l.replace(/^[-*+]\s+/, '').trim());
|
||||
return '<ul>' + items.map(i => `<li>${i}</li>`).join('') + '</ul>\n';
|
||||
});
|
||||
|
||||
// Tables (pipe tables: header | separator | rows)
|
||||
text = text.replace(/^(\|.+\|)\n\|[-| :]+\|\n((?:\|.+\|\n?)*)/gm, function (_, header, rows) {
|
||||
const headers = header.split('|').map(c => c.trim()).filter(Boolean);
|
||||
const rowLines = rows.trim().split('\n').filter(l => l.trim());
|
||||
const body = rowLines.map(r => {
|
||||
const cells = r.split('|').map(c => c.trim()).filter(Boolean);
|
||||
return '<tr>' + cells.map(c => `<td>${c}</td>`).join('') + '</tr>';
|
||||
}).join('');
|
||||
return '<table><thead><tr>' + headers.map(h => `<th>${h}</th>`).join('') + '</tr></thead><tbody>' + body + '</tbody></table>\n';
|
||||
});
|
||||
|
||||
// Restore code blocks
|
||||
text = text.replace(/\x00CODEBLOCK(\d+)\x00/g, (_, idx) => blocks[parseInt(idx)]);
|
||||
|
||||
// Double line breaks → paragraph breaks (but not inside block elements)
|
||||
// Simple approach: wrap consecutive text lines in <p> tags
|
||||
// Skip elements that are already block-level
|
||||
const blockTags = ['<h1', '<h2', '<h3', '<h4', '<h5', '<h6', '<pre', '<ul', '<ol', '<blockquote', '<hr', '<table', '<div'];
|
||||
const lines = text.split('\n');
|
||||
let html = '';
|
||||
let paraLines = [];
|
||||
|
||||
function flushPara() {
|
||||
if (paraLines.length) {
|
||||
const pText = paraLines.join('<br>');
|
||||
if (pText.trim()) {
|
||||
html += '<p>' + pText.trim() + '</p>\n';
|
||||
}
|
||||
paraLines = [];
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i].trim();
|
||||
if (!line) {
|
||||
flushPara();
|
||||
continue;
|
||||
}
|
||||
const isBlock = blockTags.some(tag => line.startsWith(tag));
|
||||
if (isBlock) {
|
||||
flushPara();
|
||||
html += line + '\n';
|
||||
} else {
|
||||
paraLines.push(line);
|
||||
}
|
||||
}
|
||||
flushPara();
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
// ── Vault API helpers ─────────────────────────────────────────────────
|
||||
async function apiFetch(url) {
|
||||
const resp = await fetch(url);
|
||||
if (!resp.ok) {
|
||||
let msg = `HTTP ${resp.status}`;
|
||||
try {
|
||||
const body = await resp.json();
|
||||
if (body.error) msg = body.error;
|
||||
} catch (_) {}
|
||||
throw new Error(msg);
|
||||
}
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
// ── Tree Node Cache ───────────────────────────────────────────────────
|
||||
// We cache directory contents so expanding/collapsing folders doesn't re-fetch.
|
||||
const treeCache = new Map();
|
||||
|
||||
async function getTree(dirPath) {
|
||||
const key = dirPath || '';
|
||||
if (treeCache.has(key)) return treeCache.get(key);
|
||||
const params = dirPath ? `?path=${encodeURIComponent(dirPath)}` : '';
|
||||
const data = await apiFetch(`${VAULT_API}/tree${params}`);
|
||||
treeCache.set(key, data);
|
||||
return data;
|
||||
}
|
||||
|
||||
function invalidateTreeCache(path) {
|
||||
// If we update a path, clear its parent cache too
|
||||
const parts = path.split('/');
|
||||
while (parts.length) {
|
||||
treeCache.delete(parts.join('/'));
|
||||
parts.pop();
|
||||
}
|
||||
treeCache.delete(''); // root
|
||||
}
|
||||
|
||||
// ── Tree Panel ────────────────────────────────────────────────────────
|
||||
let treeLoadStack = []; // tracks which nodes are expanded
|
||||
|
||||
function renderTree(dirPath, container, level) {
|
||||
level = level || 0;
|
||||
const padding = level * 18;
|
||||
|
||||
getTree(dirPath).then(data => {
|
||||
const items = data.items || [];
|
||||
for (const item of items) {
|
||||
const node = document.createElement('div');
|
||||
node.className = 'vault-tree-node';
|
||||
node.style.paddingLeft = (padding + 4) + 'px';
|
||||
|
||||
if (item.type === 'folder') {
|
||||
const isExpanded = treeLoadStack.includes(dirPath + '/' + item.name);
|
||||
const icon = isExpanded ? '▼' : '▶';
|
||||
node.innerHTML = `<span class="tree-folder-icon">${icon}</span> <span class="tree-folder-name">${escapeHtml(item.name)}</span>`;
|
||||
node.className += ' vault-tree-folder';
|
||||
node._path = dirPath ? dirPath + '/' + item.name : item.name;
|
||||
node._expanded = isExpanded;
|
||||
|
||||
if (isExpanded) {
|
||||
const childContainer = document.createElement('div');
|
||||
childContainer.className = 'vault-tree-children';
|
||||
node.appendChild(childContainer);
|
||||
renderTree(node._path, childContainer, level + 1);
|
||||
}
|
||||
|
||||
node.addEventListener('click', e => {
|
||||
e.stopPropagation();
|
||||
toggleFolder(node);
|
||||
});
|
||||
} else if (item.name.endsWith('.md') || item.name.endsWith('.txt') || item.name.endsWith('.markdown')) {
|
||||
node.innerHTML = `<span class="tree-file-icon">📄</span> <span class="tree-file-name">${escapeHtml(item.name)}</span>`;
|
||||
node.className += ' vault-tree-file';
|
||||
node._path = dirPath ? dirPath + '/' + item.name : item.name;
|
||||
node.addEventListener('click', e => {
|
||||
e.stopPropagation();
|
||||
loadFile(node._path);
|
||||
});
|
||||
} else {
|
||||
node.innerHTML = `<span class="tree-file-icon">📄</span> <span class="tree-file-name tree-muted">${escapeHtml(item.name)}</span>`;
|
||||
node.className += ' vault-tree-file vault-tree-other';
|
||||
}
|
||||
container.appendChild(node);
|
||||
}
|
||||
}).catch(err => {
|
||||
const errNode = document.createElement('div');
|
||||
errNode.className = 'vault-tree-error';
|
||||
errNode.textContent = '⚠️ ' + err.message;
|
||||
container.appendChild(errNode);
|
||||
});
|
||||
}
|
||||
|
||||
function toggleFolder(node) {
|
||||
const children = node.querySelector('.vault-tree-children');
|
||||
const icon = node.querySelector('.tree-folder-icon');
|
||||
if (children) {
|
||||
// Collapse
|
||||
node.removeChild(children);
|
||||
icon.textContent = '▶';
|
||||
node._expanded = false;
|
||||
const idx = treeLoadStack.indexOf(node._path);
|
||||
if (idx > -1) treeLoadStack.splice(idx, 1);
|
||||
} else {
|
||||
// Expand
|
||||
icon.textContent = '▼';
|
||||
node._expanded = true;
|
||||
treeLoadStack.push(node._path);
|
||||
const childContainer = document.createElement('div');
|
||||
childContainer.className = 'vault-tree-children';
|
||||
node.appendChild(childContainer);
|
||||
renderTree(node._path, childContainer, parseInt(node.style.paddingLeft) / 18 + 1);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTree(rootPath) {
|
||||
const container = document.getElementById('vault-tree');
|
||||
container.innerHTML = ''; // clear
|
||||
treeLoadStack = [];
|
||||
renderTree(rootPath, container, 0);
|
||||
}
|
||||
|
||||
// ── Content Panel ─────────────────────────────────────────────────────
|
||||
async function loadFile(filePath) {
|
||||
const panel = document.getElementById('vault-content');
|
||||
panel.innerHTML = '<div class="vault-loading">Loading...</div>';
|
||||
|
||||
try {
|
||||
const data = await apiFetch(`${VAULT_API}/read?path=${encodeURIComponent(filePath)}`);
|
||||
const html = renderMarkdown(data.content);
|
||||
|
||||
panel.innerHTML = `
|
||||
<div class="vault-file-header">
|
||||
<span class="vault-file-path">${escapeHtml(data.path)}</span>
|
||||
</div>
|
||||
<div class="vault-markdown-body">${html}</div>
|
||||
`;
|
||||
|
||||
// Wire up wiki-link clicks
|
||||
panel.querySelectorAll('.wiki-link').forEach(link => {
|
||||
link.addEventListener('click', e => {
|
||||
e.preventDefault();
|
||||
const target = link.dataset.wikiLink;
|
||||
navigateToWikiPage(target);
|
||||
});
|
||||
});
|
||||
|
||||
// Highlight current file in tree
|
||||
document.querySelectorAll('.vault-tree-file.active').forEach(el => el.classList.remove('active'));
|
||||
document.querySelectorAll('.vault-tree-file').forEach(el => {
|
||||
if (el._path === filePath) {
|
||||
el.classList.add('active');
|
||||
el.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
}
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
panel.innerHTML = `<div class="vault-error"><strong>Error:</strong> ${escapeHtml(err.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function navigateToWikiPage(pageName) {
|
||||
// Look for a file named after the wiki link
|
||||
const encoded = encodeURIComponent(pageName);
|
||||
// Try exact filename first, then search
|
||||
const possiblePaths = [
|
||||
pageName + '.md',
|
||||
'wiki/' + pageName + '.md',
|
||||
pageName + '/' + pageName + '.md',
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
try {
|
||||
await apiFetch(`${VAULT_API}/read?path=${encodeURIComponent(p)}`);
|
||||
loadFile(p);
|
||||
return;
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// Fallback: search for it
|
||||
const data = await apiFetch(`${VAULT_API}/search?q=${encodeURIComponent(pageName)}`);
|
||||
if (data.results && data.results.length > 0) {
|
||||
loadFile(data.results[0].path);
|
||||
} else {
|
||||
const panel = document.getElementById('vault-content');
|
||||
panel.innerHTML = `<div class="vault-error"><strong>Page not found:</strong> ${escapeHtml(pageName)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Search ────────────────────────────────────────────────────────────
|
||||
let searchTimeout = null;
|
||||
|
||||
function setupSearch() {
|
||||
const input = document.getElementById('vault-search-input');
|
||||
const results = document.getElementById('vault-search-results');
|
||||
|
||||
input.addEventListener('input', () => {
|
||||
clearTimeout(searchTimeout);
|
||||
const q = input.value.trim();
|
||||
if (q.length < 2) {
|
||||
results.hidden = true;
|
||||
return;
|
||||
}
|
||||
searchTimeout = setTimeout(() => performSearch(q), 300);
|
||||
});
|
||||
|
||||
// Close on Escape / click outside
|
||||
document.addEventListener('click', e => {
|
||||
if (!e.target.closest('.vault-search-box')) {
|
||||
results.hidden = true;
|
||||
}
|
||||
});
|
||||
|
||||
input.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape') results.hidden = true;
|
||||
if (e.key === 'Enter' && !results.hidden) {
|
||||
const first = results.querySelector('.vault-search-result-item');
|
||||
if (first) {
|
||||
first.click();
|
||||
results.hidden = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function performSearch(q) {
|
||||
const results = document.getElementById('vault-search-results');
|
||||
results.innerHTML = '<div class="vault-search-status">Searching...</div>';
|
||||
results.hidden = false;
|
||||
|
||||
try {
|
||||
const data = await apiFetch(`${VAULT_API}/search?q=${encodeURIComponent(q)}`);
|
||||
if (data.count === 0) {
|
||||
results.innerHTML = '<div class="vault-search-status">No results found</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
let html = `<div class="vault-search-count">${data.count} result${data.count !== 1 ? 's' : ''}</div>`;
|
||||
for (const r of data.results.slice(0, 50)) {
|
||||
const displayPath = r.path.length > 80 ? '...' + r.path.slice(-77) : r.path;
|
||||
html += `<div class="vault-search-result-item" data-path="${escapeHtml(r.path)}" data-line="${r.line}">
|
||||
<div class="vault-search-result-path">${escapeHtml(displayPath)}:${r.line}</div>
|
||||
<div class="vault-search-result-snippet">${escapeHtml(r.snippet)}</div>
|
||||
</div>`;
|
||||
}
|
||||
if (data.count > 50) {
|
||||
html += `<div class="vault-search-status">... and ${data.count - 50} more</div>`;
|
||||
}
|
||||
results.innerHTML = html;
|
||||
|
||||
results.querySelectorAll('.vault-search-result-item').forEach(item => {
|
||||
item.addEventListener('click', () => {
|
||||
loadFile(item.dataset.path);
|
||||
results.hidden = true;
|
||||
document.getElementById('vault-search-input').value = '';
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
results.innerHTML = `<div class="vault-search-status">Error: ${escapeHtml(err.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Init ──────────────────────────────────────────────────────────────
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Only init vault when its panel is shown
|
||||
const vaultPanel = document.getElementById('vault');
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!vaultPanel.hidden && !vaultPanel.dataset.vaultLoaded) {
|
||||
vaultPanel.dataset.vaultLoaded = 'true';
|
||||
initVault();
|
||||
}
|
||||
});
|
||||
observer.observe(vaultPanel, { attributes: true, attributeFilter: ['hidden'] });
|
||||
|
||||
// Also check initially
|
||||
if (!vaultPanel.hidden && !vaultPanel.dataset.vaultLoaded) {
|
||||
vaultPanel.dataset.vaultLoaded = 'true';
|
||||
initVault();
|
||||
}
|
||||
|
||||
// Toggle tree sidebar on mobile
|
||||
document.getElementById('vault-toggle-tree').addEventListener('click', () => {
|
||||
document.getElementById('vault-tree').classList.toggle('vault-tree-visible');
|
||||
});
|
||||
});
|
||||
|
||||
function initVault() {
|
||||
setupSearch();
|
||||
loadTree('');
|
||||
|
||||
// Close tree on file click in mobile view
|
||||
document.getElementById('vault-tree').addEventListener('click', e => {
|
||||
if (window.innerWidth <= 900 && e.target.closest('.vault-tree-file')) {
|
||||
document.getElementById('vault-tree').classList.remove('vault-tree-visible');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Test the config editor API endpoints."""
|
||||
import multiprocessing
|
||||
import time
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
|
||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Start server
|
||||
import uvicorn
|
||||
import requests
|
||||
|
||||
def run_server():
|
||||
uvicorn.run('server:app', host='127.0.0.1', port=8891, log_level='warning')
|
||||
|
||||
p = multiprocessing.Process(target=run_server, daemon=True)
|
||||
p.start()
|
||||
time.sleep(2)
|
||||
print('=== Server started ===')
|
||||
|
||||
BASE = 'http://127.0.0.1:8891'
|
||||
AUTH = ('shawn', 'Brett85!@')
|
||||
|
||||
def t(name, ok, detail=''):
|
||||
status = 'PASS' if ok else 'FAIL'
|
||||
print(f' [{status}] {name}' + (f' — {detail}' if detail else ''))
|
||||
|
||||
# 1. Health
|
||||
r = requests.get(f'{BASE}/health')
|
||||
t('Health endpoint', r.ok and r.json()['status'] == 'ok')
|
||||
|
||||
# 2. Config list
|
||||
r = requests.get(f'{BASE}/api/config/list', auth=AUTH)
|
||||
t('Config list returns 200', r.status_code == 200)
|
||||
data = r.json()
|
||||
t('Has files array', 'files' in data and len(data['files']) > 0, f'{len(data["files"])} files')
|
||||
|
||||
# 3. Read first file
|
||||
first_file = data['files'][0]['path']
|
||||
r = requests.get(f'{BASE}/api/config/read?path={requests.utils.quote(first_file)}', auth=AUTH)
|
||||
t('Read file returns 200', r.status_code == 200)
|
||||
rd = r.json()
|
||||
t('Has content and metadata', all(k in rd for k in ('content', 'line_count', 'size', 'last_modified')))
|
||||
t('Line count matches content', rd['line_count'] == len(rd['content'].split('\n')))
|
||||
|
||||
# 4. Unauthorized path
|
||||
r = requests.get(f'{BASE}/api/config/read?path=/etc/passwd', auth=AUTH)
|
||||
t('Rejects /etc/passwd', r.status_code == 403)
|
||||
|
||||
r = requests.get(f'{BASE}/api/config/read?path={requests.utils.quote("/home/oplabs/.bashrc")}', auth=AUTH)
|
||||
t('Rejects .bashrc', r.status_code == 403)
|
||||
|
||||
# 5. Missing file in whitelist
|
||||
missing_files = [f for f in data['files'] if f.get('missing')]
|
||||
t('Missing files reported correctly', not missing_files or all(f.get('missing') for f in missing_files))
|
||||
|
||||
# 6. YAML validation - invalid YAML
|
||||
yaml_files = [f for f in data['files'] if f['filename'].endswith('.yaml')]
|
||||
assert len(yaml_files) > 0, 'Need at least one yaml file to test validation'
|
||||
yaml_path = yaml_files[0]['path']
|
||||
|
||||
r = requests.post(f'{BASE}/api/config/save',
|
||||
json={'path': yaml_path, 'content': 'invalid: yaml: [[[bad'},
|
||||
auth=AUTH)
|
||||
t('Rejects invalid YAML', r.status_code == 400 and 'YAML validation' in r.json().get('error', ''))
|
||||
|
||||
# 7. Save valid YAML
|
||||
r = requests.post(f'{BASE}/api/config/save',
|
||||
json={'path': yaml_path, 'content': 'key: value\nnested:\n sub: data\n'},
|
||||
auth=AUTH)
|
||||
t('Saves valid YAML', r.status_code == 200 and r.json().get('saved') and 'backup_path' in r.json())
|
||||
saved = r.json()
|
||||
print(f' Backup created: {saved["backup_path"]}')
|
||||
|
||||
# 8. Verify backup exists
|
||||
bak_path = saved['backup_path']
|
||||
r = requests.get(f'{BASE}/api/config/read?path={requests.utils.quote(first_file)}', auth=AUTH)
|
||||
t('Backup file path is returned', 'bak.' in bak_path)
|
||||
print(f' Original: {saved["path"]}')
|
||||
print(f' Lines: {saved["line_count"]}, Size: {saved["size"]}')
|
||||
|
||||
# 9. Test backup endpoint directly
|
||||
r = requests.post(f'{BASE}/api/config/backup?path={requests.utils.quote(yaml_path)}', auth=AUTH)
|
||||
t('Manual backup endpoint', r.status_code == 200 and 'backup_path' in r.json())
|
||||
|
||||
# 10. HTML serving
|
||||
r = requests.get(f'{BASE}/', auth=AUTH)
|
||||
t('Serves index.html', r.status_code == 200 and 'Config Editor' in r.text)
|
||||
|
||||
p.terminate()
|
||||
p.join()
|
||||
print('\n=== All tests complete ===')
|
||||
Reference in New Issue
Block a user