ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
//! Headless rendering harness for the GUI.
//!
//! egui draws into a `Context` that needs no window, so a test can run real widget
//! code and read back the text that was actually painted. That matters here because
//! the alternative — screenshotting a live window — proved unusable: on a
//! multi-monitor setup the window handle resolves to transient popups and the
//! captured rect is whatever happened to be on top.
//!
//! More importantly, a screenshot cannot answer the question that actually matters.
//! The Profiles tab rendered all 19 of its groups perfectly while every heading was
//! drawn in the panel colour; a human looking at the window and a naive capture both
//! reported an empty tab. Reading the painted galleys distinguishes "this text was
//! never emitted" from "this text was emitted and could not be seen", which are
//! different bugs with different fixes.

use egui::Context;
use std::time::Duration;

/// Every string painted by `body`, in paint order.
///
/// Walks the tessellated output rather than instrumenting the widgets, so it sees
/// what egui actually drew — including text emitted by widgets this module knows
/// nothing about.
pub fn painted_text(ctx: &Context, body: impl FnMut(&mut egui::Ui)) -> Vec<String> {
    painted_text_sized(ctx, DEFAULT_VIEWPORT, body)
}

/// Viewport used when none is given.
///
/// Large enough that a tab's content is not clipped away. This is not cosmetic:
/// `RawInput::default()` carries no `screen_rect`, and widgets that guard on
/// `Ui::is_rect_visible` — `SectionHeader` among them — paint nothing in a
/// degenerate viewport.
pub const DEFAULT_VIEWPORT: egui::Vec2 = egui::Vec2::new(1600.0, 1200.0);

/// Every string painted by `body`, at an explicit viewport size.
pub fn painted_text_sized(
    ctx: &Context,
    size: egui::Vec2,
    mut body: impl FnMut(&mut egui::Ui),
) -> Vec<String> {
    let input = egui::RawInput {
        screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
        ..Default::default()
    };

    // Two frames, and the second is the one that counts.
    //
    // egui is immediate-mode but not stateless: a `ScrollArea` does not know its
    // content size until it has laid the content out once, and on that first frame
    // it reports a viewport that makes `Ui::is_rect_visible` false for everything
    // inside it. A tab whose body is entirely wrapped in one — the CPU and System
    // tabs both are — paints nothing at all on frame one. That read as two dead
    // tabs and was an artefact of rendering a single frame, not a defect in them.
    //
    // The body therefore has to run twice, which is why this takes `FnMut`.
    let mut run_frame = || {
        ctx.run(input.clone(), |ctx| {
            egui::CentralPanel::default().show(ctx, |ui| body(ui));
        })
    };

    let _warmup = run_frame();
    let settled = run_frame();

    let mut out = Vec::new();
    for clipped in &settled.shapes {
        collect_shape_text(&clipped.shape, &mut out);
    }
    out
}

/// Render frames until `settled` reports true or `deadline` passes, then return
/// what the last frame painted.
///
/// The two-frame warmup above handles egui's own laziness. This handles the
/// application's: four tabs load their contents on a background thread and paint
/// a spinner until it lands, and the headless path never ran the loop that
/// collects those results. A single frame therefore captured "Loading disk
/// information…" forever — which *is* painted text, so
/// `every_gui_tab_paints_text` passed while an agent reading the disk tab learned
/// nothing.
///
/// `pump` is called between frames to advance whatever the caller is waiting on.
/// Returning on a deadline rather than blocking is deliberate: a machine whose
/// disk enumeration hangs should yield a slow, honest "still loading" rather than
/// a headless command that never exits.
/// `settled` is asked about the *painted text*, not about the application's
/// internal flags. That is deliberate: a flag-based predicate makes every tab wait
/// for every loader, so tabs that render instantly — memory, network — went from
/// immediate to twelve seconds because they were waiting on a peripherals query
/// they do not draw. What the caller actually wants to know is whether *this* tab
/// still says it is loading, and the frame answers that directly.
///
/// `state` is threaded through explicitly rather than captured, because all three
/// callbacks need it and closures capturing one `&mut` cannot coexist.
pub fn painted_text_until<T>(
    ctx: &Context,
    deadline: std::time::Duration,
    state: &mut T,
    mut pump: impl FnMut(&mut T, &Context),
    mut settled: impl FnMut(&T, &[String]) -> bool,
    mut body: impl FnMut(&mut T, &mut egui::Ui),
) -> Vec<String> {
    let start = std::time::Instant::now();
    let mut last = painted_text(ctx, |ui| body(state, ui));

    while !settled(state, &last) && start.elapsed() < deadline {
        std::thread::sleep(std::time::Duration::from_millis(50));
        pump(state, ctx);
        last = painted_text(ctx, |ui| body(state, ui));
    }

    if settled(state, &last) {
        return last;
    }

    // One more pass after settling: the frame that observes a load finishing is
    // the frame *before* its data is available to draw.
    pump(state, ctx);
    let final_pass = painted_text(ctx, |ui| body(state, ui));

    // A tab that painted nothing on the very last pass should report whatever it
    // last managed rather than a blank, which would read as a dead tab.
    if final_pass.is_empty() {
        last
    } else {
        final_pass
    }
}

/// Whether a rendered frame is still showing a background load rather than data.
///
/// The tabs that load asynchronously all paint a spinner beside a line of the
/// form "Loading … information…". Matching on that is coupling to a UI string,
/// which is worth stating plainly — but the alternative, introspecting per-tab
/// loading flags, couples to more and gets the answer wrong for tabs that draw
/// none of them. `every_gui_tab_paints_text` asserts this same property from the
/// other side, so a placeholder that changes wording fails a test rather than
/// silently making the wait a no-op.
pub fn frame_is_still_loading(lines: &[String]) -> bool {
    // Matches "Loading disk information...", "Loading profile snapshot…" and the
    // bare "Loading…". An earlier version required a trailing "..." and missed
    // every placeholder using the single-character ellipsis, which is most of
    // them — the check has to be as loose as the wording actually is.
    lines.iter().any(|l| l.trim_start().starts_with("Loading"))
}

/// Text painted by `body`, joined into one haystack for substring assertions.
pub fn painted_blob(ctx: &Context, body: impl FnMut(&mut egui::Ui)) -> String {
    painted_text(ctx, body).join("\n")
}

/// Every painted string with the rectangle it occupies, at an explicit viewport.
///
/// `painted_text` answers "was this drawn"; this answers "drawn *where*". The
/// distinction matters because the two Dewey failures were different: one tab
/// painted nothing, and another painted everything and clipped it off the right
/// edge. Reading text alone catches the first and is blind to the second.
pub fn painted_text_rects_sized(
    ctx: &Context,
    size: egui::Vec2,
    mut body: impl FnMut(&mut egui::Ui),
) -> Vec<(String, egui::Rect)> {
    let input = egui::RawInput {
        screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
        ..Default::default()
    };
    let mut run_frame = || {
        ctx.run(input.clone(), |ctx| {
            egui::CentralPanel::default().show(ctx, |ui| body(ui));
        })
    };
    let _warmup = run_frame();
    let settled = run_frame();

    let mut out = Vec::new();
    for clipped in &settled.shapes {
        collect_shape_text_rects(&clipped.shape, &mut out);
    }
    out
}

/// Painted strings whose box extends past `size` horizontally.
///
/// Vertical overrun is not overflow here: every tab body is inside a
/// `ScrollArea`, so content taller than the viewport is reachable. Width is not
/// scrollable in this layout, so text past the right edge is simply unreadable.
pub fn horizontal_overflow(
    ctx: &Context,
    size: egui::Vec2,
    body: impl FnMut(&mut egui::Ui),
) -> Vec<(String, f32)> {
    painted_text_rects_sized(ctx, size, body)
        .into_iter()
        .filter(|(text, rect)| !text.trim().is_empty() && rect.max.x > size.x)
        .map(|(text, rect)| (text, rect.max.x - size.x))
        .collect()
}

/// Bring an app to the state a user actually sees before measuring it.
///
/// Two things arrive late and both change what a tab paints, so a measurement
/// taken before them is of a different screen:
///
/// - **Background loaders.** Four tabs fetch their contents off-thread and paint
///   a spinner until the data lands.
/// - **The collector's first real snapshot.** The pipeline publishes a warm-up
///   generation built from an empty source set, so GPUs, processes and
///   connections are absent from it *by construction*. On this three-GPU machine
///   the Overview's accelerator cards simply are not there yet, and the tab is
///   shorter than it will be a moment later.
///
/// Returns false if either is still outstanding when the budget runs out, so a
/// caller can decline to measure rather than measure the wrong thing.
pub fn settle(app: &mut crate::gui::app::IronMonitorApp, ctx: &Context, budget: Duration) -> bool {
    let deadline = std::time::Instant::now() + budget;

    while std::time::Instant::now() < deadline {
        app.pump_background_loaders(ctx);
        app.sync_snapshot();
        if app.has_real_snapshot() && !app.has_pending_load() {
            return true;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    false
}

/// The bottom-right corner of everything `body` actually paints.
///
/// The measurement that works on this GUI, where the other two do not.
/// `Context::used_size` reports *allocated* space — `1400x4000` for a 1400x4000
/// canvas, and `-inf` in the live app, where tabs paint through panels rather
/// than the measured `Ui`. Asking a tab how wide it wants to be is circular too:
/// every widget sizes to `available_width()`, so all thirteen report wanting
/// exactly whatever canvas they are handed.
///
/// Where text lands is not circular. Rendered at 1400 wide the Overview paints
/// out to 1382x918; at 1100 wide, 1082x918. The width follows the canvas because
/// the layout is elastic, and **the height does not** — 918 px is a real
/// property of the tab, and the number a window can be fitted to.
pub fn painted_extent(
    ctx: &Context,
    canvas: egui::Vec2,
    body: impl FnMut(&mut egui::Ui),
) -> egui::Vec2 {
    let mut extent = egui::Vec2::ZERO;
    for (text, rect) in painted_text_rects_sized(ctx, canvas, body) {
        if text.trim().is_empty() {
            continue;
        }
        extent.x = extent.x.max(rect.max.x);
        extent.y = extent.y.max(rect.max.y);
    }
    extent
}

/// Every painted shape's rectangle and what kind of shape it was.
///
/// **`painted_text_rects_sized` reads galleys, so it can only see glyphs.** That
/// is the right instrument for "is this text off the edge" and the wrong one for
/// "what made the container this wide", because a chart, a frame or a progress
/// bar paints no text and is therefore invisible to it. The `ai` tab was pinned
/// as overflowing for exactly that reason: its welcome sentence was centred in a
/// box roughly 1369 px wide at an 800 px window, so the sentence was a symptom
/// and the thing that widened the box could not be named.
///
/// `Shape::visual_bounding_rect` covers every variant — rects, circles, paths,
/// meshes — so this can answer the question the text reader cannot.
///
/// The kind is carried as a string because the caller wants to *report* it. A
/// bare rectangle that is 300 px too wide tells you where to look and not what
/// to look for.
pub fn painted_shape_rects(
    ctx: &Context,
    size: egui::Vec2,
    mut body: impl FnMut(&mut egui::Ui),
) -> Vec<(&'static str, egui::Rect)> {
    let input = egui::RawInput {
        screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
        ..Default::default()
    };
    let mut run_frame = || {
        ctx.run(input.clone(), |ctx| {
            egui::CentralPanel::default().show(ctx, |ui| body(ui));
        })
    };
    // Two frames, for the same reason the text reader needs two: a `ScrollArea`
    // does not know its content size until it has laid it out once.
    let _warmup = run_frame();
    let settled = run_frame();

    let mut out = Vec::new();
    for clipped in &settled.shapes {
        collect_shape_rects(&clipped.shape, &mut out);
    }
    out
}

fn shape_kind(shape: &egui::Shape) -> &'static str {
    match shape {
        egui::Shape::Noop => "noop",
        egui::Shape::Vec(_) => "vec",
        egui::Shape::Circle(_) => "circle",
        egui::Shape::Ellipse(_) => "ellipse",
        egui::Shape::LineSegment { .. } => "line",
        egui::Shape::Path(_) => "path",
        egui::Shape::Rect(_) => "rect",
        egui::Shape::Text(_) => "text",
        egui::Shape::Mesh(_) => "mesh",
        egui::Shape::QuadraticBezier(_) => "quadratic",
        egui::Shape::CubicBezier(_) => "cubic",
        egui::Shape::Callback(_) => "callback",
    }
}

fn collect_shape_rects(shape: &egui::Shape, out: &mut Vec<(&'static str, egui::Rect)>) {
    // A `Vec` is a container rather than a mark: recording its own bounds would
    // report the union of its children as though it were one wide widget, which
    // is the opposite of naming the culprit.
    if let egui::Shape::Vec(shapes) = shape {
        for s in shapes {
            collect_shape_rects(s, out);
        }
        return;
    }

    let rect = shape.visual_bounding_rect();
    // egui returns `NOTHING` — an inverted infinite rect — for shapes that paint
    // no pixels. Unioning one of those poisons every maximum downstream.
    if rect.is_finite() && rect.is_positive() {
        out.push((shape_kind(shape), rect));
    }
}

/// What paints furthest past the right edge, widest first.
///
/// Reports *any* shape, so the answer can be a chart or a frame rather than a
/// label. Use this when a tab overflows and the text reader has nothing to say
/// about why.
pub fn widest_overflowing_shapes(
    ctx: &Context,
    size: egui::Vec2,
    body: impl FnMut(&mut egui::Ui),
) -> Vec<(&'static str, egui::Rect, f32)> {
    let mut over: Vec<(&'static str, egui::Rect, f32)> = painted_shape_rects(ctx, size, body)
        .into_iter()
        .filter(|(_, rect)| rect.max.x > size.x)
        .map(|(kind, rect)| (kind, rect, rect.max.x - size.x))
        .collect();
    over.sort_by(|a, b| b.2.total_cmp(&a.2));
    over
}

fn collect_shape_text_rects(shape: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
    match shape {
        egui::Shape::Text(text) => {
            let s = text.galley.text();
            if !s.is_empty() {
                // `shape.visual_bounding_rect()`, not `from_min_size(pos, size)`.
                //
                // **`TextShape::pos` is an anchor, not a left edge.** For a
                // galley with a centred or right horizontal alignment the text
                // extends away from `pos`, so composing a rect from it reports a
                // box the right size in the wrong place. The AI tab's welcome
                // sentence painted its pixels at 114..693 inside an 800 px
                // window while this reader claimed 404..983 — a 183 px overrun
                // that was not on the screen, and which this guard pinned as a
                // defect for weeks.
                //
                // The bounding rect is computed by egui from the galley's own
                // mesh, so it is where the glyphs actually are. That is the only
                // thing a reader can see, and the only thing worth asserting.
                out.push((s.to_string(), shape.visual_bounding_rect()));
            }
        }
        egui::Shape::Vec(shapes) => {
            for s in shapes {
                collect_shape_text_rects(s, out);
            }
        }
        _ => {}
    }
}

fn collect_shape_text(shape: &egui::Shape, out: &mut Vec<String>) {
    match shape {
        egui::Shape::Text(text) => {
            let s = text.galley.text();
            if !s.trim().is_empty() {
                out.push(s.to_string());
            }
        }
        // Widgets compose, so text is routinely nested inside a Vec shape.
        egui::Shape::Vec(shapes) => {
            for s in shapes {
                collect_shape_text(s, out);
            }
        }
        _ => {}
    }
}

/// A context with the app's own theme applied, so tests exercise the real palette
/// rather than egui's defaults.
pub fn themed_context() -> Context {
    let ctx = Context::default();
    super::theme::apply_cyber_theme(&ctx);
    ctx
}

#[cfg(test)]
mod tests {
    use super::*;
    use egui::RichText;

    #[test]
    fn the_harness_sees_text_that_was_painted() {
        let ctx = themed_context();
        let blob = painted_blob(&ctx, |ui| {
            ui.label("a plain label");
            ui.label(RichText::new("a strong label").strong());
        });
        assert!(blob.contains("a plain label"), "got: {blob}");
        assert!(blob.contains("a strong label"), "got: {blob}");
    }

    #[test]
    fn the_harness_sees_text_nested_inside_widgets() {
        let ctx = themed_context();
        let blob = painted_blob(&ctx, |ui| {
            egui::CollapsingHeader::new("outer heading")
                .default_open(true)
                .show(ui, |ui| {
                    ui.label("nested body text");
                });
        });
        assert!(blob.contains("outer heading"), "got: {blob}");
        assert!(blob.contains("nested body text"), "got: {blob}");
    }

    /// The harness must not report text that was never drawn, or it would mask the
    /// very regressions it exists to catch.
    #[test]
    fn the_harness_does_not_invent_text() {
        let ctx = themed_context();
        let blob = painted_blob(&ctx, |ui| {
            ui.label("only this");
        });
        assert!(!blob.contains("not drawn"), "got: {blob}");
    }

    /// Reading painted text separates "never emitted" from "emitted but invisible" —
    /// the distinction a screenshot cannot make, and the one that made the Profiles
    /// tab look dead while it was rendering correctly.
    #[test]
    fn invisible_text_is_still_painted_text() {
        let ctx = themed_context();
        let panel_fill = ctx.style().visuals.panel_fill;
        let blob = painted_blob(&ctx, |ui| {
            // Deliberately drawn in the background colour, as the old theme did.
            ui.label(RichText::new("camouflaged").color(panel_fill));
        });
        assert!(
            blob.contains("camouflaged"),
            "the harness should see text regardless of its colour, so that a \
             contrast bug is diagnosable as distinct from a missing-widget bug"
        );
    }
}

/// Tests that build the real application and render real tabs.
///
/// These are the ones that can answer "does tab X work", which the colour and
/// harness tests above cannot: they exercise the actual widget code with the
/// actual application state.
#[cfg(test)]
mod app_tab_tests {
    use super::*;
    use crate::gui::app::IronMonitorApp;

    /// Constructing the app enumerates GPUs and spawns collectors. That is slow but
    /// real, and a mock would defeat the purpose of the test.
    fn app_and_ctx() -> (IronMonitorApp, egui::Context) {
        let ctx = egui::Context::default();
        let app = IronMonitorApp::with_context(&ctx);
        (app, ctx)
    }

    #[test]
    fn header_controls_do_not_overlap_or_leave_the_window() {
        let (mut app, ctx) = app_and_ctx();
        for width in [800.0, 1100.0, 1400.0] {
            let input = egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(width, 600.0),
                )),
                ..Default::default()
            };
            let _ = ctx.run(input.clone(), |ctx| app.draw_top_panel(ctx));
            let output = ctx.run(input, |ctx| app.draw_top_panel(ctx));
            let mut labels = Vec::new();
            for clipped in &output.shapes {
                collect_shape_text_rects(&clipped.shape, &mut labels);
            }
            assert!(labels.iter().any(|(text, _)| text.contains('@')));
            assert!(labels.iter().any(|(text, _)| text.ends_with(" AI")));
            let settings = labels
                .iter()
                .find(|(text, _)| text == "⚙")
                .expect("Settings control");
            assert!(
                settings.1.max.x > width - 40.0,
                "Settings should stay at the right edge"
            );
            for (index, (text, rect)) in labels.iter().enumerate() {
                assert!(
                    rect.min.x >= 0.0 && rect.max.x <= width,
                    "header label {text:?} is outside a {width}px window: {rect:?}"
                );
                for (other, other_rect) in &labels[index + 1..] {
                    assert!(
                        !rect.intersects(*other_rect),
                        "header labels {text:?} and {other:?} overlap at {width}px: \
                         {rect:?} and {other_rect:?}"
                    );
                }
            }
        }
    }

    /// The reported bug was "AI backends do not work". The CLI path answered a
    /// question correctly against Ollama, which located the fault in the GUI — but
    /// screenshots could never confirm what the tab actually drew.
    ///
    /// This renders the real tab and asserts it emits its own furniture. It does not
    /// assert a backend is reachable: that depends on whether a model server happens
    /// to be running, which is not a property of the code.
    #[test]
    fn the_ai_tab_renders_its_controls() {
        let (mut app, ctx) = app_and_ctx();

        // First frame lands inside the detection window and paints a spinner. That
        // is a working state, but asserting on it proves nothing about the tab the
        // user actually sits in front of — an accept-either assertion here passed
        // while never once exercising the post-detection UI.
        let first = painted_blob(&ctx, |ui| {
            app.draw_ai_assistant_tab(ui);
        });
        assert!(
            first.contains("Detecting AI backends"),
            "expected the detection notice on the first frame, got: {first}"
        );

        // The tab gives detection a three-second budget and then shows the controls
        // regardless. Waiting it out is slower than mocking the clock but exercises
        // the real branch.
        std::thread::sleep(std::time::Duration::from_millis(3200));

        let settled = painted_blob(&ctx, |ui| {
            app.draw_ai_assistant_tab(ui);
        });
        assert!(
            settled.contains("AI System Assistant"),
            "past the detection budget the AI tab should paint its header and \
             controls, got: {settled}"
        );
        // The controls themselves, not just the header — a tab that painted a title
        // over an empty body is the failure being guarded against.
        assert!(
            settled.contains("Model:") || settled.contains("Select model"),
            "the AI tab painted its header but not its model selector: {settled}"
        );
        // A concurrent "still probing" note is *not* a failure and must not be
        // asserted against: backend discovery outlives the three-second spinner
        // budget by design, and saying so while the controls are usable is the
        // honest state. An earlier version of this test forbade it and failed
        // against a tab that was working correctly.
        assert!(
            settled
                .lines()
                .any(|l| l.contains("Ollama") || l.contains("IronWorks") || l.contains("backend")),
            "the AI tab offered no backend at all: {settled}"
        );
    }

    /// The Overview ask bar shares state with the AI tab, so it has to render even
    /// when no model has been selected — and say which condition is unmet rather
    /// than reporting the backend dead.
    #[test]
    fn the_overview_ask_bar_renders_and_explains_itself() {
        let (mut app, ctx) = app_and_ctx();
        let blob = painted_blob(&ctx, |ui| {
            app.draw_overview_chat_bar(ui);
        });

        assert!(
            blob.contains("Ask"),
            "the ask bar is missing its label: {blob}"
        );
        // When no model is chosen the bar must name that specific condition. The
        // backend is usually reachable and merely has nothing selected, which is why
        // this says "no model" rather than "unavailable".
        if !app.agent_can_answer() {
            assert!(
                blob.contains("no model selected"),
                "with no model available the bar should say so, got: {blob}"
            );
        }
    }

    #[test]
    fn shared_chat_composer_is_visible_at_the_top_on_small_and_large_pages() {
        let (mut app, ctx) = app_and_ctx();
        for width in [320.0, 800.0, 1400.0] {
            let size = egui::vec2(width, 700.0);
            painted_text_rects_sized(&ctx, size, |ui| {
                let full_width = ui.available_width();
                let fonts = ui.style().text_styles.clone();
                app.draw_agent_composer(ui);
                assert!((ui.available_width() - full_width).abs() < 1.0);
                assert_eq!(ui.style().text_styles, fonts);
                let dashboard = ui.add(crate::gui::widgets::QuickLookPanel::new(
                    None, None, None, None,
                ));
                assert!((dashboard.rect.width() - full_width).abs() < 1.0);
                assert_eq!(dashboard.rect.height(), 48.0);
            });
            for ai_page in [false, true] {
                let text = painted_text_rects_sized(&ctx, size, |ui| {
                    if ai_page {
                        app.draw_ai_assistant_tab(ui);
                    } else {
                        app.draw_overview(ui);
                    }
                });
                assert!(!text.iter().any(|(text, _)| text == "Ask IronMonitor"));
                let (_, input) = text
                    .iter()
                    .find(|(text, _)| text.starts_with("Ask "))
                    .expect("composer input");
                assert!(input.min.y < 30.0, "{input:?}");
                let (_, send) = text
                    .iter()
                    .find(|(text, _)| text == "Send")
                    .expect("send control");
                assert!(send.max.x <= width && send.max.y < 200.0, "{send:?}");
                assert!(send.min.x > input.max.x, "input: {input:?}, send: {send:?}");
                assert!(
                    (send.center().y - input.center().y).abs() < 1.0,
                    "input: {input:?}, send: {send:?}"
                );
                let output = ctx.run(
                    egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
                        ..Default::default()
                    },
                    |ctx| {
                        egui::CentralPanel::default().show(ctx, |ui| {
                            if ai_page {
                                app.draw_ai_assistant_tab(ui);
                            } else {
                                app.draw_overview(ui);
                            }
                        });
                    },
                );
                let composer = output
                    .shapes
                    .iter()
                    .find_map(|shape| match &shape.shape {
                        egui::epaint::Shape::Rect(rect)
                            if rect.fill == super::super::theme::CyberColors::BACKGROUND_DARK
                                && rect.rect.contains(send.center())
                                && rect.rect.contains(input.center()) =>
                        {
                            Some(rect.rect)
                        }
                        _ => None,
                    })
                    .expect("dark composer background");
                assert!((composer.height() - 32.0).abs() < 1.0, "{composer:?}");
                assert!(
                    (composer.center().x - width * 0.5).abs() < 2.0,
                    "{composer:?}"
                );
                let expected_width = (width - 16.0) * (2.0 / 3.0);
                assert!(
                    (composer.width() - expected_width).abs() < 2.0,
                    "{composer:?}"
                );
            }
        }
    }

    /// The failure this whole thread began with: a tab that rendered every one of
    /// its rows while all of them were invisible. Asserted against the real tab.
    #[test]
    fn the_profiles_tab_paints_readable_headings() {
        let (mut app, ctx) = app_and_ctx();
        let blob = painted_blob(&ctx, |ui| {
            app.draw_profiles_tab(ui);
        });

        assert!(
            blob.contains("Hardware Profile Inspector"),
            "the Profiles tab did not paint its header: {blob}"
        );

        // Painted is necessary but not sufficient — the original bug painted
        // everything. Legibility is the other half.
        let visuals = ctx.style().visuals.clone();
        let strong = visuals.strong_text_color();
        let panel = visuals.panel_fill;
        let distance = (strong.r() as i32 - panel.r() as i32).abs()
            + (strong.g() as i32 - panel.g() as i32).abs()
            + (strong.b() as i32 - panel.b() as i32).abs();
        assert!(
            distance > 60,
            "Profiles headings are painted in {strong:?} on a {panel:?} panel — the \
             original failure, where all 19 groups rendered and none could be read"
        );
    }

    /// Tofu regression: the geometric-shape triangles the bundled emoji font cannot
    /// cover must not come back into headings that already draw their own arrow.
    #[test]
    fn tabs_do_not_paint_glyphs_the_bundled_fonts_lack() {
        let (mut app, ctx) = app_and_ctx();
        let blob = painted_blob(&ctx, |ui| {
            app.draw_profiles_tab(ui);
        });

        for glyph in ['\u{25BE}', '\u{25B8}'] {
            assert!(
                !blob.contains(glyph),
                "U+{:04X} is back in the Profiles tab; NotoEmoji does not cover \
                 Geometric Shapes, so it renders as a tofu box",
                glyph as u32
            );
        }
    }
}

#[cfg(test)]
mod ontology_binding_tests {
    use super::*;
    use crate::gui::widgets::{domain_section_title, SectionHeader};
    use crate::ontology::labels;

    /// The GUI must paint the ontology's spelling of a domain, not its own.
    ///
    /// Asserted through the harness rather than by calling the helper directly:
    /// a helper that returns the right string but is never reached would pass a
    /// unit test and leave the screen unchanged.
    #[test]
    fn section_headings_paint_the_ontology_domain_spelling() {
        let ctx = themed_context();
        let title = domain_section_title("gpu", "Utilization");
        let blob = painted_blob(&ctx, |ui| {
            ui.add(SectionHeader::new(&title));
        });
        assert!(
            blob.contains("GPU Utilization"),
            "expected the ontology spelling in painted output, got: {blob}"
        );
        // And the domain word is one an agent can actually query.
        assert!(labels::is_known_domain("gpu"));
    }

    /// Text painted by the GUI must map back to ids, so an agent handed a screenshot
    /// description by a user can turn it into a query.
    #[test]
    fn painted_labels_resolve_to_entity_ids() {
        let ctx = themed_context();
        let label = labels::short_label("memory.total");
        let blob = painted_blob(&ctx, |ui| {
            ui.label(&label);
        });
        assert!(blob.contains("Total"), "got: {blob}");

        let ids = labels::ids_for_label(&label);
        assert!(
            ids.iter().any(|id| id == "memory.total"),
            "the label the GUI painted does not map back to memory.total: {ids:?}"
        );
    }

    /// The regression that made Profiles look dead, caught at the level it occurred:
    /// strong text is emitted *and* distinguishable from the surface behind it.
    #[test]
    fn strong_headings_are_both_painted_and_legible() {
        let ctx = themed_context();
        let blob = painted_blob(&ctx, |ui| {
            ui.label(egui::RichText::new("Group Heading").strong());
        });
        assert!(
            blob.contains("Group Heading"),
            "strong text was not painted at all: {blob}"
        );

        let visuals = ctx.style().visuals.clone();
        let strong = visuals.strong_text_color();
        let panel = visuals.panel_fill;
        let distance = (strong.r() as i32 - panel.r() as i32).abs()
            + (strong.g() as i32 - panel.g() as i32).abs()
            + (strong.b() as i32 - panel.b() as i32).abs();
        assert!(
            distance > 60,
            "strong text {strong:?} is painted but indistinguishable from the panel \
             {panel:?} — the Profiles failure mode"
        );
    }
}

// ── Scripted inspection ──────────────────────────────────────────────────────

/// One step in a GUI script.
///
/// Deliberately smaller than the TUI's step set. The TUI needs `key` because its
/// navigation is key-driven and stateful — you press keys to get somewhere. A GUI
/// tab is addressable directly, so `goto` covers navigation entirely and there is
/// no keystroke state to drive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Step {
    /// Select a tab by name.
    Goto(String),
    /// Record the text currently painted.
    Capture,
    /// Fail unless the current frame contains this text.
    Assert(String),
    /// Fail if the current frame contains this text.
    Refute(String),
}

/// Outcome of running a GUI script.
#[derive(Debug, Default)]
pub struct ScriptResult {
    pub captures: Vec<String>,
    pub failures: Vec<String>,
}

/// Parse a GUI script. One step per line; `#` comments; blank lines ignored.
pub fn parse_script(text: &str) -> Result<Vec<Step>, String> {
    let mut steps = Vec::new();
    for (n, raw) in text.lines().enumerate() {
        let line = raw.split('#').next().unwrap_or("").trim();
        if line.is_empty() {
            continue;
        }
        let (verb, rest) = match line.split_once(char::is_whitespace) {
            Some((v, r)) => (v, r.trim()),
            None => (line, ""),
        };
        let step = match verb.to_ascii_lowercase().as_str() {
            "goto" if !rest.is_empty() => Step::Goto(rest.to_string()),
            "capture" => Step::Capture,
            "assert" if !rest.is_empty() => Step::Assert(rest.to_string()),
            "refute" if !rest.is_empty() => Step::Refute(rest.to_string()),
            other => {
                return Err(format!(
                    "line {}: unknown or incomplete step {other:?}. Steps: goto <tab>, \
                     capture, assert <text>, refute <text>. The GUI has no `key` step \
                     — tabs are addressable by name, so there is no navigation state \
                     to drive.",
                    n + 1
                ))
            }
        };
        steps.push(step);
    }
    Ok(steps)
}

/// How long a headless read waits for a tab's background loaders.
///
/// The system and peripherals loaders run several PowerShell CIM queries back to
/// back and were measured at over ten seconds. Bounded rather than unbounded so a
/// wedged reader gives a slow, honest answer instead of never returning.
pub const SETTLE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);

/// The current tab's text, once its background loaders have settled.
///
/// Both `--frame` and `--script` go through this, so an agent asserting on a tab
/// sees the same thing either way. Before it existed, `--script` captured the
/// first frame — which for four tabs was their "Loading …" placeholder, forever.
pub fn settled_tab_text(app: &mut super::app::IronMonitorApp, ctx: &Context) -> String {
    // Bounded: an Agents frame shows the recordings, not "the first scan has not finished".
    app.agents.wait_for_scan(std::time::Duration::from_secs(5));
    painted_text_until(
        ctx,
        SETTLE_DEADLINE,
        app,
        |app, ctx| app.pump_background_loaders(ctx),
        |app, lines| !frame_is_still_loading(lines) && !app.has_pending_load(),
        |app, ui| app.draw_current_tab(ui),
    )
    .join("\n")
}

/// Run a GUI script against `app`.
pub fn run_script(
    app: &mut super::app::IronMonitorApp,
    ctx: &Context,
    steps: &[Step],
) -> ScriptResult {
    let mut result = ScriptResult::default();
    let mut frame = settled_tab_text(app, ctx);

    for (i, step) in steps.iter().enumerate() {
        match step {
            Step::Goto(target) => match app.select_tab_by_name(target) {
                Ok(()) => {
                    frame = settled_tab_text(app, ctx);
                }
                Err(available) => result.failures.push(format!(
                    "step {}: unknown tab {target:?}; available: {available:?}",
                    i + 1
                )),
            },
            Step::Capture => result.captures.push(frame.clone()),
            Step::Assert(needle) => {
                if !frame.contains(needle.as_str()) {
                    result.failures.push(format!(
                        "step {}: expected {needle:?} in the painted text, not found",
                        i + 1
                    ));
                }
            }
            Step::Refute(needle) => {
                if frame.contains(needle.as_str()) {
                    result.failures.push(format!(
                        "step {}: {needle:?} should not be painted, but is",
                        i + 1
                    ));
                }
            }
        }
    }

    result
}

#[cfg(test)]
mod script_tests {
    use super::*;
    use crate::gui::app::IronMonitorApp;

    fn app_and_ctx() -> (IronMonitorApp, Context) {
        let ctx = themed_context();
        let app = IronMonitorApp::with_context(&ctx);
        (app, ctx)
    }

    #[test]
    fn scripts_parse_with_comments_and_blank_lines() {
        let steps = parse_script("# go\ngoto profiles\n\ncapture  # snap\nassert Inspector\n")
            .expect("should parse");
        assert_eq!(
            steps,
            vec![
                Step::Goto("profiles".into()),
                Step::Capture,
                Step::Assert("Inspector".into()),
            ]
        );
    }

    /// The rejection must explain why there is no `key` step, or the omission reads
    /// as an oversight rather than a decision.
    #[test]
    fn a_key_step_is_rejected_with_the_reason() {
        let err = parse_script("key 3").expect_err("the GUI has no key step");
        assert!(err.contains("key"), "got: {err}");
        assert!(
            err.contains("addressable by name"),
            "the error should say why, got: {err}"
        );
    }

    #[test]
    fn goto_changes_what_is_painted() {
        let (mut app, ctx) = app_and_ctx();
        let steps = parse_script("goto profiles\nassert Hardware Profile Inspector").unwrap();
        let result = run_script(&mut app, &ctx, &steps);
        assert!(result.failures.is_empty(), "{:?}", result.failures);
    }

    #[test]
    fn assertions_and_refutations_report_rather_than_panic() {
        let (mut app, ctx) = app_and_ctx();
        let steps =
            parse_script("goto profiles\nassert not-painted-anywhere\nrefute Inspector").unwrap();
        let result = run_script(&mut app, &ctx, &steps);
        assert_eq!(
            result.failures.len(),
            2,
            "both the failed assert and the failed refute should report: {:?}",
            result.failures
        );
    }

    #[test]
    fn an_unknown_tab_lists_the_available_ones() {
        let (mut app, ctx) = app_and_ctx();
        let steps = parse_script("goto nonsense").unwrap();
        let result = run_script(&mut app, &ctx, &steps);
        assert_eq!(result.failures.len(), 1);
        assert!(
            result.failures[0].contains("overview"),
            "should name the alternatives: {:?}",
            result.failures
        );
    }

    #[test]
    fn capture_records_the_frame_after_navigation() {
        let (mut app, ctx) = app_and_ctx();
        let steps = parse_script("goto profiles\ncapture").unwrap();
        let result = run_script(&mut app, &ctx, &steps);
        assert_eq!(result.captures.len(), 1);
        assert!(result.captures[0].contains("Hardware Profile Inspector"));
    }
}

#[cfg(test)]
mod overflow_tests {
    use super::*;

    /// Tabs in the order `select_tab_by_name` accepts them.
    const TABS: [&str; 14] = [
        "inference",
        "overview",
        "cpu",
        "accelerators",
        "memory",
        "disk",
        "processes",
        "network",
        "tools",
        "connections",
        "system",
        "peripherals",
        "profiles",
        "ai",
    ];

    /// Tabs that still paint past the right edge, pinned so the list cannot grow
    /// quietly and cannot shrink without someone noticing.
    ///
    /// Both are the same construct: a `right_to_left` layout nested inside an
    /// already-advanced `horizontal`. In this egui version that starts its cursor
    /// at the row's right edge and runs outward instead of aligning back from it,
    /// so the content lands entirely outside the window. `accelerators` puts the
    /// clock and power readings there; `memory` a "(used/buffers/cache/free)"
    /// legend, and `ai` an unwrapped welcome sentence that runs 183 px past the
    /// 800 px minimum width. The `ai` one only appears in the empty state, which
    /// is why it surfaced intermittently rather than on every run.
    ///
    /// `.wrap()` does not fix the `ai` case, which is the tell that all three are
    /// one defect: the container does not bound its child's width, so there is
    /// nothing for wrapping to wrap against.
    ///
    /// Not fixed here because neither obvious remedy works: an explicit
    /// `allocate_ui_with_layout` with a bounded width leaves the offset unchanged
    /// to the pixel. What does work is inlining the content, which moves it from
    /// right-aligned to inline — a visual decision rather than a bug fix, and not
    /// one to make silently.
    /// Tabs known to paint past the right edge. **Empty, and that is the
    /// finding.**
    ///
    /// This list held four entries. Three were fixed. The fourth, `ai`, was
    /// never a defect at all: it was this guard measuring the wrong rectangle.
    ///
    /// `painted_text_rects_sized` used to build a text's rect as
    /// `Rect::from_min_size(shape.pos, galley.size())`, which assumes `pos` is
    /// the top-left corner. **For a galley with a centred or right horizontal
    /// alignment it is an anchor and the text extends away from it**, so the
    /// rect came out the right size in the wrong place. The AI tab's welcome
    /// sentence painted at `114..693` inside an 800 px window while this guard
    /// reported `404..983` and pinned a 183 px overrun that was never on screen.
    ///
    /// It reads `Shape::visual_bounding_rect` now, which egui computes from the
    /// galley's mesh — where the glyphs actually are, which is the only thing a
    /// reader can see.
    ///
    /// **The false positive was ~70% reproducible, not 100%**, which is what
    /// made it look like a real intermittent defect rather than a broken
    /// instrument. Whether the empty state rendered at all varied between
    /// process runs; when it rendered, the bad measurement followed
    /// deterministically.
    const KNOWN_OVERFLOWING: [&str; 0] = [];

    /// No tab may paint text past the right edge of a default window.
    ///
    /// The GUI had two distinct failure modes during the Dewey port and
    /// `painted_text` sees only one: a tab that drew nothing, and a tab that drew
    /// everything and clipped it off the right edge. Reading galley *text* catches
    /// the first and is blind to the second. This reads their rectangles.
    ///
    /// It caught a real one on Overview: the chat bar reserved a hardcoded 190 px
    /// for a Send button plus a 172 px status label, so the row ran 29 px past the
    /// window at every width. The text field absorbed the slack, which is why
    /// widening the window moved the overrun rather than removing it, and why
    /// everything else inside that tab's `ScrollArea` inherited the wider content
    /// box.
    ///
    /// Widths are the shipped default (`with_inner_size([1400, 900])`) and the
    /// shipped minimum (`with_min_inner_size([800, 600])`). Height is not checked:
    /// every tab body sits in a vertical `ScrollArea`, so tall content is
    /// reachable, while width in this layout is not scrollable.
    #[test]
    fn no_tab_paints_text_past_the_right_edge() {
        let ctx = themed_context();
        let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
        let mut offenders = Vec::new();
        let mut unexpectedly_clean = Vec::new();
        let mut still_loading = Vec::new();

        for tab in TABS {
            if app.select_tab_by_name(tab).is_err() {
                continue;
            }

            // Settle the tab before measuring it — both halves.
            //
            // Four tabs fetch their contents off-thread and paint a spinner until
            // the data lands, so what this measures depends on whether the loader
            // won the race — and under the full parallel suite it sometimes does
            // and sometimes does not. That made this guard fail once and pass on
            // rerun, which is the same instrument as no guard at all.
            //
            // The loaders were once all this waited for, and that was not enough:
            // the collector's warm-up snapshot is built from an empty `Sources`,
            // so Accelerators was being measured on a machine that had no GPUs
            // yet. `settle` waits for both, and a tab that never settles is
            // skipped rather than measured mid-flight.
            if !settle(&mut app, &ctx, Duration::from_secs(30)) {
                still_loading.push(tab);
                continue;
            }

            let pinned = KNOWN_OVERFLOWING.contains(&tab);
            let mut any = false;

            for width in [1400.0_f32, 800.0] {
                let size = egui::Vec2::new(width, 900.0);
                for (text, past) in horizontal_overflow(&ctx, size, |ui| app.draw_current_tab(ui)) {
                    any = true;
                    if !pinned {
                        offenders.push(format!(
                            "{tab} @ {width:.0}px wide: {text:?} runs {past:.0}px past the edge"
                        ));
                    }
                }
            }

            // A pinned tab that has started fitting means the pin is now a lie.
            if pinned && !any {
                unexpectedly_clean.push(tab);
            }
        }

        assert!(
            offenders.is_empty(),
            "text painted outside the window, which a reader sees as clipped or missing:
  {}",
            offenders.join(
                "
  "
            )
        );

        // Reported rather than asserted: a loader that does not finish inside the
        // budget is a slow machine, not a layout defect, and failing on it would
        // make this guard about the runner instead of the GUI.
        if !still_loading.is_empty() {
            eprintln!("skipped, still loading after 5s: {still_loading:?}");
        }

        assert!(
            unexpectedly_clean.is_empty(),
            "pinned as overflowing but no longer overflowing: {unexpectedly_clean:?}. Remove them from KNOWN_OVERFLOWING so the guard covers them."
        );
    }
}

#[cfg(test)]
mod overview_extent {
    use super::*;

    /// The fit must wait for the Overview to finish loading.
    ///
    /// **This is the whole defect.** Two things arrive after the first frame and
    /// both change how tall the tab is: the background loaders, and the
    /// collector's first real snapshot. The pipeline publishes a warm-up
    /// generation built from an empty `Sources`, so it describes no GPUs *by
    /// construction* — fit against it and a three-card desktop is measured as a
    /// machine with no accelerators at all. A freshly constructed app has applied
    /// no snapshot yet, so it is in exactly that state, and the fit must decline.
    ///
    /// **An earlier note here has been withdrawn.** It recorded, as an
    /// unexplained curiosity, that the loaded Overview measured *shorter* than
    /// the unloaded one — 899.5 px against 918.5 — and guessed at a placeholder
    /// taller than its content. Both numbers came from the galley reader this
    /// harness used before it was corrected to measure painted ink. Measured
    /// properly the settled Overview is 917.5 px, which is the unloaded figure
    /// to within a pixel, and there is no curiosity to explain.
    ///
    /// Waiting is still right, for the reason it always was: the warm-up
    /// snapshot describes no GPUs by construction, so a tab measured before it
    /// lands is a different tab. That argument never depended on the numbers.
    #[test]
    fn the_fit_waits_for_the_overview_to_finish_loading() {
        let ctx = themed_context();
        let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
        app.select_tab_by_name("overview")
            .expect("overview is a tab");

        assert!(
            !app.has_real_snapshot(),
            "a freshly constructed app has applied no snapshot, warm-up or otherwise"
        );
        assert!(
            !app.autofit_to_overview_once(&ctx),
            "the window must not be fitted to an Overview that has not loaded its data"
        );

        assert!(
            settle(&mut app, &ctx, Duration::from_secs(30)),
            "the Overview did not finish loading, so there is nothing trustworthy to measure"
        );

        // The fit measures what the tab drew, so a loaded app that has not drawn
        // yet still has nothing to go on.
        assert!(
            !app.autofit_to_overview_once(&ctx),
            "loaded but never drawn: there is no shortfall recorded to fit to"
        );
        let _ = painted_extent(&ctx, egui::Vec2::new(1400.0, 900.0), |ui| {
            app.draw_current_tab(ui)
        });

        assert!(
            app.autofit_to_overview_once(&ctx),
            "once everything has loaded and been drawn, the fit must run"
        );
        assert!(
            !app.autofit_to_overview_once(&ctx),
            "and it must run only once, or every frame resizes the user's window"
        );
    }

    /// What the fit measures is the height of the painted content, not the
    /// canvas it was given.
    ///
    /// `Context::used_size` cannot answer this: it reports *allocated* space,
    /// which headlessly is the whole 4000 px canvas, and in the live app is
    /// `-inf`, because tabs paint through panels rather than the measured `Ui`.
    /// An earlier version of this fit used it and silently never ran.
    #[test]
    fn the_fit_measures_paint_rather_than_canvas() {
        let ctx = themed_context();
        let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
        app.select_tab_by_name("overview")
            .expect("overview is a tab");
        assert!(settle(&mut app, &ctx, Duration::from_secs(30)));

        let extent = painted_extent(&ctx, egui::Vec2::new(1400.0, 4000.0), |ui| {
            app.draw_current_tab(ui)
        });
        assert!(
            extent.y > 300.0 && extent.y < 3000.0,
            "the Overview should paint a windowful, not nothing and not the whole              4000 px canvas; got {:.1}",
            extent.y
        );
    }

    /// Width is not fittable, asserted with numbers rather than a comment.
    #[test]
    fn the_overview_takes_whatever_width_it_is_given() {
        let ctx = themed_context();
        let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
        app.select_tab_by_name("overview")
            .expect("overview is a tab");

        let wide = painted_extent(&ctx, egui::Vec2::new(1400.0, 4000.0), |ui| {
            app.draw_current_tab(ui)
        });
        let narrow = painted_extent(&ctx, egui::Vec2::new(1100.0, 4000.0), |ui| {
            app.draw_current_tab(ui)
        });

        assert!(
            wide.x > narrow.x + 200.0,
            "elastic layout: a 300 px wider canvas should paint wider, got {:.0} vs {:.0}",
            wide.x,
            narrow.x
        );
        assert!(
            (wide.y - narrow.y).abs() < 2.0,
            "height must not depend on width: {:.1} at 1400 vs {:.1} at 1100",
            wide.y,
            narrow.y
        );
    }
}

#[cfg(test)]
mod monochrome_tests {
    use super::*;
    use crate::gui::{
        app::ColorTheme,
        theme,
        widgets::{CyberProgressBar, MetricCard, SparklineChart, ThresholdLegend},
    };

    fn assert_grayscale(ctx: &Context, output: egui::FullOutput, label: &str) {
        let primitives = ctx.tessellate(output.shapes, output.pixels_per_point);
        let mut vertices = 0;
        for primitive in primitives {
            if let egui::epaint::Primitive::Mesh(mesh) = primitive.primitive {
                for vertex in mesh.vertices {
                    let color = vertex.color;
                    vertices += 1;
                    assert!(
                        color.r() == color.g() && color.g() == color.b(),
                        "{label} painted a colored vertex: {color:?}"
                    );
                }
            }
        }
        assert!(vertices > 0, "{label} painted nothing");
    }

    #[test]
    fn dark_monochrome_covers_every_tab_and_custom_charts() {
        let ctx = themed_context();
        let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
        theme::apply_theme(&ctx, ColorTheme::Monochrome);
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1400.0, 900.0),
            )),
            ..Default::default()
        };
        for tab in [
            "inference",
            "overview",
            "cpu",
            "accelerators",
            "memory",
            "disk",
            "processes",
            "network",
            "tools",
            "connections",
            "system",
            "peripherals",
            "profiles",
            "ai",
        ] {
            app.select_tab_by_name(tab).unwrap();
            // Loading latency depends on hardware and parallel WMI queries. It
            // is not a palette failure: check the loading state's colors too,
            // and exercise custom chart fills with deterministic data below.
            if !settle(&mut app, &ctx, Duration::from_secs(30)) {
                eprintln!("{tab}: hardware still loading; checking loading-state colors");
            }
            let mut output = None;
            for _ in 0..2 {
                output = Some(ctx.run(input.clone(), |ctx| {
                    egui::CentralPanel::default().show(ctx, |ui| app.draw_current_tab(ui));
                }));
            }
            assert_grayscale(&ctx, output.unwrap(), tab);
        }
        let output = ctx.run(input, |ctx| {
            egui::CentralPanel::default().show(ctx, |ui| {
                ui.add(CyberProgressBar::new(0.85).with_threshold_color());
                ui.add(MetricCard::new("Metric", "42").color(theme::CyberColors::NEON_GREEN));
                ui.add(
                    SparklineChart::new(vec![10.0, 30.0, 20.0, 40.0])
                        .color(theme::CyberColors::MAGENTA),
                );
                ui.add(ThresholdLegend);
            });
        });
        assert_grayscale(&ctx, output, "custom charts and widgets");
    }
}

/// The GUI on a 13" laptop: 1920x1080 at 150% is 1280x720 logical, and a
/// window sized to that work area has a 1264 px client width.
#[cfg(test)]
mod laptop_fit_tests {
    use super::*;

    const LAPTOP_WIDTH: f32 = 1264.0;

    /// How far down the window the tab strip pushes everything else.
    fn header_height(app: &mut crate::gui::app::IronMonitorApp, ctx: &Context, width: f32) -> f32 {
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(width, 720.0),
            )),
            ..Default::default()
        };
        let _ = ctx.run(input.clone(), |ctx| app.draw_top_panel(ctx));
        let mut top = 0.0;
        let _ = ctx.run(input, |ctx| {
            app.draw_top_panel(ctx);
            top = ctx.available_rect().min.y;
        });
        top
    }

    /// Thirteen tabs at the theme's padding needed a 1400 px window to stay on
    /// one row, so every 13" panel lost a second row of height to the strip.
    #[test]
    fn the_tab_strip_is_one_row_on_a_13_inch_laptop() {
        let ctx = themed_context();
        let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);

        let laptop = header_height(&mut app, &ctx, LAPTOP_WIDTH);
        let wide = header_height(&mut app, &ctx, 1600.0);
        let narrow = header_height(&mut app, &ctx, 800.0);

        // The control: the measurement can tell one row from two, or the
        // assertion below would pass on a strip that always wraps.
        assert!(
            narrow > wide + 10.0,
            "at 800 px the strip should wrap: {narrow:.0} vs {wide:.0} at 1600"
        );
        assert!(
            (laptop - wide).abs() < 1.0,
            "the strip wraps at {LAPTOP_WIDTH} px: {laptop:.0} px tall against {wide:.0} at 1600"
        );
    }

    /// Bottom edge of everything painted, text and shapes, after the chart
    /// scale has had frames to settle.
    fn overview_bottom(
        app: &mut crate::gui::app::IronMonitorApp,
        ctx: &Context,
        size: egui::Vec2,
    ) -> f32 {
        for _ in 0..3 {
            let _ = painted_shape_rects(ctx, size, |ui| app.draw_current_tab(ui));
        }
        // Text and strokes only: the panel paints a background rect the size of
        // the whole canvas, which would report every canvas as exactly full.
        painted_shape_rects(ctx, size, |ui| app.draw_current_tab(ui))
            .into_iter()
            .filter(|(kind, _)| matches!(*kind, "text" | "path" | "line" | "mesh"))
            .map(|(_, rect)| rect.max.y)
            .fold(0.0, f32::max)
    }

    /// The Overview's charts give up height before the tab scrolls, and only as
    /// much as the room requires.
    ///
    /// Measured against this machine rather than a constant, because the tab's
    /// height is not a property of the program: it grows a card per
    /// accelerator and a row per drive.
    #[test]
    fn the_overview_charts_shrink_to_the_room_and_no_further() {
        let ctx = themed_context();
        let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
        app.select_tab_by_name("overview")
            .expect("overview is a tab");
        assert!(settle(&mut app, &ctx, Duration::from_secs(30)));

        // Natural size: a canvas taller than the tab needs.
        let natural = overview_bottom(&mut app, &ctx, egui::vec2(LAPTOP_WIDTH, 4000.0));
        assert!(
            natural > 300.0 && natural < 3000.0,
            "the Overview should paint a windowful; got {natural:.0}"
        );

        // A room 40 px short of that. The one chart row every machine has, CPU
        // and memory, is 100 px and may give up half, so this is reachable
        // without a GPU. The first version asked for 120 px, counting the
        // GPU row this desktop has and CI runners do not, and failed on all
        // three of them.
        let room = natural - 40.0;
        let fitted = overview_bottom(&mut app, &ctx, egui::vec2(LAPTOP_WIDTH, room));
        // Four pixels of slack, for the sparkline's glow: it repeats the line
        // 1-3 px lower at up to 2.5 px thick, so a series at zero overhangs its
        // own graph by about 3.75 px at any chart height. It does here, where
        // the last chart is network upload on an idle link.
        assert!(
            fitted <= room + 4.0,
            "the charts did not shrink to fit: painted to {fitted:.0} in a {room:.0} px room"
        );
        assert!(
            fitted > room - 30.0,
            "the charts shrank further than the room required: painted to {fitted:.0} in {room:.0}"
        );

        // And back: given the room again, they return to natural height
        // rather than staying at whatever they last shrank to.
        let restored = overview_bottom(&mut app, &ctx, egui::vec2(LAPTOP_WIDTH, 4000.0));
        assert!(
            (restored - natural).abs() < 1.0,
            "charts did not regrow: {restored:.0} against {natural:.0}"
        );
    }
}

/// Data labels — values, units, scale ticks, legend entries — are bold, big
/// enough to read, and in a colour that stands off the surface behind them.
#[cfg(test)]
mod data_label_tests {
    use super::*;
    use crate::gui::theme::{CyberColors, DATA_LABEL_MIN_SIZE};
    use crate::gui::widgets::{
        CyberProgressBar, MetricCard, QuickLookPanel, SparklineChart, ThresholdLegend,
    };

    /// Every text section painted by `body`: its text, font and colour.
    fn painted_sections(
        ctx: &Context,
        body: impl FnMut(&mut egui::Ui),
    ) -> Vec<(String, egui::FontId, egui::Color32)> {
        let mut body = body;
        let input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1400.0, 4000.0),
            )),
            ..Default::default()
        };
        let mut run = || {
            ctx.run(input.clone(), |ctx| {
                egui::CentralPanel::default().show(ctx, |ui| body(ui));
            })
        };
        let _warmup = run();
        let output = run();

        fn walk(shape: &egui::Shape, out: &mut Vec<(String, egui::FontId, egui::Color32)>) {
            match shape {
                egui::Shape::Text(text) => {
                    let job = &text.galley.job;
                    for section in &job.sections {
                        let s = job.text[section.byte_range.clone()].trim().to_string();
                        if !s.is_empty() {
                            // `PLACEHOLDER` means "the shape's fallback colour",
                            // resolved at paint time; that is what is drawn.
                            let color = if section.format.color == egui::Color32::PLACEHOLDER {
                                text.fallback_color
                            } else {
                                section.format.color
                            };
                            out.push((s, section.format.font_id.clone(), color));
                        }
                    }
                }
                egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)),
                _ => {}
            }
        }
        let mut out = Vec::new();
        for clipped in &output.shapes {
            walk(&clipped.shape, &mut out);
        }
        out
    }

    /// WCAG 2 contrast ratio between two opaque colours.
    fn contrast(a: egui::Color32, b: egui::Color32) -> f32 {
        fn luminance(c: egui::Color32) -> f32 {
            let channel = |v: u8| {
                let v = v as f32 / 255.0;
                if v <= 0.03928 {
                    v / 12.92
                } else {
                    ((v + 0.055) / 1.055).powf(2.4)
                }
            };
            0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())
        }
        let (hi, lo) = {
            let (x, y) = (luminance(a), luminance(b));
            (x.max(y), x.min(y))
        };
        (hi + 0.05) / (lo + 0.05)
    }

    fn draw_data_widgets(ui: &mut egui::Ui) {
        ui.add(MetricCard::new("GPU 0 Temp", 63).unit("°C"));
        ui.add(
            SparklineChart::new(vec![10.0, 40.0, 90.0, 20.0])
                .title("CPU Usage")
                .unit("%")
                .max_value(100.0)
                .show_scale(true)
                .show_min_max(true)
                .height(80.0),
        );
        ui.add(QuickLookPanel::new(
            Some(42.0),
            Some(63.0),
            Some(5.0),
            Some(1.5),
        ));
        ui.add(ThresholdLegend);
        ui.add(CyberProgressBar::new(0.42).label("Used"));
    }

    #[test]
    fn data_labels_are_bold_sized_and_legible_in_every_base_theme() {
        let surfaces = [
            ("cyber", None, CyberColors::SURFACE),
            ("light", Some(()), crate::gui::theme::LightColors::SURFACE),
        ];
        for (name, light, surface) in surfaces {
            let ctx = Context::default();
            if light.is_some() {
                crate::gui::theme::apply_light_theme(&ctx);
            } else {
                crate::gui::theme::apply_cyber_theme(&ctx);
            }
            let sections = painted_sections(&ctx, draw_data_widgets);
            // The control: the widgets painted their data at all, or every
            // assertion below would pass over an empty list.
            for expected in ["63 °C", "CPU Usage", "42%", "CAREFUL", "90%+"] {
                assert!(
                    sections.iter().any(|(text, ..)| text.contains(expected)),
                    "{name}: {expected:?} was not painted: {:?}",
                    sections.iter().map(|(t, ..)| t).collect::<Vec<_>>()
                );
            }
            for (text, font, color) in &sections {
                assert_eq!(
                    font.family,
                    egui::FontFamily::Name("data".into()),
                    "{name}: data label {text:?} is not in the bold data face"
                );
                assert!(
                    font.size >= DATA_LABEL_MIN_SIZE,
                    "{name}: data label {text:?} is {} px",
                    font.size
                );
                // A translucent section is a drop shadow painted 1 px under the
                // label it belongs to; the label itself is checked on its own.
                if color.a() < 255 {
                    continue;
                }
                // 3:1 is WCAG's floor for large or bold text; the bold face is
                // what entitles these labels to it.
                let ratio = contrast(*color, surface);
                assert!(
                    ratio >= 3.0,
                    "{name}: data label {text:?} in {color:?} is {ratio:.2}:1 against {surface:?}"
                );
            }
        }
    }

    /// The fallback: a context no theme has run on has no bold family, and
    /// egui panics on an unregistered family rather than substituting one.
    #[test]
    fn data_labels_paint_on_an_unthemed_context_rather_than_panicking() {
        let ctx = Context::default();
        let sections = painted_sections(&ctx, draw_data_widgets);
        assert!(sections.iter().any(|(text, ..)| text.contains("63 °C")));
    }

    /// The Overview's own reading rows use the same face, and read on both
    /// base themes.
    #[test]
    fn overview_reading_rows_are_bold_and_legible() {
        for light in [false, true] {
            let ctx = themed_context();
            let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
            let surface = if light {
                crate::gui::theme::apply_light_theme(&ctx);
                crate::gui::theme::LightColors::SURFACE
            } else {
                CyberColors::SURFACE
            };
            app.select_tab_by_name("overview")
                .expect("overview is a tab");
            assert!(settle(&mut app, &ctx, Duration::from_secs(30)));
            let sections = painted_sections(&ctx, |ui| app.draw_current_tab(ui));

            let readings: Vec<_> = sections
                .iter()
                .filter(|(text, ..)| {
                    text.starts_with("Tasks:")
                        || text.starts_with("Capacity:")
                        || text.starts_with("Space used:")
                })
                .collect();
            assert!(
                readings.iter().any(|(text, ..)| text.starts_with("Tasks:")),
                "light={light}: the Overview status row was not painted"
            );
            for (text, font, color) in readings {
                assert_eq!(
                    font.family,
                    egui::FontFamily::Name("data".into()),
                    "light={light}: Overview reading {text:?} is not in the bold data face"
                );
                let ratio = contrast(*color, surface);
                assert!(
                    ratio >= 3.0,
                    "light={light}: Overview reading {text:?} in {color:?} is {ratio:.2}:1"
                );
            }
        }
    }
}