// ── Oumta Dashboard plugin ── // // Fullscreen view that consumes the Oumta Go backend (`oumta-dashboard`). // All reads go through `api()` below; configure the backend URL in the // hyprcrd settings overlay (oumta tab) or accept the localhost default. const h = window.hyprcrd; const $ = id => document.getElementById(id); // ── Settings / persisted state ── // // We use localStorage for now. Later we might persist via a hyprcrd setting // or a plugin-level table — see TODO.md. const LS_KEY = 'oumta-dashboard-settings'; const state = { settings: { baseUrl: 'http://localhost:8080', // e.g. https://dashboard.oumta.internal; default fits local dev authToken: '', // Keycloak bearer; empty = no auth yet pollIntervalSec: 15, }, namespaces: [], // [{ id, label, namespace }] activeNamespace: null, activeView: 'overview', liveMode: 'polling', // 'live' | 'polling' | 'error' | 'off' pollHandle: null, sseHandle: null, data: { overview: null, workloads: [], timeline: [], scopeWorkload: null }, }; function loadSettings() { try { const raw = localStorage.getItem(LS_KEY); if (raw) Object.assign(state.settings, JSON.parse(raw)); } catch {} } function saveSettings() { localStorage.setItem(LS_KEY, JSON.stringify(state.settings)); } // ── Central API surface ───────────────────────────────────────── // // Every backend call routes through `api()`. Requests go against // `state.settings.baseUrl`; the active namespace (if any) is attached // as a `namespace` query parameter, and the configured auth token is // sent as a bearer header. Response shapes are defined by the Go // backend in `internal/httpapi/contracts.go`. async function api(path, opts = {}) { const url = new URL(path, state.settings.baseUrl); if (!url.searchParams.has('namespace') && state.activeNamespace) { url.searchParams.set('namespace', state.activeNamespace.namespace); } const headers = state.settings.authToken ? { Authorization: 'Bearer ' + state.settings.authToken } : {}; const res = await fetch(url, { ...opts, headers }); if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`); return res.json(); } // ── Fullscreen overlay show/hide ───────────────────────────────── const overlay = $('oumta-overlay'); function isOpen() { return overlay?.classList.contains('open'); } function show() { if (!overlay) return; overlay.classList.add('open'); if (!state.namespaces.length) bootstrap(); else { refresh(); startLive(); } } function hide() { if (!overlay) return; overlay.classList.remove('open'); stopLive(); } function toggle() { isOpen() ? hide() : show(); } window._oumtaToggle = toggle; // ── Bootstrap: load namespaces, then first refresh ───────────── async function bootstrap() { try { const res = await api('/api/namespaces'); state.namespaces = res.items || []; state.activeNamespace = state.namespaces[0] || null; renderNamespaceTabs(); await refresh(); startLive(); } catch (e) { setLive('error', e.message); } } function renderNamespaceTabs() { const host = $('oumta-ns-tabs'); if (!host) return; host.innerHTML = state.namespaces.map(n => ` `).join(''); host.querySelectorAll('.oumta-ns-tab').forEach(btn => { btn.addEventListener('click', () => { const ns = state.namespaces.find(x => x.id === btn.dataset.ns); if (ns && ns.id !== state.activeNamespace?.id) { state.activeNamespace = ns; renderNamespaceTabs(); refresh(); } }); }); } // ── View switching ──────────────────────────────────────────── document.addEventListener('click', e => { const tab = e.target.closest('.oumta-view-tab'); if (!tab || !overlay.contains(tab)) return; switchView(tab.dataset.view); }); function switchView(view) { state.activeView = view; document.querySelectorAll('.oumta-view-tab').forEach(b => b.classList.toggle('active', b.dataset.view === view)); document.querySelectorAll('.oumta-view').forEach(s => s.classList.toggle('hidden', s.dataset.view !== view)); // Reset workload-scoped timeline when leaving timeline view if (view !== 'timeline') state.data.scopeWorkload = null; renderTimeline(); } // ── Refresh all data for the active namespace ────────────────── async function refresh() { if (!state.activeNamespace) return; try { const [ov, wl, tl] = await Promise.all([ api('/api/cluster/overview'), api('/api/workloads'), api('/api/timeline'), ]); state.data.overview = ov; state.data.workloads = wl.items || []; state.data.timeline = tl.items || []; renderAll(); } catch (e) { setLive('error', e.message); } } // ── Renderers ───────────────────────────────────────────────── function renderAll() { renderOverview(); renderWorkloads(); renderTimeline(); const genAt = state.data.overview?.updatedAtUtc; const el = $('oumta-generated-at'); if (el && genAt) el.textContent = 'last import: ' + formatTime(genAt); } function renderOverview() { const o = state.data.overview; const wl = state.data.workloads || []; if (!o) return; // Values that come directly from the Go overview endpoint [REAL]. const clusterCard = $('oumta-cluster-card'); const clusterState = o.clusterState || 'unknown'; clusterCard.dataset.state = clusterState; clusterCard.classList.toggle('oumta-fail', clusterState === 'down'); $('oumta-cluster-state').textContent = clusterState; $('oumta-cluster-updated').textContent = o.updatedAtUtc ? 'as of ' + formatTime(o.updatedAtUtc) : 'no data'; $('oumta-workloads-up').textContent = o.workloadsUp ?? '—'; $('oumta-workloads-down').textContent = o.workloadsDown ?? '—'; $('oumta-last-import').textContent = o.updatedAtUtc ? formatTime(o.updatedAtUtc) : '—'; // Any workload down → the "workloads down" tile becomes an alarm tile. const downCard = $('oumta-workloads-down').closest('.oumta-card'); if (downCard) downCard.classList.toggle('oumta-fail', (o.workloadsDown ?? 0) > 0); // Values derived client-side from the workloads list — the overview // endpoint doesn't carry these today. If the backend later adds // `incidents` / `attention` fields, prefer those over the derivation. const attention = wl.filter(w => w.state !== 'healthy') .sort((a, b) => rankState(a.state) - rankState(b.state)); $('oumta-incidents').textContent = attention.length || '—'; const incCard = $('oumta-incidents').closest('.oumta-card'); if (incCard) incCard.classList.toggle('oumta-fail', attention.length > 0); const list = $('oumta-attention-list'); if (!attention.length) { list.innerHTML = '
Nothing currently flagged.
'; return; } list.innerHTML = attention.map(a => `
${a.state} ${escapeHtml(a.name)} ${escapeHtml(a.namespace)} ${escapeHtml(a.lastReason || '')}
`).join(''); list.querySelectorAll('.oumta-attention-row').forEach(row => { row.addEventListener('click', () => openWorkload(row.dataset.wlid)); }); } // Severity order for the attention list: worst first. function rankState(s) { return { unavailable: 0, degraded: 1, healthy: 2 }[s] ?? 9; } function renderWorkloads() { const search = ($('oumta-wl-search').value || '').toLowerCase(); const filterState = $('oumta-wl-status').value; const body = $('oumta-wl-body'); const rows = (state.data.workloads || []).filter(w => { if (search && !w.name.toLowerCase().includes(search)) return false; if (filterState && w.state !== filterState) return false; return true; }); if (!rows.length) { body.innerHTML = 'No workloads match.'; return; } body.innerHTML = rows.map(w => ` ${escapeHtml(w.name)} ${escapeHtml(w.namespace)} ${w.state} ${w.replicasReady}/${w.replicasDesired} ${escapeHtml(w.cpu)} ${escapeHtml(w.memory)} ${escapeHtml(w.image)} ${escapeHtml(w.lastReason)} `).join(''); body.querySelectorAll('tr').forEach(tr => { tr.addEventListener('click', () => openWorkload(tr.dataset.wlid)); }); } function renderTimeline() { const scope = state.data.scopeWorkload; const scopeEl = $('oumta-timeline-scope'); const backEl = $('oumta-timeline-back'); if (scope) { scopeEl.textContent = 'events for ' + scope; backEl.classList.remove('hidden'); } else { scopeEl.textContent = 'all events'; backEl.classList.add('hidden'); } const events = scope ? (state.data.timeline.filter(e => e.workloadId === scope)) : state.data.timeline; const body = $('oumta-timeline-body'); if (!events.length) { body.innerHTML = '
No events.
'; return; } body.innerHTML = events.map(e => { // Recovery = letzter State-Uebergang endet in "-> healthy". // Image-Rollout = vom Backend markiert via reason "ImageRolled". // Beide kriegen eigene Badges, damit man Erholungen und neue // Images von generischen Info-Events (nur-Revision-Rollouts) // trennen kann. const isRecovery = typeof e.message === 'string' && e.message.endsWith('-> healthy'); const isImageRoll = e.reason === 'ImageRolled'; let sev = e.severity; if (isRecovery) sev = 'recovered'; else if (isImageRoll) sev = 'image'; return `
${formatTime(e.timestamp)}
${sev}
${escapeHtml(e.message)}
${escapeHtml(e.workloadId)} · ${escapeHtml(e.reason || '')}
`; }).join(''); } // ── Workload → detail-as-timeline navigation ────────────────── async function openWorkload(workloadId) { state.data.scopeWorkload = workloadId; const [nsSlug, name] = workloadId.replace('deployment/', '').split('/'); // Pull workload-scoped timeline — this REPLACES the generic one for rendering. try { const res = await api(`/api/workloads/${nsSlug}/${name}/timeline`); state.data.timeline = res.items || []; } catch (e) { setLive('error', e.message); } switchView('timeline'); } $('oumta-timeline-back')?.addEventListener('click', () => { state.data.scopeWorkload = null; // Restore the global timeline api('/api/timeline').then(r => { state.data.timeline = r.items || []; renderTimeline(); }).catch(e => setLive('error', e.message)); }); // ── Realtime (SSE) with polling fallback ────────────────────── // // Plan: open an EventSource at /api/events?namespace=… — backend // not implemented yet, so we go straight to polling. When SSE is available // we can try to connect and fall back on `error`. function startLive() { stopLive(); // TODO(api): attempt SSE first: // state.sseHandle = new EventSource(url); // state.sseHandle.onmessage = ev => applyLiveEvent(JSON.parse(ev.data)); // state.sseHandle.onerror = () => { stopLive(); startPolling(); setLive('polling'); }; // state.sseHandle.onopen = () => setLive('live'); startPolling(); } function stopLive() { if (state.pollHandle) { clearInterval(state.pollHandle); state.pollHandle = null; } if (state.sseHandle) { state.sseHandle.close(); state.sseHandle = null; } setLive('off'); } function startPolling() { const ms = (state.settings.pollIntervalSec || 15) * 1000; state.pollHandle = setInterval(refresh, ms); setLive('polling'); } function setLive(mode, detail = '') { state.liveMode = mode; const el = $('oumta-live-indicator'); const lbl = $('oumta-live-label'); if (el) el.dataset.state = mode; if (lbl) { lbl.textContent = ({ live: 'live', polling: 'polling', error: 'error' + (detail ? ' — ' + detail : ''), off: 'off', })[mode] || mode; } } // ── Header buttons ─────────────────────────────────────────── $('oumta-close')?.addEventListener('click', hide); $('oumta-refresh')?.addEventListener('click', refresh); $('oumta-wl-search')?.addEventListener('input', renderWorkloads); $('oumta-wl-status')?.addEventListener('change', renderWorkloads); $('oumta-wl-timerange')?.addEventListener('change', () => { // TODO(api): forward to /api/workloads?since= once the backend accepts it. renderWorkloads(); }); // ESC to close window.addEventListener('keydown', e => { if (e.key === 'Escape' && isOpen()) { e.preventDefault(); e.stopPropagation(); hide(); } }, { capture: true }); // ── Inject header button into hyprcrd top bar ──────────────── function injectHeaderButton() { const tasksBtn = document.getElementById('tasks-btn'); if (!tasksBtn || document.getElementById('oumta-btn')) return; const btn = document.createElement('button'); btn.id = 'oumta-btn'; btn.className = 'flex items-center gap-2 px-2.5 py-1.5 text-xs border border-t-border text-t-muted hover:border-t-accent hover:text-t-accent transition-colors'; btn.innerHTML = 'Oumta'; btn.addEventListener('click', toggle); tasksBtn.parentNode.insertBefore(btn, tasksBtn); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', injectHeaderButton); } else { injectHeaderButton(); } // ── Settings tab in hyprcrd settings ───────────────────────── function renderSettingsPanel(panelEl) { panelEl.innerHTML = `
Where the Oumta Go backend is reachable from this browser. No trailing slash.
Will be sent as Authorization: Bearer <token>. Leave empty if the API is unauthenticated.
Used as a fallback when SSE is unavailable.
`; $('oumta-set-baseurl').value = state.settings.baseUrl || ''; $('oumta-set-token').value = state.settings.authToken || ''; $('oumta-set-poll').value = state.settings.pollIntervalSec || 15; $('oumta-set-save').addEventListener('click', () => { state.settings.baseUrl = $('oumta-set-baseurl').value.trim(); state.settings.authToken = $('oumta-set-token').value.trim(); state.settings.pollIntervalSec = Math.max(5, parseInt($('oumta-set-poll').value) || 15); saveSettings(); const s = $('oumta-set-status'); s.textContent = 'saved'; setTimeout(() => { s.textContent = ''; }, 1500); // If the overlay is open, restart polling with new interval. if (isOpen()) { stopLive(); startLive(); } }); } // ── Helpers ───────────────────────────────────────────────── function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } function escapeAttr(s) { return escapeHtml(s); } function formatTime(iso) { try { const d = new Date(iso); return d.toLocaleString(); } catch { return iso; } } // ── Boot ──────────────────────────────────────────────────── loadSettings(); h?.settings?.registerTab?.({ id: 'oumta-dashboard', label: 'oumta', icon: 'ph-gauge', onShow: renderSettingsPanel, }); h?.registerPlugin?.({ name: 'oumta-dashboard', version: '0.1.0' });