File size: 56,147 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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
// Detail-page tabs: each one shows an aspect of the bound server session.
#include "Widgets.h"
#include "Windows.h"
#include <QBoxLayout>
#include <QButtonGroup>
#include <QCheckBox>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QDoubleSpinBox>
#include <QFileDialog>
#include <QFormLayout>
#include <QInputDialog>
#include <QKeyEvent>
#include <QLineEdit>
#include <QMenu>
#include <QPlainTextEdit>
#include <QScrollArea>
#include <QScrollBar>
#include <QSpinBox>
#include <QTextStream>
#include <memory>
#include <type_traits>

// ---- helpers ----------------------------------------------------------------------------
static QVBoxLayout *scrollRoot(QWidget *tab)
{
    auto *outer = new QVBoxLayout(tab);
    auto *sa = new QScrollArea;
    auto *l = new QVBoxLayout(new QWidget);
    outer->setContentsMargins(0, 0, 0, 0), outer->addWidget(sa);
    sa->setWidgetResizable(true), sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), sa->setWidget(l->parentWidget());
    l->setContentsMargins(4, 16, 10, 16), l->setSpacing(16);
    return l;
}
static QVBoxLayout *plainRoot(QWidget *tab)
{
    auto *l = new QVBoxLayout(tab);
    l->setContentsMargins(4, 16, 4, 12), l->setSpacing(10);
    return l;
}
template <class L> static L *sub(QBoxLayout *parent, int stretch = 0) // nested layout with the standard spacing
{
    auto *l = new L;
    l->setSpacing(14), parent->addLayout(l, stretch);
    return l;
}
static QGridLayout *grid(QBoxLayout *parent, int stretch = 0) { return sub<QGridLayout>(parent, stretch); }
static QHBoxLayout *row(QBoxLayout *parent, int stretch = 0) { return sub<QHBoxLayout>(parent, stretch); }
static QVBoxLayout *lay(QFrame *f) { return static_cast<QVBoxLayout *>(f->layout()); }
static QString kv(const QVector<QPair<QString, QString>> &rows)
{
    QString h = "<table>";
    for (const auto &r : rows) h += QString("<tr><td style='color:#8b95ab;padding:3px 18px 3px 0'>%1</td><td>%2</td></tr>").arg(r.first, r.second.toHtmlEscaped());
    return h + "</table>";
}
static QVector<Series> cpuSeries(const Live &h, bool steal)
{
    QVector<Series> s = {{"User", C::accent, h.s[Live::USER]}, {"System", C::violet, h.s[Live::SYS]}};
    if (P::posixCpu) s << Series{"I/O wait", C::amber, h.s[Live::IOWAIT]};
    if (P::posixCpu && steal) s << Series{"Steal", C::red, h.s[Live::STEAL]};
    return s;
}
// run a command and show the result in a status label
static void runReport(ServerSession *s, QLabel *status, const QString &cmd)
{
    status->setText("Running: " + cmd);
    s->exec(cmd, true, [st = QPointer<QLabel>(status), cmd](int code, const QString &out) {
        if (!st) return;
        st->setText(code ? "✗ " + cmd + ": " + out.trimmed().left(300) : "✓ " + cmd);
        st->setStyleSheet(QString("color: %1;").arg((code ? C::red : C::green).name()));
    });
}

// ============================================================================ Overview
struct OverviewTab : Tab {
    QVector<RingGauge *> g;
    QVector<StatTile *> t;
    TimeChart *cpu = new TimeChart("CPU", pctFmt, 100), *mem = new TimeChart("Memory", pctFmt, 100), *net = new TimeChart("Network", rateFmt),
              *io = new TimeChart("Disk I/O", rateFmt);
    QLabel *info = label({}, nullptr, true);

    OverviewTab()
    {
        auto *l = scrollRoot(this);
        auto *gp = panel(), *ip = panel("System", {info, nullptr});
        auto *gl = new QHBoxLayout;
        for (const char *n : {"CPU", "Memory", "Fullest disk", "Swap", "Temperature", "Health"}) g << new RingGauge(n), gl->addWidget(g.last());
        g[4]->crit = 85;
        lay(gp)->addLayout(gl), gp->setMinimumHeight(220), l->addWidget(gp);
        t = addTiles(grid(l), {{"Load average", C::accent}, {"Processes", C::violet}, {"TCP connections", C::teal}, {"Services", C::green}, {"Uptime", C::amber}});
        auto *mid = row(l);
        auto *charts = grid(mid, 1);
        cpu->stacked = true;
        for (auto *c : {cpu, mem, net, io}) c->setMinimumHeight(220), charts->addWidget(c, charts->count() / 2, charts->count() % 2);
        ip->setFixedWidth(330), mid->addWidget(ip), l->addStretch();
    }
    void refresh() override
    {
        const Metrics &m = s->metrics();
        const Live &h = s->live();
        const Analysis &a = s->analysis();
        const ServerConfig &c = s->config();
        g[0]->setValue(m.cpuUsage, {}, QString("%1 cores").arg(m.cpuCount));
        g[1]->setValue(m.memPct, {}, Fmt::bytes(m.memUsed) + " / " + Fmt::bytes(m.memTotal));
        g[2]->setValue(m.maxDiskPct, {}, m.fullestMount);
        g[3]->setValue(m.swapPct, {}, m.swapTotal > 0 ? Fmt::bytes(m.swapUsed) + " / " + Fmt::bytes(m.swapTotal) : "no swap");
        g[4]->setValue(qMin(100.0, m.maxTemp), m.temps.isEmpty() ? "—" : Fmt::temp(m.maxTemp), m.temps.isEmpty() ? "no sensors" : QString("%1 sensors").arg(m.temps.size()));
        g[5]->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health));
        t[0]->set(QString::number(m.load1, 'f', 2), QString("5m %1 · 15m %2").arg(m.load5, 0, 'f', 2).arg(m.load15, 0, 'f', 2), C::level(m.load1 * 100 / qMax(1, m.cpuCount), 80, 150));
        t[1]->set(QString::number(m.procs.size()), QString("%1 threads · %2 running").arg(m.threadsTotal).arg(m.procsRunning));
        t[2]->set(QString::number(m.tcp["ESTABLISHED"]), QString("%1 listening · %2 time-wait").arg(m.tcp["LISTEN"]).arg(m.tcp["TIME_WAIT"]));
        t[3]->set(QString::number(m.servicesRunning), m.servicesFailed ? QString("%1 failed").arg(m.servicesFailed) : "running · none failed", m.servicesFailed ? C::red : C::text);
        t[4]->set(Fmt::duration(m.uptime), QString("%1 user(s) logged in").arg(m.loggedUsers));
        cpu->setData(h.t, cpuSeries(h, false), span);
        mem->setData(h.t, {{"Used", C::violet, h.s[Live::MEM]}, {"Cache", C::blue, h.s[Live::CACHE], false, true}, {"Swap", C::pink, h.s[Live::SWAP], false}}, span);
        net->setData(h.t, {{"Down", C::teal, h.s[Live::RX]}, {"Up", C::pink, h.s[Live::TX]}}, span);
        io->setData(h.t, {{"Read", C::blue, h.s[Live::RD]}, {"Write", C::orange, h.s[Live::WR]}}, span);
        info->setText(kv({{"Hostname", m.hostname}, {"OS", m.os}, {"Kernel", m.kernel + " " + m.arch}, {"CPU", m.cpuModel},
                          {"Cores", QString::number(m.cpuCount) + (m.avgMhz > 0 ? QString(" @ %1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "")},
                          {"Memory", Fmt::bytes(m.memTotal)}, {"Swap", m.swapTotal > 0 ? Fmt::bytes(m.swapTotal) : "none"}, {"Virtualisation", m.virt},
                          {"Disks", QString("%1 mounted file systems").arg(m.mounts.size())}, {"Interfaces", QString::number(m.nets.size())},
                          {"GPU", m.gpus.isEmpty() ? "none" : m.gpus[0].name}, {"Connection", c.address() + " (" + transportName(c.transport) + ")"},
                          {"Sample interval", QString("%1 s").arg(c.interval)}}));
    }
};

// ============================================================================ CPU
struct CpuTab : Tab {
    QLabel *model = label({}, "H2");
    QVector<StatTile *> t;
    TimeChart *chart = new TimeChart("CPU time breakdown", pctFmt, 100), *load = new TimeChart("Load average (1 min)", numFmt(1));
    CoreGrid *cores = new CoreGrid;
    QTableWidget *temps = table({"Sensor", "Temperature"}, {300}, {1}), *gpus = table({"#", "Name", "Usage", "Memory", "Temp", "Power", "Fan"}, {40, 220, 120, 160}, {2, 3});
    QFrame *gpuPanel = panel("GPUs", {gpus});

    CpuTab()
    {
        auto *l = scrollRoot(this);
        l->addWidget(model);
        t = addTiles(grid(l), {{"Usage", C::accent}, {"Load 1 / 5 / 15", C::violet}, {"Avg frequency", C::teal}, {P::posixCpu ? "Steal / IRQ" : "Interrupts + DPC", C::orange},
                               {"Context switches", C::blue}, {"Interrupts", C::pink}, {"New processes", C::green}, {"Running / blocked", C::amber}}, 4);
        auto *r = row(l);
        chart->stacked = true, chart->setMinimumHeight(260), temps->setMinimumHeight(220);
        r->addWidget(chart, 3), r->addWidget(load, 2), l->addWidget(panel("Per core", {cores}));
        auto *b = row(l);
        b->addWidget(panel("Temperatures", {temps}), 1), b->addWidget(gpuPanel, 1), l->addStretch();
    }
    void refresh() override
    {
        const Metrics &m = s->metrics();
        const Live &h = s->live();
        model->setText(m.cpuModel.isEmpty() ? "Processor" : m.cpuModel);
        t[0]->set(Fmt::pct(m.cpuUsage), QString("user %1 · system %2").arg(Fmt::pct(m.cpuUser), Fmt::pct(m.cpuSystem)) + (P::posixCpu ? " · iowait " + Fmt::pct(m.cpuIowait) : ""), C::level(m.cpuUsage));
        t[1]->set(QString("%1 / %2 / %3").arg(m.load1, 0, 'f', 2).arg(m.load5, 0, 'f', 2).arg(m.load15, 0, 'f', 2), QString("%1% of %2 cores").arg(qRound(m.load1 * 100 / qMax(1, m.cpuCount))).arg(m.cpuCount));
        t[2]->set(m.avgMhz > 0 ? QString("%1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "n/a");
        if (P::posixCpu) t[3]->set(Fmt::pct(m.cpuSteal) + " / " + Fmt::pct(m.cpuIrq), "steal > 5% = noisy neighbours", m.cpuSteal > 5 ? C::amber : QColor());
        else t[3]->set(Fmt::pct(m.cpuIrq), "hardware interrupts and deferred calls", m.cpuIrq > 15 ? C::amber : QColor());
        t[4]->set(Fmt::count(m.ctxtPerSec) + "/s"), t[5]->set(Fmt::count(m.intrPerSec) + "/s"), t[6]->set(QString::number(m.forksPerSec, 'f', 1) + "/s");
        t[7]->set(QString("%1 / %2").arg(m.procsRunning).arg(m.procsBlocked), P::posixCpu ? "blocked = waiting for I/O" : "blocked = waiting for a CPU", m.procsBlocked > m.cpuCount ? C::amber : QColor());
        chart->setData(h.t, cpuSeries(h, true), span);
        load->setData(h.t, {{"Load", C::violet, h.s[Live::LOAD]}, {"Cores", C::faint, QVector<double>(h.t.size(), m.cpuCount), false, true}}, span);
        cores->setCores(m.cores);
        temps->clearSpans();
        fillRows(temps, m.temps, [](const TempSensor &x) { return Row{{x.name}, {Fmt::temp(x.celsius), {}, false, qMin(100.0, x.celsius)}}; });
        if (m.temps.isEmpty()) temps->setRowCount(1), cell(temps, 0, 0, {"No temperature sensors exposed (common on VMs)", C::muted}), temps->setSpan(0, 0, 1, 2);
        gpuPanel->setVisible(!m.gpus.isEmpty());
        fillRows(gpus, m.gpus, [](const GpuInfo &g) {
            return Row{{QString::number(g.index)}, {g.name}, {Fmt::pct(g.util, 0), {}, false, g.util},
                       {QString("%1 / %2 MiB").arg(g.memUsed).arg(g.memTotal), {}, false, g.memTotal > 0 ? g.memUsed * 100 / g.memTotal : 0},
                       {Fmt::temp(g.temp), C::level(g.temp, 75, 88)}, {QString("%1 W").arg(g.power)}, {Fmt::pct(g.fan, 0)}};
        });
    }
};

// ============================================================================ Memory
struct MemoryTab : Tab {
    QVector<StatTile *> t;
    SegmentBar *bar = new SegmentBar, *swap = new SegmentBar;
    TimeChart *chart = new TimeChart("Memory usage", pctFmt, 100);
    QLabel *detail = label({}, nullptr, true);
    QTableWidget *top = table({"PID", "Process", "User", "RSS", "Memory %", "Virtual"}, {80, 220, 120, 110, 160}, {4});

    MemoryTab()
    {
        auto *l = scrollRoot(this);
        t = addTiles(grid(l), {{"Used", C::violet}, {"Available", C::green}, {"Cache + buffers", C::blue}, {"Swap used", C::pink}});
        l->addWidget(panel("Composition", {bar, label("SWAP", "Section"), swap}));
        auto *r = row(l);
        auto *dp = panel("Details", {detail, nullptr});
        chart->setMinimumHeight(280), dp->setFixedWidth(300), top->setMinimumHeight(360);
        r->addWidget(chart, 3), r->addWidget(dp), l->addWidget(panel("Top memory consumers", {top}));
    }
    void refresh() override
    {
        const Metrics &m = s->metrics();
        const Live &h = s->live();
        const QColor free = C::grid.lighter(150);
        t[0]->set(Fmt::bytes(m.memUsed), Fmt::pct(m.memPct) + " of " + Fmt::bytes(m.memTotal), C::level(m.memPct));
        t[1]->set(Fmt::bytes(m.memAvailable), "free " + Fmt::bytes(m.memFree));
        t[2]->set(Fmt::bytes(m.cached + m.buffers), "reclaimable when needed");
        t[3]->set(m.swapTotal > 0 ? Fmt::bytes(m.swapUsed) : "no swap", m.swapTotal > 0 ? Fmt::pct(m.swapPct) + " of " + Fmt::bytes(m.swapTotal) : "", C::level(m.swapPct, 40, 80));
        bar->setSegments({{qMax(0.0, m.memTotal - m.memFree - m.cached - m.buffers), C::violet, "Applications"}, {m.shared, C::pink, "Shared"},
                          {m.buffers, C::teal, "Buffers"}, {qMax(0.0, m.cached - m.shared), C::blue, "Cache"}, {m.memFree, free, "Free"}}, m.memTotal);
        swap->setSegments({{m.swapUsed, C::pink, "Used"}, {m.swapTotal - m.swapUsed, free, "Free"}}, m.swapTotal);
        chart->setData(h.t, {{"Used", C::violet, h.s[Live::MEM]}, {"Cache", C::blue, h.s[Live::CACHE], false, true}, {"Swap", C::pink, h.s[Live::SWAP]}}, span);
        QVector<QPair<QString, QString>> d;
        for (auto [k, v] : {std::pair{"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}})
            d << qMakePair(QString(k), Fmt::bytes(v));
        detail->setText(kv(d));
        QVector<ProcInfo> p = m.procs;
        std::partial_sort(p.begin(), p.begin() + qMin(15, p.size()), p.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.rss > b.rss; });
        fillRows(top, p.mid(0, 15), [](const ProcInfo &x) {
            return Row{{QString::number(x.pid), C::muted}, {x.name}, {x.user, C::muted}, {Fmt::bytes(x.rss), {}, true},
                       {Fmt::pct(x.memPct), {}, false, qMin(100.0, x.memPct * 2)}, {Fmt::bytes(x.vsz), C::muted, true}};
        });
    }
};

// ============================================================================ Storage
struct StorageTab : Tab {
    QVector<StatTile *> t;
    QTableWidget *mounts = table({"Mount point", "Device", "Type", "Size", "Used", "Free", "Usage"}, {260, 140, 80, 110, 110, 110}, {6}),
                 *disks = table({"Device", "Read/s", "Write/s", "Read IOPS", "Write IOPS", "Busy", "Total read", "Total written"}, {110, 110, 110, 100, 100, 150, 120}, {5});
    TimeChart *io = new TimeChart("Disk throughput", rateFmt);

    StorageTab()
    {
        auto *l = scrollRoot(this);
        t = addTiles(grid(l), {{"Fullest file system", C::amber}, {"Read", C::blue}, {"Write", C::orange}, {"Busiest disk", C::red}});
        mounts->setMinimumHeight(220), disks->setMinimumHeight(200), io->setMinimumHeight(260);
        l->addWidget(panel("File systems", {mounts})), l->addWidget(io), l->addWidget(panel("Block devices", {disks}));
    }
    void refresh() override
    {
        const Metrics &m = s->metrics();
        t[0]->set(Fmt::pct(m.maxDiskPct), m.fullestMount, C::level(m.maxDiskPct, 80, 90));
        t[1]->set(Fmt::rate(m.diskReadBps)), t[2]->set(Fmt::rate(m.diskWriteBps)), t[3]->set(Fmt::pct(m.maxDiskUtil), m.busiestDisk, C::level(m.maxDiskUtil, 60, 90));
        io->setData(s->live().t, {{"Read", C::blue, s->live().s[Live::RD]}, {"Write", C::orange, s->live().s[Live::WR]}}, span);
        fillRows(mounts, m.mounts, [](const MountInfo &x) {
            return Row{{x.mount}, {x.device, C::muted}, {x.type, C::muted}, {Fmt::bytes(x.total), {}, true}, {Fmt::bytes(x.used), {}, true},
                       {Fmt::bytes(x.avail), {}, true}, {Fmt::pct(x.pct), {}, false, x.pct}};
        });
        fillRows(disks, m.disks, [](const DiskIO &d) {
            return Row{{d.name}, {Fmt::rate(d.readBps), C::blue, true}, {Fmt::rate(d.writeBps), C::orange, true}, {QString::number(d.readIops, 'f', 0), {}, true},
                       {QString::number(d.writeIops, 'f', 0), {}, true}, {Fmt::pct(d.util, 0), {}, false, d.util}, {Fmt::bytes(d.totalRead), C::muted, true},
                       {Fmt::bytes(d.totalWritten), C::muted, true}};
        });
    }
};

// ============================================================================ Network
struct NetworkTab : Tab {
    QVector<StatTile *> t;
    QComboBox *iface = new QComboBox;
    QStringList shown;
    TimeChart *chart = new TimeChart("Traffic", rateFmt);
    QTableWidget *tbl = table({"Interface", "State", "Speed", "Down/s", "Up/s", "Pkts in/s", "Pkts out/s", "Received", "Sent", "Errors", "Drops"}, {160, 80, 90, 110, 110, 90, 90, 110, 110, 70});

    NetworkTab()
    {
        auto *l = scrollRoot(this);
        t = addTiles(grid(l), {{"Download", C::teal}, {"Upload", C::pink}, {"Established", C::accent}, {"Listening", C::green}, {"Time-wait / close-wait", C::amber}, {"Sockets in use", C::violet}});
        auto *r = row(l);
        r->addWidget(label("Interface", "Muted")), r->addWidget(iface), r->addStretch();
        iface->setMinimumWidth(200), chart->setMinimumHeight(280), tbl->setMinimumHeight(240);
        l->addWidget(chart), l->addWidget(panel("Interfaces", {tbl}));
        connect(iface, QOverload<int>::of(&QComboBox::activated), this, [this] { refresh(); });
    }
    void refresh() override
    {
        const Metrics &m = s->metrics();
        const Live &h = s->live();
        t[0]->set(Fmt::rate(m.netRxBps), "physical interfaces"), t[1]->set(Fmt::rate(m.netTxBps));
        t[2]->set(QString::number(m.tcp["ESTABLISHED"]), "TCP"), t[3]->set(QString::number(m.tcp["LISTEN"]), "open TCP ports");
        t[4]->set(QString("%1 / %2").arg(m.tcp["TIME_WAIT"]).arg(m.tcp["CLOSE_WAIT"]), "many close-wait = app not closing sockets", m.tcp["CLOSE_WAIT"] > 100 ? C::amber : QColor());
        t[5]->set(QString::number(m.socketsUsed));
        QStringList names{"All physical (total)"};
        for (const NetIf &n : m.nets) names << n.name;
        if (names != shown) {
            const QString cur = iface->currentText();
            iface->clear(), iface->addItems(shown = names), iface->setCurrentIndex(qMax(0, names.indexOf(cur)));
        }
        const QString n = iface->currentText();
        const bool all = iface->currentIndex() <= 0;
        chart->title = "Traffic — " + (all ? "all physical interfaces" : n);
        chart->setData(h.t, {{"Down", C::teal, all ? h.s[Live::RX] : h.ifRx.value(n)}, {"Up", C::pink, all ? h.s[Live::TX] : h.ifTx.value(n)}}, span);
        fillRows(tbl, m.nets, [](const NetIf &x) {
            const QColor dim = x.virt ? C::muted : QColor();
            return Row{{x.name + (x.virt ? "  (virtual)" : ""), dim}, {x.state, x.state == "up" ? C::green : x.state == "down" ? C::red : C::muted},
                       {x.speed > 0 ? QString("%1 Mb/s").arg(x.speed) : "—", C::muted}, {Fmt::rate(x.rxBps), C::teal, true}, {Fmt::rate(x.txBps), C::pink, true},
                       {QString::number(x.rxPps, 'f', 0), dim, true}, {QString::number(x.txPps, 'f', 0), dim, true}, {Fmt::bytes(x.rxBytes), dim, true},
                       {Fmt::bytes(x.txBytes), dim, true}, {QString::number(x.errors), x.errors ? C::amber : dim, true}, {QString::number(x.drops), x.drops ? C::amber : dim, true}};
        });
    }
};

// ============================================================================ list tabs (processes, services)
using Act = QPair<QString, std::function<void()>>; // context-menu entry; empty text = separator

struct ListTab : Tab { // filterable, sortable table that keeps selection and scroll position across refreshes
    QLineEdit *filter = new QLineEdit;
    QLabel *summary = label({}, "Muted"), *status = label({}, "Muted");
    QTableWidget *tbl;
    QHBoxLayout *bar;

    ListTab(const QStringList &headers, const QVector<int> &widths, const QVector<int> &bars, const QString &hint)
    {
        auto *l = plainRoot(this);
        bar = row(l), tbl = table(headers, widths, bars);
        tbl->setSortingEnabled(true), tbl->setContextMenuPolicy(Qt::CustomContextMenu);
        filter->setClearButtonEnabled(true), filter->setMaximumWidth(300), filter->setPlaceholderText(hint);
        bar->addWidget(filter), bar->addWidget(summary), bar->addStretch();
        l->addWidget(tbl, 1), l->addWidget(status);
        connect(filter, &QLineEdit::textChanged, this, [this] { applyFilter(); });
    }
    QString selectedKey() const
    {
        const int r = tbl->currentRow();
        return r >= 0 && !tbl->isRowHidden(r) && tbl->item(r, 0) ? tbl->item(r, 0)->text() : QString();
    }
    virtual bool accept(int r) const
    {
        for (int c = 0; c < tbl->columnCount(); ++c)
            if (tbl->item(r, c) && tbl->item(r, c)->text().contains(filter->text(), Qt::CaseInsensitive)) return true;
        return false;
    }
    void applyFilter()
    {
        for (int r = 0; r < tbl->rowCount(); ++r) tbl->setRowHidden(r, !accept(r));
    }
    template <class V, class F> void fill(const V &items, F rowOf)
    {
        const QString sel = selectedKey();
        const int scroll = tbl->verticalScrollBar()->value(), col = qMax(0, tbl->currentColumn());
        int row = -1; // rows are reused: when the selected entry is gone the selection must go too, not pass to another entry
        tbl->setSortingEnabled(false), fillRows(tbl, items, rowOf), tbl->setSortingEnabled(true);
        for (int r = 0; r < tbl->rowCount() && row < 0 && !sel.isEmpty(); ++r)
            if (tbl->item(r, 0)->text() == sel) row = r;
        tbl->setCurrentCell(row, col), applyFilter(), tbl->verticalScrollBar()->setValue(scroll);
    }
    void addMenu(const QVector<Act> &items)
    {
        connect(tbl, &QWidget::customContextMenuRequested, this, [this, items](const QPoint &p) {
            if (selectedKey().isEmpty()) return;
            QMenu m;
            for (const Act &a : items) a.first.isEmpty() ? (void)m.addSeparator() : (void)m.addAction(a.first, a.second);
            m.exec(tbl->viewport()->mapToGlobal(p));
        });
    }
};

struct ProcessTab : ListTab {
    QCheckBox *freeze = new QCheckBox("Freeze list");

    ProcessTab() : ListTab({"PID", "Name", "User", "State", "CPU", "Memory", "RSS", "Threads", P::prioLabel, "Running for"}, {80, 230, 120, 100, 130, 130, 100, 80, 70}, {4, 5}, "Filter by name, user or PID…")
    {
        freeze->setToolTip("Stop refreshing so rows don't move while you pick one");
        bar->insertWidget(1, freeze), tbl->sortByColumn(4, Qt::DescendingOrder);
        QVector<Act> menu;
        for (const Cmd &c : P::procActions()) {
            menu << Act{c.label, [this, c] { run(c); }};
            if (c.button) bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second));
        }
        bar->addWidget(button("Priority…", nullptr, [this] { renice(); }));
        addMenu(menu << Act{} << Act{"Change priority…", [this] { renice(); }});
    }
    void bind(ServerSession *x) override
    {
        if (x != s) freeze->setChecked(false); // a frozen list would show the other server's PIDs
        Tab::bind(x);
    }
    void refresh() override
    {
        if (freeze->isChecked()) return;
        const Metrics &m = s->metrics();
        static const QHash<QChar, QPair<QString, QColor>> 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}}};
        int running = 0;
        fill(m.procs, [&](const ProcInfo &p) {
            const auto st = states.value(p.state, {QString(p.state), C::muted});
            running += p.state == 'R';
            return Row{{QString::number(p.pid), C::muted, true, -1, p.pid}, {p.name}, {p.user, C::muted}, {st.first, st.second},
                       {Fmt::pct(p.cpu), {}, false, qMin(100.0, p.cpu), p.cpu}, {Fmt::pct(p.memPct), {}, false, p.memPct, p.memPct},
                       {Fmt::bytes(p.rss), {}, true, -1, p.rss}, {QString::number(p.threads), {}, true, -1, p.threads},
                       {QString::number(p.nice), p.nice == P::normalPrio ? C::text : C::teal, true, -1, p.nice}, {Fmt::duration(p.age), C::muted, true, -1, p.age}};
        });
        summary->setText(QString("%1 processes · %2 running · %3 threads").arg(m.procs.size()).arg(running).arg(m.threadsTotal));
    }
    QString pidName() const { return tbl->item(tbl->currentRow(), 1)->text() + " (" + selectedKey() + ")"; }
    void run(const Cmd &c)
    {
        const int pid = selectedKey().toInt(); // read before the question: the list keeps refreshing behind it
        if (!pid) return status->setText("Select a process first.");
        if (!c.confirm || ask(this, c.label, QString("%1 %2 on %3?").arg(c.label, pidName(), s->config().name))) runReport(s, status, c.cmd.arg(pid));
    }
    void renice()
    {
        const int pid = selectedKey().toInt();
        if (!pid) return status->setText("Select a process first.");
        QStringList labels;
        for (const Cmd &c : P::priorities()) labels << c.label;
        bool ok = false;
        const int i = labels.indexOf(QInputDialog::getItem(this, "Change priority", "Priority for " + pidName() + ":", labels, labels.size() / 2, false, &ok));
        if (ok && i >= 0) runReport(s, status, P::priorities()[i].cmd.arg(pid));
    }
};

struct ServiceTab : ListTab {
    QComboBox *state = new QComboBox;
    QString sig = "?"; // not a possible signature: the first refresh always fills

    ServiceTab() : ListTab({"Service", "Active", "State", "Load", "Description"}, {300, 100, 100, 90}, {}, "Filter services…")
    {
        state->addItems({"All", "Running", "Failed", "Not running"});
        bar->insertWidget(1, state), tbl->sortByColumn(0, Qt::AscendingOrder);
        connect(state, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { applyFilter(); });
        connect(tbl, &QTableWidget::cellDoubleClicked, this, [this] { showLogs(); });
        QVector<Act> menu;
        for (const Cmd &c : P::serviceActions()) {
            menu << Act{c.label, [this, c] { act(c); }};
            bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second));
        }
        bar->addWidget(button("Logs", "Primary", [this] { showLogs(); }));
        addMenu(menu << Act{} << Act{"Show logs", [this] { showLogs(); }});
    }
    bool accept(int r) const override
    {
        const QString active = tbl->item(r, 1)->text(), sub = tbl->item(r, 2)->text();
        const int st = state->currentIndex();
        return (st == 0 || (st == 1 && sub == "running") || (st == 2 && active == "failed") || (st == 3 && sub != "running" && active != "failed")) && ListTab::accept(r);
    }
    void refresh() override
    {
        const Metrics &m = s->metrics();
        QString sg;
        for (const ServiceInfo &x : m.services) sg += x.unit + x.active + x.sub;
        if (sg == sig) return; // unchanged: keep the list still
        sig = sg;
        fill(m.services, [](const ServiceInfo &x) {
            const QColor c = x.active == "failed" ? C::red : x.sub == "running" ? C::green : x.active == "active" ? C::teal : C::muted;
            return Row{{x.unit}, {x.active, c}, {x.sub, c}, {x.load, C::muted}, {x.description, C::muted}};
        });
        summary->setText(m.services.isEmpty() ? "No services reported by this machine" : QString("%1 services · %2 running · %3 failed").arg(m.services.size()).arg(m.servicesRunning).arg(m.servicesFailed));
    }
    void act(const Cmd &c)
    {
        const QString unit = selectedKey();
        if (unit.isEmpty()) return status->setText("Select a service first.");
        if (!c.confirm || ask(this, "Confirm", QString("%1 %2 on %3?").arg(c.label, unit, s->config().name))) runReport(s, status, c.cmd.arg(P::quote(unit)));
    }
    void showLogs()
    {
        const QString unit = selectedKey();
        if (unit.isEmpty()) return;
        auto *dlg = new QDialog(this);
        auto *l = new QVBoxLayout(dlg);
        auto *b = new QHBoxLayout;
        auto *txt = new QPlainTextEdit("Loading…");
        auto *n = new QSpinBox;
        dlg->setAttribute(Qt::WA_DeleteOnClose), dlg->setWindowTitle("Logs — " + unit + " — " + s->config().name), dlg->resize(1000, 640);
        txt->setReadOnly(true), txt->setFont(QFont(C::mono(), 10)), txt->setLineWrapMode(QPlainTextEdit::NoWrap);
        n->setRange(50, 5000), n->setValue(300), n->setSuffix(" lines");
        auto load = [ss = s, t = QPointer<QPlainTextEdit>(txt), n, unit] {
            if (ss) ss->exec(P::serviceLogs(unit, n->value()), true, [t](int, const QString &out) { if (t) t->setPlainText(out), t->verticalScrollBar()->setValue(t->verticalScrollBar()->maximum()); });
        };
        l->addWidget(txt), l->addLayout(b);
        b->addWidget(n), b->addWidget(button("Reload", nullptr, load)), b->addStretch(), b->addWidget(button("Close", nullptr, [dlg] { dlg->close(); }));
        load(), dlg->show();
    }
};

// ============================================================================ Console
struct ConsoleTab : Tab {
    QPlainTextEdit *out = new QPlainTextEdit;
    QLineEdit *in = new QLineEdit;
    QCheckBox *priv = new QCheckBox("privileged");
    QStringList hist;
    int pos = 0;

    ConsoleTab()
    {
        auto *l = new QHBoxLayout(this);
        auto *left = new QVBoxLayout, *side = new QVBoxLayout;
        auto *r = new QHBoxLayout;
        auto *prompt = label("$");
        auto *run = button("Run", "Primary", [this] {
            const QString c = in->text().trimmed();
            if (c.isEmpty()) return;
            if (hist.isEmpty() || hist.last() != c) hist << c;
            pos = hist.size(), in->clear(), exec(c, priv->isChecked());
        });
        l->setContentsMargins(4, 16, 4, 12), l->setSpacing(14), l->addLayout(left, 1), l->addLayout(side);
        out->setReadOnly(true), out->setFont(QFont(C::mono(), 10)), out->setMaximumBlockCount(20000);
        out->setStyleSheet("QPlainTextEdit { background: #080b12; border-radius: 10px; padding: 10px; color: #cfe3ff; }");
        in->setFont(QFont(C::mono(), 11)), in->setPlaceholderText("Type a shell command and press Enter (↑/↓ history)"), in->installEventFilter(this);
        priv->setToolTip("Wrap in sudo -n when the server has 'Run control commands with sudo' enabled"), priv->setVisible(P::sudo);
        prompt->setStyleSheet("color: #38bdf8; font-weight: 700; font-size: 15px;");
        r->addWidget(prompt), r->addWidget(in, 1), r->addWidget(priv), r->addWidget(run), r->addWidget(button("Clear", nullptr, [this] { out->clear(); }));
        left->addWidget(out, 1), left->addLayout(r);
        connect(in, &QLineEdit::returnPressed, run, &QPushButton::click);
        auto addGroup = [&](const QString &title, const QVector<Cmd> &items, bool system) {
            auto *p = panel(title);
            p->setFixedWidth(270), side->addWidget(p);
            for (const Cmd &q : items) {
                auto *b = button(q.label, q.danger ? "Danger" : "Side", [this, q, system] {
                    if (!system || ask(this, q.label, QString("%1 on %2?%3").arg(q.label, s->config().name, q.danger ? "\n\nThe machine will be unavailable until it comes back." : ""))) exec(q.cmd, system);
                });
                b->setToolTip(q.cmd), lay(p)->addWidget(b);
            }
        };
        addGroup("Quick diagnostics", P::diagnostics(), false), addGroup("System actions", P::systemActions(), true);
        side->addStretch();
    }
    void bind(ServerSession *x) override
    {
        if (x == s) return;
        out->clear(), Tab::bind(x);
        if (x) out->appendHtml(QString("<span style='color:#8b95ab'>Console for <b>%1</b> (%2). Commands run non-interactively with a 120 s timeout.</span>").arg(x->config().name.toHtmlEscaped(), x->config().address()));
    }
    bool eventFilter(QObject *o, QEvent *e) override
    {
        const int k = e->type() == QEvent::KeyPress ? static_cast<QKeyEvent *>(e)->key() : 0;
        if (o != in || hist.isEmpty() || (k != Qt::Key_Up && k != Qt::Key_Down)) return Tab::eventFilter(o, e);
        return pos = qBound(0, pos + (k == Qt::Key_Up ? -1 : 1), hist.size()), in->setText(hist.value(pos)), true;
    }
    void exec(const QString &cmd, bool privileged)
    {
        out->appendHtml(QString("<br><span style='color:#38bdf8'><b>%1 $</b></span> %2").arg(QTime::currentTime().toString("HH:mm:ss"), cmd.toHtmlEscaped()));
        auto clock = std::make_shared<QElapsedTimer>();
        clock->start();
        s->exec(cmd, privileged, [o = QPointer<QPlainTextEdit>(out), clock](int code, const QString &text) {
            if (!o) return;
            if (!text.isEmpty()) o->appendPlainText(text.endsWith('\n') ? text.chopped(1) : text);
            o->appendHtml(QString("<span style='color:%1'>[exit %2 · %3 ms]</span>").arg(code ? "#ef4444" : "#22c55e").arg(code).arg(clock->elapsed()));
            o->verticalScrollBar()->setValue(o->verticalScrollBar()->maximum());
        }, 120000);
    }
};

// ============================================================================ Alert rules
struct RulesTab : Tab {
    QTableWidget *rules = table({"On", "Condition", "Severity", "Action", "Cooldown", "Live value"}, {50, 380, 100, 330, 100}), *live = table({"Active problems"});

    RulesTab()
    {
        auto *l = plainRoot(this);
        l->addWidget(label("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.", "Muted", true));
        auto *b = row(l);
        b->addWidget(button("+ Add rule", "Primary", [this] { editRule(-1); })), b->addWidget(button("Edit", nullptr, [this] { editRule(rules->currentRow()); }));
        b->addWidget(button("Delete", "Danger", [this] {
            auto rs = s->config().rules;
            if (rules->currentRow() >= 0 && rules->currentRow() < rs.size()) rs.remove(rules->currentRow()), store(rs);
        }));
        b->addStretch();
        b->addWidget(button("Reset to defaults", nullptr, [this] {
            if (ask(this, "Reset rules", "Replace all rules with the defaults?")) store(ServerConfig::defaultRules());
        }));
        live->setMaximumHeight(160), l->addWidget(rules, 2), l->addWidget(live, 1);
        connect(rules, &QTableWidget::cellDoubleClicked, this, [this](int r) { editRule(r); });
        connect(rules, &QTableWidget::itemChanged, this, [this](QTableWidgetItem *it) { // the "On" checkbox
            auto rs = s->config().rules;
            const bool on = it->checkState() == Qt::Checked;
            if (it->column() == 0 && it->row() < rs.size() && rs[it->row()].enabled != on) rs[it->row()].enabled = on, store(rs);
        });
    }
    void bind(ServerSession *x) override { Tab::bind(x), reload(); }
    void store(const QVector<Rule> &rs)
    {
        ServerConfig c = s->config();
        c.rules = rs, save(c), reload();
    }
    void reload()
    {
        if (!s) return;
        QSignalBlocker block(rules);
        fillRows(rules, s->config().rules, [](const Rule &r) {
            return Row{{}, {r.conditionText(), r.enabled ? QColor() : C::faint}, {r.severity, C::severity(r.severity)},
                       {r.actionText(), r.action == "notify" ? C::muted : C::violet}, {QString("%1 s").arg(r.cooldown), C::muted}};
        });
        for (int i = 0; i < rules->rowCount(); ++i) rules->item(i, 0)->setCheckState(s->config().rules[i].enabled ? Qt::Checked : Qt::Unchecked);
        refresh();
    }
    void refresh() override
    {
        const auto &rs = s->config().rules;
        const QStringList act = s->activeAlerts();
        QSignalBlocker block(rules);
        for (int i = 0; i < rs.size() && i < rules->rowCount(); ++i) {
            const double v = s->metricValue(rs[i].metric);
            cell(rules, i, 5, {QString::number(v, 'f', 1) + " " + defLabel(ruleMetrics(), rs[i].metric, true), (rs[i].op == "<" ? v < rs[i].value : v > rs[i].value) ? C::red : C::green});
        }
        fillRows(live, act, [](const QString &a) { return Row{{"⚠ " + a, C::red}}; });
        if (act.isEmpty()) live->setRowCount(1), cell(live, 0, 0, {"✓ No rule is currently triggered", C::green});
    }
    void editRule(int idx)
    {
        auto rs = s->config().rules;
        Rule r;
        r.id = ServerConfig::newId();
        if (idx >= 0 && idx < rs.size()) r = rs[idx];
        else idx = -1;
        QDialog dlg(this);
        dlg.setWindowTitle(idx < 0 ? "New rule" : "Edit rule");
        auto *f = new QFormLayout(&dlg);
        auto *metric = new QComboBox, *op = new QComboBox, *sev = new QComboBox, *action = new QComboBox;
        auto *value = new QDoubleSpinBox;
        auto *dur = new QSpinBox, *cool = new QSpinBox;
        auto *arg = new QLineEdit(r.arg);
        auto *en = new QCheckBox("Enabled");
        auto *cond = new QHBoxLayout;
        auto *bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
        for (const Def &d : ruleMetrics()) metric->addItem(d.label + (d.unit.isEmpty() ? "" : " (" + d.unit + ")"), d.key);
        for (const Def &d : P::ruleActions()) action->addItem(d.label, d.key);
        op->addItems({">", "<"}), sev->addItems({"info", "warning", "critical"});
        metric->setCurrentIndex(qMax(0, metric->findData(r.metric))), action->setCurrentIndex(qMax(0, action->findData(r.action)));
        op->setCurrentText(r.op), sev->setCurrentText(r.severity), en->setChecked(r.enabled);
        value->setRange(-1e9, 1e9), value->setValue(r.value);
        dur->setRange(0, 86400), dur->setSuffix(" s"), dur->setValue(r.duration);
        cool->setRange(10, 86400), cool->setSuffix(" s"), cool->setValue(r.cooldown);
        auto sync = [action, arg] {
            const QString hint = defLabel(P::ruleActions(), action->currentData().toString(), true);
            arg->setEnabled(!hint.isEmpty()), arg->setPlaceholderText(hint);
        };
        connect(action, QOverload<int>::of(&QComboBox::currentIndexChanged), &dlg, sync);
        connect(bb, &QDialogButtonBox::accepted, &dlg, &QDialog::accept), connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
        cond->addWidget(op), cond->addWidget(value, 1), sync();
        f->addRow("When", metric), f->addRow("is", cond), f->addRow("for at least", dur), f->addRow("Severity", sev), f->addRow("Then", action);
        f->addRow("Argument", arg), f->addRow("Repeat after", cool), f->addRow("", en), f->addRow(bb);
        if (dlg.exec() != QDialog::Accepted) return;
        r.metric = metric->currentData().toString(), r.op = op->currentText(), r.value = value->value(), r.duration = dur->value(), r.severity = sev->currentText();
        r.action = action->currentData().toString(), r.arg = arg->isEnabled() ? arg->text().trimmed() : "", r.cooldown = cool->value(), r.enabled = en->isChecked();
        idx < 0 ? (void)(rs << r) : (void)(rs[idx] = r);
        store(rs);
    }
};

// ============================================================================ History
struct HistoryTab : Tab {
    qint64 range = 86400, lastLoad = 0;
    QLabel *res = label({}, "Muted");
    QVector<TimeChart *> charts;
    QTableWidget *st = table({"Metric", "Minimum", "Average", "95th percentile", "Peak", "Points"}, {200, 150, 150, 150, 150});
    QVector<HPoint> pts;

    HistoryTab()
    {
        auto *l = scrollRoot(this);
        auto *b = row(l);
        auto *group = new QButtonGroup(this);
        b->setSpacing(6);
        for (auto [text, sec] : {std::pair{"1 h", 3600}, {"6 h", 21600}, {"24 h", 86400}, {"7 d", 604800}, {"30 d", 2592000}, {"90 d", 7776000}, {"1 y", 31536000}, {"All", 0}}) {
            auto *btn = button(text);
            btn->setCheckable(true), btn->setChecked(sec == 86400), group->addButton(btn, sec / 60), b->addWidget(btn);
        }
        b->addSpacing(14), b->addWidget(res), b->addStretch(), b->addWidget(button("Export CSV…", nullptr, [this] { exportCsv(); }));
        connect(group, &QButtonGroup::idClicked, this, [this](int id) { range = id * 60LL, reload(); });
        auto *g = grid(l);
        for (auto [title, fmt, max] : {std::tuple{"CPU", pctFmt, 100.0}, {"Memory & swap", pctFmt, 100.0}, {"Disk usage (fullest)", pctFmt, 100.0},
                                       {"Disk throughput", rateFmt, 0.0}, {"Network", rateFmt, 0.0}, {"Load average", numFmt(1), 0.0},
                                       {"Temperature", FmtFn([](double v) { return QString::number(v, 'f', 0) + "°"; }), 0.0}, {"Availability", pctFmt, 100.0}}) {
            charts << new TimeChart(title, fmt, max);
            charts.last()->setMinimumHeight(240), charts.last()->empty = "No history for this range yet", g->addWidget(charts.last(), (charts.size() - 1) / 2, (charts.size() - 1) % 2);
        }
        st->setMinimumHeight(14 * 30 + 40), l->addWidget(panel("Statistics for the selected range", {st}));
    }
    void bind(ServerSession *x) override { Tab::bind(x), lastLoad = 0; }
    void refresh() override
    {
        if (QDateTime::currentMSecsSinceEpoch() - lastLoad >= (range && range <= 21600 ? 5000 : 60000)) reload();
    }
    void reload()
    {
        lastLoad = QDateTime::currentMSecsSinceEpoch();
        const qint64 now = QDateTime::currentSecsSinceEpoch(), from = range ? now - range : qMax<qint64>(1, s->store().firstTs());
        Tier tier;
        pts = s->store().range(from, now, &tier);
        const qint64 step = qMax<qint64>(HistoryStore::step[int(tier)], s->config().interval);
        QVector<qint64> t;
        enum { CPU, CPUMAX, MEM, SWAP, DISK, RD, WR, RX, TX, RXMAX, LOAD, TEMP, TEMPMAX, AVAIL, N };
        QVector<double> v[N];
        double n = 0, up = 0;
        auto push = [&](qint64 ts, const HPoint *p) { // p = nullptr inserts a gap
            t << ts * 1000;
            const int src[N] = {H_CPU, H_CPU, H_MEM, H_SWAP, H_DISK, H_RD, H_WR, H_RX, H_TX, H_RX, H_LOAD, H_TEMP, H_TEMP, -1};
            for (int i = 0; i < N; ++i)
                v[i] << (!p ? NAN : i == AVAIL ? p->uptimePct() : !p->nUp ? NAN : (i == CPUMAX || i == RXMAX || i == TEMPMAX) ? p->max[src[i]] : p->avg[src[i]]);
        };
        for (const HPoint &p : qAsConst(pts)) {
            if (!t.isEmpty() && p.ts * 1000 - t.last() > step * 3000) push(t.last() / 1000 + step, nullptr); // app was not running
            push(p.ts, &p), n += p.n, up += p.nUp;
        }
        if (!t.isEmpty() && now * 1000 - t.last() > step * 3000) push(now, nullptr);
        const bool agg = tier != Tier::Raw;
        auto peak = [&](QVector<Series> s, const QString &name, const QColor &c, const QVector<double> &d) { if (agg) s << Series{name, c, d, false, true}; return s; };
        const QVector<QVector<Series>> data = {peak({{"Average", C::accent, v[CPU]}}, "Peak", C::red, v[CPUMAX]),
                                               {{"Memory", C::violet, v[MEM]}, {"Swap", C::pink, v[SWAP], false}}, {{"Usage", C::amber, v[DISK]}},
                                               {{"Read", C::blue, v[RD]}, {"Write", C::orange, v[WR]}},
                                               peak({{"Down", C::teal, v[RX]}, {"Up", C::pink, v[TX]}}, "Peak down", C::teal.lighter(140), v[RXMAX]),
                                               {{"Load", C::violet, v[LOAD]}}, peak({{"Average", C::orange, v[TEMP]}}, "Peak", C::red, v[TEMPMAX]),
                                               {{"Online", C::green, v[AVAIL]}}};
        for (int i = 0; i < charts.size(); ++i) charts[i]->subtitle = agg ? "avg per " + tierName(tier) : "", charts[i]->setData(t, data[i], (now - from) * 1000);
        res->setText(QString("Resolution: %1  ·  %2 points  ·  availability %3  ·  stored %4").arg(tierName(tier)).arg(pts.size()).arg(n ? Fmt::pct(up * 100 / n, 2) : "—", Fmt::bytes(s->store().diskBytes())));
        QVector<int> ms = {H_CPU, H_IOWAIT, H_LOAD, H_MEM, H_SWAP, H_DISK, H_DISKIO, H_RX, H_TX, H_RD, H_WR, H_TEMP, H_PROCS, H_GPU};
        if (!P::posixCpu) ms.remove(1);
        fillRows(st, ms, [&](int m) {
            const Stats x = stats(pts, m);
            return Row{{hNames[m]}, {fmtMetric(m, x.min), C::muted, true}, {fmtMetric(m, x.avg), {}, true}, {fmtMetric(m, x.p95), C::amber, true},
                       {fmtMetric(m, x.max), C::red, true}, {QString::number(x.count), C::muted, true}};
        });
    }
    void exportCsv()
    {
        const QString fn = QFileDialog::getSaveFileName(this, "Export history", s->config().name + "-history.csv", "CSV (*.csv)");
        QFile f(fn);
        if (fn.isEmpty() || !f.open(QIODevice::WriteOnly | QIODevice::Text)) return;
        QTextStream ts(&f);
        ts << "time,samples,online_pct";
        for (const char *k : hKeys) ts << ',' << k << "_avg," << k << "_max";
        auto num = [](float x) { return std::isnan(x) ? QString() : QString::number(x, 'f', 3); };
        for (const HPoint &p : qAsConst(pts)) {
            ts << '\n' << QDateTime::fromSecsSinceEpoch(p.ts).toString(Qt::ISODate) << ',' << p.n << ',' << p.uptimePct();
            for (int m = 0; m < H_COUNT; ++m) ts << ',' << num(p.avg[m]) << ',' << num(p.max[m]);
        }
    }
};

// ============================================================================ Insights & Autopilot
struct InsightsTab : Tab {
    RingGauge *health = new RingGauge("Health score");
    QLabel *reasons = label({}, "Muted", true), *capacity = label({}, nullptr, true);
    QVector<StatTile *> t;
    QVBoxLayout *findings = new QVBoxLayout;
    WeekHeatmap *heat = new WeekHeatmap;
    QComboBox *heatMetric = new QComboBox;
    QTableWidget *anomalies = table({"Metric", "Last 10 min", "Usual", "Deviation", "Baseline"}, {110, 110, 160, 90});
    QVector<std::function<void(AutopilotConfig &, bool load)>> binds; // autopilot form <-> config
    bool loading = false;

    // form-field builders bound to AutopilotConfig members
    QWidget *chk(const QString &text, bool AutopilotConfig::*f)
    {
        auto *w = new QCheckBox(text);
        binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setChecked(a.*f) : void(a.*f = w->isChecked()); };
        connect(w, &QCheckBox::toggled, this, [this] { store(); });
        return w;
    }
    template <class T, class W> QWidget *spin(T AutopilotConfig::*f, double lo, double hi, const QString &pre, const QString &suf)
    {
        auto *w = new W;
        w->setRange(lo, hi), w->setPrefix(pre), w->setSuffix(suf);
        if constexpr (std::is_same_v<W, QDoubleSpinBox>) w->setDecimals(f == &AutopilotConfig::anomalyZ ? 1 : 0), w->setSingleStep(f == &AutopilotConfig::anomalyZ ? 0.5 : 1);
        binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setValue(a.*f) : void(a.*f = w->value()); };
        connect(w, QOverload<T>::of(&W::valueChanged), this, [this] { store(); });
        return w;
    }
    QWidget *combo(QString AutopilotConfig::*f, const QStringList &keys, const QStringList &labels)
    {
        auto *w = new QComboBox;
        for (int i = 0; i < keys.size(); ++i) w->addItem(labels[i], keys[i]);
        binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setCurrentIndex(qMax(0, w->findData(a.*f))) : void(a.*f = w->currentData().toString()); };
        connect(w, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { store(); });
        return w;
    }

    InsightsTab()
    {
        using A = AutopilotConfig;
        using DS = QDoubleSpinBox;
        auto *l = scrollRoot(this);
        auto *top = row(l);
        auto *hp = panel("Health", {health, reasons, button("Analyze now", nullptr, [this] { s->analyzeNow(); })});
        hp->setFixedWidth(330), health->setMinimumHeight(190), top->addWidget(hp);
        auto *right = sub<QVBoxLayout>(top, 1);
        t = addTiles(grid(right), {{"Disk full forecast", C::amber}, {"Memory trend (6 h)", C::violet}, {"CPU / memory p95 (30 d)", C::accent},
                                   {"Availability 24 h", C::green}, {"Availability 7 d", C::green}, {"Availability 30 d", C::green}}, 3);
        right->addWidget(panel("Capacity planning", {capacity, nullptr}));

        auto *mid = row(l);
        auto *fp = panel("Findings from history analysis");
        auto *ap = panel("Autopilot — automatic control", {label("Acts on the findings once a minute, using statistics over the stored history. Every action is logged as an event.", "Muted", true)});
        auto *form = new QFormLayout;
        auto *runRow = new QHBoxLayout;
        auto *cmd = new QLineEdit;
        findings->setSpacing(10), lay(fp)->addLayout(findings), lay(fp)->addStretch(), mid->addWidget(fp, 1);
        runRow->addWidget(spin<double, DS>(&A::runawayCpu, 10, 6400, "≥ ", " %")), runRow->addWidget(spin<int, QSpinBox>(&A::runawayMinutes, 1, 1440, "for ", " min"));
        cmd->setFont(QFont(C::mono(), 9));
        binds << [cmd](A &a, bool ld) { ld ? cmd->setText(a.diskCleanupCommand) : void(a.diskCleanupCommand = cmd->text().trimmed()); };
        connect(cmd, &QLineEdit::editingFinished, this, [this] { store(); });
        form->addRow(chk("Autopilot enabled", &A::enabled), chk("Dry run (only report)", &A::dryRun));
        form->addRow(chk("Restart failed services", &A::restartFailed), spin<int, QSpinBox>(&A::maxRestartsPerHour, 1, 20, "", " / hour max"));
        form->addRow("Runaway processes", combo(&A::runawayMode, {"none", "renice", "terminate"}, {"Ignore", "Lower priority (renice 19)", "Terminate"}));
        form->addRow("", runRow);
        form->addRow("Memory leaks", combo(&A::leakMode, {"none", "notify", "terminate"}, {"Ignore", "Notify", "Terminate under pressure"}));
        form->addRow("  pressure ≥", spin<double, DS>(&A::leakMemPressure, 50, 100, "", " % memory"));
        form->addRow(chk("Disk cleanup", &A::diskCleanup), spin<int, QSpinBox>(&A::diskForecastDays, 1, 60, "full in < ", " days"));
        form->addRow("", spin<double, DS>(&A::diskCleanupAt, 50, 100, "or usage ≥ ", " %"));
        form->addRow("  command", cmd);
        form->addRow(chk("Anomaly alerts", &A::anomalyAlerts), spin<double, DS>(&A::anomalyZ, 1.5, 10, "z ≥ ", " σ"));
        ap->setFixedWidth(430), lay(ap)->addLayout(form), lay(ap)->addStretch(), mid->addWidget(ap, 0, Qt::AlignTop);

        auto *bot = row(l);
        heatMetric->addItems({"CPU", "Memory"}), heatMetric->setFixedWidth(140), anomalies->setMinimumHeight(230);
        connect(heatMetric, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { analysis(); });
        bot->addWidget(panel("Weekly pattern (last 4 weeks, hourly averages)", {heatMetric, heat}), 3), bot->addWidget(panel("Now vs. normal (baselines)", {anomalies}), 2);
    }
    void bind(ServerSession *x) override
    {
        Tab::bind(x);
        if (!x) return;
        AutopilotConfig a = x->config().autopilot;
        loading = true;
        for (auto &b : binds) b(a, true);
        loading = false, analysis();
    }
    void store()
    {
        if (loading || !s) return;
        ServerConfig c = s->config();
        for (auto &b : binds) b(c.autopilot, false);
        save(c);
    }
    void analysis() override
    {
        const Analysis &a = s->analysis();
        const int hi = heatMetric->currentIndex();
        health->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health));
        reasons->setText((a.healthReasons.isEmpty() ? "No deductions — everything looks healthy." : a.healthReasons.join('\n')) +
                         (a.when ? "\n\nAnalyzed " + QDateTime::fromSecsSinceEpoch(a.when).toString("HH:mm:ss") : ""));
        if (a.diskFullDays >= 0) t[0]->set(Fmt::duration(a.diskFullDays * 86400), QString("+%1 pts/day · %2").arg(a.diskSlopePerDay, 0, 'f', 2).arg(a.diskBasis), a.diskFullDays < 7 ? C::red : a.diskFullDays < 30 ? C::amber : QColor());
        else t[0]->set("Not filling", a.diskBasis.isEmpty() ? "needs ~2 h of history" : QString("trend %1 pts/day").arg(a.diskSlopePerDay, 0, 'f', 2), C::green);
        if (a.memTrendR2 > 0) t[1]->set(QString("%1%2 pts/h").arg(a.memSlopePerHour >= 0 ? "+" : "").arg(a.memSlopePerHour, 0, 'f', 2), QString("fit R² %1").arg(a.memTrendR2, 0, 'f', 2), a.memSlopePerHour > 1 && a.memTrendR2 > .8 ? C::amber : QColor());
        else t[1]->set("—", "needs ~90 min of history");
        t[2]->set(a.cpu30.count ? Fmt::pct(a.cpu30.p95, 0) + " / " + Fmt::pct(a.mem30.p95, 0) : "—", a.cpu30.count ? "avg " + Fmt::pct(a.cpu30.avg, 0) + " / " + Fmt::pct(a.mem30.avg, 0) : "collecting");
        for (int i = 0; i < 3; ++i)
            std::isnan(a.up[i]) ? t[3 + i]->set("—", "no data yet")
                                : t[3 + i]->set(Fmt::pct(a.up[i], a.up[i] >= 99.995 ? 0 : 2), "≈ " + Fmt::duration(a.down[i]) + " offline", a.up[i] >= 99.9 ? C::green : a.up[i] >= 99 ? C::amber : C::red);
        capacity->setText("<p>• " + a.capacity.join("</p><p>• ") + "</p>");
        heat->setData(a.heat[hi], a.heatN, hi ? "% memory" : "% CPU", hi ? C::violet : C::accent);
        fillRows(anomalies, a.anomalies, [](const Anomaly &x) {
            const double az = qAbs(x.z);
            return Row{{x.metric}, {fmtMetric(x.hm, x.now), {}, true}, {fmtMetric(x.hm, x.mean) + " ± " + fmtMetric(x.hm, x.sd), C::muted, true},
                       {QString("%1%2σ").arg(x.z >= 0 ? "+" : "").arg(x.z, 0, 'f', 1), az >= 3 ? C::red : az >= 2 ? C::amber : C::green, true}, {x.baseline, C::muted}};
        });

        while (QLayoutItem *it = findings->takeAt(0)) { // rebuild the finding cards
            if (it->widget()) it->widget()->deleteLater();
            delete it;
        }
        if (a.findings.isEmpty()) {
            auto *ok = label("✓  No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, service failures, overload and anomalies every minute.", nullptr, true);
            ok->setStyleSheet("color: #22c55e; padding: 10px;"), findings->addWidget(ok);
        }
        const AutopilotConfig &ap = s->config().autopilot;
        for (const Finding &f : a.findings) {
            const QColor c = C::severity(f.severity);
            auto *card = new QFrame;
            auto *cl = new QHBoxLayout(card);
            card->setObjectName("F");
            card->setStyleSheet(QString("#F { background: #1a2133; border: 1px solid #27314a; border-left: 4px solid %1; border-radius: 10px; }").arg(c.name()));
            cl->addWidget(label(QString("<span style='color:%1;font-size:11px;font-weight:700'>%2 · %3</span><br><span style='font-size:14px;font-weight:600'>%4</span><br>%5<br>"
                                        "<span style='color:#8b95ab'>→ %6</span>%7").arg(c.name(), f.severity.toUpper(), f.category.toUpper(), f.title.toHtmlEscaped(), f.detail.toHtmlEscaped(), f.advice.toHtmlEscaped(),
                                        f.autoEligible && ap.enabled ? QString("<br><span style='color:#a78bfa;font-size:11px'>%1</span>").arg(ap.dryRun ? "Autopilot (dry run) would act on this" : "Autopilot handles this automatically") : ""),
                                nullptr, true), 1);
            findings->addWidget(card);
            if (f.action.isEmpty()) continue;
            auto *b = button(f.actionLabel, f.action == "kill_pid" ? "Danger" : "Primary");
            cl->addWidget(b, 0, Qt::AlignVCenter);
            connect(b, &QPushButton::clicked, this, [this, f, pb = QPointer<QPushButton>(b)] { // the card may be rebuilt while the question is open
                if (!ask(this, f.actionLabel, QString("%1 on %2?\n\n%3").arg(f.actionLabel, s->config().name, f.title))) return;
                if (pb) pb->setEnabled(false), pb->setText("Working…");
                s->runFinding(f, false, [pb](int code, const QString &) { if (pb) pb->setText(code ? "✗ Failed" : "✓ Done"); });
            });
        }
    }
};

QVector<QPair<QString, Tab *>> makeTabs()
{
    return {{"Overview", new OverviewTab}, {"CPU", new CpuTab}, {"Memory", new MemoryTab}, {"Storage", new StorageTab}, {"Network", new NetworkTab},
            {"Processes", new ProcessTab}, {"Services", new ServiceTab}, {"History", new HistoryTab}, {"Insights && Autopilot", new InsightsTab},
            {"Alert rules", new RulesTab}, {"Console", new ConsoleTab}};
}