File size: 38,504 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
// Main window: sidebar, dashboard with server cards, server detail page, events page, tray icon.
#include "Windows.h"
#include "Widgets.h"
#include <QApplication>
#include <QBoxLayout>
#include <QCheckBox>
#include <QCloseEvent>
#include <QComboBox>
#include <QDesktopServices>
#include <QDialogButtonBox>
#include <QEventLoop>
#include <QFileDialog>
#include <QFormLayout>
#include <QLineEdit>
#include <QListWidget>
#include <QMenu>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QScrollArea>
#include <QSettings>
#include <QSpinBox>
#include <QStackedWidget>
#include <QSystemTrayIcon>
#include <QTabWidget>
#include <QUrl>
#include <memory>

struct Actions { std::function<void(const QString &)> open, edit, remove; std::function<void()> add, back; }; // set by the main window
static QColor statusColor(Status s) { return s == Status::Online ? C::green : s == Status::Connecting ? C::amber : s == Status::Offline ? C::red : C::faint; }
static QHBoxLayout *hbox()
{
    auto *h = new QHBoxLayout;
    h->setSpacing(10);
    return h;
}
static QVBoxLayout *page(QWidget *w, int top = 22)
{
    auto *l = new QVBoxLayout(w);
    w->setObjectName("Page"), l->setContentsMargins(28, top, 28, 18), l->setSpacing(14);
    return l;
}

// ============================================================================ dashboard cards
struct Card : QWidget {
    bool hover = false;
    Card() { setCursor(Qt::PointingHandCursor), setMinimumSize(320, 262); }
    QSize sizeHint() const override { return {340, 262}; }
    void enterEvent(QEvent *) override { hover = true, update(); }
    void leaveEvent(QEvent *) override { hover = false, update(); }
};

struct ServerCard : Card {
    ServerSession *s;
    const Actions *act;
    ServerCard(ServerSession *x, const Actions *a) : s(x), act(a)
    {
        connect(x, &ServerSession::updated, this, QOverload<>::of(&QWidget::update));
        connect(x, &ServerSession::analysisUpdated, this, QOverload<>::of(&QWidget::update));
    }
    void mouseReleaseEvent(QMouseEvent *e) override { if (e->button() == Qt::LeftButton) act->open(s->config().id); }
    void contextMenuEvent(QContextMenuEvent *e) override
    {
        const QString id = s->config().id;
        QMenu m;
        m.addAction("Open details", [=] { act->open(id); }), m.addAction("Reconnect", s, &ServerSession::reconnect), m.addSeparator();
        m.addAction("Edit…", [=] { act->edit(id); }), m.addAction("Remove…", [=] { act->remove(id); });
        m.exec(e->globalPos());
    }
    void paintEvent(QPaintEvent *) override
    {
        AA p(this);
        const ServerConfig &c = s->config();
        const Metrics &m = s->metrics();
        const Analysis &an = s->analysis();
        const bool live = s->online();
        const QColor sc = statusColor(s->status()), muted = live ? C::text : C::faint;
        QLinearGradient bg(0, 0, 0, height()), strip(0, 0, width(), 0);
        bg.setColorAt(0, hover ? C::cardHover : C::card), bg.setColorAt(1, C::panel);
        strip.setColorAt(0, sc), strip.setColorAt(.6, C::tint(sc, 0));
        p.setPen(QPen(hover ? C::accent : C::border, hover ? 1.5 : 1)), p.setBrush(bg), p.drawRoundedRect(QRectF(rect()).adjusted(1, 1, -1, -1), 14, 14);
        p.setPen(Qt::NoPen), p.setBrush(strip), p.drawRoundedRect(QRectF(1, 1, width() - 2, 6), 3, 3);
        p.setBrush(sc), p.drawEllipse(QPointF(22, 28), 5, 5);
        p.setFont(pxFont(font(), 16, true)), p.setPen(C::text);
        p.drawText(QRectF(36, 16, width() - 120, 24), Qt::AlignVCenter, p.fontMetrics().elidedText(c.name, Qt::ElideRight, width() - 120));
        p.setFont(pxFont(font(), 11)), p.setPen(C::muted);
        p.drawText(QRectF(36, 38, width() - 60, 16), Qt::AlignVCenter, p.fontMetrics().elidedText(c.address() + (m.os.isEmpty() ? "" : "  ·  " + m.os), Qt::ElideRight, width() - 60));
        if (live) { // health badge
            const QRectF hb(width() - 62, 12, 44, 44);
            paintRing(p, hb, an.health, C::health(an.health), 4, false);
            p.setFont(pxFont(font(), 15, true)), p.setPen(C::health(an.health)), p.drawText(hb, Qt::AlignCenter, an.grade);
        } else {
            p.setFont(pxFont(font(), 10, true));
            const QString chip = statusName(s->status()).toUpper();
            const QRectF cr(width() - p.fontMetrics().horizontalAdvance(chip) - 34, 18, p.fontMetrics().horizontalAdvance(chip) + 18, 20);
            p.setPen(sc), p.setBrush(C::tint(sc, 40)), p.drawRoundedRect(cr, 10, 10), p.drawText(cr, Qt::AlignCenter, chip);
        }
        const bool temp = !m.temps.isEmpty(); // four gauges
        const double vals[4] = {m.cpuUsage, m.memPct, m.maxDiskPct, temp ? m.maxTemp : m.swapPct}, gw = (width() - 32) / 4.0, gs = qMin(gw - 14, 70.0);
        const char *names[4] = {"CPU", "Memory", "Disk", temp ? "Temp" : "Swap"};
        for (int i = 0; i < 4; ++i) {
            const double cx = 16 + gw * i + gw / 2;
            const QRectF r(cx - gs / 2, 66, gs, gs);
            paintRing(p, r, live ? qMin(100.0, vals[i]) : 0, live ? (i == 3 && temp ? C::level(vals[i], 70, 85) : C::level(vals[i])) : C::faint, 6, live);
            p.setFont(pxFont(font(), 14, true)), p.setPen(muted);
            p.drawText(r, Qt::AlignCenter, !live ? "—" : i == 3 && temp ? QString::number(vals[i], 'f', 0) + "°" : QString::number(vals[i], 'f', 0) + "%");
            p.setFont(pxFont(font(), 11)), p.setPen(C::muted), p.drawText(QRectF(cx - gw / 2, r.bottom() - 4, gw, 16), Qt::AlignCenter, names[i]);
        }
        const QRectF sp(16, 166, width() - 32, 44); // CPU + memory sparkline (last 5 min)
        p.setPen(Qt::NoPen), p.setBrush(QColor(0, 0, 0, 40)), p.drawRoundedRect(sp, 8, 8);
        for (auto [series, color] : {std::pair{Live::MEM, C::violet}, {Live::CPU, C::accent}}) {
            const QVector<double> &v = s->live().s[series];
            const int n = qMin(150, v.size());
            if (n < 2) continue;
            QPolygonF line;
            for (int i = 0; i < n; ++i) line << QPointF(sp.right() - 4 - (sp.width() - 8) * (n - 1 - i) / 149.0, sp.bottom() - 4 - qBound(0.0, v[v.size() - n + i], 100.0) / 100 * (sp.height() - 8));
            QPolygonF area = line;
            area << QPointF(line.last().x(), sp.bottom() - 2) << QPointF(line.first().x(), sp.bottom() - 2);
            p.setPen(Qt::NoPen), p.setBrush(C::tint(color, 40)), p.drawPolygon(area);
            p.setPen(QPen(color, 1.5)), p.setBrush(Qt::NoBrush), p.drawPolyline(line);
        }
        p.setFont(pxFont(font(), 10)), p.setPen(C::accent), p.drawText(sp.adjusted(8, 3, 0, 0), Qt::AlignLeft, "CPU");
        p.setPen(C::violet), p.drawText(sp.adjusted(36, 3, 0, 0), Qt::AlignLeft, "MEM");
        p.setFont(pxFont(font(), 11));
        const QRectF ft(16, 218, width() - 32, 32);
        if (!live) {
            p.setPen(s->status() == Status::Offline ? C::red : C::muted);
            return p.drawText(ft, Qt::AlignVCenter | Qt::TextWordWrap, s->status() == Status::Disabled ? "Monitoring disabled" : s->status() == Status::Offline ? "Unreachable: " + s->lastError() : "Waiting for data…");
        }
        p.setPen(C::teal), p.drawText(ft, Qt::AlignLeft, "↓ " + Fmt::rate(m.netRxBps));
        p.setPen(C::pink), p.drawText(ft.adjusted(100, 0, 0, 0), Qt::AlignLeft, "↑ " + Fmt::rate(m.netTxBps));
        p.setPen(C::muted), p.drawText(ft, Qt::AlignRight, QString("load %1  ·  up %2").arg(m.load1, 0, 'f', 2).arg(Fmt::duration(m.uptime)));
        p.drawText(ft.adjusted(0, 16, 0, 0), Qt::AlignLeft, QString("%1 cores · %2 procs").arg(m.cpuCount).arg(m.procs.size()) + (c.autopilot.enabled ? c.autopilot.dryRun ? " · autopilot (dry run)" : " · autopilot on" : ""));
        const int rules = s->activeAlerts().size(), alerts = rules + an.findings.size();
        if (!alerts) return;
        bool crit = rules;
        for (const Finding &f : an.findings) crit |= f.severity == "critical";
        const QString txt = QString("⚠ %1").arg(alerts);
        const QColor ac = crit ? C::red : C::amber;
        const QRectF ar(ft.right() - p.fontMetrics().horizontalAdvance(txt) - 14, ft.top() + 15, p.fontMetrics().horizontalAdvance(txt) + 14, 17);
        p.setPen(Qt::NoPen), p.setBrush(C::tint(ac, 45)), p.drawRoundedRect(ar, 8, 8), p.setPen(ac), p.drawText(ar, Qt::AlignCenter, txt);
    }
};

struct AddCard : Card {
    const Actions *act;
    explicit AddCard(const Actions *a) : act(a) {}
    void mouseReleaseEvent(QMouseEvent *) override { act->add(); }
    void paintEvent(QPaintEvent *) override
    {
        AA p(this);
        const QRectF r = QRectF(rect()).adjusted(2, 2, -2, -2);
        const QPointF c = r.center() - QPointF(0, 14);
        p.setPen(QPen(hover ? C::accent : C::border, 1.5, Qt::DashLine)), p.setBrush(hover ? C::tint(C::accent, 18) : Qt::transparent), p.drawRoundedRect(r, 14, 14);
        p.setPen(QPen(hover ? C::accent : C::muted, 3, Qt::SolidLine, Qt::RoundCap));
        p.drawLine(c - QPointF(14, 0), c + QPointF(14, 0)), p.drawLine(c - QPointF(0, 14), c + QPointF(0, 14));
        p.setFont(pxFont(font(), 14, true)), p.drawText(QRectF(r.left(), c.y() + 26, r.width(), 22), Qt::AlignCenter, "Add server");
        p.setFont(pxFont(font(), 11)), p.setPen(C::faint), p.drawText(QRectF(r.left(), c.y() + 48, r.width(), 18), Qt::AlignCenter, "This machine · SSH");
    }
};

// ============================================================================ dashboard
struct DashboardPage : QWidget {
    ServerManager *mgr;
    const Actions *act;
    FlowLayout *flow = new FlowLayout(new QWidget);
    QList<ServerCard *> cards;
    AddCard *addCard;
    QLineEdit *search = new QLineEdit;
    QLabel *subtitle = label({}, "Muted");
    QVector<StatTile *> t;
    QListWidget *events = new QListWidget;

    DashboardPage(ServerManager *m, const Actions *a) : mgr(m), act(a), addCard(new AddCard(a))
    {
        auto *l = page(this);
        auto *head = hbox(), *body = hbox();
        auto *titles = new QVBoxLayout;
        auto *g = new QGridLayout;
        auto *scroll = new QScrollArea;
        auto *ev = panel("Recent events", {events});
        titles->addWidget(label("Dashboard", "H1")), titles->addWidget(subtitle);
        search->setPlaceholderText("Search servers…"), search->setClearButtonEnabled(true), search->setFixedWidth(240);
        head->addLayout(titles), head->addStretch(), head->addWidget(search), head->addWidget(button("+  Add server", "Primary", [this] { act->add(); }));
        t = addTiles(g, {{"Servers online", C::green}, {"Avg health", C::teal}, {"Active problems", C::red}, {"Avg CPU", C::accent}, {"Avg memory", C::violet}, {"Total network", C::pink}});
        scroll->setWidgetResizable(true), scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), scroll->setWidget(flow->parentWidget());
        events->setStyleSheet("QListWidget { background: transparent; border: none; } QListWidget::item { padding: 6px 2px; border-bottom: 1px solid #1f2738; }");
        events->setWordWrap(true), events->setSelectionMode(QAbstractItemView::NoSelection), ev->setFixedWidth(330);
        body->addWidget(scroll, 1), body->addWidget(ev);
        l->addLayout(head), l->addLayout(g), l->addLayout(body, 1);
        connect(search, &QLineEdit::textChanged, this, [this] { filter(); });
        connect(mgr, &ServerManager::listChanged, this, [this] { rebuild(); });
        connect(mgr, &ServerManager::alertsCleared, events, &QListWidget::clear);
        connect(mgr, &ServerManager::alertRaised, this, [this](const AlertEvent &e) {
            events->insertItem(0, e.time.toString("HH:mm:ss") + "  ·  " + e.serverName + "\n" + e.message);
            events->item(0)->setForeground(C::severity(e.severity));
            if (events->count() > 200) delete events->takeItem(200);
        });
    }
    void rebuild()
    {
        for (ServerCard *c : qAsConst(cards)) c->hide(), c->deleteLater(); // not deleted at once: a card's own menu may have caused this
        cards.clear(), flow->removeWidget(addCard);
        for (ServerSession *s : mgr->sessions()) cards << new ServerCard(s, act), flow->addWidget(cards.last());
        flow->addWidget(addCard), filter(), refresh();
    }
    void filter()
    {
        for (ServerCard *c : qAsConst(cards))
            c->setVisible(QStringList{c->s->config().name, c->s->config().host, c->s->config().group, c->s->metrics().hostname}.join(' ').contains(search->text(), Qt::CaseInsensitive));
        flow->invalidate();
    }
    void refresh()
    {
        int online = 0, total = 0, problems = 0;
        double cpu = 0, mem = 0, rx = 0, tx = 0, health = 0;
        for (ServerSession *s : mgr->sessions()) {
            if (!s->config().enabled) continue;
            ++total, problems += s->activeAlerts().size();
            if (!s->online()) continue;
            const Metrics &m = s->metrics();
            ++online, cpu += m.cpuUsage, mem += m.memPct, rx += m.netRxBps, tx += m.netTxBps, health += s->analysis().health;
            for (const Finding &f : s->analysis().findings) problems += f.severity != "info";
        }
        subtitle->setText(QString("%1 server(s) monitored  ·  updated %2").arg(mgr->sessions().size()).arg(QTime::currentTime().toString("HH:mm:ss")));
        t[0]->set(QString("%1 / %2").arg(online).arg(total), total > online ? QString("%1 unreachable").arg(total - online) : "all reachable", online == total ? C::green : C::amber);
        t[2]->set(QString::number(problems), problems ? "alerts + insights" : "all clear", problems ? C::red : C::green);
        if (!online) {
            for (int i : {1, 3, 4, 5}) t[i]->set("—");
            return;
        }
        t[1]->set(QString::number(qRound(health / online)), "score 0–100", C::health(qRound(health / online)));
        t[3]->set(Fmt::pct(cpu / online), {}, C::level(cpu / online)), t[4]->set(Fmt::pct(mem / online), {}, C::level(mem / online));
        t[5]->set(Fmt::rate(rx + tx), "↓ " + Fmt::rate(rx) + "   ↑ " + Fmt::rate(tx));
    }
};

// ============================================================================ detail page
struct DetailPage : QWidget {
    ServerManager *mgr;
    const Actions *act;
    QPointer<ServerSession> s;
    QTabWidget *tabs = new QTabWidget;
    QLabel *name = label({}, "H1"), *state = new QLabel, *sub = label({}, "Muted"), *chips = label({}, nullptr, true);
    QPushButton *pause = button("❚❚ Pause", nullptr, [this] { s->setPaused(!s->isPaused()); });
    QComboBox *span = new QComboBox;
    QList<QMetaObject::Connection> conns;

    DetailPage(ServerManager *m, const Actions *a) : mgr(m), act(a)
    {
        auto *l = page(this, 18);
        auto *head = hbox(), *nameRow = hbox();
        auto *titles = new QVBoxLayout, *spanBox = new QVBoxLayout;
        auto *power = button("⏻ Power", "Danger");
        auto *pm = new QMenu(power);
        nameRow->addWidget(name), nameRow->addWidget(state), nameRow->addStretch();
        titles->addWidget(button("‹  Dashboard", "Flat", [this] { act->back(); }), 0, Qt::AlignLeft), titles->addLayout(nameRow), titles->addWidget(sub), titles->addWidget(chips);
        for (auto [t, min] : {std::pair{"Last 5 minutes", 5}, {"Last 15 minutes", 15}, {"Last 30 minutes", 30}, {"Last hour", 60}}) span->addItem(t, min);
        span->setCurrentIndex(1), spanBox->addWidget(label("LIVE WINDOW", "Section")), spanBox->addWidget(span);
        for (bool reboot : {true, false}) {
            const QString t = reboot ? "Reboot…" : "Shut down…";
            pm->addAction(t, this, [this, t, reboot] {
                if (QMessageBox::warning(this, t, QString("%1 %2 now?").arg(t.chopped(1), s->config().name), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) s->exec(P::power(reboot), true);
            });
        }
        pm->addSeparator(), pm->addAction("Remove from monitor…", this, [this] { act->remove(s->config().id); }), power->setMenu(pm);
        head->addLayout(titles, 1), head->addLayout(spanBox);
        for (auto *b : {button("⟳ Reconnect", nullptr, [this] { s->reconnect(); }), pause, button("Edit", nullptr, [this] { act->edit(s->config().id); }), power}) head->addWidget(b, 0, Qt::AlignBottom);
        tabs->setDocumentMode(true), tabs->tabBar()->setElideMode(Qt::ElideNone), tabs->tabBar()->setExpanding(false);
        tabs->tabBar()->setFont(pxFont(tabs->tabBar()->font(), 13, true));
        for (const auto &[title, w] : makeTabs()) w->save = [this](const ServerConfig &c) { mgr->update(c); }, tabs->addTab(w, title);
        l->setSpacing(6), l->addLayout(head), l->addWidget(tabs, 1);
        connect(tabs, &QTabWidget::currentChanged, this, [this] { refreshTab(true); });
        connect(span, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { refreshTab(false); });
    }
    Tab *tab(int i) const { return static_cast<Tab *>(tabs->widget(i)); }
    void refreshTab(bool withAnalysis)
    {
        Tab *t = tab(tabs->currentIndex());
        if (!s) return;
        t->span = span->currentData().toInt() * 60000LL, t->refresh();
        if (withAnalysis) t->analysis();
    }
    void bind(ServerSession *x)
    {
        for (const auto &c : qAsConst(conns)) disconnect(c);
        conns.clear(), s = x;
        for (int i = 0; i < tabs->count(); ++i) tab(i)->bind(x);
        if (!x) return;
        conns << connect(x, &ServerSession::updated, this, [this] { header(), refreshTab(false); })
              << connect(x, &ServerSession::analysisUpdated, this, [this] { header(), tab(tabs->currentIndex())->analysis(); });
        header(), refreshTab(true);
    }
    void header()
    {
        const ServerConfig &c = s->config();
        const Metrics &m = s->metrics();
        const Analysis &a = s->analysis();
        QString h;
        auto chip = [&](const QString &t, const QString &color = "#b9c3d8") {
            if (!t.trimmed().isEmpty()) h += QString("<span style='background:#1f2a40; color:%2; white-space:nowrap;'>&nbsp;&nbsp;%1&nbsp;&nbsp;</span>&nbsp; ").arg(t.toHtmlEscaped().replace(" ", "&nbsp;").replace("-", "&#8209;"), color);
        };
        name->setText(c.name);
        state->setText("  ● " + (s->isPaused() ? QString("Paused") : statusName(s->status())).toUpper());
        state->setStyleSheet(QString("color: %1; font-weight: 700; font-size: 12px;").arg((s->isPaused() ? C::amber : statusColor(s->status())).name()));
        sub->setText(c.address() + "  ·  " + transportName(c.transport) + (m.hostname.isEmpty() ? "" : "  ·  host " + m.hostname) +
                     (s->online() ? "  ·  up " + Fmt::duration(m.uptime) : s->status() == Status::Offline ? "  ·  " + s->lastError() : ""));
        chip(m.os), chip(m.kernel.isEmpty() ? "" : P::kernelPrefix + m.kernel), chip(m.cpuCount ? QString("%1 cores").arg(m.cpuCount) : "");
        chip(m.memTotal > 0 ? Fmt::bytes(m.memTotal) + " RAM" : ""), chip(c.group, "#7dd3fc");
        if (s->online()) chip(QString("health %1 (%2)").arg(a.health).arg(a.grade), C::health(a.health).name());
        if (c.autopilot.enabled) chip(c.autopilot.dryRun ? "autopilot: dry run" : "autopilot: on", "#a78bfa");
        chips->setText(h), pause->setText(s->isPaused() ? "▶ Resume" : "❚❚ Pause");
    }
};

// ============================================================================ add / edit dialog
static bool editServer(QWidget *parent, ServerConfig &cfg, const QStringList &groups)
{
    QDialog dlg(parent);
    dlg.setWindowTitle(cfg.name.isEmpty() ? "Add server" : "Edit server — " + cfg.name);
    dlg.setMinimumWidth(620);
    auto *l = new QVBoxLayout(&dlg);
    l->setContentsMargins(24, 20, 24, 20), l->setSpacing(14);
    l->addWidget(label(cfg.name.isEmpty() ? "Add a server" : "Edit server", "H2"));
    auto *f = new QFormLayout;
    auto *name = new QLineEdit(cfg.name), *host = new QLineEdit(cfg.host), *user = new QLineEdit(cfg.user), *key = new QLineEdit(cfg.keyFile), *pass = new QLineEdit(cfg.password);
    auto *group = new QComboBox, *via = new QComboBox;
    auto *port = new QSpinBox, *interval = new QSpinBox;
    auto *sudo = new QCheckBox("Run control commands with sudo -n (needs passwordless sudo)"), *enabled = new QCheckBox("Monitoring enabled");
    auto *notes = new QPlainTextEdit(cfg.notes);
    auto *browse = button("Browse…", nullptr, [&] {
        const QString fn = QFileDialog::getOpenFileName(&dlg, "Private key", QDir::homePath() + "/.ssh");
        if (!fn.isEmpty()) key->setText(fn);
    });
    auto *test = button("Test connection");
    auto *hint = label({}, "Muted", true), *result = label({}, nullptr, true);
    group->setEditable(true), group->addItems(groups), group->setCurrentText(cfg.group);
    via->addItems({"This machine (local)", "SSH — nothing to install on the server"}), via->setCurrentIndex(int(cfg.transport));
    port->setRange(1, 65535), port->setValue(cfg.port), port->setPrefix("port ");
    interval->setRange(1, 300), interval->setValue(cfg.interval), interval->setSuffix(" s");
    pass->setEchoMode(QLineEdit::Password), sudo->setChecked(cfg.useSudo), enabled->setChecked(cfg.enabled), notes->setMaximumHeight(70);
    name->setPlaceholderText("e.g. web-01"), host->setPlaceholderText("hostname or IP address"), user->setPlaceholderText("default: your local user name");
    key->setPlaceholderText("default keys / ssh-agent (~/.ssh/id_*)"), pass->setPlaceholderText("optional — keys are recommended");
    auto *addr = hbox(), *keyRow = hbox(), *testRow = hbox();
    addr->addWidget(host, 1), addr->addWidget(port), keyRow->addWidget(key, 1), keyRow->addWidget(browse), testRow->addWidget(test), testRow->addWidget(result, 1);
    f->addRow("Name", name), f->addRow("Group", group), f->addRow("Connect via", via), f->addRow("Address", addr), f->addRow("User", user);
    f->addRow("Private key", keyRow), f->addRow("Password", pass), f->addRow("Sample every", interval), f->addRow("", enabled), f->addRow("Notes", notes);
    P::sudo ? f->insertRow(8, "", sudo) : (sudo->setParent(&dlg), sudo->hide());
    auto *bb = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel);
    l->addLayout(f), l->addWidget(hint), l->addLayout(testRow), l->addWidget(bb);
    auto collect = [&] {
        ServerConfig c = cfg;
        c.name = name->text().trimmed(), c.group = group->currentText().trimmed(), c.transport = Transport(via->currentIndex());
        c.host = c.transport == Transport::Local ? "" : host->text().trimmed(), c.port = port->value(), c.user = user->text().trimmed();
        c.keyFile = key->text().trimmed(), c.password = pass->text(), c.interval = interval->value(), c.useSudo = sudo->isChecked();
        c.enabled = enabled->isChecked(), c.notes = notes->toPlainText();
        return c;
    };
    auto show = [&](const QString &text, const QColor &c) { result->setText(text), result->setStyleSheet("color: " + c.name() + ";"); };
    auto sync = [&] {
        const bool ssh = via->currentIndex() == 1;
        for (QWidget *w : std::initializer_list<QWidget *>{host, port, user, key, browse, pass}) w->setEnabled(ssh);
        hint->setText(ssh ? P::sshHint : "Monitors the computer this program runs on. No setup needed.");
        if (!ssh && name->text().isEmpty()) name->setText("This computer");
    };
    QObject::connect(via, QOverload<int>::of(&QComboBox::currentIndexChanged), &dlg, sync);
    QObject::connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
    QObject::connect(bb, &QDialogButtonBox::accepted, &dlg, [&] {
        const ServerConfig c = collect();
        if (c.name.isEmpty() || (c.transport == Transport::SSH && c.host.isEmpty())) return show("Please enter a name and an address.", C::red);
        dlg.accept();
    });
    QPointer<Link> link;
    QObject::connect(test, &QPushButton::clicked, &dlg, [&] { // two frames prove that data and rates work
        ServerConfig c = collect();
        c.interval = 1;
        delete link;
        link = new Link(c, &dlg);
        auto engine = std::make_shared<MetricsEngine>();
        auto clock = std::make_shared<QElapsedTimer>();
        auto frames = std::make_shared<int>(0);
        clock->start(), test->setEnabled(false), show("Connecting…", C::amber);
        auto finish = [&, l = link.data()](const QString &msg, const QColor &col) { show(msg, col), test->setEnabled(true), l->disconnect(), l->deleteLater(); };
        QObject::connect(link, &Link::snapshot, &dlg, [=](const QByteArray &raw) {
            const Metrics m = engine->process(raw, QDateTime::currentMSecsSinceEpoch());
            if (++*frames == 2)
                finish(QString("✓ Connected in %1 ms — %2 · %3 · %4 cores · %5 RAM · CPU %6").arg(clock->elapsed()).arg(m.hostname, m.os).arg(m.cpuCount).arg(Fmt::bytes(m.memTotal), Fmt::pct(m.cpuUsage, 0)), C::green);
        });
        QObject::connect(link, &Link::disconnected, &dlg, [=](const QString &why) { finish("✗ " + why, C::red); });
        QTimer::singleShot(20000, link, [=] { finish("✗ Timed out after 20 s", C::red); });
        link->start();
    });
    sync();
    if (dlg.exec() != QDialog::Accepted) return false;
    cfg = collect();
    return true;
}

// ============================================================================ main window
struct MainWindow::Ui {
    ServerManager *mgr;
    Actions act;
    QStackedWidget *stack = new QStackedWidget;
    DashboardPage *dash = new DashboardPage(mgr, &act);
    DetailPage *detail = new DetailPage(mgr, &act);
    QWidget *eventsPage = new QWidget;
    QTableWidget *events = table({"Time", "Server", "Type", "Message"}, {170, 180, 100});
    QComboBox *eventFilter = new QComboBox;
    QListWidget *list = new QListWidget;
    QPushButton *navDash = button("▦   Dashboard", "Nav"), *navEvents = button("◉   Events && alerts", "Nav");
    QLabel *badge = new QLabel;
    QSystemTrayIcon *tray = nullptr;
    int unseen = 0;
    bool quitting = false;
};

struct ServerItemDelegate : QStyledItemDelegate { // sidebar row: dot, name, alert count, mini CPU/MEM bars
    ServerManager *mgr;
    ServerItemDelegate(ServerManager *m, QObject *parent) : QStyledItemDelegate(parent), mgr(m) {}
    QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const override { return {220, 58}; }
    void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override
    {
        ServerSession *s = mgr->session(i.data(Qt::UserRole).toString());
        if (!s) return;
        const QRectF r = QRectF(o.rect).adjusted(6, 2, -6, -2);
        const Metrics &m = s->metrics();
        int y = int(r.top()) + 34;
        p->save();
        p->setRenderHint(QPainter::Antialiasing), p->setPen(Qt::NoPen);
        if (o.state & (QStyle::State_Selected | QStyle::State_MouseOver)) p->setBrush(o.state & QStyle::State_Selected ? QColor(0x17304a) : C::card), p->drawRoundedRect(r, 8, 8);
        p->setBrush(statusColor(s->status())), p->drawEllipse(QPointF(r.left() + 14, r.top() + 18), 4.5, 4.5);
        p->setFont(pxFont(o.font, 13, true)), p->setPen(C::text);
        p->drawText(QRectF(r.left() + 26, r.top() + 8, r.width() - 70, 20), Qt::AlignVCenter, p->fontMetrics().elidedText(s->config().name, Qt::ElideRight, int(r.width() - 70)));
        if (const int n = s->activeAlerts().size()) {
            const QRectF b(r.right() - 26, r.top() + 10, 20, 16);
            p->setFont(pxFont(o.font, 10, true)), p->setBrush(C::red), p->setPen(Qt::NoPen), p->drawRoundedRect(b, 8, 8), p->setPen(Qt::white), p->drawText(b, Qt::AlignCenter, QString::number(n));
        }
        for (auto [lbl, v] : {std::pair{"CPU", m.cpuUsage}, {"MEM", m.memPct}}) {
            const QRectF track(r.left() + 56, y - 2, r.width() - 70, 4);
            p->setFont(pxFont(o.font, 9)), p->setPen(C::faint), p->drawText(QRectF(r.left() + 26, y - 5, 30, 10), Qt::AlignVCenter, lbl);
            p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(track, 2, 2);
            if (s->online()) p->setBrush(C::level(v)), p->drawRoundedRect(QRectF(track.left(), track.top(), track.width() * qBound(0.0, v, 100.0) / 100, 4), 2, 2);
            y += 11;
        }
        p->restore();
    }
};

MainWindow::MainWindow(ServerManager *mgr) : ui(new Ui{mgr})
{
    setWindowTitle("Server Monitor"), setWindowIcon(C::appIcon()), resize(1500, 940), setMinimumSize(1100, 700);

    // navigation and server actions
    auto nav = [this](QWidget *pageW) {
        ui->stack->setCurrentWidget(pageW);
        ui->navDash->setChecked(pageW == ui->dash), ui->navEvents->setChecked(pageW == ui->eventsPage);
        if (pageW != ui->detail) ui->list->clearSelection();
    };
    auto refreshEvents = [this] {
        QVector<AlertEvent> rs;
        for (const AlertEvent &e : ui->mgr->alerts())
            if (!ui->eventFilter->currentIndex() || e.severity == ui->eventFilter->currentText()) rs << e;
        fillRows(ui->events, rs, [](const AlertEvent &e) {
            return Row{{e.time.toString("yyyy-MM-dd HH:mm:ss"), C::muted}, {e.serverName}, {e.severity.toUpper(), C::severity(e.severity)}, {e.message}};
        });
    };
    auto showDash = [=] { nav(ui->dash), ui->dash->refresh(); };
    auto showEvents = [=] { nav(ui->eventsPage), ui->unseen = 0, ui->badge->hide(), refreshEvents(); };
    auto showServer = [=](const QString &id) {
        if (!mgr->session(id)) return;
        ui->detail->bind(mgr->session(id)), nav(ui->detail);
        for (int i = 0; i < ui->list->count(); ++i)
            if (ui->list->item(i)->data(Qt::UserRole) == id) ui->list->setCurrentRow(i);
    };
    auto groups = [mgr] {
        QStringList g;
        for (ServerSession *s : mgr->sessions())
            if (!s->config().group.isEmpty() && !g.contains(s->config().group)) g << s->config().group;
        return g;
    };
    auto addServer = [=] {
        ServerConfig c;
        c.id = ServerConfig::newId();
        if (editServer(this, c, groups())) showServer(mgr->add(c)->config().id);
    };
    auto editSrv = [=](const QString &id) {
        ServerConfig c = mgr->session(id) ? mgr->session(id)->config() : ServerConfig();
        if (mgr->session(id) && editServer(this, c, groups())) mgr->update(c);
    };
    auto removeSrv = [=](const QString &id) {
        ServerSession *s = mgr->session(id);
        if (!s) return;
        QMessageBox box(QMessageBox::Warning, "Remove server", QString("Stop monitoring \"%1\" and remove it from the list?").arg(s->config().name), QMessageBox::Cancel, this);
        auto *withHist = box.addButton("Remove + delete history", QMessageBox::DestructiveRole), *keep = box.addButton("Remove, keep history files", QMessageBox::AcceptRole);
        box.exec();
        if (box.clickedButton() != withHist && box.clickedButton() != keep) return;
        if (ui->detail->s == s) ui->detail->bind(nullptr), showDash();
        mgr->remove(id, box.clickedButton() == withHist);
    };
    auto selectedId = [this] { return ui->list->currentItem() ? ui->list->currentItem()->data(Qt::UserRole).toString() : QString(); };
    ui->act = {showServer, editSrv, removeSrv, addServer, showDash};

    // sidebar
    auto *central = new QWidget, *side = new QWidget;
    auto *h = new QHBoxLayout(central);
    auto *sl = new QVBoxLayout(side), *bt = new QVBoxLayout;
    auto *brand = hbox(), *evRow = hbox(), *btns = hbox();
    auto *logo = new QLabel, *title = label("Server Monitor");
    h->setContentsMargins(0, 0, 0, 0), h->setSpacing(0), h->addWidget(side), h->addWidget(ui->stack, 1);
    setCentralWidget(central);
    side->setObjectName("Sidebar"), side->setFixedWidth(260);
    logo->setPixmap(C::appIcon().pixmap(34, 34)), title->setStyleSheet("font-size: 16px; font-weight: 800;");
    bt->setSpacing(0), bt->addWidget(title), bt->addWidget(label("monitor · analyze · control", "Muted"));
    brand->addWidget(logo), brand->addLayout(bt, 1);
    ui->badge->setStyleSheet("background: #ef4444; color: white; border-radius: 9px; padding: 1px 7px; font-size: 11px; font-weight: 700;"), ui->badge->hide();
    evRow->addWidget(ui->navEvents, 1), evRow->addWidget(ui->badge);
    ui->navDash->setCheckable(true), ui->navEvents->setCheckable(true);
    ui->list->setStyleSheet("QListWidget { background: transparent; border: none; }");
    ui->list->setItemDelegate(new ServerItemDelegate(mgr, ui->list)), ui->list->setMouseTracking(true), ui->list->setContextMenuPolicy(Qt::CustomContextMenu);
    btns->setSpacing(6), btns->addWidget(button("+ Add", "Primary", addServer), 1);
    btns->addWidget(button("Edit", nullptr, [=] { editSrv(selectedId()); }), 1), btns->addWidget(button("Remove", "Danger", [=] { removeSrv(selectedId()); }), 1);
    sl->setContentsMargins(12, 18, 12, 14), sl->setSpacing(6);
    sl->addLayout(brand), sl->addSpacing(14), sl->addWidget(ui->navDash), sl->addLayout(evRow), sl->addSpacing(12);
    sl->addWidget(label("  SERVERS", "Section")), sl->addWidget(ui->list, 1), sl->addLayout(btns);

    // events page
    auto *el = page(ui->eventsPage);
    auto *eh = hbox();
    auto *et = new QVBoxLayout;
    et->addWidget(label("Events & alerts", "H1"));
    et->addWidget(label("Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log.", "Muted"));
    ui->eventFilter->addItems({"All events", "critical", "warning", "info", "resolved", "action"});
    eh->addLayout(et, 1), eh->addWidget(ui->eventFilter);
    eh->addWidget(button("Open log folder", nullptr, [] { QDesktopServices::openUrl(QUrl::fromLocalFile(ServerManager::configDir())); }));
    eh->addWidget(button("Clear list", nullptr, [mgr] { mgr->clearAlerts(); }));
    el->addLayout(eh), el->addWidget(ui->events, 1);
    for (QWidget *w : std::initializer_list<QWidget *>{ui->dash, ui->detail, ui->eventsPage}) ui->stack->addWidget(w);

    connect(ui->navDash, &QPushButton::clicked, this, showDash);
    connect(ui->navEvents, &QPushButton::clicked, this, showEvents);
    connect(ui->list, &QListWidget::itemClicked, this, [=](QListWidgetItem *it) { showServer(it->data(Qt::UserRole).toString()); });
    connect(ui->list, &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) {
        QListWidgetItem *it = ui->list->itemAt(pos);
        if (!it) return;
        const QString id = it->data(Qt::UserRole).toString();
        QMenu m;
        m.addAction("Open", [=] { showServer(id); }), m.addAction("Reconnect", [=] { mgr->session(id)->reconnect(); }), m.addSeparator();
        m.addAction("Move up", [=] { mgr->move(id, -1); }), m.addAction("Move down", [=] { mgr->move(id, 1); }), m.addSeparator();
        m.addAction("Edit…", [=] { editSrv(id); }), m.addAction("Remove…", [=] { removeSrv(id); });
        m.exec(ui->list->viewport()->mapToGlobal(pos));
    });
    connect(ui->eventFilter, QOverload<int>::of(&QComboBox::currentIndexChanged), this, refreshEvents);
    connect(mgr, &ServerManager::alertsCleared, this, refreshEvents);
    connect(mgr, &ServerManager::listChanged, this, [=] {
        const QString cur = selectedId();
        ui->list->clear();
        for (ServerSession *s : mgr->sessions()) {
            auto *it = new QListWidgetItem(s->config().name, ui->list);
            it->setData(Qt::UserRole, s->config().id);
            if (s->config().id == cur) ui->list->setCurrentItem(it);
        }
    });
    connect(mgr, &ServerManager::alertRaised, this, [=](const AlertEvent &e) {
        const bool important = e.severity == "critical" || e.severity == "warning" || e.severity == "action";
        if (ui->stack->currentWidget() == ui->eventsPage) refreshEvents();
        else if (important) ui->badge->setText(QString::number(++ui->unseen)), ui->badge->show();
        if (ui->tray && important && QSettings().value("notify", true).toBool())
            ui->tray->showMessage(e.serverName + " — " + e.severity, e.message, e.severity == "critical" ? QSystemTrayIcon::Critical : e.severity == "warning" ? QSystemTrayIcon::Warning : QSystemTrayIcon::Information, 8000);
    });
    auto *tick = new QTimer(this); // sidebar bars + dashboard tiles
    connect(tick, &QTimer::timeout, this, [this] {
        ui->list->viewport()->update();
        if (ui->stack->currentWidget() == ui->dash) ui->dash->refresh();
    });
    tick->start(1000);

    if (QSystemTrayIcon::isSystemTrayAvailable()) {
        ui->tray = new QSystemTrayIcon(C::appIcon(), this);
        auto *menu = new QMenu(this);
        menu->addAction("Show window", this, [this] { showNormal(), raise(), activateWindow(); });
        for (auto [text, key] : {std::pair{"Desktop notifications", "notify"}, {"Keep running in tray when closed", "closeToTray"}}) {
            QAction *a = menu->addAction(text);
            a->setCheckable(true), a->setChecked(QSettings().value(key, true).toBool());
            connect(a, &QAction::toggled, [k = QString(key)](bool on) { QSettings().setValue(k, on); });
        }
        menu->addSeparator(), menu->addAction("Quit", this, [this] { ui->quitting = true, qApp->quit(); });
        ui->tray->setContextMenu(menu), ui->tray->setToolTip("Server Monitor"), ui->tray->show();
        connect(ui->tray, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason r) {
            if (r == QSystemTrayIcon::Trigger) isVisible() && !isMinimized() ? hide() : (showNormal(), raise(), activateWindow());
        });
    }
    restoreGeometry(QSettings().value("geometry").toByteArray());
    showDash();
}

void MainWindow::closeEvent(QCloseEvent *e)
{
    QSettings st;
    st.setValue("geometry", saveGeometry());
    if (ui->quitting || !ui->tray || !st.value("closeToTray", true).toBool()) return qApp->quit();
    hide(), e->ignore();
    if (!st.value("trayHintShown").toBool()) ui->tray->showMessage("Server Monitor", "Still monitoring in the background. Right-click the tray icon to quit."), st.setValue("trayHintShown", true);
}

void MainWindow::saveSnapshots(const QString &dir)
{
    auto settle = [] { QEventLoop loop; QTimer::singleShot(700, &loop, &QEventLoop::quit), loop.exec(); }; // let animations finish
    QTabWidget *tabs = ui->detail->tabs;
    grab().save(dir + "/00-dashboard.png");
    if (ui->mgr->sessions().isEmpty()) return;
    ui->act.open(ui->mgr->sessions()[0]->config().id);
    for (int i = 0; i < tabs->count(); ++i)
        tabs->setCurrentIndex(i), settle(), grab().save(QString("%1/%2-%3.png").arg(dir).arg(i + 1, 2, 10, QChar('0')).arg(tabs->tabText(i).split(' ')[0].toLower()));
    ui->navEvents->click(), settle(), grab().save(dir + "/99-events.png");
}