overbrainer 0.9.0

Distill a large LLM into a smaller open-weights model: generate questions, collect answers, fine-tune, visualize.
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
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
//! The event loop: one task selecting over terminal input, background tasks and
//! their messages, process signals, a clock tick and, while something moves on
//! screen, the frames of motion, drawing the app when it changed. It owns the
//! terminal and runs the effects the app asks for.

use std::any::Any;
use std::io::{self, Write};
use std::panic::{self, AssertUnwindSafe};
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Stdio};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use anyhow::Context;
use crossterm::event::Event as TermEvent;
use ratatui::backend::Backend;
use ratatui::{DefaultTerminal, Terminal};
use rustix::fs::OFlags;
use tokio::process::Child;
use tokio::signal::unix::{Signal, SignalKind, signal};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;
use tokio::time::{Instant, Interval, MissedTickBehavior};
use tracing::Level;

use super::app::{App, Effect, Exit};
use super::tasks::{Done, Msg, Task, TaskId, Tasks, TrainJob};
use super::terminal::Screen;
use super::ui;
use crate::events::Observer;
use crate::update::Newer;

/// Time between two ticks of the app's clock.
const TICK: Duration = Duration::from_millis(250);
/// Shortest time between two draws.
const FRAME: Duration = Duration::from_millis(33);
/// How long an editor asked to end with SIGTERM gets before SIGKILL.
const EDITOR_GRACE: Duration = Duration::from_secs(2);

/// What the real terminal adds to the loop: process signals, the screen the
/// editor borrows, and the update check running.
pub(super) struct Real {
    signals: Signals,
    screen: Screen,
    check: Option<JoinHandle<Option<Newer>>>,
    /// Sees the events of the tasks: the metrics, when served.
    observer: Option<Arc<dyn Observer>>,
}

/// Runs the TUI on the real terminal until the app is done.
///
/// # Errors
///
/// Returns an error when drawing fails, the terminal cannot be read, the signals
/// cannot be caught, the terminal cannot be handed to the editor and back, or a
/// process signal ended the TUI.
pub(super) async fn run(
    terminal: &mut DefaultTerminal,
    app: &mut App,
    check: Option<JoinHandle<Option<Newer>>>,
    observer: Option<Arc<dyn Observer>>,
) -> anyhow::Result<()> {
    let signals = Signals::new().context("cannot catch the process signals")?;
    let (events, input) = mpsc::unbounded_channel();
    let real = Real {
        signals,
        screen: Screen::start(events),
        check,
        observer,
    };
    drive(terminal, app, input, Some(real)).await
}

/// The loop itself, on any backend, reading terminal events from `input`; with
/// `real`, also the process signals, and the editor gets the terminal. A read
/// error on `input` ends the loop with that error; `input` closing quits. It
/// starts the app's background tasks, and hands each one's end back to the app.
///
/// # Errors
///
/// Returns an error when drawing fails, the terminal cannot be read, the
/// terminal cannot be handed to the editor and back, or a process signal ended
/// the TUI.
pub(super) async fn drive<B>(
    terminal: &mut Terminal<B>,
    app: &mut App,
    input: UnboundedReceiver<io::Result<TermEvent>>,
    real: Option<Real>,
) -> anyhow::Result<()>
where
    B: Backend,
    B::Error: Send + Sync + 'static,
{
    let mut looping = Loop::new(terminal, input, &app.project.dir);
    if let Some(real) = real {
        looping.signals = Some(real.signals);
        looping.screen = Some(real.screen);
        looping.tasks.observe(real.observer);
        if let Some(check) = real.check {
            tokio::spawn(forward_check(check, looping.messages.clone()));
        }
    }
    let result = looping.run(app).await;
    if let Some(mut editor) = looping.editor.take() {
        stop_editor(&mut editor).await;
    }
    looping.settle(app).await;
    if let Some(screen) = looping.screen.take() {
        screen.stop().await;
    }
    result
}

/// What woke the loop while it settles.
enum Settling {
    /// A task ended, or none is left. Boxed: a result is far larger than the
    /// other variants.
    Ended(Option<Box<(TaskId, Result<Done, String>)>>),
    /// A process signal.
    Signal,
    /// Time to write the new log lines.
    Tick,
}

/// What woke the loop.
enum Wake {
    Input(Option<io::Result<TermEvent>>),
    Message(Msg),
    Done(TaskId, Result<Done, String>),
    Signal,
    Tick,
    Draw,
    /// A frame of motion is due.
    Frame,
}

struct Loop<'t, B: Backend> {
    terminal: &'t mut Terminal<B>,
    input: UnboundedReceiver<io::Result<TermEvent>>,
    tasks: Tasks,
    messages: UnboundedSender<Msg>,
    inbox: UnboundedReceiver<Msg>,
    tick: Interval,
    /// The process signals, with the real terminal.
    signals: Option<Signals>,
    /// The real terminal's screen, which the editor borrows.
    screen: Option<Screen>,
    /// Where lines are written once the loop ended and the screen was given
    /// back: stderr, with the real terminal.
    console: Option<Box<dyn Write + Send>>,
    /// The sequence number of the last log line written to the console.
    logged: u64,
    /// Whether the editor has the terminal: no input is read, nothing is drawn,
    /// and SIGINT is ignored (it comes from a Ctrl-C typed in the editor).
    suspended: bool,
    /// The editor running, if any.
    editor: Option<Child>,
    last_draw: Option<Instant>,
    /// When the last frame of motion was, while something moves on screen;
    /// `None` while nothing does.
    frame_at: Option<Instant>,
    /// Effects the loop could not run before it ended, for [`Loop::settle`].
    pending: Vec<Effect>,
    /// The logs exports still writing, which [`Loop::settle`] waits for.
    exports: Vec<JoinHandle<()>>,
}

impl<'t, B> Loop<'t, B>
where
    B: Backend,
    B::Error: Send + Sync + 'static,
{
    /// A loop drawing on `terminal`, reading terminal events from `input`, for
    /// the project in `dir`; no signals, no screen to hand over.
    fn new(
        terminal: &'t mut Terminal<B>,
        input: UnboundedReceiver<io::Result<TermEvent>>,
        dir: &std::path::Path,
    ) -> Self {
        let mut tick = tokio::time::interval(TICK);
        tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
        let (messages, inbox) = mpsc::unbounded_channel();
        Self {
            terminal,
            input,
            tasks: Tasks::new(dir, messages.clone()),
            messages,
            inbox,
            tick,
            signals: None,
            screen: None,
            console: None,
            logged: 0,
            suspended: false,
            editor: None,
            last_draw: None,
            frame_at: None,
            pending: Vec::new(),
            exports: Vec::new(),
        }
    }

    async fn run(&mut self, app: &mut App) -> anyhow::Result<()> {
        let mut effects = app.start();
        loop {
            self.apply_all(effects).await?;
            effects = match self.wait(app).await {
                Wake::Input(Some(Ok(event))) => app.on_input(&event),
                Wake::Input(Some(Err(error))) => {
                    return Err(anyhow::Error::new(error).context("cannot read the terminal"));
                },
                Wake::Input(None) => {
                    app.exit = Some(Exit::Quit);
                    Vec::new()
                },
                Wake::Message(message) => self.on_message(app, message)?,
                Wake::Done(id, result) => self.finished(app, id, result)?,
                Wake::Signal => app.on_signal(),
                Wake::Tick => app.on_tick(SystemTime::now()),
                Wake::Draw => Vec::new(),
                Wake::Frame => {
                    let elapsed = self.frame_elapsed();
                    app.on_frame(elapsed);
                    Vec::new()
                },
            };
            if let Err(error) = self.draw(app) {
                self.pending = effects;
                return Err(error);
            }
            if let Some(exit) = app.exit {
                return self.exit(app, effects, exit);
            }
        }
    }

    /// Applies `effects` in order; when one fails, the others are kept for
    /// [`Loop::settle`].
    async fn apply_all(&mut self, effects: Vec<Effect>) -> anyhow::Result<()> {
        let mut effects = effects.into_iter();
        while let Some(effect) = effects.next() {
            if let Err(error) = self.apply(effect).await {
                self.pending.extend(effects);
                return Err(error);
            }
        }
        Ok(())
    }

    /// Ends the loop for `exit`: the messages still in the inbox are handled,
    /// and `effects` are kept for [`Loop::settle`].
    fn exit(&mut self, app: &mut App, effects: Vec<Effect>, exit: Exit) -> anyhow::Result<()> {
        self.pending = effects;
        let more = self.drained(app)?;
        self.pending.extend(more);
        match exit {
            Exit::Quit => Ok(()),
            Exit::Signal => anyhow::bail!("interrupted by signal"),
        }
    }

    /// Task `id` ended with `result`. Every message of a task is in the inbox
    /// before its end: they are handled first, so its last lines are not lost.
    fn finished(
        &mut self,
        app: &mut App,
        id: TaskId,
        result: Result<Done, String>,
    ) -> anyhow::Result<Vec<Effect>> {
        let mut effects = self.drained(app)?;
        effects.extend(app.on_done(id, result));
        Ok(effects)
    }

    /// Handles every message already in the inbox.
    fn drained(&mut self, app: &mut App) -> anyhow::Result<Vec<Effect>> {
        let mut effects = Vec::new();
        while let Ok(message) = self.inbox.try_recv() {
            effects.extend(self.on_message(app, message)?);
        }
        Ok(effects)
    }

    /// Once the loop ended with work left (a terminal error, its input gone, or
    /// effects it could not run): the effects that must not be lost run (a
    /// training task or an edit starts, a token is cancelled), then the tasks
    /// end as on a confirmed quit and are waited for, however long: a training
    /// task is never aborted, since dropped mid-start it would leave a job or a
    /// pod that nothing finds again, and a start is never abandoned without a
    /// signal. With the real terminal, the screen is given back first and
    /// stderr says what is waited for; a signal meanwhile acts as a first one
    /// would. The ends still reach the app, for its exit notes. A logs export
    /// still writing is waited for first.
    async fn settle(&mut self, app: &mut App) {
        self.logged = app.logs.seq();
        // Catalog reads only read: nothing waits for them.
        self.tasks.abort_lookups();
        for effect in std::mem::take(&mut self.pending) {
            self.apply_late(app, effect);
        }
        // A file write: the exit's grace must not cut a `logs-*.log` short.
        for export in std::mem::take(&mut self.exports) {
            export.await.ok();
        }
        if !self.tasks.is_empty() {
            // Why the loop ended stays what it was.
            let why = app.exit;
            self.wait_tasks(app).await;
            app.exit = why.or(app.exit);
        }
        self.drain_late(app);
        self.write_logs(app);
    }

    /// Ends the tasks as a confirmed quit does and waits for them: a run still
    /// starting is detached once its job started, never abandoned; only a
    /// signal received meanwhile abandons it, as a first one would. With the
    /// real terminal, gives the screen back (so Ctrl-C raises SIGINT) and says
    /// on stderr what is waited for. The messages in the inbox are handled
    /// before each end.
    async fn wait_tasks(&mut self, app: &mut App) {
        for effect in app.on_loop_end() {
            self.apply_late(app, effect);
        }
        let lines = app.waiting_for();
        if !lines.is_empty()
            && let Some(screen) = &mut self.screen
        {
            screen.suspend().await.ok();
            self.console.get_or_insert_with(|| Box::new(io::stderr()));
        }
        self.write(&lines);
        let mut tick = tokio::time::interval(TICK);
        loop {
            let woke = tokio::select! {
                next = self.tasks.next() => Settling::Ended(next.map(Box::new)),
                () = Signals::recv(self.signals.as_mut(), true) => Settling::Signal,
                _ = tick.tick() => Settling::Tick,
            };
            let effects = match woke {
                Settling::Ended(Some(ended)) => {
                    let (id, result) = *ended;
                    self.drain_late(app);
                    app.on_done(id, result)
                },
                Settling::Ended(None) => break,
                Settling::Signal => self.interrupted(app),
                Settling::Tick => Vec::new(),
            };
            for effect in effects {
                self.apply_late(app, effect);
            }
            self.write_logs(app);
        }
    }

    /// Writes the WARN and ERROR lines logged since the last ones written (the
    /// lines the Logs view shows, such as a flow's "remove the pod" warning),
    /// once the screen was given back; nothing before.
    fn write_logs(&mut self, app: &App) {
        let Some(console) = &mut self.console else {
            return;
        };
        for line in app.logs.since(Level::WARN, self.logged) {
            writeln!(console, "{} {}: {}", line.level, line.target, line.message).ok();
            self.logged = line.seq;
        }
    }

    /// A signal while the tasks are waited for: they end as on a signal, and
    /// stderr says so.
    fn interrupted(&mut self, app: &mut App) -> Vec<Effect> {
        let effects = app.on_signal();
        if let Some(status) = &app.status {
            let said = status.text.clone();
            self.write(&[said]);
        }
        effects
    }

    /// Writes `lines` once the screen was given back; nothing before.
    fn write(&mut self, lines: &[String]) {
        if let Some(console) = &mut self.console {
            for line in lines {
                writeln!(console, "{line}").ok();
            }
        }
    }

    /// Runs `effect` once the loop ended: a training task or an edit starts
    /// (never lost, never cut, with the configuration the app keeps), a
    /// token is cancelled, a task abandoned; a
    /// reading, a stage or the editor does not start any more, nor a new run
    /// (the app notes it was not started), and a browser to open or a logs
    /// export is dropped.
    fn apply_late(&mut self, app: &mut App, effect: Effect) {
        match effect {
            Effect::Spawn(id, Task::Train(TrainJob::Start { .. })) => app.start_dropped(id),
            Effect::Spawn(
                id,
                task @ (Task::Train(_) | Task::Edit(_) | Task::SaveConfig { .. }),
            ) => {
                self.tasks.spawn(id, task);
            },
            Effect::Cancel(id) => self.tasks.cancel(id),
            Effect::Abandon(id) => self.tasks.abandon(id),
            Effect::UseConfig(source) => self.tasks.use_config(source),
            Effect::Spawn(..)
            | Effect::OpenEditor { .. }
            | Effect::OpenUrl(_)
            | Effect::ExportLogs { .. } => {},
        }
    }

    /// Handles every message in the inbox once the loop ended.
    fn drain_late(&mut self, app: &mut App) {
        while let Ok(message) = self.inbox.try_recv() {
            if matches!(message, Msg::EditorExited(_)) {
                continue;
            }
            for effect in app.on_message(message) {
                self.apply_late(app, effect);
            }
        }
    }

    /// The next thing that happens.
    async fn wait(&mut self, app: &App) -> Wake {
        let next_draw = self.next_draw();
        let draw = app.dirty && !self.suspended;
        let frame = self.next_frame(app.frame_period());
        let signals = self.signals.as_mut();
        let interrupt = !self.suspended;
        tokio::select! {
            event = self.input.recv(), if !self.suspended => Wake::Input(event),
            Some(message) = self.inbox.recv() => Wake::Message(message),
            status = wait_editor(self.editor.as_mut()), if self.editor.is_some() => {
                Wake::Message(Msg::EditorExited(status))
            },
            Some((id, result)) = self.tasks.next(), if !self.tasks.is_empty() => {
                Wake::Done(id, result)
            },
            () = Signals::recv(signals, interrupt) => Wake::Signal,
            _ = self.tick.tick() => Wake::Tick,
            () = tokio::time::sleep_until(next_draw), if draw => Wake::Draw,
            () = tokio::time::sleep_until(frame.unwrap_or(next_draw)), if frame.is_some() => {
                Wake::Frame
            },
        }
    }

    /// When the next frame of motion is due: `period` after the last one (the
    /// first one a period from now), and never before the next draw may come,
    /// so each frame that changes the screen draws it; while something moves
    /// and the editor does not have the terminal. `None` otherwise, and the
    /// frames stop.
    fn next_frame(&mut self, period: Option<Duration>) -> Option<Instant> {
        let Some(period) = period.filter(|_| !self.suspended) else {
            self.frame_at = None;
            return None;
        };
        let due = *self.frame_at.get_or_insert_with(Instant::now) + period;
        Some(self.last_draw.map_or(due, |at| due.max(at + FRAME)))
    }

    /// The time since the last frame of motion, which is now.
    fn frame_elapsed(&mut self) -> Duration {
        let now = Instant::now();
        let elapsed = self
            .frame_at
            .map_or(Duration::ZERO, |last| now.saturating_duration_since(last));
        self.frame_at = Some(now);
        elapsed
    }

    fn next_draw(&self) -> Instant {
        self.last_draw.map_or_else(Instant::now, |at| at + FRAME)
    }

    /// Draws `app` when it changed and the shortest time between two draws
    /// passed. A panic while drawing is caught and returned as an error, as a
    /// draw error is: the loop then ends and never draws again, and the tasks
    /// are settled rather than dropped with the loop (a start never cut). The
    /// owner thread's panic hook has restored the terminal by then.
    fn draw(&mut self, app: &mut App) -> anyhow::Result<()> {
        // Never `Instant::now() >= self.next_draw()`: with no draw yet, the
        // second reading of the clock can come after the first, and the first
        // frame would then never be drawn.
        let due = self.last_draw.is_none_or(|at| Instant::now() >= at + FRAME);
        if app.dirty && !self.suspended && due {
            // While frames run, the motion clock catches up with the time
            // since the last one first: an effect this draw starts (a key
            // opened a view or a dialog) starts now, not at that frame.
            if self.frame_at.is_some() {
                let elapsed = self.frame_elapsed();
                app.on_frame(elapsed);
            }
            let terminal = &mut *self.terminal;
            let drawn = panic::catch_unwind(AssertUnwindSafe(|| {
                terminal.draw(|frame| ui::render(frame, app)).map(drop)
            }));
            match drawn {
                Ok(drawn) => drawn?,
                Err(payload) => {
                    let message = panic_message(payload.as_ref());
                    tracing::error!("drawing the TUI panicked: {message}");
                    anyhow::bail!("drawing the TUI panicked: {message}");
                },
            }
            app.dirty = false;
            self.last_draw = Some(Instant::now());
        }
        Ok(())
    }

    async fn apply(&mut self, effect: Effect) -> anyhow::Result<()> {
        match effect {
            Effect::Spawn(id, task) => self.tasks.spawn(id, task),
            Effect::Cancel(id) => self.tasks.cancel(id),
            Effect::Abandon(id) => self.tasks.abandon(id),
            Effect::UseConfig(source) => self.tasks.use_config(source),
            Effect::OpenEditor { command, path } => self.open_editor(&command, path).await?,
            Effect::OpenUrl(url) => self.open_url(url),
            Effect::ExportLogs { name, lines } => self.export_logs(name, lines),
        }
        Ok(())
    }

    /// Opens `url` in a browser, detached: no terminal I/O, and the loop never
    /// waits for it. A detached task waits for the child, so no zombie is left;
    /// the runtime cancels that task when the TUI ends, so quitting never waits
    /// for it (`xdg-open` can run as long as the browser it started). Its own
    /// process group keeps a Ctrl-C or a job-control signal to the TUI from
    /// reaching it. A failed start or a non-zero exit comes back as one
    /// [`Msg::BrowserFailed`]; why is logged at debug, so no warning replaces
    /// that message on the status line.
    fn open_url(&self, url: String) {
        let started = tokio::process::Command::new(opener(cfg!(target_os = "macos")))
            .arg(&url)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .process_group(0)
            .spawn();
        match started {
            Ok(child) => {
                tokio::spawn(watch_browser(child, url, self.messages.clone()));
            },
            Err(error) => {
                tracing::debug!("cannot open a browser on {url}: {error}");
                self.messages.send(Msg::BrowserFailed(url)).ok();
            },
        }
    }

    /// Writes `lines` to `.overbrainer/<name>`, off the UI thread and off the
    /// event loop: the write runs in its own spawned task, so `Loop::run` keeps
    /// handling events while it happens, never overwriting an existing file.
    /// Reports the outcome as [`Msg::LogsExported`]. [`Loop::settle`] waits for
    /// the write, so quitting never truncates it.
    fn export_logs(&mut self, name: String, lines: Vec<String>) {
        let dir = self.tasks.project_dir().to_path_buf();
        let count = lines.len();
        let file_name = name.clone();
        let messages = self.messages.clone();
        self.exports.retain(|export| !export.is_finished());
        self.exports.push(tokio::spawn(async move {
            let written =
                tokio::task::spawn_blocking(move || write_log_export(&dir, &name, &lines)).await;
            let message = match written {
                Ok(written) => exported(file_name, count, written),
                Err(error) => Msg::LogsExported(Err(format!("export task panicked: {error}"))),
            };
            messages.send(message).ok();
        }));
    }

    /// Hands the terminal to the editor: stops reading input, drops the keys
    /// read before (they were typed for the TUI, not the editor) and leaves the
    /// alternate screen, then starts the editor, whose end comes back as
    /// [`Msg::EditorExited`]. Messages and tasks keep being handled meanwhile.
    ///
    /// The editor is started without a shell: its first word is the program, the
    /// others and the file its arguments.
    async fn open_editor(&mut self, command: &[String], path: PathBuf) -> anyhow::Result<()> {
        if let Some(screen) = &mut self.screen {
            screen
                .suspend()
                .await
                .context("cannot hand the terminal to the editor")?;
        }
        while self.input.try_recv().is_ok() {}
        self.suspended = true;
        let started = match command.split_first() {
            Some((program, args)) => tokio::process::Command::new(program)
                .args(args)
                .arg(&path)
                .kill_on_drop(true)
                .spawn(),
            None => Err(io::Error::other("no editor command")),
        };
        match started {
            Ok(child) => self.editor = Some(child),
            Err(error) => {
                self.messages.send(Msg::EditorExited(Err(error))).ok();
            },
        }
        Ok(())
    }

    /// The editor ended: takes the terminal back, repaints it all, then lets the
    /// app check the edited file.
    fn on_message(&mut self, app: &mut App, message: Msg) -> anyhow::Result<Vec<Effect>> {
        match message {
            Msg::EditorExited(status) => {
                self.editor = None;
                if let Some(screen) = &mut self.screen {
                    screen
                        .resume()
                        .context("cannot take the terminal back from the editor")?;
                }
                if let Some(signals) = &mut self.signals {
                    signals
                        .forget_interrupts()
                        .context("cannot catch the process signals")?;
                }
                self.terminal.clear()?;
                self.suspended = false;
                app.dirty = true;
                Ok(app.on_editor_exit(status))
            },
            message => Ok(app.on_message(message)),
        }
    }
}

/// Waits for the browser opener `child` of `url`, and sends
/// [`Msg::BrowserFailed`] to `messages` when it ends with an error.
async fn watch_browser(mut child: Child, url: String, messages: UnboundedSender<Msg>) {
    let why = match child.wait().await {
        Ok(status) if status.success() => return,
        Ok(status) => status.to_string(),
        Err(error) => error.to_string(),
    };
    tracing::debug!("the browser opener on {url} failed: {why}");
    messages.send(Msg::BrowserFailed(url)).ok();
}

/// Sends the answer of the update `check` to `messages` as
/// [`Msg::NewerRelease`], when there is a newer release.
async fn forward_check(check: JoinHandle<Option<Newer>>, messages: UnboundedSender<Msg>) {
    match check.await {
        Ok(Some(newer)) => {
            messages.send(Msg::NewerRelease(newer.latest)).ok();
        },
        Ok(None) => {},
        Err(error) => tracing::debug!("update check: {error}"),
    }
}

/// The program that opens a URL in the user's browser: `open` on macOS,
/// `xdg-open` elsewhere.
fn opener(macos: bool) -> &'static str {
    if macos { "open" } else { "xdg-open" }
}

/// What writing `count` lines to `.overbrainer/<name>` gave, as the app is
/// told: a file already there is named.
fn exported(name: String, count: usize, written: io::Result<()>) -> Msg {
    Msg::LogsExported(match written {
        Ok(()) => Ok((name, count)),
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
            Err(format!(".overbrainer/{name} already exists"))
        },
        Err(error) => Err(error.to_string()),
    })
}

/// Writes `lines`, one per line, to `.overbrainer/<name>` in `project_dir`, in
/// one `write_all`. Refuses to overwrite an existing file. A failed write
/// removes the partial file it created, so a later export can try `name`
/// again; a failure removing it is ignored, the write error is what is
/// returned.
///
/// # Errors
///
/// Returns an error when `name` already exists, or when the file cannot be
/// created or written.
fn write_log_export(project_dir: &Path, name: &str, lines: &[String]) -> io::Result<()> {
    let mut content = lines.join("\n");
    if !lines.is_empty() {
        content.push('\n');
    }
    let mut file = crate::project_lock::open_state_file(
        project_dir,
        name,
        OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL,
        true,
    )?;
    if let Err(error) = file.write_all(content.as_bytes()) {
        let _ = crate::project_lock::remove_state_file(project_dir, name);
        return Err(error);
    }
    Ok(())
}

/// SIGINT, SIGTERM and SIGHUP: in raw mode they only come from outside (`kill`, a
/// closed terminal), since Ctrl-C is a key.
pub(super) struct Signals {
    interrupt: Signal,
    terminate: Signal,
    hangup: Signal,
}

impl Signals {
    fn new() -> io::Result<Self> {
        Ok(Self {
            interrupt: signal(SignalKind::interrupt())?,
            terminate: signal(SignalKind::terminate())?,
            hangup: signal(SignalKind::hangup())?,
        })
    }

    /// Drops a SIGINT received while it was not listened to: a new listener
    /// only sees the ones sent after it.
    fn forget_interrupts(&mut self) -> io::Result<()> {
        self.interrupt = signal(SignalKind::interrupt())?;
        Ok(())
    }

    /// Waits for any of them, SIGINT only when `interrupt`; for ever without
    /// `signals`. A SIGINT sent meanwhile is kept until
    /// [`Signals::forget_interrupts`].
    async fn recv(signals: Option<&mut Self>, interrupt: bool) {
        let Some(signals) = signals else {
            return std::future::pending().await;
        };
        tokio::select! {
            _ = signals.interrupt.recv(), if interrupt => {},
            _ = signals.terminate.recv() => {},
            _ = signals.hangup.recv() => {},
        }
    }
}

/// The message a panic carried, when it is text.
fn panic_message(payload: &(dyn Any + Send)) -> String {
    payload
        .downcast_ref::<&str>()
        .map(|message| (*message).to_string())
        .or_else(|| payload.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "no message".to_string())
}

/// Waits for the editor to end; for ever without one.
async fn wait_editor(editor: Option<&mut Child>) -> io::Result<ExitStatus> {
    match editor {
        Some(editor) => editor.wait().await,
        None => std::future::pending().await,
    }
}

/// Stops the editor still running when the TUI ends, and waits for it, so it no
/// longer uses the terminal the guard restores: SIGTERM first, so it can put the
/// terminal back as it found it, then SIGKILL after [`EDITOR_GRACE`].
async fn stop_editor(editor: &mut Child) {
    if let Some(pid) = editor.id() {
        let asked = tokio::process::Command::new("kill")
            .args(["-TERM", &pid.to_string()])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await;
        if asked.is_ok_and(|status| status.success())
            && tokio::time::timeout(EDITOR_GRACE, editor.wait())
                .await
                .is_ok()
        {
            return;
        }
    }
    if let Err(error) = editor.kill().await {
        tracing::error!("cannot stop the editor: {error}");
    }
}

#[cfg(test)]
mod tests {
    use std::convert::Infallible;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};

    use crossterm::event::KeyCode;
    use ratatui::backend::{ClearType, TestBackend, WindowSize};
    use ratatui::buffer::Cell;
    use ratatui::layout::{Position, Size};

    use super::*;
    use crate::tui::snapshots::{app, key};

    /// An upper bound only: a shared CI runner can be far slower than a laptop.
    const LIMIT: Duration = Duration::from_secs(30);

    #[test]
    fn the_browser_opener_is_open_on_macos_and_xdg_open_elsewhere() {
        assert_eq!(opener(true), "open");
        assert_eq!(opener(false), "xdg-open");
    }

    #[tokio::test]
    async fn a_browser_opener_is_reported_only_when_it_fails()
    -> Result<(), Box<dyn std::error::Error>> {
        let (messages, mut received) = mpsc::unbounded_channel();
        let ok = tokio::process::Command::new("true").spawn()?;
        watch_browser(ok, "https://a".into(), messages.clone()).await;
        let failed = tokio::process::Command::new("false").spawn()?;
        watch_browser(failed, "https://b".into(), messages).await;
        let mut urls = Vec::new();
        while let Some(message) = received.recv().await {
            if let Msg::BrowserFailed(url) = message {
                urls.push(url);
            }
        }
        assert_eq!(urls, ["https://b"]);
        Ok(())
    }

    #[tokio::test]
    async fn only_a_newer_release_reaches_the_app() {
        let (messages, mut received) = mpsc::unbounded_channel();
        let newer = crate::update::Newer {
            latest: "0.9.0".into(),
            current: "0.4.0",
        };
        let found = tokio::spawn(async move { Some(newer) });
        forward_check(found, messages.clone()).await;
        let nothing = tokio::spawn(async { None });
        forward_check(nothing, messages).await;
        let mut versions = Vec::new();
        while let Some(message) = received.recv().await {
            if let Msg::NewerRelease(version) = message {
                versions.push(version);
            }
        }
        assert_eq!(versions, ["0.9.0"]);
    }

    #[test]
    fn an_export_to_a_file_that_exists_says_which() -> Result<(), Box<dyn std::error::Error>> {
        let project = tempfile::tempdir()?;
        let lines = vec!["line one".to_string()];
        let first = write_log_export(project.path(), "logs-x.log", &lines);
        let Msg::LogsExported(Ok((name, 1))) = exported("logs-x.log".into(), 1, first) else {
            return Err("the first export fails".into());
        };
        assert_eq!(name, "logs-x.log");
        let second = write_log_export(project.path(), "logs-x.log", &lines);
        let Msg::LogsExported(Err(error)) = exported("logs-x.log".into(), 1, second) else {
            return Err("the second export works".into());
        };
        assert_eq!(error, ".overbrainer/logs-x.log already exists");
        Ok(())
    }

    #[test]
    fn write_log_export_creates_the_file_and_refuses_to_overwrite()
    -> Result<(), Box<dyn std::error::Error>> {
        let project = tempfile::tempdir()?;
        let lines = vec!["line one".to_string(), "line two".to_string()];
        write_log_export(project.path(), "logs-x.log", &lines)?;
        let content = std::fs::read_to_string(project.path().join(".overbrainer/logs-x.log"))?;
        assert_eq!(content, "line one\nline two\n");
        let result = write_log_export(project.path(), "logs-x.log", &lines);
        let error = result.err().ok_or("expected an error")?;
        assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
        Ok(())
    }

    #[tokio::test]
    async fn a_logs_export_ends_before_the_loop_returns() -> Result<(), Box<dyn std::error::Error>>
    {
        let project = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut app = app();
        app.project.dir = project.path().to_path_buf();
        app.logs.push(crate::logging::LogLine {
            seq: 0,
            level: Level::WARN,
            target: "overbrainer".into(),
            time: SystemTime::UNIX_EPOCH,
            message: "kept".into(),
        });
        let (events, input) = mpsc::unbounded_channel();
        for code in ['5', 'x', 'q'] {
            events.send(Ok(key(KeyCode::Char(code))))?;
        }
        tokio::time::timeout(LIMIT, drive(&mut terminal, &mut app, input, None)).await??;
        let exports: Vec<_> = std::fs::read_dir(project.path().join(".overbrainer"))?
            .filter_map(Result::ok)
            .filter(|entry| entry.file_name().to_string_lossy().starts_with("logs-"))
            .map(|entry| std::fs::read_to_string(entry.path()))
            .collect::<Result<_, _>>()?;
        assert_eq!(exports.len(), 1, "{exports:?}");
        assert!(exports[0].contains("kept"), "{exports:?}");
        Ok(())
    }

    #[tokio::test]
    async fn settling_waits_for_a_running_export() -> Result<(), Box<dyn std::error::Error>> {
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut app = app();
        let (_events, input) = mpsc::unbounded_channel();
        let mut looping = Loop::new(&mut terminal, input, &app.project.dir);
        let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let flag = done.clone();
        looping.exports.push(tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            flag.store(true, std::sync::atomic::Ordering::SeqCst);
        }));
        tokio::time::timeout(LIMIT, looping.settle(&mut app)).await?;
        assert!(done.load(std::sync::atomic::Ordering::SeqCst));
        assert!(looping.exports.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn q_ends_the_loop_after_a_resize_is_drawn() -> Result<(), Box<dyn std::error::Error>> {
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut app = app();
        let (events, input) = mpsc::unbounded_channel();
        terminal.backend_mut().resize(100, 30);
        events.send(Ok(TermEvent::Resize(100, 30)))?;
        events.send(Ok(key(KeyCode::Char('5'))))?;
        events.send(Ok(key(KeyCode::Char('q'))))?;
        tokio::time::timeout(LIMIT, drive(&mut terminal, &mut app, input, None)).await??;
        let area = terminal.backend().buffer().area;
        assert_eq!((area.width, area.height), (100, 30));
        assert_eq!(app.view, crate::tui::app::View::Logs);
        Ok(())
    }

    #[tokio::test]
    async fn the_loop_ends_when_its_input_is_gone() -> Result<(), Box<dyn std::error::Error>> {
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut app = app();
        let (events, input) = mpsc::unbounded_channel();
        drop(events);
        tokio::time::timeout(LIMIT, drive(&mut terminal, &mut app, input, None)).await??;
        assert_eq!(app.exit, Some(Exit::Quit));
        Ok(())
    }

    #[tokio::test]
    async fn the_data_is_loaded_when_the_loop_starts() -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile::tempdir()?;
        let files = crate::dataset::DataFiles::new(dir.path());
        crate::dataset::rewrite(
            &files.subtopics,
            &crate::tui::snapshots::dataset().subtopics,
        )?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut app = app();
        app.project.dir = dir.path().to_path_buf();
        let (events, input) = mpsc::unbounded_channel();
        // No key ends the loop, so it cannot quit before the load ends: it runs
        // for a window far longer than a read of three records, then is dropped.
        let window = Duration::from_secs(2);
        let run = tokio::time::timeout(window, drive(&mut terminal, &mut app, input, None)).await;
        assert!(run.is_err(), "the loop ended on its own: {run:?}");
        drop(events);
        assert_eq!(app.load, None, "the load ended");
        let subtopics = app
            .dataset
            .model
            .as_ref()
            .map(|model| model.data.subtopics.len());
        assert_eq!(subtopics, Some(3));
        Ok(())
    }

    #[tokio::test]
    async fn a_read_error_ends_the_loop_with_that_error() -> Result<(), Box<dyn std::error::Error>>
    {
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut app = app();
        let (events, input) = mpsc::unbounded_channel();
        events.send(Err(io::Error::other("the terminal is gone")))?;
        drop(events);
        let result =
            tokio::time::timeout(LIMIT, drive(&mut terminal, &mut app, input, None)).await?;
        let error = result.err().map(|error| format!("{error:#}"));
        assert_eq!(
            error.as_deref(),
            Some("cannot read the terminal: the terminal is gone")
        );
        Ok(())
    }

    /// A terminal error ends the loop, but a training task still running is
    /// waited for, never aborted, and its end reaches the app.
    #[tokio::test]
    async fn a_terminal_error_waits_for_the_training_tasks()
    -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile::tempdir()?;
        let run = "20260921-133200-a1b2";
        crate::runs::Runs::new(dir.path()).save(&crate::tui::snapshots::run(
            run,
            "homelab",
            crate::runs::RunState::Running,
        ))?;
        let backend = Shared::new();
        let frame = Arc::clone(&backend.frame);
        let mut terminal = Terminal::new(backend)?;
        let mut app = app();
        app.project.dir = dir.path().to_path_buf();
        let (events, input) = mpsc::unbounded_channel();
        let run_loop = drive(&mut terminal, &mut app, input, None);
        let keys = async {
            events.send(Ok(key(KeyCode::Char('4'))))?;
            drawn(&frame, run).await?;
            events.send(Ok(key(KeyCode::Char('a'))))?;
            events.send(Err(io::Error::other("the terminal is gone")))?;
            Ok::<_, Box<dyn std::error::Error>>(())
        };
        let joined = tokio::time::timeout(LIMIT, async { tokio::join!(run_loop, keys) }).await;
        let Ok((result, sent)) = joined else {
            return Err(stalled("waiting for the loop", &app, &frame).into());
        };
        sent?;
        assert!(result.is_err());
        assert!(app.training.tasks.is_empty(), "the task was waited for");
        // No overbrainer.toml: the attach flow fails, and says why.
        let ended = app.training.ended.get(run).and_then(|e| e.error.clone());
        assert!(
            ended
                .as_deref()
                .is_some_and(|e| e.contains("overbrainer.toml")),
            "{ended:?}"
        );
        Ok(())
    }

    /// A test backend that shares the text of its screen after each draw,
    /// whose draws fail once `fail` is set, and unwind, as a view that panics
    /// would, once `unwind` is set.
    struct Shared {
        inner: TestBackend,
        frame: Arc<Mutex<String>>,
        fail: Arc<AtomicBool>,
        unwind: Arc<AtomicBool>,
    }

    impl Shared {
        fn new() -> Self {
            Self {
                inner: TestBackend::new(80, 24),
                frame: Arc::new(Mutex::new(String::new())),
                fail: Arc::new(AtomicBool::new(false)),
                unwind: Arc::new(AtomicBool::new(false)),
            }
        }
    }

    /// The error a [`TestBackend`] never returns.
    fn never(error: Infallible) -> io::Error {
        match error {}
    }

    impl Backend for Shared {
        type Error = io::Error;

        fn draw<'a, I>(&mut self, content: I) -> io::Result<()>
        where
            I: Iterator<Item = (u16, u16, &'a Cell)>,
        {
            if self.unwind.load(Ordering::SeqCst) {
                std::panic::resume_unwind(Box::new("a view failed"));
            }
            if self.fail.load(Ordering::SeqCst) {
                return Err(io::Error::other("the terminal is gone"));
            }
            self.inner.draw(content).map_err(never)?;
            let text: String = self
                .inner
                .buffer()
                .content()
                .iter()
                .map(Cell::symbol)
                .collect();
            if let Ok(mut frame) = self.frame.lock() {
                *frame = text;
            }
            Ok(())
        }

        fn hide_cursor(&mut self) -> io::Result<()> {
            self.inner.hide_cursor().map_err(never)
        }

        fn show_cursor(&mut self) -> io::Result<()> {
            self.inner.show_cursor().map_err(never)
        }

        fn get_cursor_position(&mut self) -> io::Result<Position> {
            self.inner.get_cursor_position().map_err(never)
        }

        fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> io::Result<()> {
            self.inner.set_cursor_position(position).map_err(never)
        }

        fn clear(&mut self) -> io::Result<()> {
            self.inner.clear().map_err(never)
        }

        fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {
            self.inner.clear_region(clear_type).map_err(never)
        }

        fn size(&self) -> io::Result<Size> {
            self.inner.size().map_err(never)
        }

        fn window_size(&mut self) -> io::Result<WindowSize> {
            self.inner.window_size().map_err(never)
        }

        fn flush(&mut self) -> io::Result<()> {
            self.inner.flush().map_err(never)
        }
    }

    /// Waits until `text` is on the screen shared in `frame`, 10 s at most.
    async fn drawn(frame: &Mutex<String>, text: &str) -> Result<(), String> {
        for _ in 0..1000 {
            if frame.lock().is_ok_and(|frame| frame.contains(text)) {
                return Ok(());
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        Err(format!("never drawn: {text}"))
    }

    /// Waits until the screen shows `text` and not `busy`.
    async fn drawn_without(frame: &Mutex<String>, text: &str, busy: &str) -> Result<(), String> {
        for _ in 0..1000 {
            if frame
                .lock()
                .is_ok_and(|frame| frame.contains(text) && !frame.contains(busy))
            {
                return Ok(());
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        Err(format!("never drawn: {text} without {busy}"))
    }

    /// Why a test timed out: what `app` was at and the last screen drawn, so a
    /// timeout on a slow runner says where it stopped.
    fn stalled(stage: &str, app: &App, frame: &Mutex<String>) -> String {
        let screen = frame.lock().map(|frame| frame.clone()).unwrap_or_default();
        format!(
            "timed out {stage}: view {:?}, exit {:?}, {} training task(s), status {:?}, screen {screen:?}",
            app.view,
            app.exit,
            app.training.tasks.len(),
            app.status.as_ref().map(|status| status.text.clone()),
        )
    }

    /// Frames of motion come only while something moves: the first one a
    /// period from now, then one period after the last; none once nothing
    /// moves or the editor has the terminal.
    #[tokio::test]
    async fn frames_come_only_while_something_moves() -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = looping(&mut terminal, dir.path());
        assert_eq!(looping.next_frame(None), None);
        assert_eq!(looping.frame_at, None);
        let period = Duration::from_millis(80);
        let first = looping.next_frame(Some(period)).ok_or("no frame")?;
        let started = looping.frame_at.ok_or("no start")?;
        assert_eq!(first, started + period);
        assert_eq!(looping.next_frame(Some(period)), Some(first), "not moved");
        let elapsed = looping.frame_elapsed();
        assert_eq!(looping.frame_at, Some(started + elapsed));
        looping.suspended = true;
        assert_eq!(looping.next_frame(Some(period)), None);
        assert_eq!(looping.frame_at, None, "the frames stop");
        Ok(())
    }

    /// A frame never comes before the next draw may: each frame that changes
    /// the screen draws it, rather than wake the loop once for the frame and
    /// once more for the draw.
    #[tokio::test]
    async fn a_frame_comes_at_or_after_the_draw_it_needs() -> Result<(), Box<dyn std::error::Error>>
    {
        use crate::tui::motion::FAST;
        let dir = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = looping(&mut terminal, dir.path());
        let started = Instant::now();
        looping.frame_at = Some(started);
        looping.last_draw = Some(started + Duration::from_millis(5));
        let frame = looping.next_frame(Some(FAST)).ok_or("no frame")?;
        assert_eq!(frame, started + Duration::from_millis(5) + FRAME);
        looping.last_draw = Some(started - FRAME);
        let frame = looping.next_frame(Some(FAST)).ok_or("no frame")?;
        assert_eq!(frame, started + FAST, "the draw is due already");
        Ok(())
    }

    /// While frames run, a draw first brings the motion clock to now: an
    /// effect a key starts begins when it was pressed, not at the last frame.
    #[tokio::test]
    async fn a_draw_brings_the_motion_clock_to_now() -> Result<(), Box<dyn std::error::Error>> {
        use crate::tui::motion::{Motion, MotionLevel};
        let dir = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = looping(&mut terminal, dir.path());
        let mut app = app();
        app.motion = Motion::new(MotionLevel::On);
        let gap = Duration::from_millis(50);
        looping.frame_at = Some(Instant::now().checked_sub(gap).ok_or("no instant")?);
        app.dirty = true;
        looping.draw(&mut app)?;
        assert!(app.motion.clock() >= gap, "{:?}", app.motion.clock());
        assert!(!app.dirty, "drawn");
        Ok(())
    }

    /// With motion on, the spinner of running work turns on screen while the
    /// loop waits for nothing else.
    #[tokio::test]
    async fn the_spinner_turns_while_work_runs() -> Result<(), Box<dyn std::error::Error>> {
        use crate::tui::motion::{Motion, MotionLevel};
        let backend = Shared::new();
        let frame = Arc::clone(&backend.frame);
        let mut terminal = Terminal::new(backend)?;
        let mut app = app();
        app.motion = Motion::new(MotionLevel::On);
        crate::tui::snapshots::pipeline_running(&mut app);
        let (events, input) = mpsc::unbounded_channel();
        let run_loop = drive(&mut terminal, &mut app, input, None);
        let watch = async move {
            drawn(&frame, "â ‹ answers 120/400").await?;
            drawn(&frame, "â ™ answers 120/400").await?;
            drop(events);
            Ok::<_, String>(())
        };
        let (result, watched) =
            tokio::time::timeout(LIMIT, async { tokio::join!(run_loop, watch) }).await?;
        watched?;
        result?;
        Ok(())
    }

    /// The effects of a wake whose draw failed still run: a confirmed cancel
    /// starts, and is waited for.
    #[tokio::test]
    async fn the_effects_of_a_failed_draw_still_run() -> Result<(), Box<dyn std::error::Error>> {
        let dir = crate::tui::snapshots::project()?;
        let mut record = crate::tui::snapshots::run(RUN, "homelab", crate::runs::RunState::Failed);
        record.job = None;
        crate::runs::Runs::new(dir.path()).save(&record)?;
        let backend = Shared::new();
        let (frame, fail) = (Arc::clone(&backend.frame), Arc::clone(&backend.fail));
        let mut terminal = Terminal::new(backend)?;
        let mut app = app();
        app.project.dir = dir.path().to_path_buf();
        let (events, input) = mpsc::unbounded_channel();
        let run_loop = drive(&mut terminal, &mut app, input, None);
        let keys = async {
            events.send(Ok(key(KeyCode::Char('4'))))?;
            drawn(&frame, RUN).await?;
            events.send(Ok(key(KeyCode::Char('c'))))?;
            drawn(&frame, "Cancel a run?").await?;
            // Past the shortest time between two draws: `y` is drawn at once.
            tokio::time::sleep(FRAME * 2).await;
            fail.store(true, Ordering::SeqCst);
            events.send(Ok(key(KeyCode::Char('y'))))?;
            Ok::<_, Box<dyn std::error::Error>>(())
        };
        let joined = tokio::time::timeout(LIMIT, async { tokio::join!(run_loop, keys) }).await;
        let Ok((result, sent)) = joined else {
            return Err(stalled("waiting for the loop", &app, &frame).into());
        };
        sent?;
        let error = result.err().map(|error| format!("{error:#}"));
        assert_eq!(error.as_deref(), Some("the terminal is gone"));
        let ended = app.training.ended.get(RUN).and_then(|e| e.error.clone());
        assert_eq!(ended, Some(format!("run {RUN} has not started")));
        Ok(())
    }

    /// [`crate::tui::snapshots::project_app`] on a project directory holding
    /// its configuration, `rust_pro` typed in the form of `project.name`,
    /// Enter not pressed yet.
    fn saving_app() -> Result<(tempfile::TempDir, App), Box<dyn std::error::Error>> {
        use crate::tui::snapshots::{PROJECT_CONFIG, project_app, project_env};
        let dir = tempfile::tempdir()?;
        std::fs::write(dir.path().join("overbrainer.toml"), PROJECT_CONFIG)?;
        let mut app = project_app()?;
        app.project.dir = dir.path().to_path_buf();
        app.env = project_env();
        for code in [KeyCode::Enter, KeyCode::End]
            .into_iter()
            .chain([KeyCode::Backspace; 20])
            .chain("rust_pro".chars().map(KeyCode::Char))
        {
            app.on_input(&key(code));
        }
        assert!(app.project_view.form.is_some());
        Ok((dir, app))
    }

    /// A save started, then the terminal fails (its input, or the draw after
    /// Enter, whose effects are then applied late): the save is still waited
    /// for, and the app hears how it ended.
    #[tokio::test]
    async fn a_save_is_waited_for_when_the_terminal_fails() -> Result<(), Box<dyn std::error::Error>>
    {
        for draw_fails in [false, true] {
            let (dir, mut app) = saving_app()?;
            let backend = Shared::new();
            let (frame, fail) = (Arc::clone(&backend.frame), Arc::clone(&backend.fail));
            let mut terminal = Terminal::new(backend)?;
            let (events, input) = mpsc::unbounded_channel();
            let run_loop = drive(&mut terminal, &mut app, input, None);
            let keys = async {
                // Once the start's load ended: while it runs, its spinner is
                // drawn every frame, and the draw after Enter may then not be due
                // before the save ends.
                drawn_without(&frame, "configuration", "loading").await?;
                tokio::time::sleep(FRAME * 2).await;
                if draw_fails {
                    fail.store(true, Ordering::SeqCst);
                }
                events.send(Ok(key(KeyCode::Enter)))?;
                if !draw_fails {
                    events.send(Err(io::Error::other("the terminal is gone")))?;
                }
                Ok::<_, Box<dyn std::error::Error>>(())
            };
            let joined = tokio::time::timeout(LIMIT, async { tokio::join!(run_loop, keys) }).await;
            let Ok((result, sent)) = joined else {
                return Err(stalled("waiting for the loop", &app, &frame).into());
            };
            sent?;
            assert!(result.is_err(), "{draw_fails}");
            let text = std::fs::read_to_string(dir.path().join("overbrainer.toml"))?;
            assert!(text.contains("name = \"rust_pro\""), "{draw_fails}: {text}");
            assert_eq!(app.project_view.form, None, "{draw_fails}");
            assert_eq!(app.project_view.save, None);
            assert!(
                app.exit_notes
                    .contains(&"overbrainer.toml was saved".to_string()),
                "{draw_fails}: {:?}",
                app.exit_notes
            );
        }
        Ok(())
    }

    /// A loop on `terminal` with no input, for the project in `dir`.
    fn looping<'t>(
        terminal: &'t mut Terminal<TestBackend>,
        dir: &std::path::Path,
    ) -> Loop<'t, TestBackend> {
        Loop::new(terminal, mpsc::unbounded_channel().1, dir)
    }

    const RUN: &str = "20260921-133200-a1b2";

    /// The app, following no run but for task 5, cancelling [`RUN`].
    fn cancelling_app(dir: &std::path::Path) -> App {
        use crate::tui::training::{Follow, Job};
        let mut app = app();
        app.project.dir = dir.to_path_buf();
        app.training
            .tasks
            .insert(TaskId(5), Follow::new(Job::Cancel, RUN));
        app
    }

    #[tokio::test]
    async fn the_last_lines_of_a_task_reach_the_exit_notes()
    -> Result<(), Box<dyn std::error::Error>> {
        use crate::cli::front::Report;
        let dir = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = looping(&mut terminal, dir.path());
        let mut app = cancelling_app(dir.path());
        app.leaving = Some(Exit::Quit);
        let line = format!("train: run {RUN} cancelled");
        looping
            .messages
            .send(Msg::Report(TaskId(5), Report::Line(line.clone())))?;
        looping.finished(&mut app, TaskId(5), Ok(Done::Trained(Ok(()))))?;
        assert_eq!(app.exit, Some(Exit::Quit));
        assert_eq!(app.exit_notes, [line]);
        Ok(())
    }

    /// An effect the loop could not run before it ended (here a cancel task)
    /// still runs, and is waited for.
    #[tokio::test]
    async fn a_cancel_left_pending_runs_once_the_loop_ended()
    -> Result<(), Box<dyn std::error::Error>> {
        use crate::tui::tasks::{Task, TrainJob};
        let dir = crate::tui::snapshots::project()?;
        let mut record = crate::tui::snapshots::run(RUN, "homelab", crate::runs::RunState::Failed);
        record.job = None;
        crate::runs::Runs::new(dir.path()).save(&record)?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = looping(&mut terminal, dir.path());
        let mut app = cancelling_app(dir.path());
        app.exit = Some(Exit::Quit);
        looping.pending = vec![Effect::Spawn(
            TaskId(5),
            Task::Train(TrainJob::Cancel(RUN.into())),
        )];
        tokio::time::timeout(LIMIT, looping.settle(&mut app)).await?;
        assert!(app.training.tasks.is_empty());
        let error = app.training.ended.get(RUN).and_then(|e| e.error.clone());
        assert_eq!(error, Some(format!("run {RUN} has not started")));
        assert_eq!(app.exit, Some(Exit::Quit), "why the loop ended is kept");
        Ok(())
    }

    /// A start left pending when the loop ended (a draw error) is never
    /// spawned: nothing would follow it. The exit notes say it was not started.
    #[tokio::test]
    async fn a_start_left_pending_never_runs_once_the_loop_ended()
    -> Result<(), Box<dyn std::error::Error>> {
        use crate::tui::tasks::{Task, TrainJob};
        use crate::tui::training::{Follow, Job};
        let dir = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = looping(&mut terminal, dir.path());
        let mut app = app();
        app.project.dir = dir.path().to_path_buf();
        app.training
            .tasks
            .insert(TaskId(4), Follow::new(Job::Start { runpod: true }, ""));
        looping.pending = vec![Effect::Spawn(
            TaskId(4),
            Task::Train(TrainJob::Start {
                vram_floor: crate::train::sizing::VramFloor::ToEstimate,
            }),
        )];
        tokio::time::timeout(LIMIT, looping.settle(&mut app)).await?;
        assert!(looping.tasks.is_empty(), "never spawned");
        assert!(app.training.tasks.is_empty());
        assert_eq!(
            app.exit_notes,
            [
                "a new training run was not started: the TUI ended first; start it again with \
              `overbrainer train` or t"
            ]
        );
        Ok(())
    }

    /// Once the loop ended, the messages of a task are handled before its end:
    /// its lines come before its error in the exit notes.
    #[tokio::test]
    async fn the_last_lines_of_a_task_waited_for_come_before_its_end()
    -> Result<(), Box<dyn std::error::Error>> {
        use crate::cli::front::Report;
        use crate::tui::tasks::{Task, TrainJob};
        let dir = crate::tui::snapshots::project()?;
        let mut record = crate::tui::snapshots::run(RUN, "homelab", crate::runs::RunState::Failed);
        record.job = None;
        crate::runs::Runs::new(dir.path()).save(&record)?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = looping(&mut terminal, dir.path());
        let mut app = cancelling_app(dir.path());
        app.leaving = Some(Exit::Quit);
        looping.pending = vec![Effect::Spawn(
            TaskId(5),
            Task::Train(TrainJob::Cancel(RUN.into())),
        )];
        looping
            .messages
            .send(Msg::Report(TaskId(5), Report::Line("a line".into())))?;
        tokio::time::timeout(LIMIT, looping.settle(&mut app)).await?;
        assert_eq!(
            app.exit_notes,
            ["a line".to_string(), format!("run {RUN} has not started")]
        );
        Ok(())
    }

    /// The app of the project in `dir`, with a Runpod run still provisioning
    /// as task 4.
    fn provisioning_app(dir: &std::path::Path) -> App {
        use crate::tui::training::{Follow, Job};
        let mut app = app();
        app.project.dir = dir.to_path_buf();
        app.training
            .tasks
            .insert(TaskId(4), Follow::new(Job::Start { runpod: true }, RUN));
        app
    }

    /// A loop whose input fails at once, for the project in `dir`.
    fn failing_input<'t>(
        terminal: &'t mut Terminal<TestBackend>,
        dir: &std::path::Path,
    ) -> Result<Loop<'t, TestBackend>, Box<dyn std::error::Error>> {
        let (events, input) = mpsc::unbounded_channel();
        events.send(Err(io::Error::other("the terminal is gone")))?;
        Ok(Loop::new(terminal, input, dir))
    }

    /// A loop ended by a terminal error waits for a Runpod run still
    /// provisioning, and never abandons it: no signal came.
    #[tokio::test]
    async fn a_terminal_error_never_abandons_a_provisioning_run()
    -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = failing_input(&mut terminal, dir.path())?;
        let mut app = provisioning_app(dir.path());
        let release = tokio_util::sync::CancellationToken::new();
        let abandon = looping.tasks.park(TaskId(4), release.clone());
        let result = tokio::time::timeout(LIMIT, looping.run(&mut app)).await?;
        assert!(result.is_err());
        let check = async {
            tokio::time::sleep(Duration::from_millis(200)).await;
            let abandoned = abandon.load(Ordering::SeqCst);
            release.cancel();
            abandoned
        };
        let ((), abandoned) = tokio::time::timeout(LIMIT, async {
            tokio::join!(looping.settle(&mut app), check)
        })
        .await?;
        assert!(!abandoned, "abandoned while it was waited for");
        assert!(!abandon.load(Ordering::SeqCst));
        assert!(app.training.tasks.is_empty(), "it was waited for");
        assert_eq!(app.leaving, Some(Exit::Quit));
        Ok(())
    }

    /// A signal while a loop ended by a terminal error waits abandons a Runpod
    /// run still provisioning, as a first signal would.
    #[tokio::test]
    async fn a_signal_while_the_loop_ends_abandons_a_provisioning_run()
    -> Result<(), Box<dyn std::error::Error>> {
        let _signals = crate::test_support::SIGNALS.lock().await;
        let dir = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = failing_input(&mut terminal, dir.path())?;
        looping.signals = Some(Signals::new()?);
        let mut app = provisioning_app(dir.path());
        let abandon = looping
            .tasks
            .park(TaskId(4), tokio_util::sync::CancellationToken::new());
        let result = tokio::time::timeout(LIMIT, looping.run(&mut app)).await?;
        assert!(result.is_err());
        let check = async {
            tokio::time::sleep(Duration::from_millis(200)).await;
            let abandoned = abandon.load(Ordering::SeqCst);
            raise("INT")?;
            Ok::<_, Box<dyn std::error::Error>>(abandoned)
        };
        let ((), abandoned) = tokio::time::timeout(LIMIT, async {
            tokio::join!(looping.settle(&mut app), check)
        })
        .await?;
        assert!(!abandoned?, "abandoned before the signal");
        assert!(abandon.load(Ordering::SeqCst), "abandoned on the signal");
        assert!(app.training.tasks.is_empty());
        assert_eq!(app.exit, Some(Exit::Signal));
        Ok(())
    }

    /// A panic while drawing ends the loop as a draw error does: the loop
    /// never draws again, and a Runpod run still provisioning is waited for,
    /// never dropped with the loop nor abandoned.
    #[tokio::test]
    async fn a_panic_while_drawing_ends_the_loop_as_a_draw_error()
    -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile::tempdir()?;
        let backend = Shared::new();
        backend.unwind.store(true, Ordering::SeqCst);
        let frame = Arc::clone(&backend.frame);
        let mut terminal = Terminal::new(backend)?;
        let (_events, input) = mpsc::unbounded_channel();
        let mut looping = Loop::new(&mut terminal, input, dir.path());
        let mut app = provisioning_app(dir.path());
        let release = tokio_util::sync::CancellationToken::new();
        let abandon = looping.tasks.park(TaskId(4), release.clone());
        let ran = tokio::time::timeout(LIMIT, looping.run(&mut app)).await;
        let Ok(result) = ran else {
            return Err(stalled("running the loop", &app, &frame).into());
        };
        let error = result.err().map(|error| format!("{error:#}"));
        assert_eq!(
            error.as_deref(),
            Some("drawing the TUI panicked: a view failed")
        );
        let check = async {
            tokio::time::sleep(Duration::from_millis(200)).await;
            let abandoned = abandon.load(Ordering::SeqCst);
            release.cancel();
            abandoned
        };
        let settled = tokio::time::timeout(LIMIT, async {
            tokio::join!(looping.settle(&mut app), check)
        })
        .await;
        let Ok(((), abandoned)) = settled else {
            return Err(stalled("settling", &app, &frame).into());
        };
        assert!(!abandoned);
        assert!(app.training.tasks.is_empty(), "it was waited for");
        Ok(())
    }

    /// A writer sharing what it gets, standing for stderr.
    #[derive(Clone, Default)]
    struct Console(Arc<Mutex<Vec<u8>>>);

    impl Console {
        fn text(&self) -> String {
            self.0
                .lock()
                .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
                .unwrap_or_default()
        }
    }

    impl Write for Console {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            self.0
                .lock()
                .map_err(|_| io::Error::other("poisoned"))?
                .extend_from_slice(bytes);
            Ok(bytes.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    /// A log line of the flows at `level`.
    fn logged(level: tracing::Level, message: &str) -> crate::logging::LogLine {
        crate::logging::LogLine {
            seq: 0,
            level,
            target: "overbrainer::runpod_train".into(),
            time: SystemTime::UNIX_EPOCH,
            message: message.into(),
        }
    }

    /// Once the screen is given back, what is waited for is written, then each
    /// warning or error the flows log as it arrives, and those logged last
    /// before the exit; never the other lines.
    #[tokio::test]
    async fn warnings_logged_while_the_loop_ends_are_written()
    -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile::tempdir()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        let mut looping = failing_input(&mut terminal, dir.path())?;
        let console = Console::default();
        looping.console = Some(Box::new(console.clone()));
        let mut app = provisioning_app(dir.path());
        let logs = app.logs.clone();
        let release = tokio_util::sync::CancellationToken::new();
        looping.tasks.park(TaskId(4), release.clone());
        let result = tokio::time::timeout(LIMIT, looping.run(&mut app)).await?;
        assert!(result.is_err());
        let remove = "remove the pod with `overbrainer pod rm`";
        let check = async {
            logs.push(logged(tracing::Level::INFO, "not written"));
            logs.push(logged(tracing::Level::WARN, remove));
            for _ in 0..500 {
                if console.text().contains(remove) {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
            let written = console.text().contains(remove);
            logs.push(logged(tracing::Level::ERROR, "the last line"));
            release.cancel();
            written
        };
        let ((), written) = tokio::time::timeout(LIMIT, async {
            tokio::join!(looping.settle(&mut app), check)
        })
        .await?;
        assert!(written, "written as it arrived: {}", console.text());
        let text = console.text();
        assert_eq!(
            text.lines().collect::<Vec<_>>(),
            [
                "waiting for run 20260921-133200-a1b2 to start; Ctrl-C abandons it...",
                &format!("WARN overbrainer::runpod_train: {remove}"),
                "ERROR overbrainer::runpod_train: the last line",
            ]
        );
        Ok(())
    }

    #[tokio::test]
    async fn the_editor_round_trip_saves_the_edit() -> Result<(), Box<dyn std::error::Error>> {
        let dir = crate::tui::snapshots::project()?;
        let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
        // The app already holds the data of the files, so the keys never depend
        // on when the load the loop starts ends: that load finds the same data
        // and keeps the selection.
        let mut app = crate::tui::snapshots::dataset_app();
        app.project.dir = dir.path().to_path_buf();
        app.editor = vec![
            "sh".into(),
            "-c".into(),
            "printf 'When does a borrow end?' > \"$1\"".into(),
            "editor".into(),
        ];
        let (events, input) = mpsc::unbounded_channel();
        let run = drive(&mut terminal, &mut app, input, None);
        let files = crate::dataset::DataFiles::new(dir.path());
        let keys = [
            KeyCode::Enter,
            KeyCode::Char('j'),
            KeyCode::Char('l'),
            KeyCode::Char('j'),
            KeyCode::Char('j'),
            KeyCode::Char('j'),
            KeyCode::Char('e'),
            // Typed before the editor took the terminal: dropped, not replayed.
            KeyCode::Char('5'),
        ];
        let quit = async {
            for code in keys {
                events.send(Ok(key(code)))?;
            }
            for _ in 0..100 {
                tokio::time::sleep(Duration::from_millis(50)).await;
                if files.train.exists() {
                    break;
                }
            }
            // The edit writes its files before the loop hears it ended, so `q`
            // may still find it saving and ask to confirm: `y` answers. When
            // `q` quits at once, the loop is gone and `y` is never read.
            events.send(Ok(key(KeyCode::Char('q'))))?;
            events.send(Ok(key(KeyCode::Char('y'))))
        };
        let (ran, sent) = tokio::time::timeout(LIMIT, async { tokio::join!(run, quit) }).await?;
        ran?;
        sent?;
        let questions: Vec<crate::dataset::Question> = crate::dataset::read(&files.questions)?;
        let texts: Vec<&str> = questions.iter().map(|q| q.text.as_str()).collect();
        assert!(texts.contains(&"When does a borrow end?"), "{texts:?}");
        assert!(!texts.contains(&"When does NLL end a borrow?"));
        // Quitting while the edit was saving notes that it was saved; no other note.
        assert!(
            app.exit_notes
                .iter()
                .all(|note| note.starts_with("a change was saved: ")),
            "{:?}",
            app.exit_notes
        );
        assert_eq!(app.view, crate::tui::app::View::Dataset, "4 was dropped");
        Ok(())
    }

    /// Sends `signal` to this test process, through a shell's `kill`.
    fn raise(signal: &str) -> Result<(), Box<dyn std::error::Error>> {
        let status = std::process::Command::new("sh")
            .args(["-c", &format!("kill -{signal} \"$PPID\"")])
            .status()?;
        if !status.success() {
            return Err(format!("kill -{signal}: {status}").into());
        }
        Ok(())
    }

    /// While the editor has the terminal a SIGINT is ignored, and forgotten when
    /// the TUI takes it back; SIGTERM still ends the TUI. The listeners are
    /// installed before any signal is sent, so the test process catches them.
    #[tokio::test]
    async fn sigint_is_ignored_while_the_editor_runs_and_forgotten_after()
    -> Result<(), Box<dyn std::error::Error>> {
        let _signals = crate::test_support::SIGNALS.lock().await;
        let short = Duration::from_millis(300);
        let mut signals = Signals::new()?;
        raise("INT")?;
        let suspended = tokio::time::timeout(short, Signals::recv(Some(&mut signals), false));
        assert!(suspended.await.is_err(), "SIGINT woke a suspended loop");
        signals.forget_interrupts()?;
        let resumed = tokio::time::timeout(short, Signals::recv(Some(&mut signals), true));
        assert!(resumed.await.is_err(), "the old SIGINT was replayed");
        raise("INT")?;
        tokio::time::timeout(LIMIT, Signals::recv(Some(&mut signals), true)).await?;
        raise("TERM")?;
        tokio::time::timeout(LIMIT, Signals::recv(Some(&mut signals), false)).await?;
        Ok(())
    }

    /// An editor, as `sh`, running `on_term` on SIGTERM; returned once its trap
    /// is set, so the signal cannot come first.
    async fn editor_trapping(on_term: &str) -> io::Result<Child> {
        use tokio::io::AsyncBufReadExt;
        let mut editor = tokio::process::Command::new("sh")
            .args([
                "-c",
                &format!("trap '{on_term}' TERM; echo ready; while :; do sleep 0.1; done"),
            ])
            .stdout(Stdio::piped())
            .kill_on_drop(true)
            .spawn()?;
        let Some(stdout) = editor.stdout.take() else {
            return Err(io::Error::other("no stdout"));
        };
        let mut ready = String::new();
        tokio::io::BufReader::new(stdout)
            .read_line(&mut ready)
            .await?;
        Ok(editor)
    }

    #[tokio::test]
    async fn an_editor_left_running_is_asked_to_end_then_reaped()
    -> Result<(), Box<dyn std::error::Error>> {
        let mut editor = tokio::time::timeout(LIMIT, editor_trapping("exit 3")).await??;
        tokio::time::timeout(LIMIT, stop_editor(&mut editor)).await?;
        let status = editor.try_wait()?;
        assert_eq!(
            status.and_then(|status| status.code()),
            Some(3),
            "SIGTERM first"
        );
        Ok(())
    }

    #[tokio::test]
    async fn an_editor_ignoring_sigterm_is_killed_then_reaped()
    -> Result<(), Box<dyn std::error::Error>> {
        use std::os::unix::process::ExitStatusExt;
        let mut editor = tokio::time::timeout(LIMIT, editor_trapping("")).await??;
        tokio::time::timeout(LIMIT, stop_editor(&mut editor)).await?;
        let status = editor.try_wait()?;
        assert_eq!(status.and_then(|status| status.signal()), Some(9));
        Ok(())
    }

    #[tokio::test]
    async fn a_burst_through_a_task_bus_loses_nothing_while_the_loop_draws()
    -> Result<(), Box<dyn std::error::Error>> {
        use crate::events::{Event, EventBus, Stage};
        use crate::tui::tasks::{BUS_CAPACITY, Msg, TaskId, forward};

        let mut terminal = Terminal::new(TestBackend::new(120, 40))?;
        let mut app = app();
        app.view = crate::tui::app::View::Pipeline;
        app.pipeline_task = Some(TaskId(1));
        app.pipeline.started(crate::cli::data::Command::Answers, 8);
        let bus = EventBus::with_capacity(BUS_CAPACITY);
        let (messages, mut inbox) = mpsc::unbounded_channel();
        forward(TaskId(1), bus.subscribe(), messages);
        let received = std::cell::Cell::new(0_usize);
        // Two bursts of 20 000 events, the size of a large tail read, each
        // followed by an await, as `watch` does between two reads.
        let publish = async {
            bus.publish(Event::StageStarted {
                stage: Stage::Answers,
                total: 40_000,
            });
            for burst in 0..2 {
                for n in 0..20_000 {
                    bus.publish(Event::ItemDone {
                        stage: Stage::Answers,
                        id: format!("{burst}-{n}"),
                        usage: None,
                        cost: None,
                        excluded: false,
                    });
                }
                while received.get() < 1 + (burst + 1) * 20_000 {
                    tokio::time::sleep(Duration::from_millis(1)).await;
                }
            }
            drop(bus);
        };
        let consume = async {
            while let Some(message) = inbox.recv().await {
                if let Msg::Lagged(_, skipped) = message {
                    return Err(format!("{skipped} events skipped"));
                }
                app.on_message(message);
                received.set(received.get() + 1);
                if received.get().is_multiple_of(5_000) {
                    terminal
                        .draw(|frame| ui::render(frame, &mut app))
                        .map_err(|error| error.to_string())?;
                }
            }
            Ok(received.get())
        };
        let ((), received) =
            tokio::time::timeout(LIMIT, async { tokio::join!(publish, consume) }).await?;
        assert_eq!(received?, 40_001);
        let row = app.pipeline.row(Stage::Answers);
        assert_eq!((row.finished, row.total), (40_000, 40_000));
        Ok(())
    }
}