File size: 73,358 Bytes
bad179a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
// Server Monitor page: sidebar, dashboard, server tabs and events. Plain DOM + canvas, no libraries.
// Data arrives over Server-Sent Events, actions go to the JSON API; server data only ever enters the page as text.
'use strict';
const { Fmt, hNames, fmtMetric, ruleMetrics, def, conditionText, actionText } = SM;

// ---- small helpers ----
const css = getComputedStyle(document.documentElement), FONT = css.fontFamily; // the palette lives in style.css
const C = Object.fromEntries(['panel', 'card', 'border', 'grid', 'text', 'muted', 'faint', 'accent', 'green', 'amber', 'red', 'violet', 'pink', 'teal', 'orange', 'blue']
    .map(k => [k, css.getPropertyValue('--' + k).trim()]));
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)), ok = v => v != null && !isNaN(v);
const rgb = hex => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16));
const tint = (hex, alpha) => `rgba(${rgb(hex)},${alpha / 255})`;
const mix = (a, b, t) => `rgb(${rgb(a).map((x, i) => Math.round(x + (rgb(b)[i] - x) * clamp(t, 0, 1)))})`;
const level = (pct, warn = 70, crit = 90) => pct >= crit ? C.red : pct >= warn ? C.amber : C.green;
const sevColor = s => ({ critical: C.red, warning: C.amber, resolved: C.green, action: C.violet })[s] || C.accent;
const healthColor = v => v >= 90 ? C.green : v >= 75 ? C.teal : v >= 60 ? C.amber : v >= 40 ? C.orange : C.red;
const statusColor = s => ({ Online: C.green, Connecting: C.amber, Offline: C.red })[s.status] || C.faint;
const pctFmt = v => Fmt.fix(v) + '%', numFmt = prec => v => Fmt.fix(v, prec);
const pad = n => String(n).padStart(2, '0');
function tf(ms, format) { // date formatting with Qt-style patterns
    const d = new Date(ms), part = { yyyy: d.getFullYear(), MMM: d.toLocaleString('en', { month: 'short' }), MM: pad(d.getMonth() + 1), ddd: d.toLocaleString('en', { weekday: 'short' }),
        dd: pad(d.getDate()), HH: pad(d.getHours()), mm: pad(d.getMinutes()), ss: pad(d.getSeconds()) };
    return format.replace(/yyyy|MMM|MM|ddd|dd|HH|mm|ss/g, k => part[k]);
}

// h('tag.class.class', { property | onevent | style: {} }, ...children): children are elements or text
function h(tag, props, ...kids) {
    const [name, ...cls] = tag.split('.'), el = document.createElement(name);
    el.className = cls.join(' ');
    for (const [k, v] of Object.entries(props || {})) {
        if (k === 'style') for (const [p, x] of Object.entries(v)) el.style.setProperty(p, x ?? '');
        else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
        else el[k] = v;
    }
    el.append(...kids.flat(2).filter(k => k != null && k !== false && k !== ''));
    return el;
}

async function api(path, body) { // GET without a body, POST with one
    const r = await fetch('/api/' + path, body && { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SM': '1' }, body: JSON.stringify(body) });
    const j = await r.json();
    if (!r.ok) throw new Error(j.error);
    return j;
}
addEventListener('unhandledrejection', e => { // a failed request that nobody handled: show it briefly
    const note = document.body.appendChild(h('div.toast', null, String(e.reason?.message || e.reason)));
    setTimeout(() => note.remove(), 6000);
});

// ---- hand-drawn widgets ----
const font = (ctx, px, bold) => ctx.font = `${bold ? 700 : 400} ${px}px ${FONT}`;
function text(ctx, s, x, y, px, color, align = 'left', bold = false, maxW = 0) { // vertically centred on y; maxW elides
    font(ctx, px, bold), ctx.fillStyle = color, ctx.textAlign = align, ctx.textBaseline = 'middle';
    let out = String(s);
    for (let n = out.length; maxW && n > 1 && ctx.measureText(out).width > maxW;) out = String(s).slice(0, --n) + '…';
    ctx.fillText(out, x, y);
    return ctx.measureText(out).width;
}
function box(ctx, x, y, w, hh, r, fill, stroke) {
    ctx.beginPath(), ctx.roundRect(x, y, w, hh, r), ctx.fillStyle = fill, ctx.fill();
    if (stroke) ctx.strokeStyle = stroke, ctx.lineWidth = 1, ctx.setLineDash([]), ctx.stroke();
}
function line(ctx, pts, color, width, dash = []) {
    ctx.beginPath(), pts.forEach(p => ctx.lineTo(p[0], p[1]));
    ctx.strokeStyle = color, ctx.lineWidth = width, ctx.lineCap = ctx.lineJoin = 'round', ctx.setLineDash(dash), ctx.stroke();
}
function ring(ctx, x, y, s, pct, color, thick, glow = true) { // 270° arc in the square (x, y, s)
    const arc = (angle, c, w) => { ctx.beginPath(), ctx.arc(x + s / 2, y + s / 2, (s - thick) / 2, Math.PI * .75, Math.PI * .75 + angle), ctx.strokeStyle = c, ctx.lineWidth = w, ctx.lineCap = 'round', ctx.setLineDash([]), ctx.stroke(); };
    const a = Math.PI * 1.5 * clamp(pct, 0, 100) / 100;
    arc(Math.PI * 1.5, C.grid, thick);
    if (a > .003) glow && arc(a, tint(color, 45), thick * 2), arc(a, color, thick);
}

// a canvas that fills its box and repaints when resized; draw(ctx, width, height) works in CSS pixels
function canvas(cls, draw) {
    const cv = h('canvas'), el = h('div.cv.' + cls, null, cv), ctx = cv.getContext('2d');
    el.redraw = () => {
        const w = el.clientWidth, hh = el.clientHeight, r = devicePixelRatio || 1;
        if (!w || !hh) return;
        if (cv.width !== Math.round(w * r) || cv.height !== Math.round(hh * r)) cv.width = Math.round(w * r), cv.height = Math.round(hh * r);
        ctx.setTransform(r, 0, 0, r, 0, 0), ctx.clearRect(0, 0, w, hh), draw(ctx, w, hh);
    };
    new ResizeObserver(el.redraw).observe(el);
    return el;
}

function gauge(title, warn = 70, crit = 90) { // ring gauge; set(percent, centre text, text below, colour)
    let target = 0, shown = 0, from = 0, t0 = 0, center = '', sub = '', color;
    const el = canvas('gauge', (ctx, w, hh) => {
        const s = Math.min(w - 8, hh - 28), x = (w - s) / 2;
        ring(ctx, x, 4, s, shown, color || level(target, warn, crit), Math.max(7, s * .085));
        text(ctx, center || Fmt.fix(shown) + '%', w / 2, 4 + s * .43, s * .2, C.text, 'center', true);
        text(ctx, sub, w / 2, 4 + s * .63, Math.max(10, s * .075), C.muted, 'center', false, s * .76);
        text(ctx, title, w / 2, 4 + s * .94 + 9, 13, C.text, 'center', true);
    });
    const step = now => { // 450 ms ease-out
        const k = Math.min(1, (now - t0) / 450);
        shown = from + (target - from) * (1 - (1 - k) ** 3), el.redraw();
        if (k < 1) requestAnimationFrame(step);
    };
    el.set = (pct, c = '', s = '', col) => {
        center = c, sub = s, color = col, pct ||= 0;
        if (Math.abs(pct - target) > .05) from = shown, target = pct, t0 = performance.now(), requestAnimationFrame(step);
        else el.redraw();
    };
    return el;
}

const ser = (name, color, v, fill = true, dashed = false) => ({ name, color, v, fill, dashed });
function niceCeil(v) {
    if (v <= 0) return 1;
    const e = 10 ** Math.floor(Math.log10(v)), f = v / e;
    return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * e;
}
// time chart: grid, legend with latest values, hover value, stacked areas, gaps where a value is missing
function chart(title, fmt = pctFmt, yFixed = 0, stacked = false, empty = 'Waiting for data…') { // yFixed 0 = auto scale
    let T = [], S = [], span = 0, hover = -1;
    const el = canvas('chart.panel', (ctx, w, hh) => {
        const titleW = text(ctx, el.head, 16, 20, 13, C.text, 'left', true), plot = { l: 56, t: 40, r: w - 16, b: hh - 30 }, n = T.length;
        text(ctx, el.sub, 24 + titleW, 20, 11, C.muted);
        let lx = w - 16, first = 0; // legend, right-aligned
        for (const s of [...S].reverse()) {
            const last = s.v.slice(-5).findLast(ok), label = s.name + (ok(last) ? '  ' + fmt(last) : '');
            if ((lx -= ctx.measureText(label).width) < 40 + titleW) break;
            text(ctx, label, lx, 20, 11, C.muted), box(ctx, lx -= 14, 16, 9, 9, 2, s.color), lx -= 14;
        }
        if (span) while (first < n && T[first] < T[n - 1] - span) ++first;
        if (n - first < 2 || plot.b - plot.t < 20) return text(ctx, empty, (plot.l + plot.r) / 2, (plot.t + plot.b) / 2, 13, C.faint, 'center');

        let yMax = yFixed;
        if (yMax <= 0) {
            for (let i = first; i < n; ++i) yMax = Math.max(yMax, S.reduce((sum, s) => !ok(s.v[i]) ? sum : stacked ? sum + s.v[i] : Math.max(sum, s.v[i]), 0));
            yMax = niceCeil(yMax * 1.12);
        }
        font(ctx, 10), plot.l = Math.max(40, ...[0, 1, 2, 3, 4].map(g => ctx.measureText(fmt(yMax * g / 4)).width + 18));
        const pw = plot.r - plot.l, ph = plot.b - plot.t, t1 = T[n - 1], t0 = span ? t1 - span : T[first], tr = Math.max(1, t1 - t0);
        const X = t => plot.l + (t - t0) / tr * pw, Y = v => plot.b - clamp(v, 0, yMax) / yMax * ph;
        const stamp = tr <= 72e5 ? 'HH:mm' : tr <= 2.6e8 ? 'ddd HH:mm' : tr <= 3.5e10 ? 'dd MMM' : 'MMM yyyy';
        for (let g = 0; g <= 4; ++g) { // grid, y labels, time labels
            const y = Y(yMax * g / 4), t = t0 + tr * g / 4;
            line(ctx, [[plot.l, y], [plot.r, y]], C.grid, 1, g ? [4, 3] : []);
            text(ctx, fmt(yMax * g / 4), plot.l - 8, y, 10, C.faint, 'right');
            text(ctx, tf(t, stamp), X(t), plot.b + 14, 10, C.faint, ['left', 'center', 'center', 'center', 'right'][g]);
        }
        const step = Math.max(1, Math.floor((n - first) / Math.max(50, pw * 1.5))), base = new Array(n).fill(0); // ~1.5 points per pixel
        ctx.save(), ctx.beginPath(), ctx.rect(plot.l - 2, plot.t - 4, pw + 4, ph + 6), ctx.clip();
        for (const s of S) {
            const runs = [[]]; // [x, top, bottom] points, split at gaps
            for (let i = first; i < n; i += step) {
                let sum = 0, bs = 0, c = 0;
                for (let k = i; k < Math.min(n, i + step); ++k) if (ok(s.v[k])) sum += s.v[k], bs += base[k], ++c;
                if (c) runs.at(-1).push([X(T[Math.min(n - 1, i + (step >> 1))]), Y(sum / c + (stacked ? bs / c : 0)), Y(stacked ? bs / c : 0)]);
                else if (runs.at(-1).length) runs.push([]);
            }
            if (stacked) for (let k = first; k < n; ++k) base[k] += ok(s.v[k]) ? s.v[k] : 0;
            for (const r of runs.filter(r => r.length > 1)) {
                if (s.fill) {
                    const g = ctx.createLinearGradient(0, plot.t, 0, plot.b);
                    g.addColorStop(0, tint(s.color, stacked ? 120 : 95)), g.addColorStop(1, tint(s.color, stacked ? 60 : 4));
                    ctx.beginPath(), r.forEach(p => ctx.lineTo(p[0], p[1])), r.toReversed().forEach(p => ctx.lineTo(p[0], p[2])), ctx.fillStyle = g, ctx.fill();
                }
                line(ctx, r, s.color, s.dashed ? 1.3 : 2, s.dashed ? [4, 3] : []);
            }
        }
        ctx.restore();
        if (hover < plot.l || hover > plot.r) return;
        const at = t0 + (hover - plot.l) / pw * tr, found = T.findIndex((t, i) => i >= first && t >= at), best = found < 0 ? n - 1 : found; // crosshair + tooltip
        const x = X(T[best]), lines = [tf(T[best], tr > 864e5 ? 'ddd dd MMM HH:mm' : 'HH:mm:ss'), ...S.map(s => `${s.name}: ${ok(s.v[best]) ? fmt(s.v[best]) : '—'}`)];
        let stack = 0;
        line(ctx, [[x, plot.t], [x, plot.b]], 'rgba(255,255,255,.27)', 1, [4, 3]);
        for (const s of S.filter(s => ok(s.v[best]))) {
            stack = stacked ? stack + s.v[best] : s.v[best];
            ctx.beginPath(), ctx.arc(x, Y(stack), 4, 0, 7), ctx.fillStyle = s.color, ctx.fill(), ctx.strokeStyle = C.panel, ctx.lineWidth = 2, ctx.setLineDash([]), ctx.stroke();
        }
        font(ctx, 11);
        const tw = Math.max(...lines.map(l => ctx.measureText(l).width)), tx = Math.min(x + 12, plot.r - tw - 20);
        box(ctx, tx, plot.t + 4, tw + 18, lines.length * 16 + 10, 7, 'rgba(13,17,28,.92)', C.border);
        lines.forEach((l, i) => text(ctx, l, tx + 9, plot.t + 17 + i * 16, 11, i ? C.text : C.muted));
    });
    el.head = title, el.sub = '';
    el.set = (t, s, sp = 0) => (T = t, S = s, span = sp, el.redraw()); // times in ms, series from ser(), span 0 = everything
    el.addEventListener('mousemove', e => (hover = e.offsetX, el.redraw()));
    el.addEventListener('mouseleave', () => (hover = -1, el.redraw()));
    return el;
}

// stat tiles with an accent stripe; set(index, value, text below, colour)
function tiles(defs, cols = defs.length) {
    const els = defs.map(([title, color]) => h('div.tile', { style: { '--stripe': C[color] } }, h('div.section', null, title), h('b', null, '—'), h('small')));
    const el = h('div.tiles', { style: { 'grid-template-columns': `repeat(${cols}, 1fr)` } }, els);
    el.set = (i, value, sub = '', color = '') => { const [, v, s] = els[i].children; v.textContent = value, v.style.color = color, s.textContent = sub; };
    return el;
}
function segbar() { // segment bar with a legend; set([[bytes, colour, label]], total)
    const bar = h('div.seg'), legend = h('div.legend'), el = h('div', null, bar, legend);
    el.set = (segs, total) => {
        bar.replaceChildren(...segs.map(([v, color]) => h('i', { style: { width: Math.max(0, v) / (total > 0 ? total : 1) * 100 + '%', background: color } })));
        legend.replaceChildren(...segs.map(([v, color, label]) => h('span', null, h('i', { style: { background: color } }), `${label}  ${Fmt.bytes(v)}`)));
    };
    return el;
}
const panel = (title, ...content) => h('div.panel', null, title && h('div.section', null, title), content);
const kv = rows => h('table.kv', null, rows.map(([k, v]) => h('tr', null, h('td', null, k), h('td', null, String(v)))));

// table(headers, { widths, sort: [column, descending], sortable, select, empty: [text, colour] }) -> element with fill(rows), render(), sel,
// selRow(), accept(row) and menu(). A cell is text or { t: text, c: colour, r: right-aligned, pct: bar 0–100, k: sort key, el: element };
// a row's key is row.key or its first cell's text.
const cellText = c => String(c?.t ?? c ?? ''), rowKey = r => r.key ?? cellText(r[0]);
function setCell(td, c) {
    const t = cellText(c);
    td.className = c.r ? 'r' : '', td.style.color = c.c || '';
    if (c.el) return td.firstChild === c.el || td.replaceChildren(c.el);
    if (c.pct == null) return td.textContent === t && !td.firstElementChild || (td.textContent = t);
    if (!td.firstElementChild) td.replaceChildren(h('div.bar', null, h('i'), h('span')));
    const [fill, label] = td.firstElementChild.children, p = clamp(c.pct, 0, 100);
    fill.style.width = p + '%', fill.style.background = tint(level(p), 200), label.textContent = t;
}
function table(headers, opt = {}) {
    let rows = [], sort = opt.sort;
    const body = h('tbody'), sortKey = r => r[sort[0]]?.k ?? cellText(r[sort[0]]);
    const heads = headers.map((t, i) => h('th', { style: { width: opt.widths?.[i] && opt.widths[i] + 'px' }, onclick: () => opt.sortable && (sort = [i, sort?.[0] === i && !sort[1]], el.render()) }, t));
    const el = h('div.table', null, h('table', null, h('thead', null, h('tr', null, heads)), body));
    el.render = () => {
        const list = sort ? rows.toSorted((a, b) => (sortKey(a) < sortKey(b) ? -1 : +(sortKey(a) > sortKey(b))) * (sort[1] ? -1 : 1)) : rows;
        if (body.rows[0]?.cells.length !== headers.length) body.replaceChildren();
        if (!list.length && opt.empty) return body.replaceChildren(h('tr', null, h('td', { colSpan: headers.length, style: { color: opt.empty[1] } }, opt.empty[0])));
        while (body.rows.length > list.length) body.lastChild.remove();
        list.forEach((r, i) => {
            const tr = body.rows[i] || body.appendChild(h('tr', null, headers.map(() => h('td'))));
            tr.row = r, tr.hidden = !!el.accept && !el.accept(r), tr.classList.toggle('sel', !!opt.select && rowKey(r) === el.sel);
            headers.forEach((_, j) => setCell(tr.cells[j], r[j] ?? ''));
        });
        heads.forEach((th, i) => th.dataset.sort = sort?.[0] !== i ? '' : sort[1] ? ' ▾' : ' ▴');
    };
    el.fill = r => (rows = r, rows.some(x => rowKey(x) === el.sel) || (el.sel = undefined), el.render()); // the selection goes with its entry
    el.selRow = () => rows.find(r => rowKey(r) === el.sel && (!el.accept || el.accept(r))); // a filtered-out row is not a selection
    const pick = e => { // mousedown, so a refresh between press and release cannot lose the selection
        const tr = e.target.closest('tr');
        if (tr?.row && opt.select && el.sel !== rowKey(tr.row)) el.sel = rowKey(tr.row), el.render();
        return tr?.row;
    };
    body.addEventListener('mousedown', pick);
    body.addEventListener('contextmenu', e => pick(e) && el.menu && menu(e, el.menu()));
    return el;
}

// context menu at the pointer; items are [label, action] or null for a separator
function menu(e, items) {
    e.preventDefault();
    const m = document.body.appendChild(h('div.menu', null, items.map(it => it ? h('button', { onclick: it[1] }, it[0]) : h('hr'))));
    m.style.left = Math.min(e.clientX, innerWidth - m.offsetWidth - 4) + 'px', m.style.top = Math.min(e.clientY, innerHeight - m.offsetHeight - 4) + 'px';
    for (const type of ['click', 'contextmenu']) addEventListener(type, () => m.remove(), { once: true, capture: true }); // the next one, not the event being handled
}

// modal dialog; buttons are [label, class, action]: the dialog closes with the action's result unless that is undefined
function dialog(title, content, buttons, cls = '') {
    return new Promise(resolve => {
        const d = h('dialog' + cls, { onclose: () => (d.remove(), resolve(d.result)) }, h('h2', null, title), content,
            h('div.row.end', null, buttons.map(([label, c, action]) => h('button' + c, { onclick: async () => (d.result = await action()) !== undefined && d.close() }, label))));
        document.body.append(d), d.showModal();
    });
}
const ask = (title, question, danger) => dialog(title, h('p.pre', null, question), [['Yes', danger ? '.danger' : '.primary', () => true], ['No', '', () => false]]);

// inputs bound to o[key]; `changed` runs after every edit
function fields(o, changed = () => {}) {
    const bind = (el, k, get) => (el.addEventListener('change', () => (o[k] = get(el), changed())), el);
    return {
        text: (k, props) => bind(h('input', { value: o[k], ...props }), k, el => el.value),
        num: (k, min, max, step = 1) => bind(h('input', { type: 'number', min, max, step, value: o[k] }), k, el => +(el.value = clamp(+el.value || 0, min, max))),
        check: (k, label) => h('label.check', null, bind(h('input', { type: 'checkbox', checked: o[k] }), k, el => el.checked), label),
        select: (k, options) => bind(h('select', null, options.map(([v, label]) => h('option', { value: v, selected: v === o[k] }, label))), k, el => typeof o[k] === 'number' ? +el.value : el.value),
    };
}
const form = rows => h('div.form', null, rows.map(([label, field]) => [h('div', null, label), h('div.row', null, field)])); // [label, field(s)] rows

// keeps one child per server (matched by id) so elements survive updates; `tail` elements follow
function keyed(parent, make, tail = []) {
    const old = new Map([...parent.children].map(el => [el.dataset.id, el]));
    const els = S.servers.map(s => {
        const el = old.get(s.cfg.id) || make(s.cfg.id);
        el.dataset.id = s.cfg.id;
        return el;
    });
    if ([...els, ...tail].some((el, i) => parent.children[i] !== el) || parent.children.length !== els.length + tail.length) parent.replaceChildren(...els, ...tail);
    els.forEach((el, i) => el.update(S.servers[i]));
}

// ---- state ----
// plat: platform tables from the server; id: server shown on the detail page; live, m, vals, an: its live rows, metrics, rule values, analysis
const S = { plat: null, dir: '', rule: null, defaultRules: [], servers: [], alerts: [], page: '', id: null, tab: '', span: 15, live: [], m: null, vals: {}, an: null, unseen: 0 };
const cur = () => S.servers.find(s => s.cfg.id === S.id);
const go = (...parts) => location.hash = '#/' + parts.map(encodeURIComponent).join('/');
const [, USER, SYS, IOWAIT, STEAL, MEM, CACHE, SWAP, RX, TX, RD, WR, LOAD] = Array(13).keys(); // positions in a live row (liveRow in core/session.js)
const col = k => S.live.map(r => r.v[k]), times = () => S.live.map(r => r.t), spanMs = () => S.span * 60000;
const cpuSeries = steal => [ser('User', C.accent, col(USER)), ser('System', C.violet, col(SYS)),
    ...(S.plat.posixCpu ? [ser('I/O wait', C.amber, col(IOWAIT)), ...(steal ? [ser('Steal', C.red, col(STEAL))] : [])] : [])];

// ---- server actions ----
const serverMenu = (id, first) => [first, ['Reconnect', () => api('server/reconnect', { id })], null];
async function editServer(id) { // id undefined = add
    const P = S.plat, s = S.servers.find(x => x.cfg.id === id), groups = [...new Set(S.servers.map(x => x.cfg.group).filter(Boolean))];
    if (id && !s) return;
    const c = s ? { ...s.cfg, password: '' } : { name: '', group: '', transport: 1, host: '', port: 22, user: '', keyFile: '', password: '', interval: P.interval, useSudo: false, enabled: true, notes: '' };
    const f = fields(c, () => sync()), hint = h('div.muted'), result = h('span.grow'), name = f.text('name', { placeholder: 'e.g. web-01' });
    const ssh = [f.text('host', { placeholder: 'hostname or IP address', className: 'grow' }), f.num('port', 1, 65535), f.text('user', { placeholder: 'default: your local user name' }),
        f.text('keyFile', { placeholder: P.keyHint }), f.text('password', { type: 'password', autocomplete: 'new-password', placeholder: s?.cfg.hasPassword ? 'stored — leave empty to keep it' : 'optional — keys are recommended' })];
    const group = f.text('group', { className: 'grow' }), show = (t, color) => void (result.textContent = t, result.style.color = color);
    group.setAttribute('list', 'groups');
    const sync = () => {
        ssh.forEach(el => el.disabled = !c.transport);
        hint.textContent = c.transport ? P.sshHint : 'Monitors the computer this program runs on. No setup needed.';
        if (!c.transport && !c.name) c.name = name.value = 'This computer';
    };
    const test = h('button', { onclick: async () => {
        test.disabled = true, show('Connecting…', C.amber);
        const r = await api('server/test', c).catch(e => ({ text: '✗ ' + e.message }));
        test.disabled = false, show(r.text, r.ok ? C.green : C.red);
    } }, 'Test connection');
    sync();
    const saved = await dialog(s ? 'Edit server' : 'Add a server', h('div.col', null, form([['Name', name], ['Group', [group, h('datalist', { id: 'groups' }, groups.map(g => h('option', { value: g })))]],
        ['Connect via', f.select('transport', [[0, 'This machine (local)'], [1, 'SSH — nothing to install on the server']])], ['Address', [ssh[0], 'port', ssh[1]]], ['User', ssh[2]], ['Private key', ssh[3]],
        ['Password', [ssh[4], s?.cfg.hasPassword && f.check('clearPassword', 'remove stored')]], ['Sample every', [f.num('interval', 1, 300), 's']],
        ...(P.sudo ? [['', f.check('useSudo', 'Run control commands with sudo -n (needs passwordless sudo)')]] : []), ['', f.check('enabled', 'Monitoring enabled')], ['Notes', f.text('notes', { className: 'grow' })]]),
        hint, h('div.row', null, test, result)), [['Save', '.primary', () => api(s ? 'server/update' : 'server/add', c).catch(e => show(e.message, C.red))], ['Cancel', '', () => false]], '.wide');
    if (saved?.id) go('server', saved.id);
    else if (saved && id === S.id) listen();
}
async function removeServer(id) {
    const s = S.servers.find(x => x.cfg.id === id);
    const how = s && await dialog('Remove server', h('p', null, `Stop monitoring "${s.cfg.name}" and remove it from the list?`),
        [['Remove + delete history', '.danger', () => ({ deleteHistory: true })], ['Remove, keep history files', '', () => ({})], ['Cancel', '', () => false]]);
    if (!how) return;
    if (id === S.id) go('dashboard');
    api('server/remove', { id, ...how });
}

// ---- sidebar ----
const badge = h('span.badge', { hidden: true }), sideList = h('div.list.grow');
const nav = { dashboard: h('button.nav', { onclick: () => go('dashboard') }, '▦   Dashboard'), events: h('button.nav', { onclick: () => go('events') }, '◉   Events & alerts', badge) };
const sidebar = h('aside', null, h('div.brand', null, h('img', { src: 'icon.svg', alt: '' }), h('div', null, h('b', null, 'Server Monitor'), h('small', null, 'monitor · analyze · control'))),
    nav.dashboard, nav.events, h('div.section', null, 'Servers'), sideList,
    h('div.row', null, h('button.primary.grow', { onclick: () => editServer() }, '+ Add'), h('button.grow', { onclick: () => S.id && editServer(S.id) }, 'Edit'), h('button.danger.grow', { onclick: () => removeServer(S.id) }, 'Remove')));
function sideItem(id) { // dot, name, alert count, mini CPU / memory bars
    const dot = h('i.dot'), name = h('b.grow'), count = h('span.badge'), bars = ['CPU', 'MEM'].map(l => h('div.mini', null, h('small', null, l), h('div.track', null, h('i'))));
    const el = h('div.item', { onclick: () => go('server', id), oncontextmenu: e => menu(e, [...serverMenu(id, ['Open', () => go('server', id)]),
        ['Move up', () => api('server/move', { id, delta: -1 })], ['Move down', () => api('server/move', { id, delta: 1 })], null, ['Edit…', () => editServer(id)], ['Remove…', () => removeServer(id)]]) },
        h('div.row', null, dot, name, count), bars);
    el.update = s => {
        dot.style.background = statusColor(s), name.textContent = s.cfg.name, count.textContent = s.alerts.length, count.hidden = !s.alerts.length;
        el.classList.toggle('sel', id === S.id);
        [s.m.cpuUsage, s.m.memPct].forEach((v, i) => Object.assign(bars[i].lastChild.firstChild.style, { width: (s.online ? clamp(v, 0, 100) : 0) + '%', background: level(v) }));
    };
    return el;
}

// ---- dashboard ----
function card(id) { // header, four ring gauges, CPU + memory sparkline (last 5 min), net rates, alert badge
    let s;
    const dot = h('i.dot'), name = h('b'), addr = h('small'), chip = h('span.chip'), foot = h('div.foot');
    const grade = canvas('grade', (ctx, w) => (ring(ctx, 0, 0, w, s.health, healthColor(s.health), 4, false), text(ctx, s.grade, w / 2, w / 2, 15, healthColor(s.health), 'center', true)));
    const body = canvas('rings', (ctx, w, hh) => {
        const m = s.m, on = s.online, temp = m.temps > 0, gw = w / 4, gs = Math.min(gw - 14, 70), top = hh - 44;
        [[m.cpuUsage, 'CPU'], [m.memPct, 'Memory'], [m.maxDiskPct, 'Disk'], temp ? [m.maxTemp, 'Temp'] : [m.swapPct, 'Swap']].forEach(([v, label], i) => {
            const cx = gw * i + gw / 2, hot = i === 3 && temp;
            ring(ctx, cx - gs / 2, 2, gs, on ? Math.min(100, v) : 0, !on ? C.faint : hot ? level(v, 70, 85) : level(v), 6, on);
            text(ctx, on ? Fmt.fix(v) + (hot ? '°' : '%') : '—', cx, 2 + gs / 2, 14, on ? C.text : C.faint, 'center', true);
            text(ctx, label, cx, gs + 6, 11, C.muted, 'center');
        });
        box(ctx, 0, top, w, 44, 8, 'rgba(0,0,0,.16)');
        for (const [v, color] of [[s.spark[1], C.violet], [s.spark[0], C.accent]]) {
            if (v.length < 2) continue;
            const pts = v.map((y, i) => [w - 4 - (w - 8) * (v.length - 1 - i) / 149, hh - 4 - clamp(y, 0, 100) / 100 * 36]);
            ctx.beginPath(), [...pts, [pts.at(-1)[0], hh - 2], [pts[0][0], hh - 2]].forEach(p => ctx.lineTo(...p)), ctx.fillStyle = tint(color, 40), ctx.fill();
            line(ctx, pts, color, 1.5);
        }
        text(ctx, 'CPU', 8, top + 10, 10, C.accent), text(ctx, 'MEM', 36, top + 10, 10, C.violet);
    });
    const el = h('div.card', { onclick: () => go('server', id), oncontextmenu: e => menu(e, [...serverMenu(id, ['Open details', () => go('server', id)]), ['Edit…', () => editServer(id)], ['Remove…', () => removeServer(id)]]) },
        h('div.row', null, dot, h('div.grow', null, name, addr), grade, chip), body, foot);
    el.update = x => {
        s = x;
        const m = s.m, ap = s.cfg.autopilot, n = s.alerts.length + s.findings.length, crit = s.alerts.length || s.findings.includes('critical');
        el.style.setProperty('--status', statusColor(s)), name.textContent = s.cfg.name, addr.textContent = s.address + (m.os && '  ·  ' + m.os);
        grade.hidden = !s.online, chip.hidden = s.online, chip.textContent = s.status, grade.redraw(), body.redraw();
        foot.replaceChildren(...(!s.online ? [h('span', { style: { color: s.status === 'Offline' ? C.red : C.muted } }, s.status === 'Disabled' ? 'Monitoring disabled' : s.status === 'Offline' ? 'Unreachable: ' + s.err : 'Waiting for data…')] : [
            h('div.row', null, h('span', { style: { color: C.teal } }, '↓ ' + Fmt.rate(m.netRxBps)), h('span.grow', { style: { color: C.pink } }, '↑ ' + Fmt.rate(m.netTxBps)),
                `load ${Fmt.fix(m.load1, 2)}  ·  up ${Fmt.duration(m.uptime)}`),
            h('div.row', null, h('span.grow', null, `${m.cpuCount} cores · ${m.procs} procs` + (ap.enabled ? ap.dryRun ? ' · autopilot (dry run)' : ' · autopilot on' : '')),
                n > 0 && h('span.warn', { style: { color: crit ? C.red : C.amber, background: tint(crit ? C.red : C.amber, 45) } }, '⚠ ' + n))]));
    };
    return el;
}
const dash = (() => {
    const sub = h('div.muted'), search = h('input', { type: 'search', placeholder: 'Search servers…', oninput: () => el.update() }), cards = h('div.cards'), events = h('div.events');
    const t = tiles([['Servers online', 'green'], ['Avg health', 'teal'], ['Active problems', 'red'], ['Avg CPU', 'accent'], ['Avg memory', 'violet'], ['Total network', 'pink']]);
    const add = h('div.card.add', { onclick: () => editServer() }, h('i', null, '+'), h('b', null, 'Add server'), h('small', null, 'This machine · SSH'));
    const el = h('section', null, h('div.row', null, h('div.grow', null, h('h1', null, 'Dashboard'), sub), search, h('button.primary', { onclick: () => editServer() }, '+  Add server')), t,
        h('div.row.stretch.fill', null, h('div.scroll.grow', null, cards), h('div.side', null, panel('Recent events', events))));
    el.update = () => {
        const on = S.servers.filter(s => s.cfg.enabled), live = on.filter(s => s.online), n = live.length, sum = f => live.reduce((a, s) => a + f(s), 0);
        const problems = on.reduce((a, s) => a + s.alerts.length + (s.online && s.findings.filter(f => f !== 'info').length), 0), health = Math.round(sum(s => s.health) / n);
        keyed(cards, card, [add]);
        S.servers.forEach((s, i) => cards.children[i].hidden = ![s.cfg.name, s.cfg.host, s.cfg.group, s.m.hostname].join(' ').toLowerCase().includes(search.value.toLowerCase()));
        sub.textContent = `${S.servers.length} server(s) monitored  ·  updated ${tf(Date.now(), 'HH:mm:ss')}`;
        t.set(0, `${n} / ${on.length}`, on.length > n ? `${on.length - n} unreachable` : 'all reachable', n === on.length ? C.green : C.amber);
        t.set(2, problems, problems ? 'alerts + insights' : 'all clear', problems ? C.red : C.green);
        if (!n) return [1, 3, 4, 5].forEach(i => t.set(i, '—'));
        t.set(1, health, 'score 0–100', healthColor(health));
        t.set(3, Fmt.pct(sum(s => s.m.cpuUsage) / n), '', level(sum(s => s.m.cpuUsage) / n)), t.set(4, Fmt.pct(sum(s => s.m.memPct) / n), '', level(sum(s => s.m.memPct) / n));
        t.set(5, Fmt.rate(sum(s => s.m.netRxBps + s.m.netTxBps)), `↓ ${Fmt.rate(sum(s => s.m.netRxBps))}   ↑ ${Fmt.rate(sum(s => s.m.netTxBps))}`);
    };
    el.events = () => events.replaceChildren(...S.alerts.slice(0, 200).map(e => h('div', { style: { color: sevColor(e.severity) } }, `${tf(e.time, 'HH:mm:ss')}  ·  ${e.serverName}`, h('br'), e.message)));
    return el;
})();

// ---- server tabs: each builder returns an element with refresh() (new sample) and optionally analysis() ----
function overviewTab() {
    const g = ['CPU', 'Memory', 'Fullest disk', 'Swap', 'Temperature', 'Health'].map((n, i) => gauge(n, 70, i === 4 ? 85 : 90)), info = h('div');
    const t = tiles([['Load average', 'accent'], ['Processes', 'violet'], ['TCP connections', 'teal'], ['Services', 'green'], ['Uptime', 'amber']]);
    const cpu = chart('CPU', pctFmt, 100, true), mem = chart('Memory', pctFmt, 100), net = chart('Network', Fmt.rate), io = chart('Disk I/O', Fmt.rate);
    const el = h('div.tab.scroll', null, h('div.panel.gauges', null, g), t, h('div.row.top', null, h('div.grid2.grow', null, cpu, mem, net, io), h('div.side', null, panel('System', info))));
    el.refresh = () => {
        const m = S.m, a = S.an, s = cur(), T = times(), sp = spanMs(), tcp = k => m.tcp[k] || 0;
        g[0].set(m.cpuUsage, '', m.cpuCount + ' cores'), g[1].set(m.memPct, '', `${Fmt.bytes(m.memUsed)} / ${Fmt.bytes(m.memTotal)}`), g[2].set(m.maxDiskPct, '', m.fullestMount);
        g[3].set(m.swapPct, '', m.swapTotal > 0 ? `${Fmt.bytes(m.swapUsed)} / ${Fmt.bytes(m.swapTotal)}` : 'no swap');
        g[4].set(Math.min(100, m.maxTemp), m.temps.length ? Fmt.temp(m.maxTemp) : '—', m.temps.length ? m.temps.length + ' sensors' : 'no sensors');
        g[5].set(a.health, String(a.health), 'grade ' + a.grade, healthColor(a.health));
        t.set(0, Fmt.fix(m.load1, 2), `5m ${Fmt.fix(m.load5, 2)} · 15m ${Fmt.fix(m.load15, 2)}`, level(m.load1 * 100 / Math.max(1, m.cpuCount), 80, 150));
        t.set(1, m.procs.length, `${m.threadsTotal} threads · ${m.procsRunning} running`);
        t.set(2, tcp('ESTABLISHED'), `${tcp('LISTEN')} listening · ${tcp('TIME_WAIT')} time-wait`);
        t.set(3, m.servicesRunning, m.servicesFailed ? m.servicesFailed + ' failed' : 'running · none failed', m.servicesFailed ? C.red : '');
        t.set(4, Fmt.duration(m.uptime), m.loggedUsers + ' user(s) logged in');
        cpu.set(T, cpuSeries(false), sp), mem.set(T, [ser('Used', C.violet, col(MEM)), ser('Cache', C.blue, col(CACHE), false, true), ser('Swap', C.pink, col(SWAP), false)], sp);
        net.set(T, [ser('Down', C.teal, col(RX)), ser('Up', C.pink, col(TX))], sp), io.set(T, [ser('Read', C.blue, col(RD)), ser('Write', C.orange, col(WR))], sp);
        info.replaceChildren(kv([['Hostname', m.hostname], ['OS', m.os], ['Kernel', m.kernel + ' ' + m.arch], ['CPU', m.cpuModel],
            ['Cores', m.cpuCount + (m.avgMhz > 0 ? ` @ ${Fmt.fix(m.avgMhz / 1000, 2)} GHz` : '')], ['Memory', Fmt.bytes(m.memTotal)], ['Swap', m.swapTotal > 0 ? Fmt.bytes(m.swapTotal) : 'none'],
            ['Virtualisation', m.virt], ['Disks', m.mounts.length + ' mounted file systems'], ['Interfaces', m.nets.length], ['GPU', m.gpus[0]?.name || 'none'],
            ['Connection', `${s.address} (${s.cfg.transport ? 'SSH' : 'Local'})`], ['Sample interval', s.cfg.interval + ' s']]));
    };
    return el;
}

function cpuTab() {
    const P = S.plat, model = h('h2'), cores = h('div.cores');
    const t = tiles([['Usage', 'accent'], ['Load 1 / 5 / 15', 'violet'], ['Avg frequency', 'teal'], [P.posixCpu ? 'Steal / IRQ' : 'Interrupts + DPC', 'orange'], ['Context switches', 'blue'],
        ['Interrupts', 'pink'], ['New processes', 'green'], ['Running / blocked', 'amber']], 4);
    const usage = chart('CPU time breakdown', pctFmt, 100, true), load = chart('Load average (1 min)', numFmt(1));
    const temps = table(['Sensor', 'Temperature'], { widths: [300], empty: ['No temperature sensors exposed (common on VMs)', C.muted] });
    const gpus = table(['#', 'Name', 'Usage', 'Memory', 'Temp', 'Power', 'Fan'], { widths: [40, 220, 120, 160] }), gpuPanel = panel('GPUs', gpus);
    const el = h('div.tab.scroll', null, model, t, h('div.row.top', null, h('div.grow3', null, usage), h('div.grow2', null, load)), panel('Per core', cores),
        h('div.grid2', null, panel('Temperatures', temps), gpuPanel));
    el.refresh = () => {
        const m = S.m, T = times(), f2 = v => Fmt.fix(v, 2);
        model.textContent = m.cpuModel || 'Processor';
        t.set(0, Fmt.pct(m.cpuUsage), `user ${Fmt.pct(m.cpuUser)} · system ${Fmt.pct(m.cpuSystem)}` + (P.posixCpu ? ` · iowait ${Fmt.pct(m.cpuIowait)}` : ''), level(m.cpuUsage));
        t.set(1, `${f2(m.load1)} / ${f2(m.load5)} / ${f2(m.load15)}`, `${Math.round(m.load1 * 100 / Math.max(1, m.cpuCount))}% of ${m.cpuCount} cores`);
        t.set(2, m.avgMhz > 0 ? f2(m.avgMhz / 1000) + ' GHz' : 'n/a');
        if (P.posixCpu) t.set(3, `${Fmt.pct(m.cpuSteal)} / ${Fmt.pct(m.cpuIrq)}`, 'steal > 5% = noisy neighbours', m.cpuSteal > 5 ? C.amber : '');
        else t.set(3, Fmt.pct(m.cpuIrq), 'hardware interrupts and deferred calls', m.cpuIrq > 15 ? C.amber : '');
        t.set(4, Fmt.count(m.ctxtPerSec) + '/s'), t.set(5, Fmt.count(m.intrPerSec) + '/s'), t.set(6, Fmt.fix(m.forksPerSec, 1) + '/s');
        t.set(7, `${m.procsRunning} / ${m.procsBlocked}`, P.posixCpu ? 'blocked = waiting for I/O' : 'blocked = waiting for a CPU', m.procsBlocked > m.cpuCount ? C.amber : '');
        usage.set(T, cpuSeries(true), spanMs()), load.set(T, [ser('Load', C.violet, col(LOAD)), ser('Cores', C.faint, T.map(() => m.cpuCount), false, true)], spanMs());
        cores.replaceChildren(...m.cores.map((c, i) => {
            const color = level(c.usage, 60, 85);
            return h('div', { style: { background: mix(C.card, color, c.usage / 420), 'border-color': mix(C.border, color, c.usage / 160) } },
                h('small', null, 'CPU ' + i, c.mhz > 0 && h('span', null, Fmt.fix(c.mhz / 1000, 1) + 'G')), h('b', null, pctFmt(c.usage)), h('div.track', null, h('i', { style: { width: c.usage + '%', background: color } })));
        }));
        temps.fill(m.temps.map(x => [x.name, { t: Fmt.temp(x.celsius), pct: Math.min(100, x.celsius) }]));
        gpuPanel.hidden = !m.gpus.length;
        gpus.fill(m.gpus.map(x => [x.index, x.name, { t: Fmt.pct(x.util, 0), pct: x.util }, { t: `${Fmt.num(x.memUsed)} / ${Fmt.num(x.memTotal)} MiB`, pct: x.memTotal > 0 ? x.memUsed * 100 / x.memTotal : 0 },
            { t: Fmt.temp(x.temp), c: level(x.temp, 75, 88) }, Fmt.num(x.power) + ' W', Fmt.pct(x.fan, 0)]));
    };
    return el;
}

function memoryTab() {
    const t = tiles([['Used', 'violet'], ['Available', 'green'], ['Cache + buffers', 'blue'], ['Swap used', 'pink']]), bar = segbar(), swap = segbar(), detail = h('div');
    const usage = chart('Memory usage', pctFmt, 100), top = table(['PID', 'Process', 'User', 'RSS', 'Memory %', 'Virtual'], { widths: [80, 220, 120, 110, 160] });
    const el = h('div.tab.scroll', null, t, panel('Composition', bar, h('div.section', null, 'Swap'), swap), h('div.row.top', null, h('div.grow', null, usage), h('div.side', null, panel('Details', detail))),
        panel('Top memory consumers', top));
    el.refresh = () => {
        const m = S.m, free = '#364463';
        t.set(0, Fmt.bytes(m.memUsed), `${Fmt.pct(m.memPct)} of ${Fmt.bytes(m.memTotal)}`, level(m.memPct)), t.set(1, Fmt.bytes(m.memAvailable), 'free ' + Fmt.bytes(m.memFree));
        t.set(2, Fmt.bytes(m.cached + m.buffers), 'reclaimable when needed');
        t.set(3, m.swapTotal > 0 ? Fmt.bytes(m.swapUsed) : 'no swap', m.swapTotal > 0 ? `${Fmt.pct(m.swapPct)} of ${Fmt.bytes(m.swapTotal)}` : '', level(m.swapPct, 40, 80));
        bar.set([[Math.max(0, m.memTotal - m.memFree - m.cached - m.buffers), C.violet, 'Applications'], [m.shared, C.pink, 'Shared'], [m.buffers, C.teal, 'Buffers'],
            [Math.max(0, m.cached - m.shared), C.blue, 'Cache'], [m.memFree, free, 'Free']], m.memTotal);
        swap.set([[m.swapUsed, C.pink, 'Used'], [m.swapTotal - m.swapUsed, free, 'Free']], m.swapTotal);
        usage.set(times(), [ser('Used', C.violet, col(MEM)), ser('Cache', C.blue, col(CACHE), false, true), ser('Swap', C.pink, col(SWAP))], spanMs());
        detail.replaceChildren(kv([['Total', m.memTotal], ['Used', m.memUsed], ['Available', m.memAvailable], ['Free', m.memFree], ['Buffers', m.buffers], ['Cached', m.cached], ['Shared', m.shared],
            ['Slab', m.slab], ['Dirty', m.dirty], ['Swap total', m.swapTotal], ['Swap used', m.swapUsed]].map(([k, v]) => [k, Fmt.bytes(v)])));
        top.fill(m.procs.toSorted((a, b) => b.rss - a.rss).slice(0, 15).map(p => [{ t: p.pid, c: C.muted }, p.name, { t: p.user, c: C.muted }, { t: Fmt.bytes(p.rss), r: 1 },
            { t: Fmt.pct(p.memPct), pct: Math.min(100, p.memPct * 2) }, { t: Fmt.bytes(p.vsz), c: C.muted, r: 1 }]));
    };
    return el;
}

function storageTab() {
    const t = tiles([['Fullest file system', 'amber'], ['Read', 'blue'], ['Write', 'orange'], ['Busiest disk', 'red']]), io = chart('Disk throughput', Fmt.rate);
    const mounts = table(['Mount point', 'Device', 'Type', 'Size', 'Used', 'Free', 'Usage'], { widths: [260, 140, 80, 110, 110, 110] });
    const disks = table(['Device', 'Read/s', 'Write/s', 'Read IOPS', 'Write IOPS', 'Busy', 'Total read', 'Total written'], { widths: [110, 110, 110, 100, 100, 150, 120] });
    const el = h('div.tab.scroll', null, t, panel('File systems', mounts), io, panel('Block devices', disks));
    el.refresh = () => {
        const m = S.m, right = (t, c) => ({ t, c, r: 1 });
        t.set(0, Fmt.pct(m.maxDiskPct), m.fullestMount, level(m.maxDiskPct, 80, 90)), t.set(1, Fmt.rate(m.diskReadBps)), t.set(2, Fmt.rate(m.diskWriteBps));
        t.set(3, Fmt.pct(m.maxDiskUtil), m.busiestDisk, level(m.maxDiskUtil, 60, 90));
        io.set(times(), [ser('Read', C.blue, col(RD)), ser('Write', C.orange, col(WR))], spanMs());
        mounts.fill(m.mounts.map(x => [x.mount, { t: x.device, c: C.muted }, { t: x.type, c: C.muted }, right(Fmt.bytes(x.total)), right(Fmt.bytes(x.used)), right(Fmt.bytes(x.avail)), { t: Fmt.pct(x.pct), pct: x.pct }]));
        disks.fill(m.disks.map(d => [d.name, right(Fmt.rate(d.readBps), C.blue), right(Fmt.rate(d.writeBps), C.orange), right(Fmt.fix(d.readIops)), right(Fmt.fix(d.writeIops)),
            { t: Fmt.pct(d.util, 0), pct: d.util }, right(Fmt.bytes(d.totalRead), C.muted), right(Fmt.bytes(d.totalWritten), C.muted)]));
    };
    return el;
}

function networkTab() {
    const t = tiles([['Download', 'teal'], ['Upload', 'pink'], ['Established', 'accent'], ['Listening', 'green'], ['Time-wait / close-wait', 'amber'], ['Sockets in use', 'violet']]);
    const iface = h('select', { onchange: () => el.refresh() }), traffic = chart('Traffic', Fmt.rate);
    const nets = table(['Interface', 'State', 'Speed', 'Down/s', 'Up/s', 'Pkts in/s', 'Pkts out/s', 'Received', 'Sent', 'Errors', 'Drops'], { widths: [160, 80, 90, 110, 110, 90, 90, 110, 110, 70] });
    const el = h('div.tab.scroll', null, t, h('div.row', null, h('span.muted', null, 'Interface'), iface), traffic, panel('Interfaces', nets));
    el.refresh = () => {
        const m = S.m, tcp = k => m.tcp[k] || 0, names = ['All physical (total)', ...m.nets.map(n => n.name)], right = (t, c) => ({ t, c, r: 1 });
        t.set(0, Fmt.rate(m.netRxBps), 'physical interfaces'), t.set(1, Fmt.rate(m.netTxBps)), t.set(2, tcp('ESTABLISHED'), 'TCP'), t.set(3, tcp('LISTEN'), 'open TCP ports');
        t.set(4, `${tcp('TIME_WAIT')} / ${tcp('CLOSE_WAIT')}`, 'many close-wait = app not closing sockets', tcp('CLOSE_WAIT') > 100 ? C.amber : ''), t.set(5, m.socketsUsed);
        if ([...iface.options].map(o => o.text).join('\n') !== names.join('\n')) {
            const was = iface.value;
            iface.replaceChildren(...names.map(n => h('option', null, n))), iface.selectedIndex = Math.max(0, names.indexOf(was));
        }
        const all = iface.selectedIndex <= 0, own = k => S.live.map(r => r.net[iface.value]?.[k] ?? 0);
        traffic.head = 'Traffic — ' + (all ? 'all physical interfaces' : iface.value);
        traffic.set(times(), [ser('Down', C.teal, all ? col(RX) : own(0)), ser('Up', C.pink, all ? col(TX) : own(1))], spanMs());
        nets.fill(m.nets.map(x => {
            const dim = x.virt ? C.muted : '';
            return [{ t: x.name + (x.virt ? '  (virtual)' : ''), c: dim }, { t: x.state, c: x.state === 'up' ? C.green : x.state === 'down' ? C.red : C.muted }, { t: x.speed > 0 ? x.speed + ' Mb/s' : '—', c: C.muted },
                right(Fmt.rate(x.rxBps), C.teal), right(Fmt.rate(x.txBps), C.pink), right(Fmt.fix(x.rxPps), dim), right(Fmt.fix(x.txPps), dim), right(Fmt.bytes(x.rxBytes), dim), right(Fmt.bytes(x.txBytes), dim),
                right(x.errors, x.errors ? C.amber : dim), right(x.drops, x.drops ? C.amber : dim)];
        }));
    };
    return el;
}

// filterable, sortable list that keeps its selection across refreshes (processes, services)
function listTab(headers, widths, sort, hint) {
    const filter = h('input', { type: 'search', placeholder: hint, oninput: () => tbl.render() }), summary = h('span.muted.grow'), status = h('div.muted');
    const tbl = table(headers, { widths, sort, sortable: true, select: true }), bar = h('div.row', null, filter, summary), el = h('div.tab.col', null, bar, tbl, status);
    tbl.accept = r => r.some(c => cellText(c).toLowerCase().includes(filter.value.toLowerCase()));
    el.report = async (label, path, body) => { // run a command and show the result in the status line
        status.textContent = 'Running: ' + label, status.style.color = '';
        const r = await api(path, { id: S.id, ...body });
        status.textContent = r.code ? `✗ ${r.cmd}: ${r.out.trim().slice(0, 300)}` : '✓ ' + r.cmd, status.style.color = r.code ? C.red : C.green;
    };
    el.selected = what => tbl.selRow() ? tbl.sel : void (status.textContent = `Select a ${what} first.`, status.style.color = '');
    return Object.assign(el, { tbl, bar, summary });
}

function processTab() {
    const P = S.plat, freeze = h('input', { type: 'checkbox' });
    const el = listTab(['PID', 'Name', 'User', 'State', 'CPU', 'Memory', 'RSS', 'Threads', P.prioLabel, 'Running for'], [80, 230, 120, 100, 130, 130, 100, 80, 70], [4, true], 'Filter by name, user or PID…');
    const STATES = { R: ['Running', C.green], S: ['Sleeping', C.muted], D: ['Disk wait', C.amber], Z: ['Zombie', C.red], T: ['Stopped', C.red], I: ['Idle', C.muted] };
    const picked = () => el.selected('process') && { pid: el.tbl.sel, who: `${cellText(el.tbl.selRow()[1])} (${el.tbl.sel})` }; // read before a question: the list keeps refreshing behind it
    const send = (list, i, label, p) => el.report(`${label} ${p.who}`, 'run', { list, i, arg: p.pid });
    const run = (c, i) => async () => {
        const p = picked();
        if (p && (!c.confirm || await ask(c.label, `${c.label} ${p.who} on ${cur().cfg.name}?`, c.danger))) send('procActions', i, c.label, p);
    };
    const renice = async () => {
        const p = picked(), pick = h('select', null, P.priorities.map(c => h('option', null, c.label)));
        pick.selectedIndex = P.priorities.length >> 1;
        if (p && await dialog('Change priority', h('div.col', null, `Priority for ${p.who}:`, pick), [['OK', '.primary', () => true], ['Cancel', '', () => false]])) send('priorities', pick.selectedIndex, 'Priority', p);
    };
    const acts = P.procActions.map((c, i) => [c, run(c, i)]);
    el.bar.firstChild.after(h('label.check', { title: "Stop refreshing so rows don't move while you pick one" }, freeze, 'Freeze list'));
    el.bar.append(...acts.filter(([c]) => c.button).map(([c, fn]) => h('button' + (c.danger ? '.danger' : ''), { onclick: fn }, c.label)), h('button', { onclick: renice }, 'Priority…'));
    el.tbl.menu = () => [...acts.map(([c, fn]) => [c.label, fn]), null, ['Change priority…', renice]];
    el.refresh = () => {
        const m = S.m, num = (v, c) => ({ t: v, k: v, c, r: 1 });
        if (freeze.checked) return;
        el.tbl.fill(m.procs.map(p => [num(p.pid, C.muted), p.name, { t: p.user, c: C.muted }, { t: (STATES[p.state] || [p.state])[0], c: (STATES[p.state] || [0, C.muted])[1] },
            { t: Fmt.pct(p.cpu), pct: Math.min(100, p.cpu), k: p.cpu }, { t: Fmt.pct(p.memPct), pct: p.memPct, k: p.memPct }, { ...num(p.rss), t: Fmt.bytes(p.rss) }, num(p.threads),
            num(p.nice, p.nice === P.normalPrio ? '' : C.teal), { ...num(p.age, C.muted), t: Fmt.duration(p.age) }]));
        el.summary.textContent = `${m.procs.length} processes · ${m.procs.filter(p => p.state === 'R').length} running · ${m.threadsTotal} threads`;
    };
    return el;
}

function serviceTab() {
    const P = S.plat, el = listTab(['Service', 'Active', 'State', 'Load', 'Description'], [300, 100, 100, 90], [0, false], 'Filter services…'), matches = el.tbl.accept;
    const state = h('select', { onchange: () => el.tbl.render() }, ['All', 'Running', 'Failed', 'Not running'].map(t => h('option', null, t)));
    const act = (c, i) => async () => {
        const unit = el.selected('service');
        if (unit && (!c.confirm || await ask('Confirm', `${c.label} ${unit} on ${cur().cfg.name}?`, c.danger))) el.report(`${c.label} ${unit}`, 'run', { list: 'serviceActions', i, arg: unit });
    };
    const logs = () => {
        const unit = el.tbl.selRow() && el.tbl.sel, id = S.id, out = h('pre.log', null, 'Loading…'), lines = h('input', { type: 'number', min: 50, max: 5000, value: 300 });
        const load = async () => (out.textContent = (await api('logs', { id, unit, lines: lines.value })).out, out.scrollTop = out.scrollHeight);
        if (unit) load(), dialog(`Logs — ${unit} — ${cur().cfg.name}`, h('div.col', null, out, h('div.row', null, lines, 'lines', h('button', { onclick: load }, 'Reload'))), [['Close', '', () => true]], '.wide');
    };
    const acts = P.serviceActions.map((c, i) => [c.label, act(c, i), c.danger]);
    let shown;
    el.tbl.accept = r => {
        const [, active, sub] = r.map(cellText), i = state.selectedIndex;
        return (!i || (i === 1 && sub === 'running') || (i === 2 && active === 'failed') || (i === 3 && sub !== 'running' && active !== 'failed')) && matches(r);
    };
    el.bar.firstChild.after(state);
    el.bar.append(...acts.map(([label, fn, danger]) => h('button' + (danger ? '.danger' : ''), { onclick: fn }, label)), h('button.primary', { onclick: logs }, 'Logs'));
    el.tbl.menu = () => [...acts, null, ['Show logs', logs]];
    el.tbl.addEventListener('dblclick', logs);
    el.refresh = () => {
        const m = S.m, sig = m.services.map(x => x.unit + x.active + x.sub).join();
        if (sig === shown) return; // unchanged: keep the list still
        shown = sig;
        el.tbl.fill(m.services.map(x => {
            const c = x.active === 'failed' ? C.red : x.sub === 'running' ? C.green : x.active === 'active' ? C.teal : C.muted;
            return [x.unit, { t: x.active, c }, { t: x.sub, c }, { t: x.load, c: C.muted }, { t: x.description, c: C.muted }];
        }));
        el.summary.textContent = m.services.length ? `${m.services.length} services · ${m.servicesRunning} running · ${m.servicesFailed} failed` : 'No services reported by this machine';
    };
    return el;
}

function historyTab() {
    const P = S.plat, id = S.id, RANGES = [['1 h', 3600], ['6 h', 21600], ['24 h', 86400], ['7 d', 604800], ['30 d', 2592000], ['90 d', 7776000], ['1 y', 31536000], ['All', 0]];
    let range = 86400, loaded = 0;
    const res = h('span.muted.grow'), csv = h('a.button', null, 'Export CSV…'), buttons = RANGES.map(([t, sec]) => h('button', { onclick: () => (range = sec, reload()) }, t));
    const charts = [['CPU', pctFmt, 100], ['Memory & swap', pctFmt, 100], ['Disk usage (fullest)', pctFmt, 100], ['Disk throughput', Fmt.rate], ['Network', Fmt.rate], ['Load average', numFmt(1)],
        ['Temperature', v => Fmt.fix(v) + '°'], ['Availability', pctFmt, 100]].map(([t, fmt, max]) => chart(t, fmt, max, false, 'No history for this range yet'));
    const st = table(['Metric', 'Minimum', 'Average', '95th percentile', 'Peak', 'Points'], { widths: [200, 150, 150, 150, 150] });
    const el = h('div.tab.scroll', null, h('div.row', null, buttons, res, csv), h('div.grid2', null, charts), panel('Statistics for the selected range', st));
    async function reload() {
        const query = `?id=${encodeURIComponent(id)}&range=${range}`, right = (t, c) => ({ t, c, r: 1 });
        loaded = Date.now(), csv.href = '/api/history.csv' + query, buttons.forEach((b, i) => b.classList.toggle('on', RANGES[i][1] === range));
        const d = await api('history' + query), v = d.v, peak = (name, color, data) => d.aggregated ? [ser(name, color, data, false, true)] : [];
        const data = [[ser('Average', C.accent, v.cpu), ...peak('Peak', C.red, v.cpuMax)], [ser('Memory', C.violet, v.mem), ser('Swap', C.pink, v.swap, false)], [ser('Usage', C.amber, v.disk)],
            [ser('Read', C.blue, v.rd), ser('Write', C.orange, v.wr)], [ser('Down', C.teal, v.rx), ser('Up', C.pink, v.tx), ...peak('Peak down', '#60ffeb', v.rxMax)], [ser('Load', C.violet, v.load)],
            [ser('Average', C.orange, v.temp), ...peak('Peak', C.red, v.tempMax)], [ser('Online', C.green, v.avail)]];
        charts.forEach((c, i) => (c.sub = d.aggregated ? 'avg per ' + d.tier : '', c.set(d.t, data[i], d.span)));
        res.textContent = `Resolution: ${d.tier}  ·  ${d.points} points  ·  availability ${ok(d.availability) ? Fmt.pct(d.availability, 2) : '—'}  ·  stored ${Fmt.bytes(d.bytes)}`;
        st.fill(d.stats.map((x, m) => [hNames[m], right(fmtMetric(m, x.min), C.muted), right(fmtMetric(m, x.avg)), right(fmtMetric(m, x.p95), C.amber), right(fmtMetric(m, x.max), C.red), right(x.count, C.muted)])
            .filter((_, m) => m < 14 && (P.posixCpu || m !== 1)));
    }
    el.refresh = () => Date.now() - loaded >= (range && range <= 21600 ? 5000 : 60000) && reload();
    return el;
}

function insightsTab() {
    const id = S.id, ap = { ...cur().cfg.autopilot }, f = fields(ap, () => api('server/update', { id, autopilot: ap }));
    const health = gauge('Health score'), reasons = h('div.muted.pre'), capacity = h('div.col'), findings = h('div.col'), heat = h('div.heat');
    const t = tiles([['Disk full forecast', 'amber'], ['Memory trend (6 h)', 'violet'], ['CPU / memory p95 (30 d)', 'accent'], ['Availability 24 h', 'green'], ['Availability 7 d', 'green'], ['Availability 30 d', 'green']], 3);
    const heatMetric = h('select', { onchange: () => el.analysis() }, h('option', null, 'CPU'), h('option', null, 'Memory'));
    const anomalies = table(['Metric', 'Last 10 min', 'Usual', 'Deviation', 'Baseline'], { widths: [110, 110, 160, 90] });
    const autopilot = panel('Autopilot — automatic control', h('div.muted', null, 'Acts on the findings once a minute, using statistics over the stored history. Every action is logged as an event.'), form([
        [f.check('enabled', 'Autopilot enabled'), f.check('dryRun', 'Dry run (only report)')],
        [f.check('restartFailed', 'Restart failed services'), [f.num('maxRestartsPerHour', 1, 20), '/ hour max']],
        ['Runaway processes', f.select('runawayMode', [['none', 'Ignore'], ['renice', 'Lower priority (renice 19)'], ['terminate', 'Terminate']])],
        ['', ['≥', f.num('runawayCpu', 10, 6400), '%  for', f.num('runawayMinutes', 1, 1440), 'min']],
        ['Memory leaks', f.select('leakMode', [['none', 'Ignore'], ['notify', 'Notify'], ['terminate', 'Terminate under pressure']])], ['  pressure ≥', [f.num('leakMemPressure', 50, 100), '% memory']],
        [f.check('diskCleanup', 'Disk cleanup'), ['full in <', f.num('diskForecastDays', 1, 60), 'days']], ['', ['or usage ≥', f.num('diskCleanupAt', 50, 100), '%']],
        ['  command', f.text('diskCleanupCommand', { className: 'mono grow' })], [f.check('anomalyAlerts', 'Anomaly alerts'), ['z ≥', f.num('anomalyZ', 1.5, 10, .5), 'σ']]]));
    const el = h('div.tab.scroll', null,
        h('div.row.top', null, h('div.side', null, panel('Health', health, reasons, h('button', { onclick: () => api('server/analyze', { id }) }, 'Analyze now'))), h('div.col.grow', null, t, panel('Capacity planning', capacity))),
        h('div.row.top', null, h('div.grow', null, panel('Findings from history analysis', findings)), h('div.side.wide', null, autopilot)),
        h('div.row.top', null, h('div.grow3', null, panel('Weekly pattern (last 4 weeks, hourly averages)', heatMetric, heat)), h('div.grow2', null, panel('Now vs. normal (baselines)', anomalies))));
    el.analysis = () => {
        const a = S.an, s = cur(), hi = heatMetric.selectedIndex, f2 = v => Fmt.fix(v, 2), days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
        health.set(a.health, String(a.health), 'grade ' + a.grade, healthColor(a.health));
        reasons.textContent = (a.healthReasons.join('\n') || 'No deductions — everything looks healthy.') + (a.when ? '\n\nAnalyzed ' + tf(a.when * 1000, 'HH:mm:ss') : '');
        if (a.diskFullDays >= 0) t.set(0, Fmt.duration(a.diskFullDays * 86400), `+${f2(a.diskSlopePerDay)} pts/day · ${a.diskBasis}`, a.diskFullDays < 7 ? C.red : a.diskFullDays < 30 ? C.amber : '');
        else t.set(0, 'Not filling', a.diskBasis ? `trend ${f2(a.diskSlopePerDay)} pts/day` : 'needs ~2 h of history', C.green);
        if (a.memTrendR2 > 0) t.set(1, `${a.memSlopePerHour >= 0 ? '+' : ''}${f2(a.memSlopePerHour)} pts/h`, 'fit R² ' + f2(a.memTrendR2), a.memSlopePerHour > 1 && a.memTrendR2 > .8 ? C.amber : '');
        else t.set(1, '—', 'needs ~90 min of history');
        if (a.cpu30.count) t.set(2, `${Fmt.pct(a.cpu30.p95, 0)} / ${Fmt.pct(a.mem30.p95, 0)}`, `avg ${Fmt.pct(a.cpu30.avg, 0)} / ${Fmt.pct(a.mem30.avg, 0)}`);
        else t.set(2, '—', 'collecting');
        a.up.forEach((up, i) => ok(up) ? t.set(3 + i, Fmt.pct(up, up >= 99.995 ? 0 : 2), `≈ ${Fmt.duration(a.down[i])} offline`, up >= 99.9 ? C.green : up >= 99 ? C.amber : C.red)
            : t.set(3 + i, '—', 'no data yet'));
        capacity.replaceChildren(...a.capacity.map(line => h('div', null, '• ' + line)));
        heat.replaceChildren(...days.flatMap((day, d) => [h('small', null, day.slice(0, 3)), ...a.heat[hi][d].map((v, hour) => h('i', {
            title: `${day} ${hour}:00 — ` + (ok(v) ? `avg ${Fmt.fix(v, 1)}${hi ? '% memory' : '% CPU'} (${a.heatN[d][hour]} samples)` : 'no data'),
            style: { background: ok(v) ? mix('#1b2a44', hi ? C.violet : C.accent, .15 + .85 * v / 100) : C.card } }))]),
            h('small'), ...Array.from({ length: 24 }, (_, hour) => h('small', null, hour % 3 ? '' : pad(hour) + ':00')),
            ...(a.heatN.flat().some(Boolean) ? [] : [h('p', null, 'Collecting hourly history… the weekly pattern fills in over time')]));
        anomalies.fill(a.anomalies.map(x => [x.metric, { t: fmtMetric(x.hm, x.now), r: 1 }, { t: `${fmtMetric(x.hm, x.mean)} ± ${fmtMetric(x.hm, x.sd)}`, c: C.muted, r: 1 },
            { t: `${x.z >= 0 ? '+' : ''}${Fmt.fix(x.z, 1)}σ`, c: Math.abs(x.z) >= 3 ? C.red : Math.abs(x.z) >= 2 ? C.amber : C.green, r: 1 }, { t: x.baseline, c: C.muted }]));
        findings.replaceChildren(...a.findings.map(x => {
            const color = sevColor(x.severity), auto = x.autoEligible && s.cfg.autopilot.enabled;
            const fix = x.action && h('button' + (x.action === 'kill_pid' ? '.danger' : '.primary'), { onclick: async () => { // the card may be rebuilt while the question is open
                if (!await ask(x.actionLabel, `${x.actionLabel} on ${s.cfg.name}?\n\n${x.title}`, x.action === 'kill_pid')) return;
                fix.disabled = true, fix.textContent = 'Working…';
                fix.textContent = (await api('finding', { id, key: x.key })).code ? '✗ Failed' : '✓ Done';
            } }, x.actionLabel);
            return h('div.finding', { style: { 'border-left-color': color } }, h('div.grow', null, h('small', { style: { color } }, `${x.severity} · ${x.category}`), h('b', null, x.title), h('div', null, x.detail),
                h('div.muted', null, '→ ' + x.advice), auto && h('small', { style: { color: C.violet } }, s.cfg.autopilot.dryRun ? 'Autopilot (dry run) would act on this' : 'Autopilot handles this automatically')), fix);
        }));
        if (!a.findings.length) findings.append(h('div', { style: { color: C.green } },
            '✓  No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, service failures, overload and anomalies every minute.'));
    };
    return el;
}

function rulesTab() {
    const P = S.plat, id = S.id, metrics = ruleMetrics.filter(d => P.posixCpu || d[0] !== 'iowait'), store = rules => api('server/update', { id, rules });
    const list = table(['On', 'Condition', 'Severity', 'Action', 'Cooldown', 'Live value'], { widths: [50, 380, 100, 330, 100], select: true });
    const active = table(['Active problems'], { empty: ['✓ No rule is currently triggered', C.green] });
    const edit = async old => {
        const rs = cur().cfg.rules, r = { ...(old || S.rule) }, f = fields(r, () => sync()), arg = f.text('arg', { className: 'grow' });
        const sync = () => (arg.placeholder = def(P.ruleActions, r.action)[2], arg.disabled = !arg.placeholder);
        sync();
        if (!await dialog(old ? 'Edit rule' : 'New rule', form([['When', f.select('metric', metrics.map(([k, label, unit]) => [k, label + (unit && ` (${unit})`)]))],
            ['is', [f.select('op', [['>', '>'], ['<', '<']]), f.num('value', -1e9, 1e9, 'any')]], ['for at least', [f.num('duration', 0, 86400), 's']],
            ['Severity', f.select('severity', ['info', 'warning', 'critical'].map(x => [x, x]))], ['Then', f.select('action', P.ruleActions)], ['Argument', arg],
            ['Repeat after', [f.num('cooldown', 10, 86400), 's']], ['', f.check('enabled', 'Enabled')]]), [['OK', '.primary', () => true], ['Cancel', '', () => false]])) return;
        if (arg.disabled) r.arg = '';
        store(old ? rs.map(x => x === old ? r : x) : [...rs, r]);
    };
    const selected = () => cur().cfg.rules.find(r => r.id === list.sel);
    const el = h('div.tab.col', null, h('div.muted', null, 'Threshold rules are checked on every sample. When a condition holds for its duration an alert is raised and the action runs; ' +
        'if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.'),
        h('div.row', null, h('button.primary', { onclick: () => edit() }, '+ Add rule'), h('button', { onclick: () => selected() && edit(selected()) }, 'Edit'),
            h('button.danger', { onclick: () => selected() && store(cur().cfg.rules.filter(r => r.id !== list.sel)) }, 'Delete'), h('span.grow'),
            h('button', { onclick: async () => await ask('Reset rules', 'Replace all rules with the defaults?') && store(S.defaultRules) }, 'Reset to defaults')), list, active);
    let shown, boxes;
    list.addEventListener('dblclick', () => selected() && edit(selected()));
    el.refresh = () => {
        const s = cur(), rs = s.cfg.rules;
        if (shown !== (shown = JSON.stringify(rs))) boxes = rs.map(r => h('input', { type: 'checkbox', checked: r.enabled, onchange: e => store(rs.map(x => x === r ? { ...r, enabled: e.target.checked } : x)) }));
        list.fill(rs.map((r, i) => {
            const v = S.vals[r.metric] ?? 0;
            return Object.assign([{ el: boxes[i] }, { t: conditionText(r), c: r.enabled ? '' : C.faint }, { t: r.severity, c: sevColor(r.severity) }, { t: actionText(P.ruleActions, r), c: r.action === 'notify' ? C.muted : C.violet },
                { t: r.cooldown + ' s', c: C.muted }, { t: `${Fmt.fix(v, 1)} ${def(ruleMetrics, r.metric)[2]}`, c: (r.op === '<' ? v < r.value : v > r.value) ? C.red : C.green }], { key: r.id });
        }));
        active.fill(s.alerts.map(a => [{ t: '⚠ ' + a, c: C.red }]));
    };
    return el;
}

function consoleTab() {
    const P = S.plat, s = cur(), id = S.id, out = h('div.console.mono'), sudo = h('input', { type: 'checkbox' }), past = [];
    let pos = 0;
    const say = (cls, ...parts) => { // keeps the last 2000 blocks
        out.append(h('div' + cls, null, parts)), out.childElementCount > 2000 && out.firstChild.remove(), out.scrollTop = out.scrollHeight;
    };
    const exec = async (cmd, privileged) => {
        const t0 = Date.now();
        say('.cmd', h('b', null, tf(t0, 'HH:mm:ss') + ' $ '), cmd);
        const r = await api('exec', { id, cmd, privileged });
        if (r.out) say('', r.out.replace(/\n$/, ''));
        say(r.code ? '.bad' : '.good', `[exit ${r.code} · ${Date.now() - t0} ms]`);
    };
    const run = () => {
        const c = input.value.trim();
        if (!c) return;
        if (past.at(-1) !== c) past.push(c);
        pos = past.length, input.value = '', exec(c, sudo.checked);
    };
    const input = h('input.mono.grow', { placeholder: 'Type a shell command and press Enter (↑/↓ history)', onkeydown: e => {
        if (e.key === 'Enter') return run();
        if (!past.length || !['ArrowUp', 'ArrowDown'].includes(e.key)) return;
        e.preventDefault(), pos = clamp(pos + (e.key === 'ArrowUp' ? -1 : 1), 0, past.length), input.value = past[pos] || '';
    } });
    const group = (title, items, system) => panel(title, items.map(q => h('button.left' + (q.danger ? '.danger' : ''), { title: q.cmd, onclick: async () => {
        if (!system || await ask(q.label, `${q.label} on ${s.cfg.name}?` + (q.danger ? '\n\nThe machine will be unavailable until it comes back.' : ''), q.danger)) exec(q.cmd, system);
    } }, q.label)));
    say('.muted', `Console for ${s.cfg.name} (${s.address}). Commands run non-interactively with a 120 s timeout.`);
    return h('div.tab.row.stretch', null, h('div.col.grow', null, out, h('div.row', null, h('b.prompt', null, '$'), input,
        P.sudo && h('label.check', { title: "Wrap in sudo -n when the server has 'Run control commands with sudo' enabled" }, sudo, 'privileged'),
        h('button.primary', { onclick: run }, 'Run'), h('button', { onclick: () => out.replaceChildren() }, 'Clear'))),
        h('div.side.col.scroll', null, group('Quick diagnostics', P.diagnostics, false), group('System actions', P.systemActions, true)));
}

// ---- server page ----
const TABS = { overview: ['Overview', overviewTab], cpu: ['CPU', cpuTab], memory: ['Memory', memoryTab], storage: ['Storage', storageTab], network: ['Network', networkTab],
    processes: ['Processes', processTab], services: ['Services', serviceTab], history: ['History', historyTab], insights: ['Insights & Autopilot', insightsTab],
    rules: ['Alert rules', rulesTab], console: ['Console', consoleTab] };
let feed, built = {}, builtFor; // the open live stream; tab elements of the server they were built for
const detail = (() => {
    const name = h('h1'), state = h('b.state'), sub = h('div.muted'), chips = h('div.chips'), holder = h('div.fill');
    const act = (path, extra) => api(path, { id: S.id, ...extra });
    const pause = h('button', { onclick: () => act('server/pause', { paused: !cur().paused }) });
    const power = reboot => async () => await ask(reboot ? 'Reboot…' : 'Shut down…', `${reboot ? 'Reboot' : 'Shut down'} ${cur().cfg.name} now?`, true) && act('power', { reboot });
    const span = h('select', { onchange: () => (S.span = +span.value, el.refresh()) }, [5, 15, 30, 60].map(min => h('option', { value: min, selected: min === S.span }, min === 60 ? 'Last hour' : `Last ${min} minutes`)));
    const bar = h('div.tabbar', null, Object.entries(TABS).map(([key, [title]]) => h('button', { onclick: () => go('server', S.id, key) }, title)));
    const el = h('section', null, h('div.row.end', null, h('div.grow', null, h('button.flat', { onclick: () => go('dashboard') }, '‹  Dashboard'), h('div.row', null, name, state), sub, chips),
        h('label.col', null, h('div.section', null, 'Live window'), span), h('button', { onclick: () => act('server/reconnect') }, '⟳ Reconnect'), pause, h('button', { onclick: () => editServer(S.id) }, 'Edit'),
        h('button.danger', { onclick: e => menu(e, [['Reboot…', power(true)], ['Shut down…', power(false)], null, ['Remove from monitor…', () => removeServer(S.id)]]) }, '⏻ Power')), bar, holder);
    el.refresh = withAnalysis => { // header, then the visible tab
        const s = cur(), c = s?.cfg, m = s?.m;
        if (!s) return;
        name.textContent = c.name, state.textContent = '● ' + (s.paused ? 'Paused' : s.status), state.style.color = s.paused ? C.amber : statusColor(s);
        sub.textContent = [s.address, c.transport ? 'SSH' : 'Local', m.hostname && 'host ' + m.hostname, s.online ? 'up ' + Fmt.duration(m.uptime) : s.status === 'Offline' && s.err].filter(Boolean).join('  ·  ');
        chips.replaceChildren(...[[m.os], [m.kernel && S.plat.kernelPrefix + m.kernel], [m.cpuCount && m.cpuCount + ' cores'], [m.memTotal > 0 && Fmt.bytes(m.memTotal) + ' RAM'], [c.group, '#7dd3fc'],
            [s.online && `health ${s.health} (${s.grade})`, healthColor(s.health)], [c.autopilot.enabled && (c.autopilot.dryRun ? 'autopilot: dry run' : 'autopilot: on'), C.violet]]
            .filter(([t]) => t).map(([t, color]) => h('span.chip', { style: { color } }, t)));
        pause.textContent = s.paused ? '▶ Resume' : '❚❚ Pause';
        [...bar.children].forEach((b, i) => b.classList.toggle('on', Object.keys(TABS)[i] === S.tab));
        if (!S.m) return holder.replaceChildren(); // the first event of the stream brings the data
        const tab = built[S.tab] ??= (withAnalysis = true, TABS[S.tab][1]());
        if (holder.firstChild !== tab) holder.replaceChildren(tab), withAnalysis = true;
        tab.refresh?.(), withAnalysis && tab.analysis?.();
    };
    return el;
})();
function listen() { // (re)opens the live stream: server list and events, plus the samples of the server on the detail page
    feed?.close(), S.m = null;
    feed = new EventSource('/api/events' + (S.id ? '?id=' + encodeURIComponent(S.id) : ''));
    const on = (event, fn) => feed.addEventListener(event, e => fn(JSON.parse(e.data)));
    on('hello', d => {
        const missed = S.plat ? d.alerts.filter(a => a.time > (S.alerts[0]?.time || 0)).reverse() : []; // raised while the stream was being reopened
        Object.assign(S, d), document.title = `Server Monitor (${d.plat.name})`, route();
        missed.length ? missed.forEach(alertsChanged) : alertsChanged();
    });
    on('state', d => (S.servers = d, cur() || S.page !== 'server' ? stateChanged() : route()));
    on('alert', d => (S.alerts.unshift(d), S.alerts.length = Math.min(S.alerts.length, 2000), alertsChanged(d)));
    on('alerts', d => (S.alerts = d, S.unseen = 0, alertsChanged()));
    on('live', d => (Object.assign(S, { live: d.rows, m: d.m, vals: d.vals, an: d.an }), detail.refresh(true)));
    on('sample', d => (S.m = d.m, S.vals = d.vals, S.live.push(d.row), S.live.length > 1800 && S.live.shift(), detail.refresh()));
    on('analysis', d => (S.an = d, detail.refresh(true)));
}

// ---- events page ----
const eventsPage = (() => {
    const list = table(['Time', 'Server', 'Type', 'Message'], { widths: [170, 180, 100] }), kind = h('select', { onchange: () => el.update() }, ['All events', 'critical', 'warning', 'info', 'resolved', 'action'].map(t => h('option', null, t)));
    const where = h('div.muted'), notify = h('input', { type: 'checkbox', checked: localStorage.notify === '1', onchange: async () => localStorage.notify = +(notify.checked &&= await Notification.requestPermission() === 'granted') });
    const el = h('section', null, h('div.row', null, h('div.grow', null, h('h1', null, 'Events & alerts'), where), h('label.check', null, notify, 'Browser notifications'), kind,
        h('a.button', { href: '/api/alerts.log' }, 'Download alerts.log'), h('button', { onclick: () => api('alerts/clear', {}) }, 'Clear list')), list);
    el.update = () => {
        where.textContent = `Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log in ${S.dir}`;
        list.fill(S.alerts.filter(e => !kind.selectedIndex || e.severity === kind.value).map(e => [{ t: tf(e.time, 'yyyy-MM-dd HH:mm:ss'), c: C.muted }, e.serverName, { t: e.severity.toUpperCase(), c: sevColor(e.severity) }, e.message]));
    };
    return el;
})();
function alertsChanged(latest) { // latest = the event that just arrived, if any
    const important = ['critical', 'warning', 'action'].includes(latest?.severity);
    if (S.page === 'events') S.unseen = 0;
    else if (important) ++S.unseen;
    if (important && localStorage.notify === '1' && Notification.permission === 'granted') new Notification(`${latest.serverName} — ${latest.severity}`, { body: latest.message, icon: 'icon.svg' });
    badge.textContent = S.unseen, badge.hidden = !S.unseen, dash.events(), eventsPage.update();
}

// ---- pages and routing: #/dashboard, #/events, #/server/<id or position>/<tab> ----
const pages = { dashboard: dash, server: detail, events: eventsPage };
function route() {
    const [page, ref, tab] = location.hash.replace(/^#\/?/, '').split('/').map(decodeURIComponent), s = S.servers.find(x => x.cfg.id === ref) || S.servers[+ref];
    const id = page === 'server' && s ? s.cfg.id : null;
    S.page = id ? 'server' : page === 'events' ? 'events' : 'dashboard', S.tab = tab in TABS ? tab : 'overview';
    if (id && id !== builtFor) built = {}, builtFor = id;
    if (id !== S.id) S.id = id, listen();
    for (const [k, el] of Object.entries(pages)) el.hidden = k !== S.page, nav[k]?.classList.toggle('on', k === S.page);
    stateChanged(), S.page === 'events' && alertsChanged();
}
function stateChanged() {
    keyed(sideList, sideItem), S.page === 'dashboard' ? dash.update() : detail.refresh();
}

document.body.append(sidebar, h('main', null, Object.values(pages)));
listen(), addEventListener('hashchange', route);