feat(client): upgrade Dashboard, Charts & Server Detail views for v1.1

This commit is contained in:
tyuXX 2026-11-28 05:16:46 +00:00
parent 3a28a2332f
commit c003afa9df
4 changed files with 578 additions and 47 deletions

View file

@ -163,8 +163,10 @@
<input id="srv-tags" name="tags" placeholder="prod, web"> <input id="srv-tags" name="tags" placeholder="prod, web">
</div> </div>
</div> </div>
<p id="srv-test-msg" class="form-msg" aria-live="polite"></p>
<p id="srv-reg-err" class="form-msg err-text" aria-live="polite"></p> <p id="srv-reg-err" class="form-msg err-text" aria-live="polite"></p>
<div class="dialog-actions"> <div class="dialog-actions">
<button id="srv-test-conn-btn" type="button" class="btn mutating-action">Test Connection</button>
<button id="srv-reg-cancel" type="button" class="btn">Cancel</button> <button id="srv-reg-cancel" type="button" class="btn">Cancel</button>
<button type="submit" class="btn btn-primary mutating-action">Register Server</button> <button type="submit" class="btn btn-primary mutating-action">Register Server</button>
</div> </div>

View file

@ -97,3 +97,44 @@ export function createRangeChartSvg(
svg.appendChild(poly); svg.appendChild(poly);
return svg; return svg;
} }
export function createDualRangeChartSvg(
seriesA: number[],
seriesB: number[],
options: { colorA?: string; colorB?: string; maxVal?: number } = {},
): SVGSVGElement {
const computedMax =
options.maxVal ??
Math.max(
1,
...seriesA.map((v) => (Number.isFinite(v) ? v : 0)),
...seriesB.map((v) => (Number.isFinite(v) ? v : 0)),
);
const svg = document.createElementNS(SVG_NS, 'svg');
svg.setAttribute('viewBox', '0 0 600 120');
svg.setAttribute('preserveAspectRatio', 'none');
svg.setAttribute('class', 'chart-svg');
const midLine = document.createElementNS(SVG_NS, 'line');
midLine.setAttribute('x1', '0');
midLine.setAttribute('y1', '60');
midLine.setAttribute('x2', '600');
midLine.setAttribute('y2', '60');
midLine.setAttribute('stroke', 'var(--border)');
midLine.setAttribute('stroke-dasharray', '4 4');
svg.appendChild(midLine);
const addLine = (vals: number[], stroke: string) => {
const poly = document.createElementNS(SVG_NS, 'polyline');
poly.setAttribute('fill', 'none');
poly.setAttribute('stroke', stroke);
poly.setAttribute('stroke-width', '2');
poly.setAttribute('points', buildPolylinePoints(vals, 600, 120, 0, computedMax));
svg.appendChild(poly);
};
addLine(seriesA, options.colorA ?? 'var(--accent)');
addLine(seriesB, options.colorB ?? 'var(--warn)');
return svg;
}

View file

@ -21,8 +21,11 @@ import {
type ClientState, type ClientState,
type ServerEntry, type ServerEntry,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
const sparkHistory = new Map<string, number[]>(); const sparkHistory = new Map<string, number[]>();
let fleetFilter: 'all' | 'connected' | 'issues' = 'all';
let fleetSearch = '';
function statusBadgeClass(status: string): string { function statusBadgeClass(status: string): string {
if (status === 'connected') return 'badge badge-ok'; if (status === 'connected') return 'badge badge-ok';
@ -65,11 +68,18 @@ function renderProbesInto(container: Element, probes: ProbeSample[]): void {
container.replaceChildren(); container.replaceChildren();
if (probes.length === 0) return; if (probes.length === 0) return;
for (const p of probes) { for (const p of probes) {
const tlsNote =
p.certExpiryDays !== undefined ? ` TLS:${p.certExpiryDays}d` : '';
const cls = !p.ok || (p.certExpiryDays !== undefined && p.certExpiryDays <= 0)
? 'badge-err'
: p.certExpiryDays !== undefined && p.certExpiryDays <= 14
? 'badge-warn'
: 'badge-ok';
container.append( container.append(
el( el(
'span', 'span',
{ class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` }, { class: `badge ${cls}` },
`${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}`, `${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}${tlsNote}`,
), ),
); );
} }
@ -123,6 +133,7 @@ export function patchDashboardServerStates(states: ServerRuntimeState[]): boolea
badge.textContent = `[${st.status.toUpperCase()}]`; badge.textContent = `[${st.status.toUpperCase()}]`;
badge.className = statusBadgeClass(st.status); badge.className = statusBadgeClass(st.status);
} }
card.setAttribute('data-status', st.status);
const osBadge = card.querySelector('[data-field="os"]'); const osBadge = card.querySelector('[data-field="os"]');
if (osBadge && st.osDetected) { if (osBadge && st.osDetected) {
osBadge.textContent = st.osDetected; osBadge.textContent = st.osDetected;
@ -142,12 +153,16 @@ async function openRegisterServerDialog(
const form = document.getElementById('dialog-srv-form') as HTMLFormElement; const form = document.getElementById('dialog-srv-form') as HTMLFormElement;
const credSelect = document.getElementById('srv-cred') as HTMLSelectElement; const credSelect = document.getElementById('srv-cred') as HTMLSelectElement;
const jumpSelect = document.getElementById('srv-jump') as HTMLSelectElement; const jumpSelect = document.getElementById('srv-jump') as HTMLSelectElement;
const testMsgEl = document.getElementById('srv-test-msg') as HTMLElement;
const errEl = document.getElementById('srv-reg-err') as HTMLElement; const errEl = document.getElementById('srv-reg-err') as HTMLElement;
const testBtn = document.getElementById('srv-test-conn-btn') as HTMLButtonElement;
const closeBtn = document.getElementById('srv-reg-close') as HTMLButtonElement; const closeBtn = document.getElementById('srv-reg-close') as HTMLButtonElement;
const cancelBtn = document.getElementById('srv-reg-cancel') as HTMLButtonElement; const cancelBtn = document.getElementById('srv-reg-cancel') as HTMLButtonElement;
form.reset(); form.reset();
errEl.textContent = ''; errEl.textContent = '';
testMsgEl.textContent = '';
testMsgEl.className = 'form-msg';
credSelect.replaceChildren(); credSelect.replaceChildren();
try { try {
@ -174,8 +189,69 @@ async function openRegisterServerDialog(
jumpSelect.append(el('option', { value: s.config.id }, `${s.config.id} (${s.config.host})`)); jumpSelect.append(el('option', { value: s.config.id }, `${s.config.id} (${s.config.host})`));
} }
const buildPayload = () => {
const fd = new FormData(form);
const id = String(fd.get('id') ?? '').trim();
const tagsRaw = String(fd.get('tags') ?? '');
const tags = tagsRaw
.split(',')
.map((t) => t.trim())
.filter(Boolean);
return {
id,
name: String(fd.get('name') ?? id).trim(),
host: String(fd.get('host') ?? '').trim(),
port: Number(fd.get('port') ?? 22),
username: String(fd.get('username') ?? '').trim(),
credentialId: String(fd.get('credentialId') ?? '').trim(),
jumpHostId: String(fd.get('jumpHostId') ?? '').trim() || undefined,
osHint: String(fd.get('osHint') ?? 'auto'),
pollIntervalSec: Number(fd.get('pollIntervalSec') ?? 10),
tags,
};
};
const onTestConn = async () => {
errEl.textContent = '';
testBtn.disabled = true;
testMsgEl.className = 'form-msg muted';
testMsgEl.textContent = 'Testing SSH handshake...';
try {
const payload = buildPayload();
const res = await apiFetch<{
ok: boolean;
latencyMs: number;
osDetected?: string;
hostFingerprint?: string;
tofuRequired?: boolean;
hostKeyMismatch?: { expectedFingerprint: string; actualFingerprint: string };
error?: string;
}>('/api/servers/test-connection', {
method: 'POST',
body: payload,
});
if (res.ok) {
testMsgEl.className = 'form-msg ok-text';
testMsgEl.textContent = `Connected in ${Math.round(res.latencyMs)}ms (${res.osDetected ?? 'unknown OS'})${res.hostFingerprint ? ` · fp ${res.hostFingerprint}` : ''}`;
} else {
testMsgEl.className = res.hostKeyMismatch ? 'form-msg err-text' : 'form-msg warn-text';
testMsgEl.textContent = res.hostKeyMismatch
? `HOST KEY MISMATCH: ${res.hostKeyMismatch.actualFingerprint}`
: res.tofuRequired
? `TOFU required (${res.hostFingerprint ?? 'unknown fingerprint'}): ${res.error ?? 'save then approve TOFU'}`
: res.error ?? 'Connection test failed';
}
} catch (err) {
testMsgEl.className = 'form-msg err-text';
testMsgEl.textContent = extractErrorMessage(err);
} finally {
testBtn.disabled = false;
}
};
const cleanup = () => { const cleanup = () => {
form.removeEventListener('submit', onSubmit); form.removeEventListener('submit', onSubmit);
testBtn.removeEventListener('click', onTestConn);
closeBtn.removeEventListener('click', onClose); closeBtn.removeEventListener('click', onClose);
cancelBtn.removeEventListener('click', onClose); cancelBtn.removeEventListener('click', onClose);
dialog.removeEventListener('close', onDialogClose); dialog.removeEventListener('close', onDialogClose);
@ -190,34 +266,18 @@ async function openRegisterServerDialog(
const onSubmit = async (ev: Event) => { const onSubmit = async (ev: Event) => {
ev.preventDefault(); ev.preventDefault();
errEl.textContent = ''; errEl.textContent = '';
const fd = new FormData(form); const payload = buildPayload();
const id = String(fd.get('id') ?? '').trim();
const tagsRaw = String(fd.get('tags') ?? '');
const tags = tagsRaw
.split(',')
.map((t) => t.trim())
.filter(Boolean);
try { try {
await apiFetch('/api/servers', { await apiFetch('/api/servers', {
method: 'POST', method: 'POST',
body: { body: payload,
id,
name: String(fd.get('name') ?? id).trim(),
host: String(fd.get('host') ?? '').trim(),
port: Number(fd.get('port') ?? 22),
username: String(fd.get('username') ?? '').trim(),
credentialId: String(fd.get('credentialId') ?? '').trim(),
jumpHostId: String(fd.get('jumpHostId') ?? '').trim() || undefined,
osHint: String(fd.get('osHint') ?? 'auto'),
pollIntervalSec: Number(fd.get('pollIntervalSec') ?? 10),
tags,
},
}); });
await apiFetch(`/api/servers/${encodeURIComponent(id)}/reconnect`, { await apiFetch(`/api/servers/${encodeURIComponent(payload.id)}/reconnect`, {
method: 'POST', method: 'POST',
}).catch(() => undefined); }).catch(() => undefined);
if (dialog.open) dialog.close(); if (dialog.open) dialog.close();
showToast(`Server "${payload.id}" registered.`, 'ok');
await onRegistered(); await onRegistered();
} catch (err) { } catch (err) {
errEl.textContent = extractErrorMessage(err); errEl.textContent = extractErrorMessage(err);
@ -225,12 +285,106 @@ async function openRegisterServerDialog(
}; };
form.addEventListener('submit', onSubmit); form.addEventListener('submit', onSubmit);
testBtn.addEventListener('click', onTestConn);
closeBtn.addEventListener('click', onClose); closeBtn.addEventListener('click', onClose);
cancelBtn.addEventListener('click', onClose); cancelBtn.addEventListener('click', onClose);
dialog.addEventListener('close', onDialogClose); dialog.addEventListener('close', onDialogClose);
dialog.showModal(); dialog.showModal();
} }
async function openImportSshConfigDialog(onImported: () => Promise<void>): Promise<void> {
const dlg = el('dialog', { class: 'dialog-wide', 'aria-labelledby': 'imp-ssh-title' });
const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close');
const credSelect = el('select', { class: 'input-sm' });
const textarea = el('textarea', {
rows: 8,
class: 'code-editor',
placeholder: 'Host prod-web\n HostName 10.0.1.12\n User ops\n Port 22',
}) as HTMLTextAreaElement;
const msgEl = el('p', { class: 'form-msg' });
const previewBox = el('div', { class: 'stack' });
const previewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Preview');
const applyBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Import Hosts');
try {
const creds = await apiFetch<{ credentials: Array<{ id: string; type: string }> }>('/api/vault/credentials');
for (const c of creds.credentials.filter((x) => x.type === 'ssh-key' || x.type === 'ssh-password')) {
credSelect.append(el('option', { value: c.id }, `${c.id} (${c.type})`));
}
} catch {
// Vault may be locked or empty
}
if (credSelect.options.length === 0) {
credSelect.append(el('option', { value: '' }, 'No SSH credential (unlock Vault first)'));
}
const close = () => {
if (dlg.open) dlg.close();
dlg.remove();
};
closeBtn.addEventListener('click', close);
dlg.addEventListener('close', () => dlg.remove());
const runImport = async (apply: boolean) => {
msgEl.className = 'form-msg muted';
msgEl.textContent = apply ? 'Importing hosts...' : 'Parsing SSH config...';
previewBox.replaceChildren();
try {
const res = await apiFetch<{
entries: Array<{ alias: string; id: string; host: string; port: number; username: string; jumpHostAlias?: string }>;
warnings: string[];
createdIds: string[];
}>('/api/servers/import-ssh-config', {
method: 'POST',
body: {
configText: textarea.value,
defaultCredentialId: credSelect.value || undefined,
apply,
},
});
if (res.warnings.length > 0) {
previewBox.append(el('div', { class: 'warn-text mono' }, `Warnings: ${res.warnings.join(' | ')}`));
}
if (res.entries.length === 0) {
previewBox.append(el('div', { class: 'muted' }, 'No concrete Host blocks found.'));
} else {
for (const e of res.entries) {
previewBox.append(
el('div', { class: 'mono' }, `${e.alias} -> ${e.username}@${e.host}:${e.port}${e.jumpHostAlias ? ` (via ${e.jumpHostAlias})` : ''}`),
);
}
}
if (apply) {
msgEl.className = 'form-msg ok-text';
msgEl.textContent = `Imported ${res.createdIds.length} server(s): ${res.createdIds.join(', ')}`;
showToast(`Imported ${res.createdIds.length} server(s) from SSH config.`, 'ok');
close();
await onImported();
} else {
msgEl.className = 'form-msg ok-text';
msgEl.textContent = `Previewed ${res.entries.length} host(s).`;
}
} catch (err) {
msgEl.className = 'form-msg err-text';
msgEl.textContent = extractErrorMessage(err);
}
};
previewBtn.addEventListener('click', () => void runImport(false));
applyBtn.addEventListener('click', () => void runImport(true));
dlg.append(
el('div', { class: 'row-between' }, el('h1', { id: 'imp-ssh-title' }, 'Import OpenSSH Config'), closeBtn),
el('div', { class: 'row' }, el('label', {}, 'Default SSH Credential:'), credSelect),
textarea,
msgEl,
previewBox,
el('div', { class: 'dialog-actions' }, previewBtn, applyBtn),
);
document.body.append(dlg);
dlg.showModal();
}
export async function renderDashboardView( export async function renderDashboardView(
root: HTMLElement, root: HTMLElement,
state: ClientState, state: ClientState,
@ -303,18 +457,90 @@ export async function renderDashboardView(
void renderDashboardView(root, state); void renderDashboardView(root, state);
}); });
const importSshBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm mutating-action' },
'Import SSH Config',
);
importSshBtn.addEventListener('click', () => {
void openImportSshConfigDialog(() => renderDashboardView(root, state));
});
const connCount = servers.filter((s) => s.runtime.status === 'connected').length;
const issueCount = servers.length - connCount;
const vaultSummary = !state.vaultRuntimeReady const vaultSummary = !state.vaultRuntimeReady
? 'Vault: sealed (master key required)' ? 'Vault: sealed (master key required)'
: state.vaultState === 'unlocked' : state.vaultState === 'unlocked'
? 'Vault: unlocked (editable)' ? 'Vault: unlocked (editable)'
: 'Vault: locked (collectors & secrets active)'; : 'Vault: locked (collectors & secrets active)';
const filterSearchInput = el('input', {
type: 'search',
class: 'input-sm',
placeholder: 'Filter host / tag / name...',
value: fleetSearch,
'aria-label': 'Filter servers',
}) as HTMLInputElement;
const filterButtons = (['all', 'connected', 'issues'] as const).map((mode) => {
const label =
mode === 'all'
? `All (${servers.length})`
: mode === 'connected'
? `Connected (${connCount})`
: `Issues (${issueCount})`;
const b = el(
'button',
{ type: 'button', class: `btn btn-sm${fleetFilter === mode ? ' btn-primary' : ''}` },
label,
);
b.addEventListener('click', () => {
fleetFilter = mode;
applyFleetFilter();
for (const btn of filterButtons) btn.classList.remove('btn-primary');
b.classList.add('btn-primary');
});
return b;
});
const applyFleetFilter = () => {
const q = fleetSearch.trim().toLowerCase();
for (const card of root.querySelectorAll('[data-server-card]')) {
const st = card.getAttribute('data-status') ?? '';
const hay = card.getAttribute('data-search') ?? '';
const matchMode =
fleetFilter === 'all'
? true
: fleetFilter === 'connected'
? st === 'connected'
: st !== 'connected';
const matchQ = !q || hay.includes(q);
(card as HTMLElement).hidden = !(matchMode && matchQ);
}
};
filterSearchInput.addEventListener('input', () => {
fleetSearch = filterSearchInput.value;
applyFleetFilter();
});
root.append( root.append(
el( el(
'div', 'div',
{ class: 'panel row-between' }, { class: 'panel stack' },
el('div', {}, el('h1', {}, `Fleet Monitor (${servers.length} servers)`), el('span', { class: 'muted' }, vaultSummary)), el(
el('div', { class: 'row' }, registerBtn, rotateFleetBtn, refreshBtn), 'div',
{ class: 'row-between' },
el('div', {}, el('h1', {}, `Fleet Monitor (${connCount}/${servers.length} connected)`), el('span', { class: 'muted' }, vaultSummary)),
el('div', { class: 'row' }, registerBtn, importSshBtn, rotateFleetBtn, refreshBtn),
),
el(
'div',
{ class: 'row-between' },
el('div', { class: 'row' }, ...filterButtons),
filterSearchInput,
),
), ),
actionStatus, actionStatus,
); );
@ -523,7 +749,12 @@ export async function renderDashboardView(
const card = el( const card = el(
'article', 'article',
{ class: 'panel panel-region', 'data-server-card': config.id }, {
class: 'panel panel-region',
'data-server-card': config.id,
'data-status': runtime.status,
'data-search': `${config.id} ${config.name} ${config.host} ${config.tags.join(' ')}`.toLowerCase(),
},
el( el(
'div', 'div',
{ class: 'row-between' }, { class: 'row-between' },
@ -568,4 +799,5 @@ export async function renderDashboardView(
grid.append(card); grid.append(card);
} }
root.append(grid); root.append(grid);
applyFleetFilter();
} }

View file

@ -1,19 +1,23 @@
import type { DiskSample, ProbeSample } from '../../../shared/ws-protocol.js'; import type { DiskSample, ProbeSample } from '../../../shared/ws-protocol.js';
import { apiFetch } from '../api.js'; import { apiFetch } from '../api.js';
import { createRangeChartSvg } from '../charts.js'; import { createDualRangeChartSvg, createRangeChartSvg } from '../charts.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { import {
el, el,
extractErrorMessage, extractErrorMessage,
fmtBytesPerSec,
fmtTime, fmtTime,
type ServerEntry, type ServerEntry,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
type DetailTab = 'metrics' | 'inspector' | 'keys' | 'tunnels'; type DetailTab = 'metrics' | 'inspector' | 'keys' | 'tunnels';
let activeTab: DetailTab = 'metrics'; let activeTab: DetailTab = 'metrics';
let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h'; let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h';
let procSortBy: 'cpu' | 'mem' = 'cpu'; let procSortBy: 'cpu' | 'mem' = 'cpu';
let inspectSudo = false;
let showAllKnownHosts = false;
export async function renderServerDetailView( export async function renderServerDetailView(
root: HTMLElement, root: HTMLElement,
@ -37,6 +41,36 @@ export async function renderServerDetailView(
} }
const header = el('section', { class: 'panel' }); const header = el('section', { class: 'panel' });
const testConnBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm mutating-action' },
'Test SSH',
);
testConnBtn.addEventListener('click', async () => {
testConnBtn.disabled = true;
try {
const res = await apiFetch<{
ok: boolean;
latencyMs: number;
osDetected?: string;
hostFingerprint?: string;
error?: string;
}>('/api/servers/test-connection', {
method: 'POST',
body: entry.config,
});
if (res.ok) {
showToast(`SSH OK in ${Math.round(res.latencyMs)}ms (${res.osDetected ?? 'unknown'})`, 'ok');
} else {
showToast(`SSH test failed: ${res.error ?? 'unknown error'}`, 'err');
}
} catch (err) {
showToast(extractErrorMessage(err), 'err');
} finally {
testConnBtn.disabled = false;
}
});
const reconnBtn = el( const reconnBtn = el(
'button', 'button',
{ type: 'button', class: 'btn btn-sm mutating-action' }, { type: 'button', class: 'btn btn-sm mutating-action' },
@ -110,6 +144,7 @@ export async function renderServerDetailView(
'div', 'div',
{ class: 'row' }, { class: 'row' },
el('span', { class: 'badge' }, `[${entry.runtime.status.toUpperCase()}]`), el('span', { class: 'badge' }, `[${entry.runtime.status.toUpperCase()}]`),
testConnBtn,
reconnBtn, reconnBtn,
delBtn, delBtn,
el('a', { href: '#dashboard', class: 'btn btn-sm' }, '← Dashboard'), el('a', { href: '#dashboard', class: 'btn btn-sm' }, '← Dashboard'),
@ -127,7 +162,7 @@ export async function renderServerDetailView(
} else if (activeTab === 'inspector') { } else if (activeTab === 'inspector') {
await renderInspectorTab(body, serverId); await renderInspectorTab(body, serverId);
} else if (activeTab === 'keys') { } else if (activeTab === 'keys') {
await renderKeysTab(body, serverId); await renderKeysTab(body, serverId, `${entry.config.host}:${entry.config.port}`);
} else { } else {
const { renderTunnelsPanel } = await import('./tunnels-panel.js'); const { renderTunnelsPanel } = await import('./tunnels-panel.js');
await renderTunnelsPanel(body, serverId); await renderTunnelsPanel(body, serverId);
@ -135,13 +170,20 @@ export async function renderServerDetailView(
} }
async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<void> { async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<void> {
const data = await apiFetch<{ const [data, probeHistRes] = await Promise.all([
range: string; apiFetch<{
granularity: 'raw' | '1h' | '1d'; range: string;
points: Array<Record<string, number>>; granularity: 'raw' | '1h' | '1d';
latestDisks: DiskSample[]; points: Array<Record<string, number>>;
latestProbes: Array<ProbeSample & { ts: number }>; latestDisks: DiskSample[];
}>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`); latestProbes: Array<ProbeSample & { ts: number }>;
probeHistory?: Array<ProbeSample & { ts: number }>;
diskHistory?: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>;
}>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`),
apiFetch<{ samples: Array<ProbeSample & { ts: number }> }>(
`/api/servers/${encodeURIComponent(serverId)}/probes/history?range=${activeRange}`,
).catch(() => ({ samples: [] })),
]);
const rangeBar = el( const rangeBar = el(
'div', 'div',
@ -173,6 +215,22 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
return p.memTotalMb ? ((p.memUsedMb ?? 0) / p.memTotalMb) * 100 : 0; return p.memTotalMb ? ((p.memUsedMb ?? 0) / p.memTotalMb) * 100 : 0;
}); });
const loadSeries = data.points.map((p) => p.load1m ?? p.loadMax ?? 0); const loadSeries = data.points.map((p) => p.load1m ?? p.loadMax ?? 0);
const netRxSeries = data.points.map((p) => p.netRxBps ?? p.netRxAvgBps ?? 0);
const netTxSeries = data.points.map((p) => p.netTxBps ?? p.netTxAvgBps ?? 0);
const diskMaxByTs = new Map<number, number>();
for (const d of data.diskHistory ?? []) {
const prev = diskMaxByTs.get(d.ts) ?? 0;
if (d.usedPct > prev) diskMaxByTs.set(d.ts, d.usedPct);
}
const diskSeries = data.points.some((p) => p.diskMaxPct !== undefined)
? data.points.map((p) => p.diskMaxPct ?? 0)
: [...diskMaxByTs.entries()].sort((a, b) => a[0] - b[0]).map((x) => x[1]);
const probeHistory = probeHistRes.samples.length > 0 ? probeHistRes.samples : (data.probeHistory ?? []);
const probeLatencySeries = probeHistory.map((p) => p.latencyMs ?? 0);
const lastRx = netRxSeries.at(-1) ?? 0;
const lastTx = netTxSeries.at(-1) ?? 0;
const chartsGrid = el( const chartsGrid = el(
'div', 'div',
@ -180,6 +238,25 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
el('div', { class: 'panel' }, el('h2', {}, 'CPU %'), createRangeChartSvg(cpuSeries, { maxVal: 100 })), el('div', { class: 'panel' }, el('h2', {}, 'CPU %'), createRangeChartSvg(cpuSeries, { maxVal: 100 })),
el('div', { class: 'panel' }, el('h2', {}, 'Memory %'), createRangeChartSvg(memSeries, { maxVal: 100, color: 'var(--ok)' })), el('div', { class: 'panel' }, el('h2', {}, 'Memory %'), createRangeChartSvg(memSeries, { maxVal: 100, color: 'var(--ok)' })),
el('div', { class: 'panel' }, el('h2', {}, 'Load Average (1m)'), createRangeChartSvg(loadSeries, { color: 'var(--warn)' })), el('div', { class: 'panel' }, el('h2', {}, 'Load Average (1m)'), createRangeChartSvg(loadSeries, { color: 'var(--warn)' })),
el(
'div',
{ class: 'panel' },
el('h2', {}, 'Net I/O (RX / TX)'),
el('div', { class: 'muted mono' }, `RX ${fmtBytesPerSec(lastRx)} | TX ${fmtBytesPerSec(lastTx)}`),
createDualRangeChartSvg(netRxSeries, netTxSeries, { colorA: 'var(--accent)', colorB: 'var(--warn)' }),
),
el(
'div',
{ class: 'panel' },
el('h2', {}, 'Max Disk %'),
createRangeChartSvg(diskSeries, { maxVal: 100, color: 'var(--err)' }),
),
el(
'div',
{ class: 'panel' },
el('h2', {}, 'Probe Latency (ms)'),
createRangeChartSvg(probeLatencySeries, { color: 'var(--ok)' }),
),
); );
body.append(chartsGrid); body.append(chartsGrid);
@ -202,16 +279,82 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
diskPanel.append(el('div', { class: 'table-wrap' }, dTable)); diskPanel.append(el('div', { class: 'table-wrap' }, dTable));
body.append(diskPanel); body.append(diskPanel);
// Probes table // Probes table + Run Now + Probe History summary
const probePanel = el('section', { class: 'panel' }); const probePanel = el('section', { class: 'panel' });
probePanel.append(el('h2', {}, 'Endpoint Health Probes')); const okProbes = probeHistory.filter((p) => p.ok).length;
const failProbes = probeHistory.length - okProbes;
probePanel.append(
el(
'div',
{ class: 'row-between' },
el('h2', {}, 'Endpoint Health Probes'),
el(
'span',
{ class: 'muted mono' },
probeHistory.length > 0 ? `${probeHistory.length} checks (${okProbes} ok / ${failProbes} fail in ${activeRange})` : 'No probe history in range',
),
),
);
const pTable = el('table'); const pTable = el('table');
pTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Probe ID'), el('th', {}, 'Status'), el('th', {}, 'HTTP Code'), el('th', {}, 'Latency'), el('th', {}, 'Checked At'), el('th', {}, 'Detail')))); pTable.append(
el(
'thead',
{},
el(
'tr',
{},
el('th', {}, 'Probe ID'),
el('th', {}, 'Status'),
el('th', {}, 'HTTP Code'),
el('th', {}, 'Latency'),
el('th', {}, 'TLS Expiry'),
el('th', {}, 'Checked At'),
el('th', {}, 'Detail'),
el('th', {}, 'Action'),
),
),
);
const pBody = el('tbody'); const pBody = el('tbody');
if (data.latestProbes.length === 0) { if (data.latestProbes.length === 0) {
pBody.append(el('tr', {}, el('td', { colspan: 6, class: 'muted' }, 'No probe results recorded yet.'))); pBody.append(el('tr', {}, el('td', { colspan: 8, class: 'muted' }, 'No probe results recorded yet.')));
} else { } else {
for (const p of data.latestProbes) { for (const p of data.latestProbes) {
const tlsBadge =
p.certExpiryDays !== undefined
? el(
'span',
{
class: `badge ${
p.certExpiryDays <= 0
? 'badge-err'
: p.certExpiryDays <= 14
? 'badge-warn'
: 'badge-ok'
}`,
},
`${p.certExpiryDays}d`,
)
: el('span', { class: 'muted' }, '—');
const runBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Run Now');
runBtn.addEventListener('click', async () => {
runBtn.disabled = true;
try {
const runRes = await apiFetch<{ sample: ProbeSample }>(
`/api/servers/${encodeURIComponent(serverId)}/probes/${encodeURIComponent(p.probeId)}/run`,
{ method: 'POST', body: {} },
);
showToast(
`Probe "${p.probeId}": ${runRes.sample.ok ? `OK (${Math.round(runRes.sample.latencyMs)}ms)` : runRes.sample.error ?? 'FAIL'}`,
runRes.sample.ok ? 'ok' : 'err',
);
body.replaceChildren();
await renderMetricsTab(body, serverId);
} catch (err) {
showToast(extractErrorMessage(err), 'err');
} finally {
runBtn.disabled = false;
}
});
pBody.append( pBody.append(
el( el(
'tr', 'tr',
@ -220,8 +363,10 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
el('td', {}, el('span', { class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` }, p.ok ? 'OK' : 'FAIL')), el('td', {}, el('span', { class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` }, p.ok ? 'OK' : 'FAIL')),
el('td', { class: 'mono' }, p.statusCode ? String(p.statusCode) : '—'), el('td', { class: 'mono' }, p.statusCode ? String(p.statusCode) : '—'),
el('td', { class: 'mono' }, `${Math.round(p.latencyMs)} ms`), el('td', { class: 'mono' }, `${Math.round(p.latencyMs)} ms`),
el('td', {}, tlsBadge),
el('td', { class: 'mono' }, fmtTime(p.ts)), el('td', { class: 'mono' }, fmtTime(p.ts)),
el('td', { class: 'mono err-text' }, p.error ?? '—'), el('td', { class: 'mono err-text' }, p.error ?? '—'),
el('td', {}, runBtn),
), ),
); );
} }
@ -234,6 +379,11 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<void> { async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<void> {
const sortCpuBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'cpu' ? ' btn-primary' : ''}` }, 'Sort CPU'); const sortCpuBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'cpu' ? ' btn-primary' : ''}` }, 'Sort CPU');
const sortMemBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'mem' ? ' btn-primary' : ''}` }, 'Sort RAM'); const sortMemBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'mem' ? ' btn-primary' : ''}` }, 'Sort RAM');
const sudoBtn = el(
'button',
{ type: 'button', class: `btn btn-sm mutating-action${inspectSudo ? ' btn-primary' : ''}` },
inspectSudo ? 'Sudo: ON' : '+Sudo',
);
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh Snapshot'); const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh Snapshot');
sortCpuBtn.addEventListener('click', () => { sortCpuBtn.addEventListener('click', () => {
@ -246,13 +396,18 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<
body.replaceChildren(); body.replaceChildren();
void renderInspectorTab(body, serverId); void renderInspectorTab(body, serverId);
}); });
sudoBtn.addEventListener('click', () => {
inspectSudo = !inspectSudo;
body.replaceChildren();
void renderInspectorTab(body, serverId);
});
refreshBtn.addEventListener('click', () => { refreshBtn.addEventListener('click', () => {
body.replaceChildren(); body.replaceChildren();
void renderInspectorTab(body, serverId); void renderInspectorTab(body, serverId);
}); });
body.append( body.append(
el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, refreshBtn)), el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, sudoBtn, refreshBtn)),
); );
try { try {
@ -262,18 +417,53 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<
processes: Array<{ pid: number; user: string; cpuPct: number; memPct: number; rssMb: number; command: string }>; processes: Array<{ pid: number; user: string; cpuPct: number; memPct: number; rssMb: number; command: string }>;
ports: Array<{ proto: string; localAddress: string; process: string }>; ports: Array<{ proto: string; localAddress: string; process: string }>;
thermals: Array<{ zone: string; tempC: number }>; thermals: Array<{ zone: string; tempC: number }>;
}>(`/api/servers/${encodeURIComponent(serverId)}/inspect`); }>(`/api/servers/${encodeURIComponent(serverId)}/inspect?sort=${procSortBy}&sudo=${inspectSudo ? 'true' : 'false'}`);
const sortedProcs = [...res.processes].sort((a, b) => const sortedProcs = [...res.processes].sort((a, b) =>
procSortBy === 'cpu' ? b.cpuPct - a.cpuPct : b.memPct - a.memPct, procSortBy === 'cpu' ? b.cpuPct - a.cpuPct : b.memPct - a.memPct,
); );
const procTable = el('table'); const procTable = el('table');
procTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'PID'), el('th', {}, 'User'), el('th', {}, 'CPU%'), el('th', {}, 'MEM%'), el('th', {}, 'RSS'), el('th', {}, 'Command')))); procTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'PID'), el('th', {}, 'User'), el('th', {}, 'CPU%'), el('th', {}, 'MEM%'), el('th', {}, 'RSS'), el('th', {}, 'Command'), el('th', {}, 'Signal'))));
const pBody = el('tbody'); const pBody = el('tbody');
for (const p of sortedProcs) { for (const p of sortedProcs) {
const makeSigBtn = (sig: 'SIGTERM' | 'SIGKILL', cls: string) => {
const b = el('button', { type: 'button', class: `btn btn-sm ${cls} mutating-action` }, sig === 'SIGTERM' ? 'TERM' : 'KILL');
b.addEventListener('click', async () => {
const ok = await confirmDialog(
'dialog-confirm',
`Send ${sig} to PID ${p.pid} (${p.command.slice(0, 48)}) on ${serverId}?`,
);
if (!ok) return;
try {
const sigRes = await apiFetch<{ ok: boolean; error?: string }>(
`/api/servers/${encodeURIComponent(serverId)}/processes/${p.pid}/signal`,
{ method: 'POST', body: { signal: sig, sudo: inspectSudo } },
);
showToast(
sigRes.ok ? `Sent ${sig} to PID ${p.pid}.` : `Signal ${sig} failed: ${sigRes.error ?? 'error'}`,
sigRes.ok ? 'ok' : 'err',
);
body.replaceChildren();
await renderInspectorTab(body, serverId);
} catch (err) {
showToast(extractErrorMessage(err), 'err');
}
});
return b;
};
pBody.append( pBody.append(
el('tr', {}, el('td', { class: 'mono' }, String(p.pid)), el('td', { class: 'mono' }, p.user), el('td', { class: 'mono' }, `${p.cpuPct}`), el('td', { class: 'mono' }, `${p.memPct}`), el('td', { class: 'mono' }, `${p.rssMb}M`), el('td', { class: 'mono' }, p.command.slice(0, 90))), el(
'tr',
{},
el('td', { class: 'mono' }, String(p.pid)),
el('td', { class: 'mono' }, p.user),
el('td', { class: 'mono' }, `${p.cpuPct}`),
el('td', { class: 'mono' }, `${p.memPct}`),
el('td', { class: 'mono' }, `${p.rssMb}M`),
el('td', { class: 'mono' }, p.command.slice(0, 90)),
el('td', {}, el('div', { class: 'row' }, makeSigBtn('SIGTERM', ''), makeSigBtn('SIGKILL', 'btn-danger'))),
),
); );
} }
procTable.append(pBody); procTable.append(pBody);
@ -306,7 +496,7 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<
} }
} }
async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void> { async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: string): Promise<void> {
const msg = el('p', { class: 'form-msg' }); const msg = el('p', { class: 'form-msg' });
const rotateBtn = el( const rotateBtn = el(
'button', 'button',
@ -330,7 +520,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void>
const r = res.results[0]; const r = res.results[0];
if (r?.ok) { if (r?.ok) {
body.replaceChildren(); body.replaceChildren();
await renderKeysTab(body, serverId); await renderKeysTab(body, serverId, hostPortKey);
} else { } else {
msg.className = 'form-msg err-text'; msg.className = 'form-msg err-text';
msg.textContent = `Rotation failed (rolledBack=${String(r?.rolledBack)}): ${r?.error ?? 'unknown'}`; msg.textContent = `Rotation failed (rolledBack=${String(r?.rolledBack)}): ${r?.error ?? 'unknown'}`;
@ -359,7 +549,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void>
body: { credentialId: deploySelect.value }, body: { credentialId: deploySelect.value },
}); });
body.replaceChildren(); body.replaceChildren();
await renderKeysTab(body, serverId); await renderKeysTab(body, serverId, hostPortKey);
} catch (err) { } catch (err) {
msg.className = 'form-msg err-text'; msg.className = 'form-msg err-text';
msg.textContent = extractErrorMessage(err); msg.textContent = extractErrorMessage(err);
@ -376,6 +566,72 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void>
msg, msg,
); );
// Known Hosts (Multi-Algo)
try {
const khRes = await apiFetch<{
knownHosts: Array<{ hostPort: string; algorithm: string; fingerprint: string; updatedAt: number }>;
}>('/api/servers/known-hosts');
const filteredKh = showAllKnownHosts
? khRes.knownHosts
: khRes.knownHosts.filter((kh) => kh.hostPort === hostPortKey);
const scopeBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm' },
showAllKnownHosts ? `Filter ${hostPortKey}` : `Show All (${khRes.knownHosts.length})`,
);
scopeBtn.addEventListener('click', () => {
showAllKnownHosts = !showAllKnownHosts;
body.replaceChildren();
void renderKeysTab(body, serverId, hostPortKey);
});
const khTable = el('table');
khTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Host:Port'), el('th', {}, 'Algorithm'), el('th', {}, 'Fingerprint'), el('th', {}, 'Updated'), el('th', {}, 'Action'))));
const khBody = el('tbody');
if (filteredKh.length === 0) {
khBody.append(el('tr', {}, el('td', { colspan: 5, class: 'muted' }, 'No trusted host keys in scope.')));
} else {
for (const kh of filteredKh) {
const delKhBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
delKhBtn.addEventListener('click', async () => {
const ok = await confirmDialog(
'dialog-confirm',
`Remove trusted ${kh.algorithm} key for ${kh.hostPort}? Next connection will require TOFU approval.`,
);
if (!ok) return;
await apiFetch(
`/api/servers/known-hosts?hostPort=${encodeURIComponent(kh.hostPort)}&algorithm=${encodeURIComponent(kh.algorithm)}`,
{ method: 'DELETE' },
);
showToast(`Deleted ${kh.algorithm} key for ${kh.hostPort}.`, 'ok');
body.replaceChildren();
await renderKeysTab(body, serverId, hostPortKey);
});
khBody.append(
el(
'tr',
{},
el('td', { class: 'mono' }, kh.hostPort),
el('td', { class: 'mono' }, kh.algorithm),
el('td', { class: 'mono' }, kh.fingerprint),
el('td', { class: 'mono' }, fmtTime(kh.updatedAt)),
el('td', {}, delKhBtn),
),
);
}
}
khTable.append(khBody);
body.append(
el(
'section',
{ class: 'panel' },
el('div', { class: 'row-between' }, el('h2', {}, 'Trusted Host Keys (known_hosts)'), scopeBtn),
el('div', { class: 'table-wrap' }, khTable),
),
);
} catch (err) {
body.append(el('div', { class: 'panel err-text' }, extractErrorMessage(err)));
}
try { try {
const res = await apiFetch<{ const res = await apiFetch<{
entries: Array<{ entries: Array<{
@ -410,7 +666,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void>
body: { fingerprint: k.fingerprint }, body: { fingerprint: k.fingerprint },
}); });
body.replaceChildren(); body.replaceChildren();
await renderKeysTab(body, serverId); await renderKeysTab(body, serverId, hostPortKey);
}); });
} }
kBody.append( kBody.append(