/* ==========================================================================
Headroom frontend — no build step, ES modules only.
========================================================================== */
import { lineChart, ring, sparkline, bandColor } from './charts.js';
const app = document.getElementById('app');
const bootEl = document.getElementById('boot');
const modalRoot = document.getElementById('modal-root');
const toastRoot = document.getElementById('toast-root');
/* --------------------------------------------------------------------------
Icons
-------------------------------------------------------------------------- */
const ICONS = {
dashboard: ' ',
server: ' ',
chart: ' ',
bell: ' ',
plug: ' ',
sparkles: ' ',
code: ' ',
settings: ' ',
search: ' ',
refresh: ' ',
plus: ' ',
x: ' ',
play: ' ',
check: ' ',
upload: ' ',
trash: ' ',
logout: ' ',
shield: ' ',
arrowRight: ' ',
arrowLeft: ' ',
arrowUp: ' ',
arrowDown: ' ',
menu: ' ',
alert: ' ',
info: ' ',
database: ' ',
layers: ' ',
network: ' ',
bolt: ' ',
box: ' ',
key: ' ',
clock: ' ',
copy: ' ',
download: ' ',
external: ' ',
cpu: ' ',
lock: ' ',
list: ' ',
cap: ' ',
chevronDown: ' ',
minus: ' ',
activity: ' ',
filter: ' ',
dollar: ' ',
mail: ' ',
git: ' ',
terminal: ' ',
spark: ' ',
};
const BRAND_SVG = ` `;
function icon(name, cls = 'ic') {
return `${ICONS[name] || ICONS.plug} `;
}
/* --------------------------------------------------------------------------
Utilities
-------------------------------------------------------------------------- */
const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const META = () => state.boot?.meta || { metrics: {}, asset_types: {}, util_metrics: [] };
const METRICS = () => META().metrics || {};
const TYPES = () => META().asset_types || {};
const BAND_LABELS = { healthy: 'Healthy', watch: 'Watch', tight: 'Tight', critical: 'Critical', unknown: 'No data' };
function band(value) {
if (value == null || Number.isNaN(Number(value))) return 'unknown';
const n = Number(value);
if (n >= 90) return 'critical';
if (n >= 80) return 'tight';
if (n >= 60) return 'watch';
return 'healthy';
}
function trimNum(value, digits = 1) {
if (value == null || Number.isNaN(Number(value))) return '—';
const n = Number(value);
const fixed = n.toFixed(digits);
return fixed.replace(/\.0+$/, '').replace(/(\.\d*?)0+$/, '$1');
}
function pct(value, digits = 1) {
if (value == null || Number.isNaN(Number(value))) return '—';
return `${trimNum(value, digits)}%`;
}
function gb(value) {
if (value == null || Number.isNaN(Number(value))) return '—';
const n = Number(value);
if (Math.abs(n) >= 1024) return `${trimNum(n / 1024, n >= 10240 ? 0 : 1)} TB`;
return `${trimNum(n, 0)} GB`;
}
function days(value) {
if (value == null || Number.isNaN(Number(value))) return '—';
const n = Number(value);
if (n < 1) return '<1 day';
if (n < 45) return `${Math.round(n)} days`;
if (n < 365) return `${trimNum(n / 30.44, 1)} months`;
return `${trimNum(n / 365, 1)} years`;
}
function timeAgo(value) {
if (!value) return 'never';
const t = new Date(value).getTime();
if (!Number.isFinite(t)) return '—';
const seconds = Math.max(0, Math.round((Date.now() - t) / 1000));
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
if (seconds < 86400 * 30) return `${Math.floor(seconds / 86400)}d ago`;
return new Date(t).toLocaleDateString();
}
function fmtDate(value, withTime = false) {
if (!value) return '—';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return String(value);
return date.toLocaleString([], withTime ? { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' } : { year: 'numeric', month: 'short', day: 'numeric' });
}
function metricMeta(key) {
return METRICS()[key] || { label: key, unit: '', kind: 'other' };
}
function metricValue(key, value) {
if (value == null) return '—';
const meta = metricMeta(key);
const unit = meta.unit || '';
const n = Number(value);
if (unit === '%') return `${trimNum(n, 1)}%`;
const formatted = Math.abs(n) >= 1000 ? Math.round(n).toLocaleString() : trimNum(n, 2);
return unit ? `${formatted} ${unit}` : formatted;
}
function statusPill(status, label = '') {
const key = status || 'unknown';
return `${esc(BAND_LABELS[key] || label || key)} `;
}
const ASSET_ICON = { hypervisor: 'server', storage: 'database', nas: 'database', appliance: 'box', network: 'network', power: 'bolt', server: 'server', cluster: 'layers' };
const MODULE_ICON = { proxmox: 'layers', esxi: 'server', splunk: 'chart', truenas: 'database', linux: 'terminal', windows: 'server', 'http-json': 'code' };
const typeIcon = (type) => icon(ASSET_ICON[type] || 'server');
const assetHref = (id) => `#/assets/${encodeURIComponent(id)}`;
const trendCell = (asset) => {
const slope = Number(asset?.slope_per_day || 0);
if (Math.abs(slope) < 0.02) return `${icon('minus')} stable `;
const up = slope > 0;
return `${icon(up ? 'arrowUp' : 'arrowDown')} ${trimNum(Math.abs(slope), 2)} pp/d `;
};
const moduleName = (id) => (state.boot?.meta ? id : id);
/* --------------------------------------------------------------------------
State
-------------------------------------------------------------------------- */
const state = {
boot: null,
route: { name: 'overview', id: null },
windowDays: 7,
renderToken: 0,
assetFilters: { q: '', type: '', module: '' },
alertResolved: false,
apiTab: 'rest',
settingsTab: 'general',
chat: [],
chatLoading: false,
simResult: null,
assetMetric: null,
pollTimer: null,
};
/* --------------------------------------------------------------------------
API
-------------------------------------------------------------------------- */
function parseError(data, status) {
const detail = data && data.detail;
if (detail && typeof detail === 'object') return { message: detail.message || `Request failed (${status})`, code: detail.code, feature: detail.feature, detail };
return { message: typeof detail === 'string' ? detail : `Request failed (${status})`, code: null, feature: null, detail };
}
async function request(path, options = {}) {
const opts = { credentials: 'same-origin', ...options };
const isForm = opts.body instanceof FormData;
opts.headers = { ...(isForm ? {} : { 'Content-Type': 'application/json' }), ...(options.headers || {}) };
const response = await fetch(`/api${path}`, opts);
const type = response.headers.get('content-type') || '';
const data = type.includes('json') ? await response.json().catch(() => null) : await response.text();
if (!response.ok) {
const error = parseError(data, response.status);
if (response.status === 401 && state.boot) showLogin();
if (response.status === 402) openUpgrade(error.feature);
const err = new Error(error.message);
err.status = response.status;
err.code = error.code;
err.feature = error.feature;
throw err;
}
return data;
}
const get = (path) => request(path);
const post = (path, body) => request(path, { method: 'POST', body: body === undefined ? undefined : JSON.stringify(body) });
const put = (path, body) => request(path, { method: 'PUT', body: JSON.stringify(body) });
const del = (path) => request(path, { method: 'DELETE' });
function toastError(error) {
if (!error || error.status === 402) return;
toast(error.message || 'Something went wrong', 'error');
}
/* --------------------------------------------------------------------------
Toasts / modal
-------------------------------------------------------------------------- */
function toast(message, kind = 'ok', title = '') {
const icons = { ok: 'check', error: 'alert', warn: 'alert', info: 'info' };
const el = document.createElement('div');
el.className = `toast ${kind}`;
el.innerHTML = `${icon(icons[kind] || 'info')}
${title ? `${esc(title)} ` : ''}${esc(message)}
`;
toastRoot.appendChild(el);
setTimeout(() => {
el.classList.add('leaving');
setTimeout(() => el.remove(), 200);
}, kind === 'error' ? 6200 : 4200);
}
let modalEscape = null;
function closeModal() {
modalRoot.innerHTML = '';
if (modalEscape) {
document.removeEventListener('keydown', modalEscape);
modalEscape = null;
}
}
function openModal({ title, sub = '', body = '', footer = '', wide = false, narrow = false, onMount = null, onClose = null }) {
closeModal();
const size = wide ? 'wide' : narrow ? 'narrow' : '';
modalRoot.innerHTML = `
${title} ${sub ? `
${sub}
` : ''}
${icon('x')}
${body}
${footer ? `` : ''}
`;
const backdrop = modalRoot.querySelector('[data-backdrop]');
const close = () => { const callback = onClose; closeModal(); if (callback) callback(); };
backdrop.addEventListener('click', (event) => { if (event.target === backdrop) close(); });
modalRoot.querySelectorAll('[data-close]').forEach((button) => button.addEventListener('click', close));
modalEscape = (event) => { if (event.key === 'Escape') close(); };
document.addEventListener('keydown', modalEscape);
if (onMount) onMount(modalRoot.querySelector('.modal'), close);
return modalRoot.querySelector('.modal');
}
function confirmDialog({ title, message, confirmLabel = 'Confirm', danger = false }) {
return new Promise((resolve) => {
let settled = false;
const finish = (value) => { if (settled) return; settled = true; closeModal(); resolve(value); };
openModal({
title: esc(title),
narrow: true,
body: `${message}
`,
footer: `Cancel ${esc(confirmLabel)} `,
onMount(modal) {
modal.querySelector('[data-cancel]').addEventListener('click', () => finish(false));
modal.querySelector('[data-yes]').addEventListener('click', () => finish(true));
},
onClose() { if (!settled) { settled = true; resolve(false); } },
});
});
}
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
toast('Copied to clipboard');
} catch {
const area = document.createElement('textarea');
area.value = text;
document.body.appendChild(area);
area.select();
document.execCommand('copy');
area.remove();
toast('Copied to clipboard');
}
}
/* --------------------------------------------------------------------------
Boot / login
-------------------------------------------------------------------------- */
async function init() {
try {
const data = await get('/bootstrap');
state.boot = data;
startApp();
} catch (error) {
if (error.status === 401) {
showLogin();
} else {
showBootError(error.message);
}
}
}
function showBootError(message) {
if (!bootEl) return;
bootEl.hidden = false;
app.hidden = true;
const sub = bootEl.querySelector('.boot-sub');
if (sub) sub.textContent = message;
bootEl.classList.add('boot-failed');
if (!bootEl.querySelector('.boot-error')) {
const div = document.createElement('div');
div.className = 'boot-error';
div.textContent = 'The API did not respond correctly. Verify the server log and reload.';
bootEl.appendChild(div);
}
}
function showLogin(message = '') {
state.boot = null;
state.renderToken += 1;
if (state.pollTimer) { clearInterval(state.pollTimer); state.pollTimer = null; }
if (bootEl) bootEl.hidden = true;
app.hidden = false;
document.title = 'Sign in — Headroom';
app.innerHTML = `
${BRAND_SVG}
HEADROOM
Capacity operations console
Know your headroom. Before you run out.
Modular capacity intelligence for Proxmox, ESXi, NAS, Splunk and every other corner of your homelab. Forecast exhaustion, simulate upgrades and let your fleet tell you what it needs next.
${icon('chart')} Days-to-full forecasts and pressure scoring across every asset.
${icon('plug')} Seven bundled integrations, plus custom modules and push ingestion.
${icon('sparkles')} What-if planning, local insights and an MCP server for AI agents.
Secure sign-in
Welcome back
Sign in to your capacity console.
${icon('info')}First run uses admin / admin. Change it in Settings.
`;
const form = app.querySelector('#login-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const button = app.querySelector('#login-submit');
const error = app.querySelector('#login-error');
error.textContent = '';
button.disabled = true;
button.innerHTML = `${icon('refresh')} Signing in…`;
const payload = Object.fromEntries(new FormData(form).entries());
try {
await post('/auth/login', payload);
await init();
} catch (err) {
error.textContent = err.message;
button.disabled = false;
button.innerHTML = `Sign in ${icon('arrowRight')}`;
app.querySelector('#login-pass').focus();
}
});
}
/* --------------------------------------------------------------------------
Shell
-------------------------------------------------------------------------- */
const NAV = [
{ section: 'Operations' },
{ key: 'overview', label: 'Overview', icon: 'dashboard', href: '#/overview' },
{ key: 'assets', label: 'Assets', icon: 'server', href: '#/assets' },
{ key: 'capacity', label: 'Capacity & forecast', icon: 'chart', href: '#/capacity' },
{ key: 'alerts', label: 'Alerts', icon: 'bell', href: '#/alerts' },
{ section: 'Platform' },
{ key: 'modules', label: 'Modules', icon: 'plug', href: '#/modules' },
{ key: 'copilot', label: 'Copilot', icon: 'sparkles', href: '#/copilot' },
{ key: 'api', label: 'API & MCP', icon: 'code', href: '#/api' },
{ section: 'System' },
{ key: 'settings', label: 'Settings', icon: 'settings', href: '#/settings' },
];
function navKey(route) {
if (route.name === 'asset') return 'assets';
return route.name;
}
function startApp() {
if (!state.boot) return;
if (bootEl) bootEl.hidden = true;
app.hidden = false;
document.title = `${state.boot.site_name} — Headroom`;
const user = state.boot.user;
const initial = esc((user.username || '?').slice(0, 1).toUpperCase());
app.innerHTML = `
`;
renderEditionCard();
updateNav();
bindShell();
location.hash = location.hash && location.hash !== '#/' ? location.hash : '#/overview';
renderRoute();
startPolling();
}
function renderEditionCard() {
const slot = document.getElementById('edition-slot');
if (!slot || !state.boot) return;
const edition = state.boot.edition;
const paid = edition.edition !== 'community';
const p = paid
? (edition.source === 'trial' ? `${edition.days_left ?? 0} days left in the Enterprise trial.` : `${esc(edition.customer || 'Licensed')} · ${edition.days_left ?? '—'} days remaining.`)
: 'Custom modules, LLM copilot, MCP server and 400-day retention.';
slot.innerHTML = `
${esc(edition.label)}
${p}
${paid ? 'Manage license' : 'Upgrade to Enterprise'}
`;
}
function updateNav() {
const key = navKey(state.route);
document.querySelectorAll('.nav-item').forEach((item) => item.classList.toggle('active', item.dataset.nav === key));
const count = Number(state.boot?.open_alerts || 0);
const badge = document.getElementById('nav-alert-count');
if (badge) {
badge.textContent = count > 99 ? '99+' : String(count);
badge.hidden = count === 0;
}
document.querySelectorAll('[data-lock]').forEach((lock) => {
const feature = lock.dataset.lock === 'copilot' ? 'llm_copilot' : 'mcp_server';
const unlocked = state.boot?.features?.[feature] || lock.dataset.lock === 'copilot';
lock.hidden = unlocked;
});
}
function setPage(title, sub = '') {
const titleEl = document.getElementById('tb-title');
const subEl = document.getElementById('tb-sub');
if (titleEl) titleEl.textContent = title;
if (subEl) subEl.textContent = sub;
}
function bindShell() {
document.addEventListener('click', (event) => {
const menuToggle = event.target.closest('[data-menu-toggle]');
if (menuToggle) {
document.getElementById('sidebar')?.classList.toggle('open');
return;
}
if (event.target.closest('.sidebar .nav-item')) {
document.getElementById('sidebar')?.classList.remove('open');
}
const userButton = event.target.closest('[data-user-menu]');
if (userButton) {
document.getElementById('user-menu')?.toggleAttribute('hidden');
return;
}
if (!event.target.closest('#user-menu')) {
document.getElementById('user-menu')?.setAttribute('hidden', '');
}
if (event.target.closest('[data-logout]')) {
event.preventDefault();
logout();
}
if (event.target.closest('[data-open-settings]')) {
location.hash = '#/settings';
}
const windowButton = event.target.closest('[data-window]');
if (windowButton) {
state.windowDays = Number(windowButton.dataset.window) || 7;
renderRoute();
}
if (event.target.closest('[data-refresh]')) {
renderRoute();
}
if (event.target.closest('[data-upgrade]')) {
openUpgrade(event.target.closest('[data-upgrade]').dataset.upgrade || '');
}
});
window.addEventListener('hashchange', () => {
if (!state.boot) return;
renderRoute();
window.scrollTo({ top: 0, behavior: 'smooth' });
});
}
async function logout() {
try { await post('/auth/logout'); } catch { /* ignore */ }
state.chat = [];
showLogin();
location.hash = '';
}
/* --------------------------------------------------------------------------
Router
-------------------------------------------------------------------------- */
function parseHash() {
const raw = (location.hash || '').replace(/^#\/?/, '');
if (!raw) return { name: 'overview', id: null };
const parts = raw.split('/');
if (parts[0] === 'assets' && parts[1]) return { name: 'asset', id: decodeURIComponent(parts.slice(1).join('/')) };
const name = parts[0];
const known = ['overview', 'assets', 'capacity', 'alerts', 'modules', 'copilot', 'api', 'settings'];
return { name: known.includes(name) ? name : 'overview', id: null };
}
const VIEWS = {};
async function renderRoute(silent = false) {
if (!state.boot) return;
const route = parseHash();
state.route = route;
updateNav();
const token = ++state.renderToken;
const view = document.getElementById('view');
if (!view) return;
if (!silent) view.innerHTML = loadingHtml();
try {
const renderer = VIEWS[route.name];
if (!renderer) throw new Error('Unknown view');
await renderer({ route, view, token });
} catch (error) {
if (token !== state.renderToken) return;
if (error.status === 401) return;
view.innerHTML = errorState(error);
}
}
function loadingHtml() {
return ``;
}
function errorState(error) {
return `
${icon('alert')}
Could not load this view
${esc(error?.message || 'Unexpected error')}
${icon('refresh')} Try again
`;
}
function pageHead({ eyebrow = '', title, sub = '', actions = '' }) {
return `
${eyebrow ? `
${esc(eyebrow)}
` : ''}
${title} ${sub ? `
${sub}
` : ''}
${actions ? `
${actions}
` : ''}
`;
}
function windowSeg() {
const options = [[1, '24h'], [7, '7d'], [30, '30d'], [90, '90d']];
return `${options.map(([value, label]) => `${label} `).join('')}
`;
}
function refreshButton() {
return `${icon('refresh')} Refresh `;
}
function startPolling() {
if (state.pollTimer) clearInterval(state.pollTimer);
state.pollTimer = setInterval(async () => {
if (document.hidden || !state.boot || document.querySelector('.modal-backdrop')) return;
const active = document.activeElement;
if (active && ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName)) return;
await refreshBootstrap();
if (['overview', 'assets'].includes(state.route.name)) renderRoute(true);
}, 45000);
}
async function refreshBootstrap() {
try {
const data = await get('/bootstrap');
state.boot = data;
renderEditionCard();
updateNav();
return data;
} catch { return null; }
}
/* --------------------------------------------------------------------------
Upgrade / trial
-------------------------------------------------------------------------- */
async function openUpgrade(feature = '') {
let editions = null;
try { editions = await get('/editions'); } catch { /* ignore */ }
const labels = state.boot?.feature_labels || {};
const enterpriseFeatures = [];
if (editions) {
for (const group of editions.matrix || []) {
for (const item of group.features) {
if (item.enterprise && !item.community) enterpriseFeatures.push(item.label);
}
}
}
const featureLabel = feature && labels[feature] ? labels[feature] : '';
const trialAvailable = editions ? editions.trial_available : false;
const body = `
${featureLabel ? `${icon('lock')}
${esc(featureLabel)} is an Enterprise capability.
` : ''}
Enterprise adds the tooling you need when the lab stops being just a lab: upload your own modules, talk to your fleet through an LLM, expose capacity data over MCP, and keep a year of history.
${(enterpriseFeatures.length ? enterpriseFeatures : ['Custom module uploads', 'LLM copilot', 'MCP server for AI agents', 'Unlimited assets', '400-day retention', 'Audit export and webhooks']).map((item) => `
${icon('check')}${esc(item)}
`).join('')}
${trialAvailable ? `${icon('sparkles')}
30-day Enterprise trial — unlock everything now, no payment details.
` : `${icon('info')}
A trial has already been used on this installation. Activate a license key to continue with Enterprise features.
`}
`;
openModal({
title: 'Unlock Headroom Enterprise',
sub: 'Upgrade the edition of this installation',
wide: true,
body,
footer: `
${trialAvailable ? `${icon('sparkles')} Start 30-day trial ` : ''}
${icon('key')} Activate key
Not now `,
onMount(modal, close) {
const trial = modal.querySelector('[data-trial]');
if (trial) trial.addEventListener('click', async () => {
trial.disabled = true;
try {
await post('/license/trial');
await refreshBootstrap();
close();
toast('Enterprise trial started — all features are unlocked', 'ok', 'Trial active');
renderRoute();
} catch (error) { trial.disabled = false; toastError(error); }
});
modal.querySelector('[data-activate]').addEventListener('click', async () => {
const key = modal.querySelector('#license-key').value.trim();
if (!key) { toast('Paste a license key first', 'warn'); return; }
try {
await post('/license/activate', { key });
await refreshBootstrap();
close();
toast('License activated. Welcome to Enterprise.', 'ok', 'Edition upgraded');
renderRoute();
} catch (error) { toastError(error); }
});
},
});
}
/* --------------------------------------------------------------------------
Shared components
-------------------------------------------------------------------------- */
function emptyState(title, text, action = '') {
return `${icon('database')}
${esc(title)} ${esc(text)}
${action}
`;
}
function resourceCard(key, label, data, accent = 'accent') {
const util = data?.util;
const b = band(util);
const unit = key === 'storage' ? gb : key === 'cpu' ? (v) => `${trimNum(v, 0)} cores` : gb;
const total = unit(data?.total ?? 0);
const used = unit(data?.used ?? 0);
const growth = key === 'storage' ? gb(data?.growth_per_day ?? 0) : key === 'cpu' ? `${trimNum(data?.growth_per_day ?? 0, 2)} cores` : gb(data?.growth_per_day ?? 0);
return `
${esc(label)}
${used} / ${total}
${pct(util)} utilized
${ring(util ?? 0, { size: 74, stroke: 7, band: b })}
Free ${unit(data?.free ?? 0)}
Growth / day ${growth}
Runway ${days(data?.days_to_full)}
`;
}
function alertRow(alert, options = {}) {
const open = alert.state === 'open';
return `
${options.resolve && open ? `
${icon('check')} Resolve ` : ''}
`;
}
function minModuleName(id) {
const modules = state.boot?.modules || [];
return modules.find((module) => module.id === id)?.name || id;
}
/* --------------------------------------------------------------------------
Overview
-------------------------------------------------------------------------- */
VIEWS.overview = async ({ view, token }) => {
setPage('Fleet overview', 'Capacity posture across every integrated system');
const data = await get(`/overview?window=${state.windowDays}`);
if (token !== state.renderToken) return;
const k = data.kpis;
const storage = data.resources.storage;
const nearest = k.nearest_exhaustion;
const storageBand = band(storage.util);
const pressureBand = band(k.avg_pressure);
const timeline = data.timeline || {};
const series = [
{ key: 'cpu', label: 'CPU', color: 'var(--cyan)', points: timeline.cpu_pct || [] },
{ key: 'mem', label: 'Memory', color: 'var(--watch)', points: timeline.mem_pct || [] },
{ key: 'storage', label: 'Storage', color: 'var(--accent)', points: timeline.storage_pct || [], area: true },
].filter((item) => item.points.length);
const openAlerts = data.alerts || [];
const modules = data.modules || [];
view.innerHTML = `
${pageHead({
eyebrow: 'Operations',
title: 'Fleet overview',
sub: `Live headroom across ${k.asset_count} assets in ${k.module_count} modules. ${k.last_collection ? `Last collection ${timeAgo(k.last_collection)}.` : 'Waiting for the first collection.'}`,
actions: `${windowSeg()}${refreshButton()}`,
})}
Managed assets ${icon('server')}
${k.asset_count}assets
${k.modules_online} of ${k.module_count} modules online
Average pressure ${icon('activity')}
${Math.round(k.avg_pressure)}/ 100
${statusPill(pressureBand)}weighted utilization + growth
Storage headroom ${icon('database')}
${pct(storage.util)}used
${gb(storage.used)} of ${gb(storage.total)} · ${gb(storage.free)} free
Needs attention ${icon('bell')}
${k.open_alerts}open alerts
${nearest ? `Nearest exhaustion: ${esc(nearest.name)} ` : 'No exhaustion projected'}
${nearest ? `${icon('alert')}
${esc(nearest.name)} runs out of ${esc((metricMeta(nearest.metric).label || '').toLowerCase())} in ${days(nearest.days_to_full)} (${fmtDate(nearest.eta_date)}). Currently ${pct(nearest.util)} used. Open asset →
` : ''}
Fleet utilization Average utilization across active assets · last ${state.windowDays === 1 ? '24 hours' : `${state.windowDays} days`}
Pressure leaders Highest risk first
${resourceCard('storage', 'Storage pool', data.resources.storage)}
${resourceCard('cpu', 'Compute pool', data.resources.cpu)}
${resourceCard('mem', 'Memory pool', data.resources.mem)}
Fastest movers Largest utilization growth per day
Asset Utilization Growth Runway
${(data.movers || []).length ? data.movers.map((asset) => `
${typeIcon(asset.type)} ${esc(asset.name)}
${esc(asset.module_name)}
${pct(asset.util)}
${trendCell(asset)}
${days(asset.days_to_full)}
`).join('') : `No growth detected Growth will appear here as utilization rises over time. `}
Open alerts ${k.open_alerts} unresolved
${openAlerts.length ? openAlerts.map((alert) => alertRow(alert)).join('') : emptyState('No open alerts', 'Every policy is within its threshold.')}
`;
if (series.length) {
lineChart(view.querySelector('#fleet-chart'), series, { height: 282, max: 100, valueFormat: (value) => `${Math.round(value)}%`, ariaLabel: 'Fleet utilization over time' });
} else {
view.querySelector('#fleet-chart').innerHTML = 'No telemetry in this window yet.
';
}
view.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; }));
};
/* --------------------------------------------------------------------------
Assets
-------------------------------------------------------------------------- */
function assetFilteredRows(items) {
const filter = state.assetFilters;
const needle = filter.q.trim().toLowerCase();
return items.filter((asset) => {
if (filter.type && asset.type !== filter.type) return false;
if (filter.module && asset.module_id !== filter.module) return false;
if (!needle) return true;
return asset.name.toLowerCase().includes(needle)
|| asset.module_name.toLowerCase().includes(needle)
|| (asset.cluster || '').toLowerCase().includes(needle)
|| (asset.site || '').toLowerCase().includes(needle)
|| (asset.tags || []).some((tag) => tag.toLowerCase().includes(needle));
});
}
function assetRow(asset) {
return `
${typeIcon(asset.type)}
${esc(asset.name)}
${esc(asset.module_name)}${asset.cluster ? ` · ${esc(asset.cluster)}` : ''}
${esc(asset.type_label || asset.type)} ${asset.site ? `${esc(asset.site)}
` : ''}
${statusPill(asset.status, asset.status_label)}
${trendCell(asset)}
${days(asset.days_to_full)}
${timeAgo(asset.last_seen)}
`;
}
VIEWS.assets = async ({ view, token }) => {
setPage('Asset inventory', 'Every monitored system in one list');
const data = await get('/assets');
if (token !== state.renderToken) return;
const items = data.items || [];
const types = TYPES();
const modules = [...new Map(items.map((asset) => [asset.module_id, asset.module_name])).entries()];
const filter = state.assetFilters;
view.innerHTML = `
${pageHead({
eyebrow: 'Inventory',
title: 'Assets',
sub: `${items.length} active assets reported by ${modules.length} module${modules.length === 1 ? '' : 's'}. Click any row for forecasts and recommendations.`,
actions: `${windowSeg()}${icon('download')} Export CSV ${refreshButton()}`,
})}
${icon('search')}
All types
${Object.entries(types).map(([key, meta]) => `${esc(meta.label || key)} `).join('')}
All modules
${modules.map(([id, name]) => `${esc(name)} `).join('')}
Showing ${assetFilteredRows(items).length} of ${items.length}
${icon('x')} Clear
Asset Type Utilization Pressure Trend Runway Last seen
${assetFilteredRows(items).map(assetRow).join('') || `No assets match Adjust the filters or enable another module. `}
`;
const tbody = view.querySelector('#asset-tbody');
const count = view.querySelector('#asset-count');
const refreshRows = () => {
const filtered = assetFilteredRows(items);
tbody.innerHTML = filtered.length ? filtered.map(assetRow).join('') : `No assets match Adjust the filters or enable another module. `;
count.textContent = `Showing ${filtered.length} of ${items.length}`;
tbody.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; }));
};
const bindRowClicks = () => tbody.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; }));
bindRowClicks();
view.querySelector('#asset-search').addEventListener('input', (event) => {
state.assetFilters.q = event.target.value;
refreshRows();
});
view.querySelector('#filter-type').addEventListener('change', (event) => {
state.assetFilters.type = event.target.value;
refreshRows();
});
view.querySelector('#filter-module').addEventListener('change', (event) => {
state.assetFilters.module = event.target.value;
refreshRows();
});
view.querySelector('#clear-filters').addEventListener('click', () => {
state.assetFilters = { q: '', type: '', module: '' };
view.querySelector('#asset-search').value = '';
view.querySelector('#filter-type').value = '';
view.querySelector('#filter-module').value = '';
refreshRows();
});
};
/* --------------------------------------------------------------------------
Asset detail
-------------------------------------------------------------------------- */
VIEWS.asset = async ({ view, token, route }) => {
const data = await get(`/assets/${encodeURIComponent(route.id)}?window=30`);
if (token !== state.renderToken) return;
const asset = data.asset;
const analysis = data.analysis || {};
const cards = data.cards || [];
const forecasts = data.forecasts || {};
const reco = data.recommendation || {};
const assetAlerts = data.alerts || [];
setPage(asset.name, `${asset.module_name} · ${asset.type_label}`);
const capacity = asset.capacity || {};
const capacityRows = [
['Primary metric', metricMeta(analysis.primary_metric).label || analysis.primary_metric],
['Headroom', pct(analysis.headroom_pct)],
['Growth', `${analysis.slope_per_day > 0 ? '+' : ''}${trimNum(analysis.slope_per_day, 2)} pp/day`],
['Days to full', days(analysis.days_to_full)],
['Projected full', analysis.eta_date ? fmtDate(analysis.eta_date) : '—'],
['Last sample', timeAgo(asset.last_seen)],
['First seen', fmtDate(asset.first_seen)],
['Module status', data.module?.status ? `${data.module.status}${data.module.enabled ? '' : ' · disabled'}` : 'unknown'],
];
if (capacity.cpu_cores != null) capacityRows.push(['CPU cores', trimNum(capacity.cpu_cores, 0)]);
if (capacity.mem_gb != null) capacityRows.push(['Memory', gb(capacity.mem_gb)]);
if (capacity.storage_gb != null) capacityRows.push(['Storage', gb(capacity.storage_gb)]);
Object.entries(asset.meta || {}).slice(0, 8).forEach(([key, value]) => capacityRows.push([key.replace(/_/g, ' '), String(value)]));
const selected = cards.some((card) => card.key === state.assetMetric) ? state.assetMetric : (cards[0]?.key || analysis.primary_metric);
const selectedCard = cards.find((card) => card.key === selected);
view.innerHTML = `
${icon('arrowLeft')} All assets
${ring(analysis.pressure ?? 0, { size: 96, stroke: 9 })}
${esc(asset.name)} ${statusPill(analysis.status, analysis.status_label)}
${esc(asset.type_label || asset.type)}
${esc(asset.module_name)}
${asset.cluster ? `· ${esc(asset.cluster)} ` : ''}
${asset.site ? `· ${esc(asset.site)} ` : ''}
· Last seen ${timeAgo(asset.last_seen)}
${analysis.stale ? 'stale telemetry ' : ''}
${icon(analysis.trend === 'rising' ? 'arrowUp' : analysis.trend === 'falling' ? 'arrowDown' : 'minus')} ${esc(analysis.trend)}
${esc(reco.level || 'info')}
${esc(reco.title || 'Capacity assessment')}
${esc(reco.detail || '')}
${reco.action ? `
${icon('arrowRight')}${esc(reco.action)}
` : ''}
${cards.map((card) => {
const meta = metricMeta(card.key);
const delta = card.delta_24h;
const color = meta.kind === 'util' ? bandColor(band(card.value)) : 'var(--cyan)';
return `
${esc(card.label)}${esc(meta.unit || '')}
${esc(metricValue(card.key, card.value))} ${delta != null && delta !== 0 ? `${delta > 0 ? '+' : ''}${trimNum(delta, 1)} ` : ''}
${sparkline(card.series, color)}
`;
}).join('') || `
${icon('info')} No metric cards were reported for this asset.
`}
Capacity & metadata Declared capacity and collection state
${capacityRows.map(([label, value]) => `
${esc(label)} ${esc(value)} `).join('')}
${(asset.tags || []).length ? `
${asset.tags.map((tag) => `${esc(tag)} `).join('')}
` : ''}
Trend & forecast Observed history plus projected trajectory
Observed Forecast
${cards.map((card) => `${esc(card.label)} `).join('')}
Forecasts Linear projection over the next 90 days
${Object.keys(forecasts).length ? `
Metric Current Growth Days to full
${Object.entries(forecasts).map(([key, forecast]) => `
${esc(metricMeta(key).label || key)}
${esc(metricValue(key, asset.metrics?.[key]))}
${forecast.slope_per_day > 0 ? '+' : ''}${trimNum(forecast.slope_per_day, 2)} pp/d
${days(forecast.days_to_full)}
`).join('')}
` : `${icon('info')} No upward trend detected in the current window, so no exhaustion forecast is available.
`}
Alert history ${assetAlerts.filter((alert) => alert.state === 'open').length} open · ${assetAlerts.length} total
${assetAlerts.length ? assetAlerts.slice(0, 8).map((alert) => alertRow(alert)).join('') : emptyState('No alerts', 'This asset has never crossed a policy threshold.')}
`;
const drawChart = (key) => {
const card = cards.find((item) => item.key === key);
const container = view.querySelector('#asset-chart');
if (!card || !container) return;
const meta = metricMeta(key);
const series = [{ label: card.label, color: 'var(--accent)', points: card.series, area: true, dot: true }];
const forecast = forecasts[key];
if (forecast) series.push({ label: 'Forecast', color: 'var(--violet)', points: forecast.points, dashed: true });
const isPct = meta.unit === '%';
lineChart(container, series, {
height: 272,
max: isPct ? 100 : undefined,
valueFormat: (value) => (isPct ? `${Math.round(value)}%` : `${trimNum(value, 0)}${meta.unit ? ` ${meta.unit}` : ''}`),
ariaLabel: `${card.label} trend`,
});
const callout = view.querySelector('#forecast-callout');
callout.innerHTML = forecast
? `${icon('chart')}
${esc(card.label)} is growing ${forecast.slope_per_day > 0 ? '+' : ''}${trimNum(forecast.slope_per_day, 2)} ${isPct ? 'pp' : meta.unit || 'units'}/day${forecast.days_to_full ? ` and reaches capacity in ${days(forecast.days_to_full)} ` : ''}. The dashed line projects 90 days at the current rate.
`
: `${icon('info')}
No positive growth trend for this metric in the selected window.
`;
};
drawChart(selected);
view.querySelectorAll('[data-metric-tab]').forEach((button) => button.addEventListener('click', () => {
state.assetMetric = button.dataset.metricTab;
view.querySelectorAll('[data-metric-tab]').forEach((tab) => tab.classList.toggle('on', tab === button));
drawChart(button.dataset.metricTab);
}));
view.querySelectorAll('[data-run-module]').forEach((button) => button.addEventListener('click', async () => {
button.disabled = true;
button.classList.add('is-busy');
try {
const result = await post(`/modules/${encodeURIComponent(button.dataset.runModule)}/run`);
toast(`${result.assets} assets refreshed in ${result.duration_ms} ms`, 'ok', 'Collection complete');
await refreshBootstrap();
renderRoute();
} catch (error) { toastError(error); }
finally { button.disabled = false; button.classList.remove('is-busy'); }
}));
};
/* --------------------------------------------------------------------------
Capacity & what-if
-------------------------------------------------------------------------- */
VIEWS.capacity = async ({ view, token }) => {
setPage('Capacity & forecast', 'Pools, groups and upgrade planning');
const [data, modulesData] = await Promise.all([get(`/capacity?window=${state.windowDays}`), get('/modules')]);
if (token !== state.renderToken) return;
const groups = data.groups || [];
const modules = (modulesData.items || []).filter((module) => module.enabled);
view.innerHTML = `
${pageHead({
eyebrow: 'Planning',
title: 'Capacity & forecast',
sub: 'Aggregated pools, per-cluster pressure and a what-if simulator for the next hardware decision.',
actions: `${windowSeg()}${refreshButton()}`,
})}
${resourceCard('storage', 'Storage pool', data.totals.storage)}
${resourceCard('cpu', 'Compute pool', data.totals.cpu)}
${resourceCard('mem', 'Memory pool', data.totals.mem)}
Clusters & groups Grouped by cluster label, falling back to module
${groups.length} groups
Group Module Assets Peak utilization Pressure Storage runway Storage
${groups.length ? groups.map((group) => {
const storage = group.resources?.storage || {};
return `
${icon('layers')} ${esc(group.name)}
${esc(group.site || group.types.join(', '))}
${esc(group.module_name)}
${group.asset_count}
${statusPill(group.status, group.status_label)}
${days(group.days_to_full)}
${pct(storage.util)}
`;
}).join('') : `No groups yet Enable at least one module to build capacity groups. `}
What-if simulator Model growth and added capacity before you buy hardware
${icon('sparkles')} local model
${icon('info')}
Set a horizon and growth assumption, add planned capacity, then run the model. The simulator also projects every resource pool at the end of the horizon.
`;
const form = view.querySelector('#sim-form');
const output = view.querySelector('#sim-output');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const button = form.querySelector('button[type="submit"]');
button.disabled = true;
button.classList.add('is-busy');
const formData = new FormData(form);
const payload = {
horizon_days: Number(formData.get('horizon_days') || 90),
growth_multiplier: Number(formData.get('growth_multiplier') || 1),
add_storage_gb: Number(formData.get('add_storage_gb') || 0),
add_cpu_cores: Number(formData.get('add_cpu_cores') || 0),
add_mem_gb: Number(formData.get('add_mem_gb') || 0),
disable_modules: formData.getAll('disable_modules'),
};
try {
const result = await post('/capacity/simulate', payload);
state.simResult = result;
renderSimulation(output, result);
} catch (error) { toastError(error); }
finally { button.disabled = false; button.classList.remove('is-busy'); }
});
form.addEventListener('reset', () => {
setTimeout(() => {
output.innerHTML = `${icon('info')}
Set a horizon and growth assumption, add planned capacity, then run the model.
`;
}, 0);
});
if (state.simResult) renderSimulation(output, state.simResult);
};
function renderSimulation(output, result) {
const verdictMap = {
healthy: ['healthy', 'Comfortable headroom', 'The fleet stays below 60% on all modeled resources.'],
watch: ['watch', 'Keep watching', 'The plan keeps everything below 80%, but headroom is shrinking.'],
tight: ['tight', 'Tight after the plan', 'At least one resource exceeds 80% at the end of the horizon.'],
critical: ['critical', 'Exceeds safe capacity', 'At least one resource is projected above 90%. Add capacity or reduce growth.'],
};
const [vClass, vTitle, vText] = verdictMap[result.verdict] || verdictMap.watch;
const resourceLabels = { storage: 'Storage', cpu: 'Compute', mem: 'Memory' };
const resourceUnits = { storage: 'GB', cpu: 'cores', mem: 'GB' };
output.innerHTML = `
${ring(result.verdict === 'healthy' ? 42 : result.verdict === 'watch' ? 68 : result.verdict === 'tight' ? 85 : 96, { size: 58, stroke: 6, band: vClass })}
${vTitle} ${vText}
${esc(result.verdict)}
${['storage', 'cpu', 'mem'].map((key) => {
const resource = result.resources[key];
return `
${resourceLabels[key]} ${pct(resource.util_after)} after
Before${pct(resource.util_before)}
After plan${pct(resource.util_after)}
Projected use${trimNum(resource.projected_used, 0)} ${resourceUnits[key]}
Headroom${trimNum(resource.headroom_after, 0)} ${resourceUnits[key]}
`;
}).join('')}
${icon('info')}
${result.asset_count} assets included${result.disabled_modules.length ? ` · excluded: ${result.disabled_modules.map(esc).join(', ')}` : ''} · horizon ${result.horizon_days} days · growth ×${result.growth_multiplier}
${result.findings.map((finding) => `${icon('arrowRight')}${esc(finding)} `).join('')}
Projected utilization Current plan vs. added capacity
${['storage', 'cpu', 'mem'].map((key) => `${resourceLabels[key]} `).join('')}
Current plan With additions
`;
const drawSim = (resource) => {
const before = result.series.before.map((point) => ({ t: point.t, v: point.values[resource] ?? 0 }));
const after = result.series.after.map((point) => ({ t: point.t, v: point.values[resource] ?? 0 }));
lineChart(output.querySelector('#sim-chart'), [
{ label: 'Current plan', color: 'var(--crit)', points: before, dashed: true },
{ label: 'With additions', color: 'var(--accent)', points: after, area: true, dot: true },
], { height: 240, max: 100, valueFormat: (value) => `${Math.round(value)}%`, ariaLabel: 'Projected utilization' });
};
drawSim('storage');
output.querySelectorAll('[data-sim-resource]').forEach((button) => button.addEventListener('click', () => {
output.querySelectorAll('[data-sim-resource]').forEach((item) => item.classList.toggle('on', item === button));
drawSim(button.dataset.simResource);
}));
}
/* --------------------------------------------------------------------------
Alerts & policies
-------------------------------------------------------------------------- */
VIEWS.alerts = async ({ view, token }) => {
setPage('Alerts', 'Policy breaches and threshold history');
const [data, policiesData] = await Promise.all([get(`/alerts?include_resolved=${state.alertResolved}`), get('/policies')]);
if (token !== state.renderToken) return;
const items = data.items || [];
const policies = policiesData.items || [];
const canOperate = ['admin', 'operator'].includes(state.boot.user.role);
const utilMetrics = META().util_metrics || ['cpu_pct', 'mem_pct', 'storage_pct'];
view.innerHTML = `
${pageHead({
eyebrow: 'Operations',
title: 'Alerts',
sub: `${data.open} open · ${data.critical} critical · ${data.warning} warning`,
actions: ` Include resolved${icon('download')} Export ${refreshButton()}`,
})}
${state.alertResolved ? 'Alert history' : 'Open alerts'} Ordered by severity, then newest first
${data.critical} critical
${items.length ? items.map((alert) => alertRow(alert, { resolve: canOperate })).join('') : emptyState('No alerts', state.alertResolved ? 'No alerts have been recorded yet.' : 'Everything is within policy thresholds.')}
Policy coverage Thresholds evaluated after every collection
How it works
Each enabled policy is evaluated against every asset that reports the metric. Crossing the warning threshold opens a warning; crossing critical updates it. Values below warning resolve it automatically.
Warning and critical are percentages. One open alert per asset, metric and policy. Resolve manually to close it without waiting for the next collection.
Policies ${policies.length} configured
${canOperate ? `${icon('plus')} Add policy ` : ''}
`;
view.querySelector('#show-resolved').addEventListener('change', (event) => {
state.alertResolved = event.target.checked;
renderRoute();
});
const policyById = (id) => policies.find((policy) => String(policy.id) === String(id));
view.querySelectorAll('[data-resolve]').forEach((button) => button.addEventListener('click', async () => {
button.disabled = true;
try {
await post(`/alerts/${button.dataset.resolve}/resolve`);
toast('Alert resolved');
await refreshBootstrap();
renderRoute();
} catch (error) { toastError(error); button.disabled = false; }
}));
view.querySelectorAll('[data-new-policy]').forEach((button) => button.addEventListener('click', () => openPolicyModal(null, utilMetrics)));
view.querySelectorAll('[data-policy-edit]').forEach((button) => button.addEventListener('click', () => openPolicyModal(policyById(button.dataset.policyEdit), utilMetrics)));
view.querySelectorAll('[data-policy-toggle]').forEach((input) => input.addEventListener('change', async () => {
const policy = policyById(input.dataset.policyToggle);
if (!policy) return;
try {
await put(`/policies/${policy.id}`, { name: policy.name, metric: policy.metric, warn: policy.warn, crit: policy.crit, enabled: input.checked });
toast(`Policy ${input.checked ? 'enabled' : 'disabled'}`);
renderRoute();
} catch (error) { toastError(error); input.checked = !input.checked; }
}));
view.querySelectorAll('[data-policy-delete]').forEach((button) => button.addEventListener('click', async () => {
const policy = policyById(button.dataset.policyDelete);
if (!policy) return;
if (!(await confirmDialog({ title: 'Delete policy', message: `Delete ${esc(policy.name)} ? Open alerts from this policy will be resolved.`, confirmLabel: 'Delete policy', danger: true }))) return;
try {
await del(`/policies/${policy.id}`);
toast('Policy deleted');
await refreshBootstrap();
renderRoute();
} catch (error) { toastError(error); }
}));
};
function openPolicyModal(policy, utilMetrics) {
const isEdit = Boolean(policy);
const metricOptions = [...new Set([...(utilMetrics || []), ...(policy ? [policy.metric] : [])])];
openModal({
title: isEdit ? 'Edit policy' : 'New capacity policy',
sub: isEdit ? esc(policy.name) : 'Alerts are evaluated after every module run',
body: ``,
footer: `Cancel ${icon('check')} ${isEdit ? 'Save changes' : 'Create policy'} `,
onMount(modal, close) {
const form = modal.querySelector('#policy-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
const payload = {
name: String(formData.get('name') || '').trim(),
metric: String(formData.get('metric') || 'storage_pct'),
warn: Number(formData.get('warn')),
crit: Number(formData.get('crit')),
enabled: formData.get('enabled') === 'on',
};
if (payload.warn >= payload.crit) { toast('Warning must be below critical', 'warn'); return; }
try {
if (isEdit) await put(`/policies/${policy.id}`, payload);
else await post('/policies', payload);
close();
toast(isEdit ? 'Policy updated' : 'Policy created');
await refreshBootstrap();
renderRoute();
} catch (error) { toastError(error); }
});
},
});
}
/* --------------------------------------------------------------------------
Modules
-------------------------------------------------------------------------- */
function moduleStatusText(module) {
if (!module.enabled) return 'Disabled';
if (module.status === 'ok') return 'Connected';
if (module.status === 'error') return 'Collection failed';
if (module.status === 'pending') return 'Awaiting first run';
if (module.status === 'missing') return 'Files missing';
return module.status || 'Unknown';
}
function moduleDot(module) {
if (!module.enabled) return 'disabled';
if (module.status === 'ok') return 'ok';
if (module.status === 'error') return 'error';
if (module.status === 'pending') return 'pending';
return 'disabled';
}
VIEWS.modules = async ({ view, token }) => {
setPage('Modules', 'Integrations, collector health and custom plugins');
const data = await get('/modules');
if (token !== state.renderToken) return;
const modules = data.items || [];
const isAdmin = state.boot.user.role === 'admin';
const canOperate = ['admin', 'operator'].includes(state.boot.user.role);
const customAllowed = Boolean(state.boot.features.custom_modules);
const limit = Number(state.boot.limits?.assets ?? -1);
const limitWarning = limit > 0 && state.boot.asset_count >= limit;
const types = [...new Map(modules.map((m) => [m.module_type, m])).values()];
view.innerHTML = `
${pageHead({
eyebrow: 'Platform',
title: 'Modules',
sub: 'Toggle collectors, tune connections and upload your own integrations. Multiple instances of the same module type are supported.',
actions: `${isAdmin ? `${icon('plus')} Add instance ` : ''}${customAllowed ? `${icon('upload')} Upload module ` : `${icon('lock')} Upload unavailable `}${refreshButton()}`,
})}
${limitWarning ? `${icon('alert')}
Community asset limit reached (${limit}). New assets will not be stored until the limit is raised. Upgrade for unlimited assets ${icon('arrowRight')}
` : ''}
${modules.length} instances · ${types.length} types · ${modules.filter((module) => module.enabled).length} enabled · ${modules.reduce((sum, module) => sum + (module.asset_count || 0), 0)} assets
${modules.filter((module) => module.source === 'bundled').length} bundled instances
${modules.filter((module) => module.source === 'custom').length} custom instances
${!isAdmin ? `${icon('lock')} read-only ` : ''}
${modules.map((module) => {
const isCustom = module.source === 'custom';
const instanceCount = module.instance_count || 1;
const canDelete = isAdmin && (isCustom || instanceCount > 1);
return `
${esc(module.description || 'No description provided.')}
${esc(moduleStatusText(module))} ${module.message ? `· ${esc(module.message.length > 62 ? `${module.message.slice(0, 62)}…` : module.message)} ` : ''}
Assets ${module.asset_count || 0}
Interval ${module.interval_seconds || 300}s
Last run ${timeAgo(module.last_run)}
Instance ${esc(module.id)}
`;
}).join('')}
${modules.length ? '' : `${emptyState('No modules installed', 'Add an instance or upload a module package.', customAllowed ? `${icon('upload')} Upload module ` : '')} `}`;
const moduleById = (id) => modules.find((module) => module.id === id);
view.querySelectorAll('[data-module-toggle]').forEach((input) => input.addEventListener('change', async () => {
const module = moduleById(input.dataset.moduleToggle);
if (!module) return;
input.disabled = true;
try {
await put(`/modules/${encodeURIComponent(module.id)}`, { enabled: input.checked });
toast(`${module.name} ${input.checked ? 'enabled — first collection is starting' : 'disabled'}`);
await refreshBootstrap();
renderRoute();
if (input.checked) setTimeout(() => { if (state.route.name === 'modules') renderRoute(true); }, 3200);
} catch (error) { toastError(error); input.checked = !input.checked; input.disabled = false; }
}));
view.querySelectorAll('[data-module-run]').forEach((button) => button.addEventListener('click', async () => {
const module = moduleById(button.dataset.moduleRun);
button.disabled = true;
button.classList.add('is-busy');
try {
const result = await post(`/modules/${encodeURIComponent(module.id)}/run`);
toast(`${result.assets} assets · ${result.metrics} metrics · ${result.duration_ms} ms`, 'ok', `${module.name} collected`);
await refreshBootstrap();
renderRoute();
} catch (error) { toastError(error); }
finally { button.disabled = false; button.classList.remove('is-busy'); }
}));
view.querySelectorAll('[data-module-test]').forEach((button) => button.addEventListener('click', async () => {
const module = moduleById(button.dataset.moduleTest);
button.disabled = true;
button.classList.add('is-busy');
try {
const result = await post(`/modules/${encodeURIComponent(module.id)}/test`);
toast(result.message || 'Connection test completed', result.ok ? 'ok' : 'warn', `${module.name} test`);
} catch (error) { toastError(error); }
finally { button.disabled = false; button.classList.remove('is-busy'); }
}));
view.querySelectorAll('[data-module-config]').forEach((button) => button.addEventListener('click', () => openModuleConfig(moduleById(button.dataset.moduleConfig))));
view.querySelectorAll('[data-module-logs]').forEach((button) => button.addEventListener('click', () => openModuleLogs(moduleById(button.dataset.moduleLogs))));
view.querySelectorAll('[data-module-delete]').forEach((button) => button.addEventListener('click', async () => {
const module = moduleById(button.dataset.moduleDelete);
if (!module) return;
if (!(await confirmDialog({ title: 'Delete instance', message: `Delete instance ${esc(module.name)} and remove its assets and metric history? This cannot be undone.`, confirmLabel: 'Delete instance', danger: true }))) return;
try {
await del(`/modules/${encodeURIComponent(module.id)}`);
toast(`${module.name} removed`);
await refreshBootstrap();
renderRoute();
} catch (error) { toastError(error); }
}));
view.querySelectorAll('[data-module-clone]').forEach((button) => button.addEventListener('click', async () => {
const module = moduleById(button.dataset.moduleClone);
if (!module || !(state.boot.user && state.boot.user.role === 'admin')) return;
try {
const label = prompt(`Name for new ${module.type_name || module.name} instance`, `${module.name} 2`);
if (label === null) return;
await post('/modules/instances', { module_type: module.module_type, name: label, copy_from: module.id });
toast('Instance added', 'ok');
await refreshBootstrap();
renderRoute();
} catch (error) { toastError(error); }
}));
const addInstance = view.querySelector('#add-module-instance');
if (addInstance) {
addInstance.addEventListener('click', async () => {
if (!(state.boot.user && state.boot.user.role === 'admin')) return;
const choices = types.map((m) => `${esc(m.type_name || m.name)} (${esc(m.module_type)}) `).join('');
openModal({
title: 'Add module instance',
sub: 'Create another collector instance for the same module type',
body: ``,
footer: `Cancel ${icon('plus')} Add instance `,
onMount(modal, close) {
const form = modal.querySelector('#add-instance-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
try {
await post('/modules/instances', { module_type: String(formData.get('module_type') || ''), name: String(formData.get('name') || '') });
close();
toast('Instance added', 'ok');
await refreshBootstrap();
renderRoute();
} catch (error) { toastError(error); }
});
},
});
});
}
const upload = view.querySelector('#upload-module');
if (upload) upload.addEventListener('click', openUploadModal);
const uploadAgain = view.querySelector('[data-upload-again]');
if (uploadAgain) uploadAgain.addEventListener('click', openUploadModal);
};
function openModuleConfig(module) {
if (!module) return;
if (state.boot.user.role !== 'admin') { toast('Administrator role required', 'warn'); return; }
const config = module.config || {};
const secretSet = module.secret_set || {};
const fields = (module.settings_schema || []).map((item) => {
const key = item.key;
const label = item.label || key;
const type = item.type || 'text';
const value = config[key];
const help = item.help ? `${esc(item.help)} ` : '';
if (type === 'boolean') {
return ` ${esc(label)} ${help}
`;
}
if (type === 'select') {
const options = (item.options || []).map((option) => {
const optionValue = typeof option === 'object' ? option.value : option;
const optionLabel = typeof option === 'object' ? (option.label || option.value) : option;
return `${esc(optionLabel)} `;
}).join('');
return `${esc(label)} ${options} ${help}
`;
}
if (type === 'textarea') {
return `${esc(label)} ${help}
`;
}
if (type === 'password') {
const placeholder = secretSet[key] ? 'Saved — leave blank to keep the current value' : (item.placeholder || '');
return `${esc(label)} ${help}
`;
}
const inputType = type === 'number' ? 'number' : 'text';
const step = type === 'number' ? ' step="any"' : '';
return `${esc(label)} ${help}
`;
}).join('');
const demo = config.demo;
openModal({
title: `Configure ${module.name}`,
sub: `${module.source} module · v${esc(module.version || '—')}`,
wide: true,
body: `
${icon('shield')}
Secrets are masked in the UI and stored in the local SQLite database. Module code runs in an isolated subprocess with a 90-second timeout.
`,
footer: `Cancel ${icon('check')} Save configuration `,
onMount(modal, close) {
const form = modal.querySelector('#module-config-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const payload = {};
for (const item of module.settings_schema || []) {
const element = form.elements.namedItem(item.key);
if (!element) continue;
if ((item.type || 'text') === 'boolean') payload[item.key] = element.checked;
else if ((item.type || 'text') === 'number') payload[item.key] = element.value === '' ? (config[item.key] ?? 0) : Number(element.value);
else payload[item.key] = element.value;
}
try {
await put(`/modules/${encodeURIComponent(module.id)}`, { config: payload });
close();
toast(`${module.name} configuration saved`);
renderRoute();
} catch (error) { toastError(error); }
});
},
});
}
function openModuleLogs(module) {
if (!module) return;
openModal({
title: `${module.name} logs`,
sub: 'Most recent collector output',
wide: true,
body: `${icon('refresh')}
Loading logs…
`,
footer: `Close ${icon('refresh')} Reload `,
onMount(modal) {
const load = async () => {
const body = modal.querySelector('#module-logs-body');
body.innerHTML = `${icon('refresh')}
Loading logs…
`;
try {
const data = await get(`/modules/${encodeURIComponent(module.id)}/logs`);
body.innerHTML = data.logs ? `${esc(data.logs)} ` : `${icon('info')}
No log output yet. Run the module once to collect diagnostics.
`;
} catch (error) {
body.innerHTML = `${icon('alert')}
${esc(error.message)}
`;
}
};
load();
modal.querySelector('#reload-logs').addEventListener('click', load);
},
});
}
function openUploadModal() {
if (!state.boot.features.custom_modules) { openUpgrade('custom_modules'); return; }
openModal({
title: 'Upload a module',
sub: 'Signed-out-of-the-box: a zip with manifest.json and module.py',
wide: true,
body: `
${icon('upload')}
Drop a module zip here
or click to choose a file · max 2 MB
${icon('shield')}
Uploads are validated: manifest schema, module id, package paths and size. Module code executes in a subprocess with resource limits. Review third-party code before enabling it.
${icon('code')}
The package must contain manifest.json and module.py at the root (or inside one top-level folder).
`,
footer: `Cancel ${icon('upload')} Upload & register `,
onMount(modal, close) {
let file = null;
const drop = modal.querySelector('#upload-drop');
const input = modal.querySelector('#upload-file');
const selected = modal.querySelector('#upload-selected');
const submit = modal.querySelector('#upload-submit');
const choose = (chosen) => {
if (!chosen) return;
file = chosen;
selected.innerHTML = `${icon('box')}${esc(chosen.name)} ${(chosen.size / 1024).toFixed(1)} KB
`;
submit.disabled = false;
};
drop.addEventListener('click', () => input.click());
input.addEventListener('change', () => choose(input.files[0]));
drop.addEventListener('dragover', (event) => { event.preventDefault(); drop.style.borderColor = 'var(--accent)'; });
drop.addEventListener('dragleave', () => { drop.style.borderColor = ''; });
drop.addEventListener('drop', (event) => {
event.preventDefault();
drop.style.borderColor = '';
choose(event.dataTransfer.files[0]);
});
submit.addEventListener('click', async () => {
if (!file) return;
submit.disabled = true;
submit.classList.add('is-busy');
const formData = new FormData();
formData.append('file', file);
try {
const result = await request('/modules/upload', { method: 'POST', body: formData });
close();
toast(`${result.name} v${result.version} registered. Configure and enable it to collect.`, 'ok', 'Module uploaded');
renderRoute();
} catch (error) {
toastError(error);
submit.disabled = false;
submit.classList.remove('is-busy');
}
});
},
});
}
/* --------------------------------------------------------------------------
Copilot
-------------------------------------------------------------------------- */
function inlineMarkdown(text) {
return text
.replace(/\*\*(.+?)\*\*/g, '$1 ')
.replace(/`([^`]+)`/g, '$1');
}
function markdown(text) {
const lines = esc(text || '').split('\n');
const out = [];
let inList = false;
for (const raw of lines) {
const line = raw.trimEnd();
if (/^\s*[-*]\s+/.test(line)) {
if (!inList) { out.push(''); inList = true; }
out.push(`${inlineMarkdown(line.replace(/^\s*[-*]\s+/, ''))} `);
continue;
}
if (inList) { out.push(' '); inList = false; }
if (!line.trim()) continue;
out.push(`${inlineMarkdown(line)}
`);
}
if (inList) out.push('');
return out.join('');
}
VIEWS.copilot = async ({ view, token }) => {
setPage('Copilot', 'Capacity analysis and conversational planning');
let aiConfig = { config: {}, suggested_questions: [] };
try { aiConfig = await get('/ai/config'); } catch { /* ignore */ }
if (token !== state.renderToken) return;
const features = state.boot.features || {};
const config = aiConfig.config || {};
const suggestions = aiConfig.suggested_questions || [];
const edition = state.boot.edition;
const llm = features.llm_copilot;
view.innerHTML = `
${pageHead({
eyebrow: 'AI operations',
title: 'Capacity copilot',
sub: 'Ask about risk, growth or the next upgrade. Local analysis works on every edition; conversational answers unlock with Enterprise.',
actions: `${llm ? (config.configured ? 'LLM connected' : 'LLM not configured') : 'Local analysis'} ${icon('trash')} Clear chat `,
})}
Ask Headroom Grounded in your live fleet data
${llm && config.configured ? 'live context ' : 'deterministic insights '}
${suggestions.map((question) => `${esc(question)} `).join('')}
Fleet context What the copilot can see
Managed assets ${state.boot.asset_count}
Open alerts ${state.boot.open_alerts}
Modules online ${state.boot.scheduler?.modules_ran ?? '—'}
Edition ${esc(edition.label)}
Copilot modes Graceful degradation by edition
${icon('check')}
Local analysis Deterministic capacity briefing from live metrics. Included in Community.
${icon(llm ? 'check' : 'lock')}
LLM narrative Conversational answers through any OpenAI-compatible endpoint.
${icon('code')}
MCP agents Expose the same data to Claude Desktop or another MCP client.
Setup →
Provider ${llm ? (config.configured ? esc(config.model) : 'Not configured') : 'Enterprise capability'}
${llm
? `
Base URL ${esc(config.base_url || '—')}
Model ${esc(config.model || '—')}
API key ${config.key_set ? 'saved' : 'not set'}
${icon('settings')} Configure provider `
: `
Connect OpenAI, Azure OpenAI, Ollama, LM Studio or LiteLLM. Without a provider, Headroom still gives you the full local analysis.
${icon('sparkles')} Unlock LLM copilot `}
`;
const log = view.querySelector('#chat-log');
const form = view.querySelector('#chat-form');
const input = view.querySelector('#chat-text');
const send = view.querySelector('#chat-send');
const renderLog = () => {
log.innerHTML = `
${state.chat.map((message) => {
const isUser = message.role === 'user';
return `
${icon(isUser ? 'server' : 'sparkles')}
${markdown(message.content)}
${message.note ? `
${esc(message.note)}
` : ''}
${message.upgrade ? `
${icon('lock')}
Enterprise unlocks conversational answers with your own LLM provider. Start trial ${icon('arrowRight')}
` : ''}
${message.mode ? `
${message.mode === 'llm' ? icon('sparkles') : icon('activity')} ${message.mode === 'llm' ? 'LLM narrative' : 'Local analysis'}
` : ''}
`;
}).join('')}
${state.chatLoading ? `` : ''}`;
log.scrollTop = log.scrollHeight;
};
const appendError = (error) => {
state.chat.push({ role: 'assistant', content: `I could not complete that request: ${error.message}`, error: true });
};
const ask = async (text, { hidden = false } = {}) => {
if (state.chatLoading) return;
if (!hidden) state.chat.push({ role: 'user', content: text });
state.chatLoading = true;
renderLog();
send.disabled = true;
try {
const messages = state.chat.filter((message) => !message.hidden && !message.error && message.role !== 'system').map((message) => ({ role: message.role, content: message.content }));
const response = await post('/ai/chat', { messages });
state.chat.push({
role: 'assistant',
content: response.message || 'No response',
note: response.note,
mode: response.mode,
upgrade: Boolean(response.upgrade_required),
});
} catch (error) {
appendError(error);
} finally {
state.chatLoading = false;
send.disabled = false;
renderLog();
}
};
renderLog();
if (!state.chat.length && !state.chatLoading) {
ask('Give me a capacity briefing for this fleet.', { hidden: true });
}
form.addEventListener('submit', (event) => {
event.preventDefault();
const text = input.value.trim();
if (!text || state.chatLoading) return;
input.value = '';
input.style.height = '42px';
ask(text);
});
input.addEventListener('keydown', (event) => {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
form.requestSubmit();
}
});
input.addEventListener('input', () => {
input.style.height = '42px';
input.style.height = `${Math.min(150, input.scrollHeight)}px`;
});
view.querySelectorAll('[data-question]').forEach((button) => button.addEventListener('click', () => ask(button.dataset.question)));
view.querySelector('[data-clear-chat]').addEventListener('click', () => {
state.chat = [];
renderLog();
ask('Give me a capacity briefing for this fleet.', { hidden: true });
});
const configButton = view.querySelector('[data-ai-config]');
if (configButton) configButton.addEventListener('click', () => openAiConfigModal(config));
if (llm && !config.configured) {
// Keep the local briefing visible and make configuration discoverable.
if (!state.chat.some((message) => message.note)) {
// no-op: response note will explain the fallback
}
}
};
function openAiConfigModal(config) {
if (!state.boot.features.llm_copilot) { openUpgrade('llm_copilot'); return; }
openModal({
title: 'LLM provider',
sub: 'Any OpenAI-compatible chat completions endpoint',
wide: true,
body: `
Base URL
Headroom appends /chat/completions. Works with OpenAI, Azure, Ollama, LM Studio and LiteLLM.
Model
API key
${icon('shield')}
The key is stored server-side in SQLite and never returned to the browser. Only fleet aggregates and alert messages are sent to the provider — no credentials.
`,
footer: `Cancel ${icon('check')} Save provider `,
onMount(modal, close) {
const form = modal.querySelector('#ai-config-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
const payload = { base_url: String(formData.get('base_url') || ''), model: String(formData.get('model') || '') };
const key = String(formData.get('api_key') || '');
if (key) payload.api_key = key;
try {
await put('/ai/config', payload);
close();
toast('LLM provider saved');
renderRoute();
} catch (error) { toastError(error); }
});
},
});
}
/* --------------------------------------------------------------------------
API & MCP
-------------------------------------------------------------------------- */
const API_ENDPOINTS = [
['GET', '/api/overview', 'Fleet KPIs, pools, leaders and timeline'],
['GET', '/api/assets', 'Asset inventory with pressure and forecasts'],
['GET', '/api/assets/{id}', 'Timeseries, forecast and recommendation'],
['GET', '/api/capacity', 'Groups and aggregated resource pools'],
['POST', '/api/capacity/simulate', 'What-if simulation'],
['GET', '/api/alerts', 'Open or resolved alerts'],
['GET', '/api/modules', 'Collector health and configuration'],
['POST', '/api/modules/{id}/run', 'Trigger a collection'],
['POST', '/api/ingest/{module_id}', 'Push assets and metrics'],
['POST', '/api/mcp', 'MCP JSON-RPC endpoint'],
];
VIEWS.api = async ({ view, token }) => {
setPage('API & MCP', 'Automation surface for scripts and AI agents');
const [mcpCatalog, keysData, aiConfig] = await Promise.all([
get('/mcp').catch(() => null),
state.boot.user.role === 'admin' ? get('/keys').catch(() => null) : Promise.resolve(null),
get('/ai/config').catch(() => null),
]);
if (token !== state.renderToken) return;
const tab = state.apiTab;
const base = location.origin;
const keys = keysData?.items || [];
const cat = mcpCatalog || { enabled: false, tools: [], resources: [], example: {} };
const config = aiConfig?.config || {};
const tabs = [['rest', 'REST API'], ['keys', 'API keys'], ['mcp', 'MCP server'], ['ai', 'AI provider']];
const restPanel = `
Authenticate Two supported methods
${icon('shield')}
Session cookie — used by this UI. X-API-Key — create a key for scripts and agents. Keys inherit the role you assign.
Base URL ${esc(base)}
Auth header X-API-Key: hr_…
Endpoints ${API_ENDPOINTS.length} commonly used routes
${API_ENDPOINTS.map(([method, path, desc]) => `
${method} ${path}${desc}
`).join('')}
Quick start Read the fleet with an API key
${icon('copy')} Copy
curl -s ${esc(base)}/api/overview \\
-H "X-API-Key: hr_your_key_here"
curl -s ${esc(base)}/api/assets \\
-H "X-API-Key: hr_your_key_here"
${icon('code')}
Push custom telemetry into an enabled module: POST /api/ingest/http-json with {"assets":[{ "external_id":"ups-1", "name":"UPS", "type":"power", "metrics":{"load_pct":42} }]}.
`;
const keysPanel = keysData === null
? `${icon('lock')}
Administrator role required to manage API keys.
`
: `
API keys ${keys.length} active
Name Prefix Role Last used Actions
${keys.length ? keys.map((key) => `
${esc(key.name)}
created ${fmtDate(key.created_at)}
${esc(key.prefix)}…
${esc(key.role)}
${key.last_used ? timeAgo(key.last_used) : 'never'}
${icon('trash')}
`).join('') : `No API keys Create one to automate Headroom. `}
Create a key Shown once, stored hashed
Name
Role Viewer — read only Operator — run modules Admin — full control
${icon('plus')} Create API key
${icon('shield')}
Revoke unused keys regularly. The plaintext key is never stored and cannot be recovered.
`;
const mcpPanel = `
${cat.enabled ? '' : `
MCP server is an Enterprise capability
Give Claude Desktop, Cursor or a custom agent read access to capacity data and the ability to run collectors. Uses the same signed API keys as the REST API.
${icon('sparkles')} Start a trial
`}
Connection Streamable HTTP · JSON-RPC 2.0
${cat.enabled ? 'enabled' : 'locked'}
Endpoint ${esc(base)}/api/mcp
Protocol ${esc(cat.protocol_version || '2024-11-05')}
Auth X-API-Key
Tools ${cat.tools?.length || 0}
${icon('activity')} Ping MCP
${icon('copy')} Copy client config
Client config Claude Desktop example
${esc(JSON.stringify(cat.example || {}, null, 2))}
Resources Read-only context objects
URI Description
${(cat.resources || []).map((resource) => `${esc(resource.uri)}${esc(resource.description || resource.name)} `).join('')}
Tools ${cat.tools?.length || 0} capabilities
Tool Description
${(cat.tools || []).map((tool) => `${esc(tool.name)}${esc(tool.description)} `).join('')}
`;
const aiPanel = `
Provider configuration ${state.boot.features.llm_copilot ? 'Enterprise enabled' : 'Enterprise capability'}
${state.boot.features.llm_copilot
? `
Base URL
Model
API key
${icon('check')} Save provider
`
: `
${icon('lock')}
LLM copilot requires Enterprise. The local deterministic analysis remains available in the copilot view.
${icon('sparkles')} Unlock LLM copilot `}
Provider status OpenAI-compatible
Configured ${config.configured ? 'yes' : 'no'}
Base URL ${esc(config.base_url || '—')}
Model ${esc(config.model || '—')}
Key ${config.key_set ? 'saved' : 'not set'}
${icon('info')}
${esc(config.provider_hint || 'Any OpenAI-compatible chat completions endpoint.')}
${icon('sparkles')} Open copilot
`;
const panels = { rest: restPanel, keys: keysPanel, mcp: mcpPanel, ai: aiPanel };
view.innerHTML = `
${pageHead({ eyebrow: 'Platform', title: 'API & MCP', sub: 'Everything in Headroom is available over the REST API. Enterprise adds an MCP server, API keys with roles and an LLM provider.', actions: `${icon('external')} API docs ${refreshButton()}` })}
${tabs.map(([key, label]) => `${label} `).join('')}
${panels[tab] || restPanel}`;
view.querySelectorAll('[data-api-tab]').forEach((button) => button.addEventListener('click', () => {
state.apiTab = button.dataset.apiTab;
renderRoute();
}));
view.querySelectorAll('[data-copy-target]').forEach((button) => button.addEventListener('click', () => {
const target = view.querySelector(`#${button.dataset.copyTarget}`);
if (target) copyText(target.textContent);
}));
if (tab === 'keys' && keysData !== null) {
view.querySelectorAll('[data-key-delete]').forEach((button) => button.addEventListener('click', async () => {
if (!(await confirmDialog({ title: 'Revoke API key', message: 'Any client using this key will lose access immediately.', confirmLabel: 'Revoke key', danger: true }))) return;
try {
await del(`/keys/${button.dataset.keyDelete}`);
toast('API key revoked');
renderRoute();
} catch (error) { toastError(error); }
}));
const form = view.querySelector('#key-form');
form?.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
try {
const result = await post('/keys', { name: String(formData.get('name') || ''), role: String(formData.get('role') || 'viewer') });
openModal({
title: 'API key created',
sub: 'Copy it now — it is shown only once',
body: `${icon('key')}
${esc(result.name)} · ${esc(result.role)}
${esc(result.key)} `,
footer: `${icon('copy')} Copy key Done `,
onMount(modal, close) {
modal.querySelector('[data-copy-key]').addEventListener('click', () => copyText(result.key));
modal.querySelector('[data-close]').addEventListener('click', () => { close(); renderRoute(); });
},
});
} catch (error) { toastError(error); }
});
}
if (tab === 'mcp') {
const ping = view.querySelector('#mcp-ping');
ping?.addEventListener('click', async () => {
const output = view.querySelector('#mcp-result');
output.hidden = false;
output.textContent = 'Calling initialize…';
try {
const result = await post('/mcp', { jsonrpc: '2.0', id: 1, method: 'initialize', params: {} });
output.textContent = JSON.stringify(result, null, 2);
if (result.error) toast(result.error.message || 'MCP call returned an error', 'warn');
else toast('MCP server responded', 'ok');
} catch (error) {
output.textContent = error.message;
toastError(error);
}
});
}
if (tab === 'ai') {
const form = view.querySelector('#ai-page-form');
form?.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
const payload = { base_url: String(formData.get('base_url') || ''), model: String(formData.get('model') || '') };
const key = String(formData.get('api_key') || '');
if (key) payload.api_key = key;
try {
await put('/ai/config', payload);
toast('LLM provider saved');
renderRoute();
} catch (error) { toastError(error); }
});
}
};
/* --------------------------------------------------------------------------
Settings
-------------------------------------------------------------------------- */
VIEWS.settings = async ({ view, token }) => {
setPage('Settings', 'Edition, security and platform configuration');
const isAdmin = state.boot.user.role === 'admin';
const [settings, license, editions, auditData] = await Promise.all([
get('/settings'),
get('/license'),
get('/editions').catch(() => null),
isAdmin ? get('/audit?limit=100').catch(() => null) : Promise.resolve(null),
]);
if (token !== state.renderToken) return;
const tabs = [['general', 'General'], ['license', 'Edition & license'], ['security', 'Security'], ['audit', 'Audit log'], ['about', 'About']];
const tab = tabs.some(([key]) => key === state.settingsTab) ? state.settingsTab : 'general';
const paid = license.edition !== 'community';
const matrix = editions?.matrix || [];
const audit = auditData?.items || [];
const sched = settings.scheduler || {};
const assetLimit = Number(license.limits?.assets ?? 40);
const assetCount = Number(state.boot.asset_count || 0);
const assetUsage = assetLimit > 0 ? Math.min(100, Math.round((assetCount / assetLimit) * 100)) : 0;
const maxRetention = Number(license.limits?.retention_days || 30);
const trialAvailable = Boolean(license.trial_available) && !paid;
const canModify = isAdmin;
const disabled = canModify ? '' : 'disabled';
const currentLicense = paid
? `
${license.source === 'trial'
? ring(Math.max(0, Math.min(100, ((Number(license.days_left) || 0) / 30) * 100)), { size: 62, stroke: 7, suffix: 'days' })
: `
${icon('shield')} `}
${esc(license.label)}
${license.customer ? `${esc(license.customer)} · ` : ''}${license.expires ? `Valid until ${fmtDate(license.expires)}` : 'Open-ended license'}${license.days_left != null ? ` · ${license.days_left} days left` : ''}
${license.source === 'trial' ? 'TRIAL' : 'ACTIVE'}
`
: `
${icon('layers')}
Community edition
Free forever · ${license.limits?.assets ?? 40} assets · ${license.limits?.retention_days ?? 30}-day retention · bundled modules only
${icon('sparkles')} Upgrade
`;
const matrixRows = matrix.map((group) => `
${esc(group.group)}
${group.features.map((feature) => `
${esc(feature.label)}
${icon('check')}
`).join('')}
`).join('');
const generalPanel = `
Site & retention Applied to dashboards, exports and the API
${canModify ? '' : 'read only '}
${sched.running ? 'scheduler running' : 'scheduler stopped'}
Tick interval ${esc(String(sched.interval_seconds ?? '—'))}s
Collections run ${esc(String(sched.runs ?? 0))}
Last tick duration ${sched.last_tick_ms != null ? `${esc(String(sched.last_tick_ms))} ms` : '—'}
Database ${esc(settings.db_path)}
Modules directory ${esc(settings.modules_dir)}
Admin account ${esc(settings.admin_user)}
${sched.last_error ? `
${icon('alert')}
Last scheduler error ${esc(sched.last_error)}
` : ''}
Asset allowance ${assetLimit > 0 ? 'Community cap' : 'Enterprise — unlimited'}
${assetCount}${assetLimit > 0 ? ` / ${assetLimit}` : ''}
${assetLimit > 0
? `${Math.max(0, assetLimit - assetCount)} asset slot${assetLimit - assetCount === 1 ? '' : 's'} remaining. The oldest idle assets are never evicted automatically.`
: `No hard limit. ${assetCount} assets are currently tracked across ${state.boot.edition.features?.length || 0} enabled capabilities.`}
Maintenance Destructive operations
Re-seed the installation with the realistic demo fleet. This clears assets, telemetry, alerts and the audit trail before loading a fresh dataset.
`;
const licensePanel = `
${currentLicense}
${license.invalid_license ? `${icon('alert')}
Stored license could not be verified. It may have been issued by another installation or has been tampered with. Activate a valid key to restore Enterprise features.
` : ''}
${license.trial_expired ? `${icon('clock')}
The 30-day trial has ended. Your data is intact; Enterprise capabilities are locked until you activate a license.
` : ''}
Administrator unlock Enable Enterprise features without a license key
Activate a license Signed locally with HMAC — no phone home
License key
Paste the key exactly as issued. ${canModify ? 'Activation takes effect immediately.' : 'Administrator role required.'}
${icon('key')} Activate license
${trialAvailable ? `
${icon('sparkles')}
30-day Enterprise trial — no payment details, no phone home. One trial per installation.
${icon('sparkles')} Start trial ` : ''}
${paid ? `
${icon('x')} Deactivate license ` : ''}
Plan comparison ${matrix.reduce((sum, group) => sum + group.features.length, 0)} capabilities
Capability Community Enterprise
${matrixRows || `Could not load the edition matrix. `}
${state.boot.dev_license_enabled ? `
Development license issuer Visible because HEADROOM_ALLOW_DEV_LICENSE is enabled
DEV
` : ''}`;
const securityPanel = `
Change password ${esc(state.boot.user.username)} · ${esc(state.boot.user.role)}
Access Session and credentials
Signed in as ${esc(state.boot.user.username)}
Role ${esc(state.boot.user.role)}
Session HttpOnly cookie
API keys ${isAdmin ? 'manageable' : 'admin only'}
Edition ${esc(license.label)}
${icon('key')} Manage API keys
${icon('logout')} Sign out
`;
const auditPanel = !isAdmin
? `${icon('lock')}
The audit trail is visible to administrators only.
`
: `
Audit trail Latest ${audit.length} recorded actions
${state.boot.features.audit_export
? `${icon('download')} Export CSV `
: `${icon('lock')} Export with Enterprise `}
${refreshButton()}
When Actor Action Target Detail
${audit.length ? audit.map((item) => `
${esc(fmtDate(item.ts, true))}
${esc(item.actor)}
${esc(item.action)}
${esc(item.target || '—')}
${esc(item.detail || '—')}
`).join('') : `No audit entries yet Administrative actions will appear here. `}
`;
const enabledFeatures = state.boot.edition.features || [];
const aboutPanel = `
About Headroom Know your headroom. Before you run out.
v${esc(state.boot.version)}
Headroom is a modular capacity-management console for homelabs and small fleets. It collects utilisation from hypervisors, storage, log platforms and bare-metal hosts, forecasts exhaustion, evaluates policies and lets you simulate upgrades before you buy hardware.
Edition ${esc(license.label)}
Source ${esc(license.source)}
Assets tracked ${assetCount}
Open alerts ${state.boot.open_alerts ?? 0}
API version v1
Storage SQLite (WAL)
Resources Documentation and integration points
${icon('info')}
MCI / AI integration is implemented as MCP (JSON-RPC over HTTP) plus an OpenAI-compatible copilot provider, so agents and local LLMs can read capacity data with the same API keys.
${icon('terminal')}
The installation is fully self-hosted. No telemetry leaves this machine; the only outbound calls are to the integrations and LLM provider you configure yourself.
${paid ? '' : `
Ready for the next rack?
Enterprise removes the 40-asset cap, keeps 400 days of history, unlocks custom module uploads, webhooks, audit export and the MCP server.
${icon('check')}Unlimited assets
${icon('check')}Custom modules
${icon('check')}LLM copilot
${icon('check')}MCP server
${icon('sparkles')} Unlock Enterprise
`}`;
const panels = { general: generalPanel, license: licensePanel, security: securityPanel, audit: auditPanel, about: aboutPanel };
view.innerHTML = `
${pageHead({ eyebrow: 'System', title: 'Settings', sub: 'Edition, security, retention and platform maintenance.', actions: refreshButton() })}
${tabs.map(([key, label]) => `${label} `).join('')}
${panels[tab] || generalPanel}`;
view.querySelectorAll('[data-settings-tab]').forEach((button) => button.addEventListener('click', () => {
state.settingsTab = button.dataset.settingsTab;
renderRoute();
}));
const refreshAll = async () => {
await refreshBootstrap();
renderRoute();
};
if (tab === 'general' && canModify) {
view.querySelector('#settings-form')?.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const retention = Number(formData.get('retention_days'));
if (!Number.isFinite(retention)) { toast('Enter a retention period', 'warn'); return; }
try {
await put('/settings', {
site_name: String(formData.get('site_name') || ''),
retention_days: retention,
alert_webhook: String(formData.get('alert_webhook') || ''),
});
toast('Settings saved');
await refreshAll();
} catch (error) { toastError(error); }
});
view.querySelector('[data-reseed]')?.addEventListener('click', async () => {
const ok = await confirmDialog({
title: 'Re-seed demo data',
message: 'This deletes every asset, sample, alert, policy and audit entry, then installs the demo fleet again. API keys and users are preserved. Continue?',
confirmLabel: 'Re-seed installation',
danger: true,
});
if (!ok) return;
try {
const result = await post('/admin/reseed');
toast(`${result.assets} assets restored`, 'ok', 'Demo data re-seeded');
await refreshAll();
} catch (error) { toastError(error); }
});
}
if (tab === 'license') {
view.querySelector('#enterprise-toggle')?.addEventListener('change', async (event) => {
if (!(state.boot.user && state.boot.user.role === 'admin')) {
event.target.checked = !event.target.checked;
return;
}
try {
await post('/license/enterprise', { enabled: event.target.checked });
toast(event.target.checked ? 'Enterprise mode enabled' : 'Enterprise mode disabled', 'ok');
await refreshAll();
} catch (error) {
toastError(error);
await refreshAll();
}
});
view.querySelector('#license-form')?.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const key = String(formData.get('key') || '').trim();
if (!key) { toast('Paste a license key first', 'warn'); return; }
try {
await post('/license/activate', { key });
toast('License activated. Enterprise features are unlocked.', 'ok', 'Edition upgraded');
await refreshAll();
} catch (error) { toastError(error); }
});
view.querySelector('[data-start-trial]')?.addEventListener('click', async (event) => {
const button = event.currentTarget;
button.disabled = true;
try {
await post('/license/trial');
toast('30-day Enterprise trial started', 'ok', 'Trial active');
await refreshAll();
} catch (error) { button.disabled = false; toastError(error); }
});
view.querySelector('[data-deactivate-license]')?.addEventListener('click', async () => {
const ok = await confirmDialog({
title: 'Deactivate license',
message: 'The installation returns to the Community edition. Existing data stays, but Enterprise features become unavailable immediately.',
confirmLabel: 'Deactivate',
danger: true,
});
if (!ok) return;
try {
await del('/license');
toast('License deactivated');
await refreshAll();
} catch (error) { toastError(error); }
});
view.querySelector('#dev-license-form')?.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(event.target);
try {
const result = await post('/license/dev-issue', {
customer: String(formData.get('customer') || 'Homelab'),
days: Number(formData.get('days') || 365),
});
openModal({
title: 'Development license issued',
sub: `${esc(result.customer)} · ${esc(String(result.days))} days`,
body: `${icon('key')}
This key is signed for this installation only .
${esc(result.key)} `,
footer: `${icon('copy')} Copy ${icon('check')} Activate now Close `,
onMount(modal, close) {
modal.querySelector('[data-copy-dev-key]').addEventListener('click', () => copyText(result.key));
modal.querySelector('[data-activate-dev-key]').addEventListener('click', async () => {
try {
await post('/license/activate', { key: result.key });
close();
toast('Development license activated', 'ok', 'Enterprise');
await refreshAll();
} catch (error) { toastError(error); }
});
},
});
} catch (error) { toastError(error); }
});
}
if (tab === 'security') {
view.querySelector('#password-form')?.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const next = String(formData.get('new_password') || '');
if (next !== String(formData.get('confirm_password') || '')) {
toast('New passwords do not match', 'warn');
return;
}
try {
await put('/auth/password', {
current_password: String(formData.get('current_password') || ''),
new_password: next,
});
event.target.reset();
toast('Password updated');
} catch (error) { toastError(error); }
});
view.querySelector('[data-goto-api-keys]')?.addEventListener('click', () => {
state.apiTab = 'keys';
location.hash = '#/api';
});
}
if (tab === 'audit' && isAdmin) {
view.querySelector('[data-audit-export]')?.addEventListener('click', async () => {
try {
const csv = await request('/export/audit.csv');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'headroom-audit.csv';
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
toast('Audit log exported');
} catch (error) { toastError(error); }
});
}
};
init();