feat(client): add live fleet dashboard, sparkline charts, Server Inspector, TOFU/MITM dialogs, and Key Manager UI

This commit is contained in:
tyuXX 2026-11-26 18:55:10 +00:00
parent 2d7709035b
commit 75b969f044
9 changed files with 1200 additions and 46 deletions

View file

@ -419,7 +419,75 @@ dialog::backdrop {
color: var(--err);
}
.metric-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 6px;
margin: 8px 0;
}
.metric-cell {
padding: 6px;
background: var(--bg);
border: 1px solid var(--border);
}
.metric-label {
font-size: 11px;
color: var(--fg-muted);
}
.metric-val {
font-size: 14px;
font-weight: 700;
}
.spark-svg {
display: block;
width: 100%;
height: 44px;
background: var(--bg);
border: 1px solid var(--border);
}
.chart-svg {
display: block;
width: 100%;
height: 120px;
background: var(--bg);
border: 1px solid var(--border);
}
.disk-bar {
height: 6px;
background: var(--bg);
border: 1px solid var(--border);
margin-top: 2px;
}
.disk-fill {
height: 100%;
background: var(--accent);
}
.alert-box {
border: 1px solid var(--err);
background: var(--bg-panel);
padding: 10px 12px;
margin-bottom: 12px;
}
.tofu-box {
border: 1px solid var(--warn);
background: var(--bg-panel);
padding: 10px 12px;
margin-bottom: 12px;
}
@media (max-width: 767px) {
.metric-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.grid-2,
.grid-3,
.config-layout {

View file

@ -115,6 +115,68 @@
</div>
</dialog>
<!-- Register Server Modal -->
<dialog id="dialog-server-reg" class="dialog-wide" aria-labelledby="dialog-srv-title">
<div class="row-between">
<h1 id="dialog-srv-title">Register Target Server</h1>
<button id="srv-reg-close" type="button" class="btn btn-sm">Close</button>
</div>
<form id="dialog-srv-form" class="stack">
<div class="grid-2">
<div>
<label for="srv-id">Server ID</label>
<input id="srv-id" name="id" placeholder="prod-web-01" required autofocus>
</div>
<div>
<label for="srv-name">Display Name</label>
<input id="srv-name" name="name" placeholder="Prod Web 01" required>
</div>
<div>
<label for="srv-host">Host / IP</label>
<input id="srv-host" name="host" placeholder="10.10.0.12" required>
</div>
<div>
<label for="srv-port">SSH Port</label>
<input id="srv-port" name="port" type="number" min="1" max="65535" value="22" required>
</div>
<div>
<label for="srv-user">Username</label>
<input id="srv-user" name="username" placeholder="ops" required>
</div>
<div>
<label for="srv-cred">Vault Credential ID</label>
<select id="srv-cred" name="credentialId" required></select>
</div>
<div>
<label for="srv-jump">Bastion / Jump Host (Optional)</label>
<select id="srv-jump" name="jumpHostId"></select>
</div>
<div>
<label for="srv-os">OS Hint</label>
<select id="srv-os" name="osHint">
<option value="auto">auto (uname -s)</option>
<option value="linux">linux</option>
<option value="bsd">bsd</option>
<option value="macos">macos</option>
</select>
</div>
<div>
<label for="srv-poll">Poll Interval (sec)</label>
<input id="srv-poll" name="pollIntervalSec" type="number" min="2" max="3600" value="10" required>
</div>
<div>
<label for="srv-tags">Tags (comma-separated)</label>
<input id="srv-tags" name="tags" placeholder="prod, web">
</div>
</div>
<p id="srv-reg-err" class="form-msg err-text" aria-live="polite"></p>
<div class="dialog-actions">
<button id="srv-reg-cancel" type="button" class="btn">Cancel</button>
<button type="submit" class="btn btn-primary mutating-action">Register Server</button>
</div>
</form>
</dialog>
<script type="module" src="/main.js"></script>
</body>
</html>

99
src/client/ts/charts.ts Normal file
View file

@ -0,0 +1,99 @@
const SVG_NS = 'http://www.w3.org/2000/svg';
export function maxChartPointsForViewport(): number {
return window.innerWidth < 768 ? 60 : 120;
}
function buildPolylinePoints(
values: number[],
width: number,
height: number,
minVal: number,
maxVal: number,
): string {
const cap = maxChartPointsForViewport();
const sliced = values.length > cap ? values.slice(values.length - cap) : values;
if (sliced.length === 0) return '';
if (sliced.length === 1) {
const y = computeY(sliced[0]!, height, minVal, maxVal);
return `0,${y} ${width},${y}`;
}
const span = Math.max(0.0001, maxVal - minVal);
const stepX = width / (sliced.length - 1);
return sliced
.map((v, idx) => {
const x = (idx * stepX).toFixed(1);
const norm = Math.max(0, Math.min(1, (v - minVal) / span));
const y = (height - 4 - norm * (height - 8)).toFixed(1);
return `${x},${y}`;
})
.join(' ');
}
function computeY(v: number, height: number, minVal: number, maxVal: number): string {
const span = Math.max(0.0001, maxVal - minVal);
const norm = Math.max(0, Math.min(1, (v - minVal) / span));
return (height - 4 - norm * (height - 8)).toFixed(1);
}
export function createSparklineSvg(values: number[], maxVal = 100): SVGSVGElement {
const svg = document.createElementNS(SVG_NS, 'svg');
svg.setAttribute('viewBox', '0 0 240 44');
svg.setAttribute('preserveAspectRatio', 'none');
svg.setAttribute('class', 'spark-svg');
svg.setAttribute('aria-hidden', 'true');
const poly = document.createElementNS(SVG_NS, 'polyline');
poly.setAttribute('fill', 'none');
poly.setAttribute('stroke', 'var(--accent)');
poly.setAttribute('stroke-width', '1.75');
poly.setAttribute('points', buildPolylinePoints(values, 240, 44, 0, maxVal));
svg.appendChild(poly);
return svg;
}
export function updateSparklineSvg(
svg: SVGSVGElement | null,
values: number[],
maxVal = 100,
): void {
if (!svg) return;
const poly = svg.querySelector('polyline');
if (!poly) return;
poly.setAttribute('points', buildPolylinePoints(values, 240, 44, 0, maxVal));
}
export function createRangeChartSvg(
values: number[],
options: { minVal?: number; maxVal?: number; color?: string } = {},
): SVGSVGElement {
const minVal = options.minVal ?? 0;
const computedMax =
options.maxVal ?? Math.max(1, ...values.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 poly = document.createElementNS(SVG_NS, 'polyline');
poly.setAttribute('fill', 'none');
poly.setAttribute('stroke', options.color ?? 'var(--accent)');
poly.setAttribute('stroke-width', '2');
poly.setAttribute(
'points',
buildPolylinePoints(values, 600, 120, minVal, computedMax),
);
svg.appendChild(poly);
return svg;
}

View file

@ -18,7 +18,13 @@ import {
} from './state.js';
import { renderAuthView } from './views/auth-view.js';
import { renderConfigView } from './views/config-view.js';
import {
patchDashboardServerStates,
patchDashboardServerTick,
renderDashboardView,
} from './views/dashboard-view.js';
import { renderSectionShell } from './views/section-shells.js';
import { renderServerDetailView } from './views/server-detail-view.js';
import { renderSettingsView } from './views/settings-view.js';
import { renderVaultView } from './views/vault-view.js';
import { MultiplexWsClient } from './ws-client.js';
@ -49,9 +55,14 @@ const state: ClientState = {
overview: null,
};
function currentRouteFromHash(): RouteId {
const raw = window.location.hash.replace(/^#/, '') as RouteId;
return VALID_ROUTES.has(raw) ? raw : 'dashboard';
function parseRouteFromHash(): { route: RouteId; serverId?: string } {
const raw = window.location.hash.replace(/^#/, '');
if (raw.startsWith('server/')) {
const serverId = decodeURIComponent(raw.slice('server/'.length));
if (serverId) return { route: 'server-detail', serverId };
}
const route = raw as RouteId;
return VALID_ROUTES.has(route) ? { route } : { route: 'dashboard' };
}
function updateTopBarUi(): void {
@ -85,9 +96,10 @@ function updateTopBarUi(): void {
stepupBadge.hidden = true;
}
const activeNavRoute = state.route === 'server-detail' ? 'dashboard' : state.route;
for (const link of nav.querySelectorAll('.nav-link')) {
const r = link.getAttribute('data-route');
link.classList.toggle('active', r === state.route);
link.classList.toggle('active', r === activeNavRoute);
}
const errCount = state.overview?.diagnostics.errors.length ?? 0;
@ -121,6 +133,16 @@ async function renderCurrentView(): Promise<void> {
}
const route = state.route;
if (route === 'dashboard') {
await renderDashboardView(root, state);
return;
}
if (route === 'server-detail' && state.selectedServerId) {
await renderServerDetailView(root, state.selectedServerId, () => {
window.location.hash = '#dashboard';
});
return;
}
if (route === 'config') {
await renderConfigView(root, state.overview!, async () => {
await refreshOverview();
@ -153,7 +175,9 @@ async function renderCurrentView(): Promise<void> {
return;
}
renderSectionShell(root, route, state.overview!);
if (route !== 'server-detail') {
renderSectionShell(root, route, state.overview!);
}
}
async function triggerPanicLock(): Promise<void> {
@ -205,7 +229,6 @@ async function syncStatusAndRender(): Promise<void> {
setApiSafeMode(state.safeMode);
if (state.authenticated) {
// Sync device safe mode to server session if device enforces read-only
if (deviceSafe && !status.safeMode) {
await apiFetch('/api/auth/safe-mode', {
method: 'POST',
@ -219,7 +242,9 @@ async function syncStatusAndRender(): Promise<void> {
}
async function bootstrapApp(): Promise<void> {
state.route = currentRouteFromHash();
const parsed = parseRouteFromHash();
state.route = parsed.route;
state.selectedServerId = parsed.serverId;
await syncStatusAndRender();
if (state.authenticated) {
wsClient.connect();
@ -269,6 +294,13 @@ document.addEventListener('DOMContentLoaded', () => {
void renderCurrentView();
}
});
} else if (frame.type === 'metrics:tick' && state.authenticated && state.route === 'dashboard') {
patchDashboardServerTick(frame);
} else if (frame.type === 'servers:state' && state.authenticated && state.route === 'dashboard') {
const needsRefresh = patchDashboardServerStates(frame.states);
if (needsRefresh) {
void renderCurrentView();
}
}
});
@ -309,7 +341,9 @@ document.addEventListener('DOMContentLoaded', () => {
});
window.addEventListener('hashchange', () => {
state.route = currentRouteFromHash();
const parsed = parseRouteFromHash();
state.route = parsed.route;
state.selectedServerId = parsed.serverId;
void renderCurrentView();
});

View file

@ -1,11 +1,16 @@
import type {
ConfigError,
ConfigWarning,
DiskSample,
MetricSample,
ProbeSample,
ServerRuntimeState,
VaultState,
} from '../../shared/ws-protocol.js';
export type RouteId =
| 'dashboard'
| 'server-detail'
| 'systems'
| 'terminal'
| 'sftp'
@ -38,6 +43,33 @@ export interface ConfigOverview {
settings: Record<string, unknown>;
}
export interface ServerEntry {
config: {
id: string;
name: string;
host: string;
port: number;
username: string;
credentialId: string;
jumpHostId?: string;
sudoCredentialId?: string;
tags: string[];
osHint: 'auto' | 'linux' | 'bsd' | 'macos';
pollIntervalSec: number;
probes: Array<Record<string, unknown>>;
enabled: boolean;
};
runtime: ServerRuntimeState;
telemetry: {
serverId: string;
os?: 'linux' | 'bsd' | 'macos';
sample?: MetricSample;
disks: DiskSample[];
probes: Record<string, ProbeSample>;
lastError?: string;
} | null;
}
export interface ClientState {
bootstrapped: boolean;
authenticated: boolean;
@ -48,6 +80,7 @@ export interface ClientState {
elevatedUntil: number | null;
theme: string;
route: RouteId;
selectedServerId?: string;
overview: ConfigOverview | null;
}
@ -92,6 +125,23 @@ export function fmtTime(ts: number | string | null | undefined): string {
return Number.isNaN(d.getTime()) ? '—' : d.toISOString().replace('T', ' ').slice(0, 19);
}
export function fmtBytesPerSec(bps: number): string {
if (!Number.isFinite(bps) || bps <= 0) return '0 B/s';
if (bps < 1024) return `${Math.round(bps)} B/s`;
if (bps < 1024 * 1024) return `${(bps / 1024).toFixed(1)} KB/s`;
return `${(bps / (1024 * 1024)).toFixed(2)} MB/s`;
}
export function fmtUptime(sec: number): string {
if (!Number.isFinite(sec) || sec <= 0) return '0m';
const d = Math.floor(sec / 86400);
const h = Math.floor((sec % 86400) / 3600);
const m = Math.floor((sec % 3600) / 60);
if (d > 0) return `${d}d ${h}h`;
if (h > 0) return `${h}h ${m}m`;
return `${m}m`;
}
export function extractErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}

View file

@ -0,0 +1,445 @@
import type {
DiskSample,
MetricSample,
ProbeSample,
ServerRuntimeState,
} from '../../../shared/ws-protocol.js';
import { apiFetch } from '../api.js';
import { createSparklineSvg, updateSparklineSvg } from '../charts.js';
import { confirmDialog } from '../dialogs.js';
import {
el,
extractErrorMessage,
fmtBytesPerSec,
fmtUptime,
type ClientState,
type ServerEntry,
} from '../state.js';
const sparkHistory = new Map<string, number[]>();
function statusBadgeClass(status: string): string {
if (status === 'connected') return 'badge badge-ok';
if (status === 'host_key_mismatch' || status === 'auth_error') return 'badge badge-err';
if (status === 'tofu_pending' || status === 'connecting' || status === 'vault_locked') {
return 'badge badge-warn';
}
return 'badge';
}
function pushSparkPoint(serverId: string, cpuPct: number): number[] {
const arr = sparkHistory.get(serverId) ?? [];
arr.push(cpuPct);
if (arr.length > 120) arr.shift();
sparkHistory.set(serverId, arr);
return arr;
}
function renderDisksInto(container: Element, disks: DiskSample[]): void {
container.replaceChildren();
if (disks.length === 0) {
container.append(el('span', { class: 'muted' }, 'No disk samples yet'));
return;
}
for (const d of disks.slice(0, 4)) {
const fill = el('div', { class: 'disk-fill', style: `width:${Math.min(100, d.usedPct)}%` });
container.append(
el(
'div',
{ class: 'mono' },
el('div', { class: 'row-between' }, el('span', {}, `${d.mountPoint} (${d.fsType})`), el('span', {}, `${d.usedPct}%`)),
el('div', { class: 'disk-bar' }, fill),
),
);
}
}
function renderProbesInto(container: Element, probes: ProbeSample[]): void {
container.replaceChildren();
if (probes.length === 0) return;
for (const p of probes) {
container.append(
el(
'span',
{ class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` },
`${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}`,
),
);
}
}
export function patchDashboardServerTick(tick: {
serverId: string;
sample: MetricSample;
disks: DiskSample[];
probes?: ProbeSample[];
}): void {
const card = document.querySelector(`[data-server-card="${CSS.escape(tick.serverId)}"]`);
if (!card) return;
const cpuEl = card.querySelector('[data-field="cpu"]');
const memEl = card.querySelector('[data-field="mem"]');
const loadEl = card.querySelector('[data-field="load"]');
const netEl = card.querySelector('[data-field="net"]');
const upEl = card.querySelector('[data-field="uptime"]');
const disksEl = card.querySelector('[data-field="disks"]');
const probesEl = card.querySelector('[data-field="probes"]');
const svg = card.querySelector('svg.spark-svg') as SVGSVGElement | null;
if (cpuEl) cpuEl.textContent = `${tick.sample.cpuPct.toFixed(1)}%`;
if (memEl) {
const pct =
tick.sample.memTotalMb > 0
? Math.round((tick.sample.memUsedMb / tick.sample.memTotalMb) * 100)
: 0;
memEl.textContent = `${Math.round(tick.sample.memUsedMb)}/${Math.round(tick.sample.memTotalMb)}MB (${pct}%)`;
}
if (loadEl) loadEl.textContent = tick.sample.load1m.toFixed(2);
if (netEl) {
netEl.textContent = `↓${fmtBytesPerSec(tick.sample.netRxBps)} ↑${fmtBytesPerSec(tick.sample.netTxBps)}`;
}
if (upEl) upEl.textContent = `Up ${fmtUptime(tick.sample.uptimeSec)}`;
if (disksEl) renderDisksInto(disksEl, tick.disks);
if (probesEl && tick.probes) renderProbesInto(probesEl, tick.probes);
const pts = pushSparkPoint(tick.serverId, tick.sample.cpuPct);
updateSparklineSvg(svg, pts, 100);
}
export function patchDashboardServerStates(states: ServerRuntimeState[]): boolean {
let needsFullRefresh = false;
for (const st of states) {
const card = document.querySelector(`[data-server-card="${CSS.escape(st.serverId)}"]`);
if (!card) continue;
const badge = card.querySelector('[data-field="status"]');
if (badge) {
badge.textContent = `[${st.status.toUpperCase()}]`;
badge.className = statusBadgeClass(st.status);
}
const osBadge = card.querySelector('[data-field="os"]');
if (osBadge && st.osDetected) {
osBadge.textContent = st.osDetected;
}
if (st.tofuPending || st.hostKeyMismatch) {
needsFullRefresh = true;
}
}
return needsFullRefresh;
}
async function openRegisterServerDialog(
existingServers: ServerEntry[],
onRegistered: () => Promise<void>,
): Promise<void> {
const dialog = document.getElementById('dialog-server-reg') as HTMLDialogElement;
const form = document.getElementById('dialog-srv-form') as HTMLFormElement;
const credSelect = document.getElementById('srv-cred') as HTMLSelectElement;
const jumpSelect = document.getElementById('srv-jump') as HTMLSelectElement;
const errEl = document.getElementById('srv-reg-err') as HTMLElement;
const closeBtn = document.getElementById('srv-reg-close') as HTMLButtonElement;
const cancelBtn = document.getElementById('srv-reg-cancel') as HTMLButtonElement;
form.reset();
errEl.textContent = '';
credSelect.replaceChildren();
try {
const creds = await apiFetch<{
state: string;
credentials: Array<{ id: string; name: string; type: string }>;
}>('/api/vault/credentials');
const sshCreds = creds.credentials.filter(
(c) => c.type === 'ssh-key' || c.type === 'ssh-password',
);
if (sshCreds.length === 0) {
credSelect.append(el('option', { value: 'cred-main' }, 'cred-main (add in Vault)'));
} else {
for (const c of sshCreds) {
credSelect.append(el('option', { value: c.id }, `${c.id} (${c.type})`));
}
}
} catch {
credSelect.append(el('option', { value: 'cred-main' }, 'cred-main'));
}
jumpSelect.replaceChildren(el('option', { value: '' }, 'None (direct SSH)'));
for (const s of existingServers) {
jumpSelect.append(el('option', { value: s.config.id }, `${s.config.id} (${s.config.host})`));
}
const cleanup = () => {
form.removeEventListener('submit', onSubmit);
closeBtn.removeEventListener('click', onClose);
cancelBtn.removeEventListener('click', onClose);
dialog.removeEventListener('close', onDialogClose);
dialog.returnValue = '';
};
const onClose = () => {
if (dialog.open) dialog.close();
};
const onDialogClose = () => cleanup();
const onSubmit = async (ev: Event) => {
ev.preventDefault();
errEl.textContent = '';
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);
try {
await apiFetch('/api/servers', {
method: 'POST',
body: {
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`, {
method: 'POST',
}).catch(() => undefined);
if (dialog.open) dialog.close();
await onRegistered();
} catch (err) {
errEl.textContent = extractErrorMessage(err);
}
};
form.addEventListener('submit', onSubmit);
closeBtn.addEventListener('click', onClose);
cancelBtn.addEventListener('click', onClose);
dialog.addEventListener('close', onDialogClose);
dialog.showModal();
}
export async function renderDashboardView(
root: HTMLElement,
state: ClientState,
): Promise<void> {
root.replaceChildren();
const res = await apiFetch<{ servers: ServerEntry[] }>('/api/servers');
const servers = res.servers;
const actionStatus = el('p', { class: 'form-msg' });
const registerBtn = el(
'button',
{ type: 'button', class: 'btn btn-primary btn-sm mutating-action' },
'+ Register Server',
);
registerBtn.addEventListener('click', () => {
void openRegisterServerDialog(servers, () => renderDashboardView(root, state));
});
const rotateFleetBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm mutating-action' },
'Rotate Fleet Keys',
);
rotateFleetBtn.addEventListener('click', async () => {
const ok = await confirmDialog(
'dialog-confirm',
'Rotate SSH keys atomically across all enabled servers? Old keys stay active if any verification fails.',
);
if (!ok) return;
actionStatus.textContent = 'Rotating fleet SSH keys...';
try {
const rot = await apiFetch<{
results: Array<{ serverId: string; ok: boolean; rolledBack?: boolean; error?: string }>;
}>('/api/servers/rotate-keys', {
method: 'POST',
body: { all: true },
});
const okCount = rot.results.filter((r) => r.ok).length;
actionStatus.className = okCount === rot.results.length ? 'form-msg ok-text' : 'form-msg warn-text';
actionStatus.textContent = `Key rotation finished: ${okCount}/${rot.results.length} succeeded.`;
await renderDashboardView(root, state);
} catch (err) {
actionStatus.className = 'form-msg err-text';
actionStatus.textContent = extractErrorMessage(err);
}
});
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh');
refreshBtn.addEventListener('click', () => {
void renderDashboardView(root, state);
});
root.append(
el(
'div',
{ class: 'panel row-between' },
el('div', {}, el('h1', {}, `Fleet Monitor (${servers.length} servers)`), el('span', { class: 'muted' }, `Vault: ${state.vaultState}`)),
el('div', { class: 'row' }, registerBtn, rotateFleetBtn, refreshBtn),
),
actionStatus,
);
// MITM Host-Key Mismatch Alerts
for (const s of servers) {
const mismatch = s.runtime.hostKeyMismatch;
if (!mismatch) continue;
const resetBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-danger mutating-action' },
'Inspect & Reset Host Key',
);
resetBtn.addEventListener('click', async () => {
const ok = await confirmDialog(
'dialog-confirm',
`MITM WARNING: Reset trusted host key for ${mismatch.hostPortKey} to ${mismatch.actualFingerprint}?`,
);
if (!ok) return;
await apiFetch(`/api/servers/${encodeURIComponent(s.config.id)}/host-key/reset`, {
method: 'POST',
body: { fingerprint: mismatch.actualFingerprint },
});
await renderDashboardView(root, state);
});
root.append(
el(
'div',
{ class: 'alert-box' },
el('strong', { class: 'err-text' }, `[SECURITY ALERT] SSH Host Key Mismatch on ${s.config.name} (${mismatch.hostPortKey})`),
el('div', { class: 'mono' }, `Expected: ${mismatch.expectedFingerprint}`),
el('div', { class: 'mono err-text' }, `Observed: ${mismatch.actualFingerprint}`),
el('div', { class: 'row' }, resetBtn),
),
);
}
// Pending TOFU Host-Key Prompts
for (const s of servers) {
const tofu = s.runtime.tofuPending;
if (!tofu) continue;
const trustBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-primary mutating-action' },
'Trust Host Key (TOFU)',
);
trustBtn.addEventListener('click', async () => {
await apiFetch(`/api/servers/${encodeURIComponent(s.config.id)}/tofu/approve`, {
method: 'POST',
body: { fingerprint: tofu.fingerprint },
});
await renderDashboardView(root, state);
});
root.append(
el(
'div',
{ class: 'tofu-box' },
el('strong', { class: 'warn-text' }, `[TOFU CONFIRMATION] First connection to ${s.config.name} (${tofu.hostPortKey})`),
el('div', { class: 'mono' }, `${tofu.algorithm} ${tofu.fingerprint}`),
el('div', { class: 'row' }, trustBtn),
),
);
}
if (servers.length === 0) {
root.append(
el(
'section',
{ class: 'panel' },
el('p', { class: 'muted' }, 'No target servers configured yet. Click "+ Register Server" to begin agentless SSH monitoring.'),
),
);
return;
}
const grid = el('div', { class: 'grid-2' });
for (const entry of servers) {
const { config, runtime, telemetry } = entry;
const sample = telemetry?.sample;
if (sample) pushSparkPoint(config.id, sample.cpuPct);
const pts = sparkHistory.get(config.id) ?? (sample ? [sample.cpuPct] : []);
const cpuText = sample ? `${sample.cpuPct.toFixed(1)}%` : '—';
const memPct =
sample && sample.memTotalMb > 0
? Math.round((sample.memUsedMb / sample.memTotalMb) * 100)
: 0;
const memText = sample
? `${Math.round(sample.memUsedMb)}/${Math.round(sample.memTotalMb)}MB (${memPct}%)`
: '—';
const loadText = sample ? sample.load1m.toFixed(2) : '—';
const netText = sample
? `↓${fmtBytesPerSec(sample.netRxBps)} ↑${fmtBytesPerSec(sample.netTxBps)}`
: '—';
const upText = sample ? `Up ${fmtUptime(sample.uptimeSec)}` : runtime.lastError ?? 'Awaiting poll';
const disksBox = el('div', { class: 'stack', 'data-field': 'disks' });
renderDisksInto(disksBox, telemetry?.disks ?? []);
const probesBox = el('div', { class: 'row', 'data-field': 'probes' });
renderProbesInto(probesBox, Object.values(telemetry?.probes ?? {}));
const reconnBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm mutating-action' },
'Reconnect',
);
reconnBtn.addEventListener('click', async () => {
reconnBtn.disabled = true;
await apiFetch(`/api/servers/${encodeURIComponent(config.id)}/reconnect`, {
method: 'POST',
}).catch(() => undefined);
await renderDashboardView(root, state);
});
const card = el(
'article',
{ class: 'panel panel-region', 'data-server-card': config.id },
el(
'div',
{ class: 'row-between' },
el(
'div',
{},
el('strong', {}, config.name),
el('span', { class: 'muted mono' }, ` (${config.username}@${config.host}:${config.port})`),
),
el(
'div',
{ class: 'row' },
el('span', { class: 'badge', 'data-field': 'os' }, runtime.osDetected ?? telemetry?.os ?? config.osHint),
el('span', { class: statusBadgeClass(runtime.status), 'data-field': 'status' }, `[${runtime.status.toUpperCase()}]`),
),
),
el(
'div',
{ class: 'metric-grid' },
el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'CPU'), el('div', { class: 'metric-val mono', 'data-field': 'cpu' }, cpuText)),
el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'RAM'), el('div', { class: 'metric-val mono', 'data-field': 'mem' }, memText)),
el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'LOAD 1m'), el('div', { class: 'metric-val mono', 'data-field': 'load' }, loadText)),
el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'NET'), el('div', { class: 'metric-val mono', 'data-field': 'net' }, netText)),
),
createSparklineSvg(pts, 100),
disksBox,
probesBox,
el(
'div',
{ class: 'row-between', style: 'margin-top:8px' },
el('span', { class: 'muted mono', 'data-field': 'uptime' }, upText),
el(
'div',
{ class: 'row' },
reconnBtn,
el('a', { href: `#server/${encodeURIComponent(config.id)}`, class: 'btn btn-sm btn-primary' }, 'Inspect / Keys'),
),
),
);
grid.append(card);
}
root.append(grid);
}

View file

@ -2,45 +2,11 @@ import { el, type ConfigOverview, type RouteId } from '../state.js';
export function renderSectionShell(
root: HTMLElement,
route: Exclude<RouteId, 'config' | 'vault' | 'settings'>,
route: Exclude<RouteId, 'dashboard' | 'server-detail' | 'config' | 'vault' | 'settings'>,
overview: ConfigOverview,
): void {
root.replaceChildren();
if (route === 'dashboard') {
const summary = el('div', { class: 'grid-3' });
summary.append(
el('div', { class: 'panel' }, el('h2', {}, 'Servers'), el('div', { class: 'mono' }, `${overview.servers.length} configured`), el('a', { href: '#config', class: 'btn btn-sm' }, 'Manage Servers')),
el('div', { class: 'panel' }, el('h2', {}, 'Custom Systems'), el('div', { class: 'mono' }, `${overview.systems.length} presets/definitions`), el('a', { href: '#systems', class: 'btn btn-sm' }, 'View Systems')),
el('div', { class: 'panel' }, el('h2', {}, 'Workflows & Alerts'), el('div', { class: 'mono' }, `${overview.workflows.length} DAGs, ${(overview.alerts.rules ?? []).length} rules`), el('a', { href: '#workflows', class: 'btn btn-sm' }, 'View Workflows')),
);
root.append(summary);
const srvPanel = el('section', { class: 'panel panel-region' });
srvPanel.append(el('h1', {}, 'Fleet Inventory (Phase 2 Live SSH Telemetry Ready)'));
if (overview.servers.length === 0) {
srvPanel.append(
el('p', { class: 'muted' }, 'No server JSON configs yet. Add one in Config -> servers/<id>.json.'),
);
} else {
const grid = el('div', { class: 'grid-2' });
for (const s of overview.servers) {
grid.append(
el(
'div',
{ class: 'panel' },
el('div', { class: 'row-between' }, el('strong', {}, String(s.name ?? s.id)), el('span', { class: 'badge' }, s.enabled === false ? 'DISABLED' : 'CONFIGURED')),
el('div', { class: 'mono muted' }, `${String(s.username)}@${String(s.host)}:${String(s.port ?? 22)}`),
el('div', { class: 'muted' }, `Cred: ${String(s.credentialId)} | Poll: ${String(s.pollIntervalSec ?? 10)}s`),
),
);
}
srvPanel.append(grid);
}
root.append(srvPanel);
return;
}
if (route === 'systems') {
const panel = el('section', { class: 'panel' });
panel.append(
@ -115,8 +81,8 @@ export function renderSectionShell(
'section',
{ class: 'panel' },
el('h1', {}, label),
el('p', { class: 'muted' }, 'Interactive SSH client, lazy-loaded xterm.js, and SFTP manager activate in Phase 3 after SSHPool in Phase 2.'),
el('a', { href: '#config', class: 'btn btn-sm' }, 'Configure Servers'),
el('p', { class: 'muted' }, 'Interactive SSH client, lazy-loaded xterm.js, and SFTP manager activate in Phase 3.'),
el('a', { href: '#dashboard', class: 'btn btn-sm' }, 'Back to Fleet Dashboard'),
),
);
}

View file

@ -0,0 +1,430 @@
import type { DiskSample, ProbeSample } from '../../../shared/ws-protocol.js';
import { apiFetch } from '../api.js';
import { createRangeChartSvg } from '../charts.js';
import { confirmDialog } from '../dialogs.js';
import {
el,
extractErrorMessage,
fmtTime,
type ServerEntry,
} from '../state.js';
type DetailTab = 'metrics' | 'inspector' | 'keys';
let activeTab: DetailTab = 'metrics';
let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h';
let procSortBy: 'cpu' | 'mem' = 'cpu';
export async function renderServerDetailView(
root: HTMLElement,
serverId: string,
onNavigateDashboard: () => void,
): Promise<void> {
root.replaceChildren();
const listRes = await apiFetch<{ servers: ServerEntry[] }>('/api/servers');
const entry = listRes.servers.find((s) => s.config.id === serverId);
if (!entry) {
root.append(
el(
'section',
{ class: 'panel' },
el('h1', {}, `Server "${serverId}" not found`),
el('a', { href: '#dashboard', class: 'btn btn-sm' }, 'Back to Dashboard'),
),
);
return;
}
const header = el('section', { class: 'panel' });
const reconnBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm mutating-action' },
'Reconnect SSH',
);
reconnBtn.addEventListener('click', async () => {
reconnBtn.disabled = true;
await apiFetch(`/api/servers/${encodeURIComponent(serverId)}/reconnect`, {
method: 'POST',
}).catch(() => undefined);
await renderServerDetailView(root, serverId, onNavigateDashboard);
});
const delBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-danger mutating-action' },
'Delete Server',
);
delBtn.addEventListener('click', async () => {
const ok = await confirmDialog(
'dialog-confirm',
`Delete server configuration "${serverId}"?`,
);
if (!ok) return;
await apiFetch(`/api/servers/${encodeURIComponent(serverId)}`, {
method: 'DELETE',
});
onNavigateDashboard();
});
const tabsRow = el(
'div',
{ class: 'row', style: 'margin-top:8px' },
...(['metrics', 'inspector', 'keys'] as DetailTab[]).map((t) => {
const b = el(
'button',
{
type: 'button',
class: `btn btn-sm${activeTab === t ? ' btn-primary' : ''}`,
},
t === 'metrics'
? 'Metrics & Probes'
: t === 'inspector'
? 'Server Inspector'
: 'SSH Keys & Rotation',
);
b.addEventListener('click', () => {
activeTab = t;
void renderServerDetailView(root, serverId, onNavigateDashboard);
});
return b;
}),
el('a', { href: '#config', class: 'btn btn-sm' }, 'Edit JSON'),
);
header.append(
el(
'div',
{ class: 'row-between' },
el(
'div',
{},
el('h1', {}, `${entry.config.name} (${entry.config.id})`),
el('div', { class: 'mono muted' }, `${entry.config.username}@${entry.config.host}:${entry.config.port}${entry.config.jumpHostId ? ` via ${entry.config.jumpHostId}` : ''}`),
),
el(
'div',
{ class: 'row' },
el('span', { class: 'badge' }, `[${entry.runtime.status.toUpperCase()}]`),
reconnBtn,
delBtn,
el('a', { href: '#dashboard', class: 'btn btn-sm' }, '← Dashboard'),
),
),
tabsRow,
);
root.append(header);
const body = el('div', { class: 'stack' });
root.append(body);
if (activeTab === 'metrics') {
await renderMetricsTab(body, serverId);
} else if (activeTab === 'inspector') {
await renderInspectorTab(body, serverId);
} else {
await renderKeysTab(body, serverId);
}
}
async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<void> {
const data = await apiFetch<{
range: string;
granularity: 'raw' | '1h' | '1d';
points: Array<Record<string, number>>;
latestDisks: DiskSample[];
latestProbes: Array<ProbeSample & { ts: number }>;
}>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`);
const rangeBar = el(
'div',
{ class: 'panel row-between' },
el('strong', {}, `Time-Series (${data.granularity} granularity, ${data.points.length} samples)`),
el(
'div',
{ class: 'row' },
...(['1h', '6h', '24h', '7d', '30d'] as const).map((r) => {
const b = el(
'button',
{ type: 'button', class: `btn btn-sm${activeRange === r ? ' btn-primary' : ''}` },
r,
);
b.addEventListener('click', () => {
activeRange = r;
body.replaceChildren();
void renderMetricsTab(body, serverId);
});
return b;
}),
),
);
body.append(rangeBar);
const cpuSeries = data.points.map((p) => p.cpuPct ?? p.cpuAvg ?? 0);
const memSeries = data.points.map((p) => {
if (p.memAvgPct !== undefined) return p.memAvgPct;
return p.memTotalMb ? ((p.memUsedMb ?? 0) / p.memTotalMb) * 100 : 0;
});
const loadSeries = data.points.map((p) => p.load1m ?? p.loadMax ?? 0);
const chartsGrid = el(
'div',
{ class: 'grid-3' },
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', {}, 'Load Average (1m)'), createRangeChartSvg(loadSeries, { color: 'var(--warn)' })),
);
body.append(chartsGrid);
// Disks table
const diskPanel = el('section', { class: 'panel' });
diskPanel.append(el('h2', {}, 'Mounted Real Filesystems'));
const dTable = el('table');
dTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Mount'), el('th', {}, 'FS'), el('th', {}, 'Used / Total (MB)'), el('th', {}, 'Used %'))));
const dBody = el('tbody');
if (data.latestDisks.length === 0) {
dBody.append(el('tr', {}, el('td', { colspan: 4, class: 'muted' }, 'No disk samples recorded yet.')));
} else {
for (const d of data.latestDisks) {
dBody.append(
el('tr', {}, el('td', { class: 'mono' }, d.mountPoint), el('td', { class: 'mono' }, d.fsType), el('td', { class: 'mono' }, `${Math.round(d.usedMb)} / ${Math.round(d.totalMb)}`), el('td', { class: 'mono' }, `${d.usedPct}%`)),
);
}
}
dTable.append(dBody);
diskPanel.append(el('div', { class: 'table-wrap' }, dTable));
body.append(diskPanel);
// Probes table
const probePanel = el('section', { class: 'panel' });
probePanel.append(el('h2', {}, 'Endpoint Health Probes'));
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'))));
const pBody = el('tbody');
if (data.latestProbes.length === 0) {
pBody.append(el('tr', {}, el('td', { colspan: 6, class: 'muted' }, 'No probe results recorded yet.')));
} else {
for (const p of data.latestProbes) {
pBody.append(
el(
'tr',
{},
el('td', { class: 'mono' }, p.probeId),
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' }, `${Math.round(p.latencyMs)} ms`),
el('td', { class: 'mono' }, fmtTime(p.ts)),
el('td', { class: 'mono err-text' }, p.error ?? '—'),
),
);
}
}
pTable.append(pBody);
probePanel.append(el('div', { class: 'table-wrap' }, pTable));
body.append(probePanel);
}
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 sortMemBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'mem' ? ' btn-primary' : ''}` }, 'Sort RAM');
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh Snapshot');
sortCpuBtn.addEventListener('click', () => {
procSortBy = 'cpu';
body.replaceChildren();
void renderInspectorTab(body, serverId);
});
sortMemBtn.addEventListener('click', () => {
procSortBy = 'mem';
body.replaceChildren();
void renderInspectorTab(body, serverId);
});
refreshBtn.addEventListener('click', () => {
body.replaceChildren();
void renderInspectorTab(body, serverId);
});
body.append(
el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, refreshBtn)),
);
try {
const res = await apiFetch<{
os: string;
collectedAt: number;
processes: Array<{ pid: number; user: string; cpuPct: number; memPct: number; rssMb: number; command: string }>;
ports: Array<{ proto: string; localAddress: string; process: string }>;
thermals: Array<{ zone: string; tempC: number }>;
}>(`/api/servers/${encodeURIComponent(serverId)}/inspect`);
const sortedProcs = [...res.processes].sort((a, b) =>
procSortBy === 'cpu' ? b.cpuPct - a.cpuPct : b.memPct - a.memPct,
);
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'))));
const pBody = el('tbody');
for (const p of sortedProcs) {
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))),
);
}
procTable.append(pBody);
const portTable = el('table');
portTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Proto'), el('th', {}, 'Listen Address'), el('th', {}, 'Process'))));
const portBody = el('tbody');
for (const pt of res.ports) {
portBody.append(el('tr', {}, el('td', { class: 'mono' }, pt.proto), el('td', { class: 'mono' }, pt.localAddress), el('td', { class: 'mono' }, pt.process)));
}
portTable.append(portBody);
const thermPanel = el('section', { class: 'panel' });
thermPanel.append(el('h2', {}, `Thermal Sensors (${res.thermals.length})`));
if (res.thermals.length === 0) {
thermPanel.append(el('p', { class: 'muted' }, 'No thermal zones exposed on this host.'));
} else {
for (const th of res.thermals) {
thermPanel.append(el('div', { class: 'mono' }, `${th.zone}: ${th.tempC} °C`));
}
}
body.append(
el('section', { class: 'panel panel-region' }, el('h2', {}, `Top Processes (${res.os}, ${fmtTime(res.collectedAt)})`), el('div', { class: 'table-wrap' }, procTable)),
el('section', { class: 'panel panel-region' }, el('h2', {}, 'Listening Sockets'), el('div', { class: 'table-wrap' }, portTable)),
thermPanel,
);
} catch (err) {
body.append(el('div', { class: 'panel err-text' }, extractErrorMessage(err)));
}
}
async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void> {
const msg = el('p', { class: 'form-msg' });
const rotateBtn = el(
'button',
{ type: 'button', class: 'btn btn-primary btn-sm mutating-action' },
'Atomic Zero-Lockout Rotate Key',
);
rotateBtn.addEventListener('click', async () => {
const ok = await confirmDialog(
'dialog-confirm',
`Generate a new Ed25519 keypair, verify connection on "${serverId}", update server JSON, and remove the old key?`,
);
if (!ok) return;
msg.textContent = 'Rotating SSH key...';
try {
const res = await apiFetch<{
results: Array<{ ok: boolean; newCredentialId?: string; rolledBack?: boolean; error?: string }>;
}>('/api/servers/rotate-keys', {
method: 'POST',
body: { serverIds: [serverId] },
});
const r = res.results[0];
if (r?.ok) {
body.replaceChildren();
await renderKeysTab(body, serverId);
} else {
msg.className = 'form-msg err-text';
msg.textContent = `Rotation failed (rolledBack=${String(r?.rolledBack)}): ${r?.error ?? 'unknown'}`;
}
} catch (err) {
msg.className = 'form-msg err-text';
msg.textContent = extractErrorMessage(err);
}
});
const deploySelect = el('select', { class: 'input-sm' });
const deployBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Deploy Vault Key');
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')) {
deploySelect.append(el('option', { value: c.id }, c.id));
}
} catch {
// Vault locked or empty
}
deployBtn.addEventListener('click', async () => {
if (!deploySelect.value) return;
try {
await apiFetch(`/api/servers/${encodeURIComponent(serverId)}/keys/deploy`, {
method: 'POST',
body: { credentialId: deploySelect.value },
});
body.replaceChildren();
await renderKeysTab(body, serverId);
} catch (err) {
msg.className = 'form-msg err-text';
msg.textContent = extractErrorMessage(err);
}
});
body.append(
el(
'div',
{ class: 'panel row-between' },
el('div', { class: 'row' }, deploySelect, deployBtn),
rotateBtn,
),
msg,
);
try {
const res = await apiFetch<{
entries: Array<{
lineNumber: number;
keyType: string;
fingerprint: string;
comment?: string;
isCurrentServerKey: boolean;
matchedVaultCredentialId?: string;
}>;
}>(`/api/servers/${encodeURIComponent(serverId)}/keys`);
const kTable = el('table');
kTable.append(el('thead', {}, el('tr', {}, el('th', {}, '#'), el('th', {}, 'Type'), el('th', {}, 'Fingerprint'), el('th', {}, 'Comment / Vault'), el('th', {}, 'Action'))));
const kBody = el('tbody');
for (const k of res.entries) {
const revBtn = el(
'button',
{
type: 'button',
class: 'btn btn-sm btn-danger mutating-action',
disabled: k.isCurrentServerKey ? true : undefined,
},
k.isCurrentServerKey ? 'Active Key' : 'Revoke',
);
if (!k.isCurrentServerKey) {
revBtn.addEventListener('click', async () => {
const ok = await confirmDialog('dialog-confirm', `Remove key ${k.fingerprint} from ~/.ssh/authorized_keys?`);
if (!ok) return;
await apiFetch(`/api/servers/${encodeURIComponent(serverId)}/keys/revoke`, {
method: 'POST',
body: { fingerprint: k.fingerprint },
});
body.replaceChildren();
await renderKeysTab(body, serverId);
});
}
kBody.append(
el(
'tr',
{},
el('td', { class: 'mono' }, String(k.lineNumber)),
el('td', { class: 'mono' }, k.keyType),
el('td', { class: 'mono' }, k.fingerprint),
el(
'td',
{ class: 'mono' },
`${k.comment ?? '—'}${k.matchedVaultCredentialId ? ` [vault:${k.matchedVaultCredentialId}]` : ''}`,
),
el('td', {}, revBtn),
),
);
}
kTable.append(kBody);
body.append(el('section', { class: 'panel' }, el('h2', {}, '~/.ssh/authorized_keys'), el('div', { class: 'table-wrap' }, kTable)));
} catch (err) {
body.append(el('div', { class: 'panel err-text' }, extractErrorMessage(err)));
}
}

View file

@ -8,7 +8,7 @@ export class MultiplexWsClient {
private reconnectTimer: number | null = null;
private pingTimer: number | null = null;
private shouldRun = false;
private channels = new Set<string>(['config', 'alerts']);
private channels = new Set<string>(['config', 'alerts', 'metrics']);
private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>();
private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>();