vcon-server 0.4.5

Stores vCons encrypted at rest, on local disk or in an S3 bucket (as objects or Parquet files), and returns them to authorized readers.
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
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
//! The terminal UI's page, website/content/docs/tui.md, against the code:
//! its keys table, its client file table, its sizes and limits, each
//! message it quotes and each screen it shows. A page that says what the
//! code does not do, or leaves out a message the code can show, fails here.

use std::collections::BTreeSet;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::sync::Arc;

use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::crossterm::event::{KeyCode, KeyModifiers};
use time::OffsetDateTime;
use time::macros::datetime;

use super::client;
use super::keys::BINDINGS;
use super::screens::Screen;
use super::state::{Action, ApiError, Event, KeyInfo, Page, Row, State, View};
use super::view::{self, Theme};
use crate::api::Problem;
use crate::mcp::stdio;
use crate::secret_file::{self, Refusal};

const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);

/// A file of the repository, by its path from the root.
fn read(path: &str) -> String {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(path);
    std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
}

fn page() -> String {
    read("website/content/docs/tui.md")
}

/// The number signs a heading line starts with; 0 for any other line.
fn level(line: &str) -> usize {
    let signs = line.chars().take_while(|c| *c == '#').count();
    if signs > 0 && line.chars().nth(signs) == Some(' ') {
        signs
    } else {
        0
    }
}

/// The text under the heading `heading` (its line, with its number signs),
/// up to the next heading of its level or a higher one. Lines inside a code
/// block are never headings.
fn section(text: &str, heading: &str) -> String {
    let wanted = level(heading);
    let mut out = Vec::new();
    let mut inside = false;
    let mut fenced = false;
    for line in text.lines() {
        if line.trim_start().starts_with("```") {
            fenced = !fenced;
        }
        let here = if fenced { 0 } else { level(line) };
        if inside && here > 0 && here <= wanted {
            break;
        }
        if inside {
            out.push(line);
        }
        if !fenced && line == heading {
            inside = true;
        }
    }
    assert!(inside, "the page has the heading {heading:?}");
    out.join("\n")
}

/// The cells of a table row.
fn cells(line: &str) -> Vec<String> {
    line.trim()
        .trim_start_matches('|')
        .trim_end_matches('|')
        .split('|')
        .map(|cell| cell.trim().to_owned())
        .collect()
}

/// The rows of every table in `text` whose header starts with the cell
/// `first`: each row's cells, without the header and the rule under it.
fn table(text: &str, first: &str) -> Vec<Vec<String>> {
    let mut rows = Vec::new();
    let mut inside = false;
    for line in text.lines() {
        let line = line.trim();
        if !line.starts_with('|') {
            inside = false;
            continue;
        }
        let row = cells(line);
        if row.first().map(String::as_str) == Some(first) {
            inside = true;
        } else if inside && !row.iter().all(|cell| cell.chars().all(|c| c == '-')) {
            rows.push(row);
        }
    }
    rows
}

/// The text of the first code span in `cell`.
fn code_span(cell: &str) -> Option<&str> {
    let rest = cell.split_once('`')?.1;
    Some(rest.split_once('`')?.0)
}

/// The parts of a quoted message between its placeholders: `<reason>`,
/// `<path>` and the like, a lower-case word or words between angle
/// brackets, stand for any text.
fn fragments(quoted: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut rest = quoted;
    let mut part = String::new();
    while let Some((before, after)) = rest.split_once('<') {
        part.push_str(before);
        match after.split_once('>') {
            Some((name, tail))
                if !name.is_empty() && name.chars().all(|c| c.is_ascii_lowercase() || c == ' ') =>
            {
                out.push(std::mem::take(&mut part));
                rest = tail;
            }
            _ => {
                part.push('<');
                rest = after;
            }
        }
    }
    part.push_str(rest);
    out.push(part);
    out
}

/// Whether `said` holds the quoted message: each of its fragments, in
/// order.
fn holds(said: &str, quoted: &str) -> bool {
    let mut rest = said;
    for fragment in fragments(quoted) {
        match rest.split_once(fragment.as_str()) {
            Some((_, after)) => rest = after,
            None => return false,
        }
    }
    true
}

// The states the UI can be in, made by the state machine.

fn row(n: u16) -> Row {
    Row {
        uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16{n:04}"),
        stored_at: "2026-10-25T12:00:00Z".to_owned(),
        updated_at: "2026-10-25T12:30:00Z".to_owned(),
        version: format!("4f0c4b0a1d2e3f405162738495a6{n:04}"),
    }
}

fn connecting() -> State {
    State::new("https://vcon.example.com:8443", (80, 24)).0
}

fn keyed(tenant: Option<&str>, scopes: &[&str]) -> State {
    let mut state = connecting();
    state.step(
        Event::KeyInfo(Ok(KeyInfo {
            id: "0123456789abcdef".to_owned(),
            tenant: tenant.map(str::to_owned),
            scopes: scopes.iter().map(|scope| (*scope).to_owned()).collect(),
        })),
        NOW,
    );
    state
}

fn reader() -> State {
    keyed(Some("8c41f2d9a07e4b5c9d13e6f0a2b4c7d8"), &["read"])
}

fn listed(rows: u16, more: bool) -> State {
    let mut state = reader();
    state.step(
        Event::Page(Ok(Page {
            vcons: (0..rows).map(row).collect(),
            next: more.then(|| "cursor-2".to_owned()),
        })),
        NOW,
    );
    state
}

fn press(mut state: State, actions: &[Action]) -> State {
    for action in actions {
        state.step(Event::Action(*action), NOW);
    }
    state
}

/// The state at start when the server's answer for the key is `error`.
fn refused(error: ApiError) -> State {
    let mut state = connecting();
    state.step(Event::KeyInfo(Err(error)), NOW);
    state
}

/// The lines of the screen `state` is drawn as, without color.
fn frame(state: &State, columns: u16, lines: u16) -> Vec<String> {
    let mut terminal = Terminal::new(TestBackend::new(columns, lines)).expect("a terminal");
    terminal
        .draw(|frame| view::draw(frame, state, Theme { color: false }))
        .expect("a frame");
    let buffer = terminal.backend().buffer();
    (0..lines)
        .map(|y| (0..columns).map(|x| buffer[(x, y)].symbol()).collect())
        .collect()
}

/// What the screen says, as a reader reads it: its lines joined, so a
/// sentence wrapped over two lines is one sentence.
fn said(state: &State) -> String {
    frame(state, 80, 24)
        .iter()
        .map(|line| line.trim())
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// A certificate refusal rustls reports for a server certificate that is
/// marked as a certificate authority's.
#[derive(Debug)]
struct CaUsedAsEndEntity;

impl std::fmt::Display for CaUsedAsEndEntity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("a certificate authority's certificate")
    }
}

impl std::error::Error for CaUsedAsEndEntity {}

/// Every refusal of a server certificate the UI has words for.
fn certificate_refusals() -> Vec<String> {
    use rustls::CertificateError as Refused;
    [
        Refused::Other(rustls::OtherError(Arc::new(CaUsedAsEndEntity))),
        Refused::UnknownIssuer,
        Refused::NotValidForName,
        Refused::Expired,
        Refused::NotValidYet,
    ]
    .iter()
    .map(|error| {
        let advice = client::certificate_advice(error).expect("advice for this refusal");
        said(&refused(ApiError::Untrusted(advice.to_owned())))
    })
    .collect()
}

/// What the command writes to standard error, after `vcon-server: `, when
/// it cannot start: one entry for each way.
fn start_failures() -> Vec<String> {
    let dir = tempfile::tempdir().expect("temp dir");
    let at = |name: &str| dir.path().join(name);
    let file = |name: &str, bytes: &[u8], mode: u32| {
        let path = at(name);
        std::fs::write(&path, bytes).expect("write");
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).expect("chmod");
        path
    };
    let client_file = |text: &str| {
        let refused = stdio::parse_client(text).expect_err("a client file that is refused");
        format!("client file: {refused}").replace('\n', " ")
    };
    let token = |path: &Path| {
        stdio::token(path)
            .expect_err("a key file that is refused")
            .to_string()
    };
    let ca = |path: &Path| {
        stdio::https_client(Some(path))
            .expect_err("a CA file that is refused")
            .to_string()
    };
    let source = |text: &'static str, holding: &str| {
        text.lines()
            .find(|line| line.contains(holding))
            .unwrap_or_else(|| panic!("the source holds {holding:?}"))
            .trim()
            .to_owned()
    };
    let main = include_str!("../main.rs");
    vec![
        format!(
            "client file: {}",
            stdio::client_config(&at("missing.toml")).expect_err("no such file")
        ),
        client_file("url = \"http://vcon.example.com:8443\"\nkey_file = \"/k\"\n"),
        client_file("url = \"https://vcon.example.com:8443\"\nkey_file = \"/k\"\ntoken = \"t\"\n"),
        client_file("key_file = \"/k\"\n"),
        token(&at("missing.token")),
        token(&file("open.token", b"vcs_0011223344556677_secret\n", 0o644)),
        token(&file("empty.token", b"\n", 0o600)),
        token(&file("two.token", b"vcs_a vcs_b\n", 0o600)),
        token(&file("binary.token", &[0xff, 0xfe], 0o600)),
        token(dir.path()),
        secret_file::describe(
            "key_file",
            &at("other.token"),
            Refusal::Owner {
                uid: 1001,
                process: 1000,
            },
        ),
        ca(&at("missing.pem")),
        ca(&file("empty.pem", b"", 0o644)),
        super::require_terminal(false, true).expect_err("no input"),
        super::require_terminal(true, false).expect_err("no output"),
        super::require_terminal(false, false).expect_err("neither"),
        source(main, "memory cannot be locked: "),
        source(main, "core dumps cannot be turned off: "),
        source(main, "this build has no terminal UI: "),
        source(
            include_str!("../tui.rs"),
            "map_err(|e| format!(\"the terminal: ",
        ),
    ]
}

/// What the UI makes of the server's answer when the server refuses a
/// request with `problem`: the problem document the API sends, read by the
/// UI's own conversion.
fn answered(problem: Problem) -> ApiError {
    let body = serde_json::to_vec(&problem.document()).expect("JSON");
    client::answer::<KeyInfo>(problem.status().as_u16(), &body).expect_err("a refusal is not a key")
}

#[test]
fn a_refusal_is_shown_with_the_title_of_the_servers_problem_document() {
    assert_eq!(
        answered(Problem::Unavailable).to_string(),
        "the server answered 503 (The service cannot answer now)",
        "the status and the problem's title, not the name of its type"
    );
    assert_eq!(
        answered(Problem::Unauthorized).to_string(),
        "the server refused the key (401)",
        "a 401 has words of its own"
    );
}

#[test]
fn an_answer_with_no_problem_document_is_shown_by_its_status_alone() {
    let refused = client::answer::<KeyInfo>(404, b"").expect_err("not a key");
    assert_eq!(
        refused.to_string(),
        "the server answered 404",
        "what a url with a path gives: the server has no such route"
    );
    assert!(
        quoted_messages(&page()).contains(&refused.to_string()),
        "and the page has a row for it"
    );
}

/// What the screen says in each state in which something is wrong.
fn screen_failures() -> Vec<String> {
    let mut next_page_failed = press(listed(3, true), &[Action::More]);
    next_page_failed.step(Event::Page(Err(client::no_answer(client::TIMEOUT))), NOW);
    let mut gone = press(listed(3, false), &[Action::Open, Action::Refresh]);
    gone.step(
        Event::Page(Ok(Page {
            vcons: vec![row(7)],
            next: None,
        })),
        NOW,
    );
    let mut out = vec![
        said(&refused(client::no_answer(client::TIMEOUT))),
        said(&refused(ApiError::Unreachable(
            "error sending request for url (https://vcon.example.com:8443/key): client error (Connect): tcp connect error: Connection refused (os error 111)".to_owned(),
        ))),
        said(&refused(ApiError::Status(401, None))),
        said(&refused(ApiError::Status(404, None))),
        said(&refused(answered(Problem::Unavailable))),
        said(&refused(answered(Problem::AuditFailed))),
        said(&refused(ApiError::Malformed("expected value at line 1 column 1".to_owned()))),
        said(&keyed(None, &[])),
        said(&keyed(Some("8c41f2d9a07e4b5c9d13e6f0a2b4c7d8"), &["write"])),
        said(&next_page_failed),
        said(&gone),
        frame(&listed(3, false), 39, 8)
            .iter()
            .map(|line| line.trim())
            .filter(|line| !line.is_empty())
            .collect::<Vec<_>>()
            .join(" "),
    ];
    out.extend(certificate_refusals());
    out
}

/// What the screen says in each state in which nothing is wrong.
fn screen_states() -> Vec<String> {
    vec![
        said(&connecting()),
        said(&reader()),
        said(&listed(0, false)),
        said(&listed(3, false)),
        said(&listed(3, true)),
        said(&press(listed(3, true), &[Action::More])),
        said(&press(listed(3, false), &[Action::Open])),
        said(&press(listed(3, false), &[Action::Open, Action::Refresh])),
        said(&press(listed(3, false), &[Action::Help])),
    ]
}

/// The message each row of the page's troubleshooting tables quotes.
fn quoted_messages(page: &str) -> Vec<String> {
    table(&section(page, "## When it does not work"), "Message")
        .iter()
        .map(|row| {
            code_span(row.first().expect("a first cell"))
                .unwrap_or_else(|| panic!("the row {row:?} quotes its message as code"))
                .to_owned()
        })
        .collect()
}

// Messages.

#[test]
fn every_message_the_page_quotes_is_one_the_code_writes() {
    let written: Vec<String> = start_failures()
        .into_iter()
        .chain(screen_failures())
        .chain(screen_states())
        .collect();
    let quoted = quoted_messages(&page());
    assert!(
        quoted.len() >= 20,
        "the tables quote the messages: {}",
        quoted.len()
    );
    for message in quoted {
        assert!(
            written.iter().any(|said| holds(said, &message)),
            "the page quotes {message:?}, which the code does not write"
        );
    }
}

#[test]
fn every_start_failure_has_a_row_on_the_page() {
    let quoted = quoted_messages(&page());
    for failure in start_failures() {
        assert!(
            quoted.iter().any(|message| holds(&failure, message)),
            "no row of the page is for the start failure {failure:?}"
        );
    }
}

#[test]
fn every_failure_the_screen_shows_has_a_row_on_the_page() {
    let quoted = quoted_messages(&page());
    for failure in screen_failures() {
        assert!(
            quoted.iter().any(|message| holds(&failure, message)),
            "no row of the page is for the screen that says {failure:?}"
        );
    }
}

#[test]
fn each_certificate_refusal_has_a_row_of_its_own() {
    let quoted = quoted_messages(&page());
    let mut rows = BTreeSet::new();
    for refusal in certificate_refusals() {
        let row = quoted
            .iter()
            .find(|message| {
                message.starts_with("the server's certificate was refused: ")
                    && holds(&refusal, message)
            })
            .unwrap_or_else(|| panic!("no certificate row for {refusal:?}"));
        rows.insert(row.clone());
    }
    assert_eq!(rows.len(), 5, "five refusals, five rows: {rows:?}");
}

#[test]
fn every_row_says_the_cause_and_what_to_do() {
    for row in table(&section(&page(), "## When it does not work"), "Message") {
        assert_eq!(row.len(), 3, "message, cause, what to do: {row:?}");
        assert!(
            row.iter().all(|cell| !cell.is_empty()),
            "no empty cell: {row:?}"
        );
    }
}

#[test]
fn the_troubleshooting_is_grouped_by_where_the_message_appears() {
    let section = section(&page(), "## When it does not work");
    let groups: Vec<&str> = section.lines().filter(|line| level(line) == 3).collect();
    assert!(
        groups.len() >= 4,
        "the messages are in groups, each under a heading: {groups:?}"
    );
    let mut grouped = 0_usize;
    for group in groups {
        let rows = table(&self::section(&page(), group), "Message");
        assert!(
            !rows.is_empty() && rows.len() <= 8,
            "{group} holds a short table: {} rows",
            rows.len()
        );
        grouped = grouped.saturating_add(rows.len());
    }
    assert_eq!(
        grouped,
        table(&section, "Message").len(),
        "every row is in a group: no table stands before the first heading"
    );
}

#[test]
fn the_page_shows_the_two_lines_that_end_every_failure_on_the_screen() {
    let lines = frame(&refused(client::no_answer(client::TIMEOUT)), 80, 24);
    // The status line is first and the key hints are last; what the
    // failure says is between them.
    let said: Vec<&str> = lines
        .iter()
        .skip(1)
        .take(lines.len().saturating_sub(2))
        .map(|line| line.trim_end())
        .filter(|line| !line.is_empty())
        .collect();
    let last_two = said
        .rchunks(2)
        .next()
        .expect("a failure has at least two lines")
        .join("\n");
    assert!(
        last_two.starts_with("Press r to try again"),
        "what r and q do, then what r cannot do: {last_two}"
    );
    assert!(
        section(&page(), "## When it does not work").contains(&last_two),
        "the page shows them as the screen has them: {last_two}"
    );
}

#[test]
fn the_page_quotes_what_the_screen_says_in_each_state_that_is_not_a_failure() {
    let page = page();
    for words in [
        "Connecting to the server...",
        "Loading vCons...",
        "Reading the list again...",
        "Reading the next page...",
        "This tenant has no vCons.",
        "Content is not shown: this view lists metadata only.",
        "more on the server",
    ] {
        assert!(
            screen_states().iter().any(|said| said.contains(words)),
            "the code writes {words:?}"
        );
        assert!(page.contains(words), "the page quotes {words:?}");
    }
}

// Keys.

/// A key as the page writes it.
fn key_name(code: KeyCode, modifiers: KeyModifiers) -> String {
    let name = match code {
        KeyCode::Char(c) if modifiers == KeyModifiers::CONTROL => {
            return format!("Ctrl-{}", c.to_ascii_uppercase());
        }
        KeyCode::Char(c) => return format!("`{c}`"),
        KeyCode::Down => "Down",
        KeyCode::Up => "Up",
        KeyCode::Home => "Home",
        KeyCode::End => "End",
        KeyCode::PageUp => "PgUp",
        KeyCode::PageDown => "PgDn",
        KeyCode::Enter => "Enter",
        KeyCode::Esc => "Esc",
        KeyCode::Backspace => "Backspace",
        other => panic!("the page has no name for {other:?}"),
    };
    name.to_owned()
}

/// What a binding does, as the help view says it, without the other keys
/// the help view names in parentheses: the page's first column has them.
fn does(text: &str) -> &str {
    text.split_once(" (also ")
        .map_or(text, |(before, _)| before)
}

/// Whether `action` does anything in `view`: the state changes, or a
/// request is made. The list holds 30 vCons with more on the server, and
/// the eleventh is selected, so every movement has somewhere to go.
fn works(view: View, action: Action) -> bool {
    let list = press(listed(30, true), &[Action::Down; 10]);
    let state = match view {
        View::List => list,
        View::Detail => press(list, &[Action::Open]),
        View::Help => press(list, &[Action::Help]),
    };
    let mut after = state.clone();
    let asked = after.step(Event::Action(action), NOW);
    !asked.is_empty() || after != state
}

fn keys_table() -> Vec<Vec<String>> {
    table(&section(&page(), "### Keys"), "Key")
}

#[test]
fn the_keys_table_has_a_row_for_every_binding_with_every_key() {
    let rows = keys_table();
    assert_eq!(rows.len(), BINDINGS.len(), "one row for each binding");
    for (binding, row) in BINDINGS.iter().zip(&rows) {
        let keys: Vec<String> = binding
            .keys
            .iter()
            .map(|(code, modifiers)| key_name(*code, *modifiers))
            .collect();
        assert_eq!(
            row.first().map(String::as_str),
            Some(keys.join(", ").as_str()),
            "the keys of {:?}, in the order the help view lists the bindings",
            binding.action
        );
    }
}

#[test]
fn the_keys_table_says_what_the_help_view_says_each_key_does() {
    for (binding, row) in BINDINGS.iter().zip(&keys_table()) {
        assert_eq!(
            row.get(1).map(String::as_str),
            Some(does(binding.does)),
            "what {:?} does",
            binding.action
        );
    }
}

#[test]
fn the_keys_table_says_in_which_views_each_key_does_something() {
    for (binding, row) in BINDINGS.iter().zip(&keys_table()) {
        for (column, view) in [(2, View::List), (3, View::Detail), (4, View::Help)] {
            let wanted = if works(view, binding.action) {
                "yes"
            } else {
                "no"
            };
            assert_eq!(
                row.get(column).map(String::as_str),
                Some(wanted),
                "{:?} in the {view:?} view",
                binding.action
            );
        }
    }
}

#[test]
fn the_views_reader_knows_a_key_that_does_nothing_from_one_that_does() {
    assert!(works(View::List, Action::Open), "Enter opens a vCon");
    assert!(
        !works(View::Detail, Action::Open),
        "Enter does nothing in the detail view"
    );
    assert!(
        !works(View::List, Action::Back),
        "Esc does nothing in the list"
    );
    assert!(
        !works(View::Help, Action::Refresh),
        "help takes only the keys that close it and quit"
    );
    assert!(
        works(View::Detail, Action::More),
        "n reads on from the detail view"
    );
}

/// Each row of the page's table of last lines: the screen as the page
/// names it, and the states drawn as that screen.
fn last_line_screens() -> Vec<(&'static str, Vec<State>)> {
    let no_read = || keyed(Some("8c41f2d9a07e4b5c9d13e6f0a2b4c7d8"), &["write"]);
    let mut first_page_failed = reader();
    first_page_failed.step(Event::Page(Err(ApiError::Status(503, None))), NOW);
    vec![
        ("The list, with more on the server", vec![listed(3, true)]),
        ("The list, every vCon read", vec![listed(3, false)]),
        ("The list of one vCon", vec![listed(1, false)]),
        (
            "The list while the next page is read",
            vec![press(listed(3, true), &[Action::More])],
        ),
        (
            "A tenant with no vCons, or a failure that `r` can try again",
            vec![
                listed(0, false),
                refused(client::no_answer(client::TIMEOUT)),
                refused(ApiError::Status(401, None)),
                first_page_failed,
            ],
        ),
        (
            "`Connecting to the server...`, `Loading vCons...`, or a key that may not list",
            vec![connecting(), reader(), keyed(None, &[]), no_read()],
        ),
        (
            "The detail view",
            vec![press(listed(3, false), &[Action::Open])],
        ),
        (
            "The detail view of the only vCon",
            vec![press(listed(1, false), &[Action::Open])],
        ),
        (
            "The detail view while the list is read again",
            vec![press(listed(3, false), &[Action::Open, Action::Refresh])],
        ),
        ("Help", vec![press(listed(3, true), &[Action::Help])]),
    ]
}

#[test]
fn the_page_lists_the_last_line_of_each_screen_as_the_ui_draws_it() {
    let rows = table(&section(&page(), "### Read the screen"), "Screen");
    let screens = last_line_screens();
    assert_eq!(rows.len(), screens.len(), "one row for each screen");
    for (row, (name, states)) in rows.iter().zip(screens) {
        assert_eq!(
            row.first().map(String::as_str),
            Some(name),
            "the screens, in order"
        );
        for state in states {
            let lines = frame(&state, 80, 24);
            let footer = lines.last().expect("24 lines").trim_end();
            assert_eq!(
                row.get(1).map(String::as_str),
                Some(format!("`{footer}`").as_str()),
                "the last line of {name:?}"
            );
        }
    }
}

#[test]
fn the_page_says_that_a_key_not_in_the_table_does_nothing() {
    let page = page().replace('\n', " ");
    assert!(
        super::translate(&ratatui::crossterm::event::Event::Key(
            ratatui::crossterm::event::KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)
        ))
        .is_none(),
        "x is not bound"
    );
    assert!(
        page.contains("Any other key does nothing"),
        "and the page says so"
    );
}

#[test]
fn the_page_says_that_the_mouse_does_nothing() {
    use ratatui::crossterm::event::{Event as Input, MouseButton, MouseEvent, MouseEventKind};
    let click = Input::Mouse(MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: 3,
        row: 3,
        modifiers: KeyModifiers::NONE,
    });
    assert!(super::translate(&click).is_none(), "a click is no action");
    assert!(
        page().replace('\n', " ").contains("The mouse does nothing"),
        "and the page says so"
    );
}

// The client file.

fn client_table() -> Vec<Vec<String>> {
    table(&section(&page(), "### The client file"), "Key")
}

/// A client file with the example of each row of the page's table but
/// the row for `without`.
fn client_text(without: Option<&str>) -> String {
    client_table()
        .iter()
        .filter_map(|row| {
            let key = code_span(row.first()?)?;
            let example = code_span(row.get(4)?)?;
            (Some(key) != without).then(|| format!("{key} = {example}\n"))
        })
        .collect()
}

#[test]
fn the_client_file_table_names_the_keys_the_file_takes() {
    let keys: Vec<String> = client_table()
        .iter()
        .map(|row| {
            code_span(row.first().expect("a key"))
                .expect("as code")
                .to_owned()
        })
        .collect();
    assert_eq!(keys, ["url", "key_file", "ca"], "the three keys, in order");
}

#[test]
fn the_examples_in_the_client_file_table_make_a_file_the_command_takes() {
    let config = stdio::parse_client(&client_text(None)).expect("the examples parse");
    assert_eq!(
        config.url, "https://vcon.example.com:8443",
        "the address of the pages' server"
    );
    assert!(config.key_file.is_absolute(), "a full path: {config:?}");
    assert!(config.ca.is_some(), "the CA is in the table: {config:?}");
}

#[test]
fn the_client_file_table_says_which_keys_are_required() {
    for row in client_table() {
        let key = code_span(row.first().expect("a key")).expect("as code");
        let outcome = stdio::parse_client(&client_text(Some(key)));
        let required = match row.get(1).map(String::as_str) {
            Some("yes") => true,
            Some("no") => false,
            other => panic!("required is yes or no, not {other:?}"),
        };
        assert_eq!(
            outcome.is_err(),
            required,
            "a file without {key}: {outcome:?}"
        );
    }
}

#[test]
fn a_key_the_table_does_not_name_is_refused() {
    let text = format!("{}proxy = \"http://192.0.2.1:3128\"\n", client_text(None));
    let refused = stdio::parse_client(&text).expect_err("an unknown key");
    assert!(
        refused.to_string().contains("unknown field `proxy`"),
        "the file takes the table's keys only: {refused}"
    );
}

#[test]
fn the_page_says_the_url_has_no_path_and_what_one_gives() {
    assert_eq!(
        format!("{}/key", client::base("https://vcon.example.com:8443/mcp")),
        "https://vcon.example.com:8443/mcp/key",
        "a path in url goes before every request's path"
    );
    let row = client_table()
        .into_iter()
        .find(|row| row.first().map(String::as_str) == Some("`url`"))
        .expect("the url row");
    assert!(
        row.get(3).is_some_and(|cell| cell.contains("no path")),
        "the meaning of url says so: {row:?}"
    );
}

#[test]
fn a_trailing_slash_in_url_is_not_a_path() {
    assert_eq!(
        client::base("https://vcon.example.com:8443/"),
        "https://vcon.example.com:8443",
        "so the page's example may be written with or without it"
    );
}

#[test]
fn key_file_is_read_as_written_so_the_page_asks_for_a_full_path() {
    let config = stdio::parse_client(
        "url = \"https://vcon.example.com:8443\"\nkey_file = \"~/tui.token\"\n",
    )
    .expect("it parses");
    assert_eq!(
        config.key_file,
        Path::new("~/tui.token"),
        "a tilde is not the home directory"
    );
    let row = client_table()
        .into_iter()
        .find(|row| row.first().map(String::as_str) == Some("`key_file`"))
        .expect("the key_file row");
    assert!(
        row.get(3)
            .is_some_and(|cell| cell.contains("full path") && cell.contains("`~`")),
        "the meaning of key_file says so: {row:?}"
    );
}

// Sizes, limits and the environment.

/// The value of the row of the sizes table whose first cell is `name`.
fn limit(name: &str) -> String {
    table(&section(&page(), "### Sizes and limits"), "What")
        .into_iter()
        .find(|row| row.first().map(String::as_str) == Some(name))
        .and_then(|row| row.get(1).cloned())
        .unwrap_or_else(|| panic!("the sizes table has the row {name:?}"))
}

/// The fewest columns at which the list's header holds `column`.
fn first_width_with(column: &str) -> u16 {
    let state = listed(3, false);
    (40..=200)
        .find(|columns| {
            frame(&state, *columns, 24)
                .get(1)
                .is_some_and(|header| header.contains(column))
        })
        .unwrap_or_else(|| panic!("no width shows {column}"))
}

#[test]
fn the_page_states_the_vcons_read_at_a_time() {
    assert_eq!(
        limit("vCons read at a time"),
        client::PAGE.to_string(),
        "the page size the UI asks for"
    );
    assert!(
        client::page_path(None).ends_with(&format!("limit={}", client::PAGE)),
        "and it is what the request carries"
    );
}

#[test]
fn the_page_states_the_time_allowed_for_one_request() {
    assert_eq!(
        limit("Time allowed for one request"),
        format!("{} seconds", client::TIMEOUT.as_secs()),
        "the limit after which the screen says no answer"
    );
}

#[test]
fn the_page_states_the_smallest_terminal() {
    let state = listed(3, false);
    let too_small = |columns, lines| {
        frame(&state, columns, lines)
            .join(" ")
            .contains("Terminal too small")
    };
    assert!(!too_small(40, 8), "40 by 8 is drawn");
    assert!(too_small(39, 8), "one column fewer is not");
    assert!(too_small(40, 7), "one line fewer is not");
    assert_eq!(
        limit("Smallest terminal"),
        "40 columns by 8 lines",
        "as the page says"
    );
}

#[test]
fn the_page_states_the_width_from_which_each_column_is_shown() {
    for (row, column) in [
        ("Stored time shown from", "STORED"),
        ("Updated time shown from", "UPDATED"),
        ("Version shown from", "VERSION"),
    ] {
        assert_eq!(
            limit(row),
            format!("{} columns", first_width_with(column)),
            "the first width whose header holds {column}"
        );
    }
}

#[test]
fn the_uuid_is_shown_whole_at_the_smallest_width() {
    let lines = frame(&listed(3, false), 40, 8);
    assert!(
        lines.iter().any(|line| line.contains(&row(0).uuid)),
        "a uuid is never cut: {lines:?}"
    );
}

#[test]
fn the_environment_table_says_when_color_is_used() {
    let rows = table(&section(&page(), "### Environment"), "Variable");
    let names: Vec<&str> = rows
        .iter()
        .filter_map(|row| code_span(row.first()?))
        .collect();
    assert_eq!(
        names,
        ["NO_COLOR", "TERM"],
        "the two variables the UI reads"
    );
    assert!(
        view::theme(None, Some("xterm-256color")).color,
        "color by default"
    );
    assert!(
        !view::theme(Some("1"), Some("xterm-256color")).color,
        "NO_COLOR turns it off"
    );
    assert!(
        !view::theme(None, Some("dumb")).color,
        "TERM=dumb turns it off"
    );
    assert!(!view::theme(None, None).color, "no TERM turns it off");
}

#[test]
fn the_page_says_that_an_empty_no_color_does_not_count() {
    assert!(
        view::theme(Some(""), Some("xterm-256color")).color,
        "an empty NO_COLOR is not a request"
    );
    let rows = table(&section(&page(), "### Environment"), "Variable");
    let row = rows.first().expect("the NO_COLOR row");
    assert!(
        row.get(1).is_some_and(|cell| cell.contains("empty")),
        "and the row says so: {row:?}"
    );
}

#[test]
fn the_page_says_that_no_proxy_setting_is_used() {
    assert!(
        include_str!("../mcp/stdio.rs").contains("reqwest::Client::builder().no_proxy()"),
        "the client connects directly"
    );
    assert!(
        section(&page(), "### Environment").contains("`HTTPS_PROXY`"),
        "and the page names the variable a reader would try"
    );
}

#[test]
fn the_exit_codes_on_the_page_are_the_two_the_command_has() {
    let rows = table(&section(&page(), "### The command"), "Exit code");
    let codes: Vec<&str> = rows
        .iter()
        .filter_map(|row| row.first().map(String::as_str))
        .collect();
    assert_eq!(codes, ["0", "1"], "ExitCode::SUCCESS and ExitCode::FAILURE");
}

// Screens.

/// The screens in website/data/tui-screens.json: each name, with its
/// columns and its lines as text.
fn screens() -> Vec<(String, u64, Vec<String>)> {
    let data: serde_json::Value =
        serde_json::from_str(&read("website/data/tui-screens.json")).expect("JSON");
    data.as_object()
        .expect("an object")
        .iter()
        .map(|(name, screen)| {
            let lines = screen["lines"]
                .as_array()
                .expect("lines")
                .iter()
                .map(|line| {
                    line.as_array()
                        .expect("runs")
                        .iter()
                        .map(|run| run["text"].as_str().expect("text"))
                        .collect()
                })
                .collect();
            (
                name.clone(),
                screen["columns"].as_u64().expect("columns"),
                lines,
            )
        })
        .collect()
}

/// The screens `text` shows, with each one's label.
fn shown(text: &str) -> Vec<(String, String)> {
    text.split("<tui_screen name=\"")
        .skip(1)
        .map(|rest| {
            let (name, rest) = rest.split_once('"').expect("the name ends");
            let label = rest
                .split_once("label=\"")
                .and_then(|(_, rest)| rest.split_once('"'))
                .map_or("", |(label, _)| label);
            (name.to_owned(), label.to_owned())
        })
        .collect()
}

#[test]
fn every_screen_the_page_shows_is_one_the_ui_draws() {
    let drawn: BTreeSet<String> = screens().into_iter().map(|(name, _, _)| name).collect();
    for (name, _) in shown(&page()) {
        assert!(
            drawn.contains(&name),
            "the page shows the screen {name:?}, which tui-screens.json does not hold"
        );
    }
}

#[test]
fn every_screen_the_ui_draws_for_the_site_is_shown_on_the_page() {
    let shown: BTreeSet<String> = shown(&page()).into_iter().map(|(name, _)| name).collect();
    for (name, _, _) in screens() {
        assert!(
            shown.contains(&name),
            "tui-screens.json holds the screen {name:?}, which the page does not show"
        );
    }
}

#[test]
fn the_page_shows_each_view_and_each_state() {
    let shown: BTreeSet<String> = shown(&page()).into_iter().map(|(name, _)| name).collect();
    for wanted in [
        "list",
        "detail",
        "help",
        "empty",
        "not-connected",
        "narrow",
        "wide",
        "next-page-failed",
    ] {
        assert!(shown.contains(wanted), "the page shows {wanted}");
    }
}

#[test]
fn each_screen_is_shown_once_with_a_label_of_its_own() {
    // The page opens with the list, which its own section shows again:
    // no other screen is shown twice.
    let shown = shown(&screens_section());
    assert_eq!(
        self::shown(&page()).len(),
        shown.len().saturating_add(1),
        "the screens of the sections, and the one the page opens with"
    );
    let opening = self::shown(&page()).remove(0);
    assert_eq!(opening.0, "list", "the page opens with the list");
    assert!(
        shown.iter().all(|(_, label)| *label != opening.1),
        "and says it in other words than the list's section"
    );
    let names: BTreeSet<&str> = shown.iter().map(|(name, _)| name.as_str()).collect();
    let labels: BTreeSet<&str> = shown.iter().map(|(_, label)| label.as_str()).collect();
    assert_eq!(names.len(), shown.len(), "no screen twice");
    assert_eq!(labels.len(), shown.len(), "no label twice");
    for (name, label) in &shown {
        assert!(
            label.len() >= 40,
            "the label of {name} says what the screen shows: {label:?}"
        );
    }
}

#[test]
fn no_line_of_a_screen_is_wider_than_its_terminal() {
    for (name, columns, lines) in screens() {
        for line in lines {
            assert!(
                u64::try_from(line.chars().count()).expect("a count") <= columns,
                "{name}: {line:?} fits {columns} columns"
            );
        }
    }
}

#[test]
fn the_screens_have_no_tenant_or_address_that_is_not_an_example() {
    for (name, _, lines) in screens() {
        let first = lines.first().expect("a first line");
        assert!(
            name == "too-small" || first.contains("vcon.example.com:8443"),
            "{name}: the server is the pages' example: {first:?}"
        );
    }
}

#[test]
fn the_home_page_shows_a_screen_the_ui_draws() {
    let home = read("website/templates/index.html");
    let drawn: BTreeSet<String> = screens().into_iter().map(|(name, _, _)| name).collect();
    let names: Vec<String> = shown(&home).into_iter().map(|(name, _)| name).collect();
    assert_eq!(names, ["list"], "the home page shows the list");
    assert!(drawn.contains("list"), "which the UI draws");
}

// The page as a guide.

#[test]
fn the_page_opens_with_what_the_reader_gets() {
    let page = page();
    let body = page.splitn(3, "+++").nth(2).expect("a body").trim_start();
    let first = body.split("\n\n").next().expect("a first paragraph");
    assert!(
        first.starts_with("`vcon-server tui` shows"),
        "what it shows, first: {first:?}"
    );
    for word in ["data directory", "master key", "catalog"] {
        assert!(
            !first.contains(word),
            "what it does not open comes later: {first:?}"
        );
    }
    let screen = body.find("<tui_screen name=\"list\"").expect("the list");
    let heading = body.find("\n## ").expect("a first heading");
    assert!(screen < heading, "a real screen before the first heading");
}

#[test]
fn the_page_does_not_tell_the_reader_about_the_projects_tests() {
    let page = page().replace('\n', " ");
    for words in ["CI runs", "a test fails", "test fails when", "is tested"] {
        assert!(
            !page.contains(words),
            "the reader did not ask how the page is tested: {words:?}"
        );
    }
}

#[test]
fn the_page_says_who_should_use_another_tool_before_the_steps() {
    let page = page();
    let choose = page
        .find("\n## Is this the right tool")
        .expect("the section");
    let start = page.find("\n## Before you start").expect("the section");
    assert!(choose < start, "the choice comes before the set-up");
    let rows = table(&section(&page, "## Is this the right tool"), "To");
    assert!(rows.len() >= 6, "a row for each thing a reader may want");
    for row in rows {
        assert_eq!(row.len(), 4, "the task and three tools: {row:?}");
    }
}

#[test]
fn what_the_ui_does_not_do_is_a_no_in_the_first_table() {
    let rows = table(&section(&page(), "## Is this the right tool"), "To");
    let ui: Vec<&str> = rows
        .iter()
        .filter_map(|row| row.get(1).map(String::as_str))
        .collect();
    assert!(
        ui.iter().filter(|cell| **cell == "no").count() >= 4,
        "content, search, writes and the other views: {ui:?}"
    );
    assert!(
        ui.iter().all(|cell| *cell == "yes" || *cell == "no"),
        "yes or no, nothing between: {ui:?}"
    );
}

#[test]
fn before_you_start_is_a_table_that_says_where_each_thing_is_needed() {
    let rows = table(&section(&page(), "## Before you start"), "Have");
    assert!(rows.len() >= 5, "each thing to have ready: {}", rows.len());
    for row in rows {
        let place = row.get(1).map(String::as_str);
        assert!(
            matches!(
                place,
                Some("the server" | "the terminal's machine" | "both")
            ),
            "where it is needed: {row:?}"
        );
    }
}

#[test]
fn the_two_machine_set_up_is_a_procedure_of_its_own() {
    let page = page();
    let section = section(&page, "## Set it up for a terminal on another machine");
    let steps = section
        .lines()
        .filter(|line| {
            line.split_once(". ")
                .is_some_and(|(n, _)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
        })
        .count();
    assert!(steps >= 4, "numbered steps: {steps}");
    assert!(
        section.contains("On the server") && section.contains("On the terminal's machine"),
        "each step says where it is done"
    );
}

#[test]
fn there_is_a_section_for_each_thing_a_person_wants_to_do() {
    let section = section(&page(), "## Use it");
    for task in [
        "### Read the screen",
        "### Find a vCon",
        "### See when a vCon was stored",
        "### See whether more vCons exist",
        "### Read the next page",
        "### Read the list again",
        "### Use a vCon's uuid elsewhere",
        "### Get help",
        "### Leave",
    ] {
        assert!(
            section.lines().any(|line| line == task),
            "the page has {task:?}"
        );
    }
}

#[test]
fn no_command_on_the_page_is_skipped_and_none_needs_a_here_document() {
    let page = page();
    assert!(
        !page.contains("docs-test: skip"),
        "every command on the page is run"
    );
    assert!(!page.contains("<<"), "no command reads a here-document");
}

#[test]
fn the_token_is_not_kept_in_a_shell_variable() {
    let page = page();
    for line in page.lines().filter(|line| line.contains("key create")) {
        assert!(
            !line.contains("=$("),
            "the answer that holds the token goes to the file, not to a variable: {line}"
        );
    }
}

#[test]
fn the_page_says_how_to_take_the_access_away() {
    let section = section(&page(), "## Remove access");
    assert!(
        section.contains("key revoke"),
        "the key is revoked on the server"
    );
    assert!(
        section.contains("tui.token"),
        "and the token file is removed"
    );
}

#[test]
fn the_security_section_names_the_four_things_a_reader_asks() {
    let section = section(&page(), "## Security");
    let rows = table(&section, "Question");
    assert!(rows.len() >= 4, "token, certificate, content, records");
    for words in ["token", "certificate", "content", "audit"] {
        assert!(
            rows.iter()
                .any(|row| row.first().is_some_and(|cell| cell.contains(words))),
            "a row about the {words}"
        );
    }
}

// The other pages that name the terminal UI.

#[test]
fn the_command_line_page_names_the_client_file_keys_of_the_table() {
    let section = section(
        &read("website/content/docs/command-line.md"),
        "## The terminal UI",
    );
    for row in client_table() {
        let key = row.first().expect("a key");
        assert!(section.contains(key.as_str()), "it names {key}");
    }
    assert!(
        section.contains("@/docs/tui.md"),
        "and links to the terminal UI's page"
    );
}

#[test]
fn the_command_line_page_and_this_page_give_the_same_exit_codes() {
    let section = section(
        &read("website/content/docs/command-line.md"),
        "## The terminal UI",
    )
    .replace('\n', " ");
    assert!(
        section.contains("code 0 when the user quits") && section.contains("code 1 when"),
        "0 on quit and 1 on a failure to start"
    );
}

#[test]
fn every_page_that_names_the_command_links_to_its_page() {
    for (path, link) in [
        ("README.md", "https://vcon-server.com/docs/tui/"),
        ("website/content/docs/status.md", "@/docs/tui.md"),
        ("website/content/docs/how-to.md", "@/docs/tui.md"),
        ("website/content/docs/command-line.md", "@/docs/tui.md"),
        ("website/content/docs/lets-encrypt.md", "@/docs/tui.md"),
        ("website/content/docs/upgrading.md", "@/docs/tui.md"),
        ("website/templates/index.html", "@/docs/tui.md"),
        (
            "website/static/llms.txt",
            "https://vcon-server.com/docs/tui/",
        ),
    ] {
        let text = read(path);
        assert!(text.contains("tui"), "{path} names the terminal UI");
        assert!(text.contains(link), "{path} links to its page");
    }
}

#[test]
fn no_page_says_the_ui_shows_content() {
    for path in [
        "README.md",
        "website/content/_index.md",
        "website/content/docs/status.md",
        "website/content/docs/command-line.md",
    ] {
        let text = read(path).replace('\n', " ");
        assert!(
            text.contains("never its content")
                || text.contains("never a vCon's content")
                || text.contains("never asks for a vCon's content")
                || text.contains("never their content"),
            "{path} says the terminal UI never shows a vCon's content"
        );
    }
}

#[test]
fn the_indexes_describe_the_page_as_its_front_matter_does() {
    let page = page();
    let description = page
        .lines()
        .find_map(|line| line.strip_prefix("description = \""))
        .and_then(|rest| rest.strip_suffix('"'))
        .expect("a description");
    assert!(
        !description.contains("build"),
        "the build is not the reader's first question: {description}"
    );
    assert!(
        read("docs/README.md").contains(description),
        "docs/README.md has it word for word"
    );
    assert!(
        read("website/static/llms.txt").contains(description),
        "llms.txt has it word for word"
    );
}

// The readers above.

#[test]
fn the_section_reader_stops_at_the_next_heading_of_its_level() {
    let text = "# a\n## b\none\n### c\ntwo\n## d\nthree\n";
    assert_eq!(
        section(text, "## b"),
        "one\n### c\ntwo",
        "the subsection stays"
    );
    assert_eq!(section(text, "### c"), "two", "a higher heading ends it");
}

#[test]
fn the_section_reader_does_not_take_a_comment_in_a_code_block_for_a_heading() {
    let text = "## a\n```sh\n# not a heading\nls\n```\nafter\n## b\n";
    assert_eq!(
        section(text, "## a"),
        "```sh\n# not a heading\nls\n```\nafter",
        "the block is part of the section"
    );
}

#[test]
fn the_table_reader_takes_the_rows_under_the_header_it_is_given() {
    let text = "| Key | Does |\n|---|---|\n| `j` | down |\n\n| Other | x |\n|---|---|\n| a | b |\n";
    assert_eq!(
        table(text, "Key"),
        vec![vec!["`j`".to_owned(), "down".to_owned()]],
        "the other table is not read"
    );
}

#[test]
fn the_table_reader_reads_each_table_with_that_header() {
    let text = "| Message | Do |\n|---|---|\n| a | b |\n\ntext\n\n| Message | Do |\n|---|---|\n| c | d |\n";
    assert_eq!(table(text, "Message").len(), 2, "both tables' rows");
}

#[test]
fn a_placeholder_stands_for_any_text() {
    assert!(
        holds(
            "key_file /home/a/t: holds no single token",
            "key_file <path>: holds no single token"
        ),
        "the path differs from reader to reader"
    );
    assert!(
        !holds(
            "key_file /home/a/t: gone",
            "key_file <path>: holds no single token"
        ),
        "the words around it must be there"
    );
}

#[test]
fn the_fragments_of_a_message_are_found_in_order() {
    assert!(holds("a then b", "a <x> b"), "a before b");
    assert!(!holds("b then a", "a <x> b"), "not b before a");
}

#[test]
fn an_angle_bracket_that_is_not_a_placeholder_is_text() {
    assert_eq!(
        fragments("a < b and <Name> and <ok>"),
        ["a < b and <Name> and ", ""],
        "only a lower-case word between brackets is a placeholder"
    );
}

#[test]
fn a_message_without_a_placeholder_is_one_fragment() {
    assert_eq!(
        fragments("this key lacks the read scope"),
        ["this key lacks the read scope"],
        "the whole message"
    );
}

#[test]
fn the_code_span_reader_takes_the_first_span() {
    assert_eq!(code_span("`url` and `ca`"), Some("url"), "the first one");
    assert_eq!(code_span("no code"), None, "none");
}

#[test]
fn the_screen_reader_finds_names_and_labels() {
    let text = "{{ <tui_screen name=\"list\" label=\"The list.\" /> }} and {{ <tui_screen name=\"help\" label={x.l} /> }}";
    assert_eq!(
        shown(text),
        [
            ("list".to_owned(), "The list.".to_owned()),
            ("help".to_owned(), String::new())
        ],
        "a label that is not text is empty"
    );
}

// Every screen in the code's list (`Screen::ALL`) is on the page.

/// The section of the page that holds one section for each screen.
fn screens_section() -> String {
    section(&page(), "## Screens")
}

/// The section of `screen`.
fn screen_section(screen: Screen) -> String {
    section(&screens_section(), &format!("### {}", screen.title()))
}

/// The anchor the site gives a heading: lower case, with one hyphen for
/// each run of other characters.
fn anchor(title: &str) -> String {
    let mut out = String::new();
    for c in title.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_lowercase());
        } else if !out.ends_with('-') {
            out.push('-');
        }
    }
    out.trim_matches('-').to_owned()
}

/// The data file's entry for each screen name.
fn screen_data() -> serde_json::Map<String, serde_json::Value> {
    serde_json::from_str::<serde_json::Value>(&read("website/data/tui-screens.json"))
        .expect("JSON")
        .as_object()
        .expect("an object")
        .clone()
}

/// What a press of `action` does to `state`, apart from clearing the
/// notice, which every key does: whether the state changed or a request
/// was made.
fn does_something(state: &State, action: Action) -> bool {
    let mut after = state.clone();
    let asked = after.step(Event::Action(action), NOW);
    after.notice.clone_from(&state.notice);
    !asked.is_empty() || after != *state
}

const MOVES: [Action; 6] = [
    Action::Up,
    Action::Down,
    Action::Top,
    Action::Bottom,
    Action::PageUp,
    Action::PageDown,
];

#[test]
fn the_code_lists_25_screens_with_a_name_and_a_title_each() {
    let names: BTreeSet<&str> = Screen::ALL.iter().map(|s| s.name()).collect();
    let titles: BTreeSet<&str> = Screen::ALL.iter().map(|s| s.title()).collect();
    let anchors: BTreeSet<String> = Screen::ALL.iter().map(|s| anchor(s.title())).collect();
    assert_eq!(Screen::ALL.len(), 25, "the screens the UI can draw");
    assert_eq!(names.len(), 25, "a name each");
    assert_eq!(titles.len(), 25, "a title each");
    assert_eq!(anchors.len(), 25, "and a link target each");
}

#[test]
fn the_list_of_screens_holds_every_view() {
    for view in [View::List, View::Detail, View::Help] {
        assert!(
            Screen::ALL.iter().any(|screen| screen.view() == view),
            "a screen of the {view:?} view"
        );
    }
}

#[test]
fn every_screen_in_the_code_has_a_section_on_the_page() {
    let headings: Vec<String> = screens_section()
        .lines()
        .filter(|line| level(line) == 3)
        .map(|line| line.trim_start_matches("### ").to_owned())
        .collect();
    let titles: Vec<&str> = Screen::ALL.iter().map(|s| s.title()).collect();
    assert_eq!(
        headings, titles,
        "one section for each screen of Screen::ALL, in its order, and no other"
    );
}

#[test]
fn every_screen_in_the_code_is_drawn_in_the_data_file_and_no_other_is() {
    let drawn: Vec<String> = screen_data().keys().cloned().collect();
    let names: BTreeSet<&str> = Screen::ALL.iter().map(|s| s.name()).collect();
    let names: Vec<&str> = names.into_iter().collect();
    assert_eq!(
        drawn, names,
        "tui-screens.json holds the screens of Screen::ALL"
    );
}

#[test]
fn each_screens_section_draws_that_screen_and_no_other() {
    for screen in Screen::ALL {
        let names: Vec<String> = shown(&screen_section(screen))
            .into_iter()
            .map(|(name, _)| name)
            .collect();
        assert_eq!(
            names,
            [screen.name()],
            "the section {:?} shows its own screen",
            screen.title()
        );
    }
}

#[test]
fn each_screens_section_lists_the_keys_of_that_screen() {
    for screen in Screen::ALL {
        let text = screen_section(screen);
        let listed: Vec<&str> = text
            .split("<tui_keys name=\"")
            .skip(1)
            .filter_map(|rest| rest.split('"').next())
            .collect();
        assert_eq!(
            listed,
            [screen.name()],
            "the section {:?} lists its own keys",
            screen.title()
        );
    }
}

#[test]
fn the_keys_the_site_lists_for_a_screen_are_the_bindings_that_act_there() {
    let data = screen_data();
    for screen in Screen::ALL {
        let listed: Vec<(String, String)> = data[screen.name()]["keys"]
            .as_array()
            .unwrap_or_else(|| panic!("{} has keys", screen.name()))
            .iter()
            .map(|key| {
                (
                    key["key"].as_str().expect("a key").to_owned(),
                    key["does"].as_str().expect("what it does").to_owned(),
                )
            })
            .collect();
        let state = screen.state();
        let acting: Vec<(String, String)> = BINDINGS
            .iter()
            .filter(|binding| state.acts(binding.action))
            .map(|binding| (binding.label.to_owned(), binding.does.to_owned()))
            .collect();
        assert_eq!(listed, acting, "the keys of {}", screen.name());
    }
}

#[test]
fn a_key_listed_for_a_screen_does_something_there_and_no_other_key_does() {
    for screen in Screen::ALL {
        let state = screen.state();
        let listed: Vec<Action> = screen.keys().iter().map(|b| b.action).collect();
        let can_move = MOVES.iter().any(|action| does_something(&state, *action));
        for binding in &BINDINGS {
            let action = binding.action;
            // A key that moves is listed where the selection can move,
            // also when it is at the end that key moves toward.
            let does = if MOVES.contains(&action) {
                can_move
            } else {
                does_something(&state, action)
            };
            assert_eq!(
                listed.contains(&action),
                does,
                "{}: {action:?} is listed exactly when a press does something",
                screen.name()
            );
        }
    }
}

#[test]
fn quit_and_help_are_listed_for_every_screen() {
    for screen in Screen::ALL {
        let labels: Vec<&str> = screen.keys().iter().map(|b| b.label).collect();
        assert!(labels.contains(&"q"), "{}: q quits", screen.name());
        assert!(labels.contains(&"?"), "{}: ? is help", screen.name());
    }
}

#[test]
fn the_waiting_screens_list_help_and_quit_only() {
    for screen in [Screen::Connecting, Screen::Loading] {
        let labels: Vec<&str> = screen.keys().iter().map(|b| b.label).collect();
        assert_eq!(labels, ["?", "q"], "{}", screen.name());
    }
}

#[test]
fn the_help_screen_lists_the_keys_that_close_it_and_quit() {
    let labels: Vec<&str> = Screen::Help.keys().iter().map(|b| b.label).collect();
    assert_eq!(labels, ["Esc", "?", "q"], "nothing else acts in help");
}

#[test]
fn a_key_that_may_not_list_has_no_refresh_and_other_failures_have() {
    for (screen, wanted) in [
        (Screen::OperatorKey, false),
        (Screen::NoReadScope, false),
        (Screen::NotConnected, true),
        (Screen::RefusedKey, true),
        (Screen::RefusedCertificate, true),
        (Screen::ServerError, true),
        (Screen::DetailFailed, true),
        (Screen::NextPageFailed, true),
    ] {
        let labels: Vec<&str> = screen.keys().iter().map(|b| b.label).collect();
        assert_eq!(labels.contains(&"r"), wanted, "{}: r", screen.name());
    }
}

#[test]
fn the_failure_screens_are_the_ones_that_say_something_failed() {
    let failures: Vec<&str> = Screen::ALL
        .iter()
        .filter(|screen| screen.failure())
        .map(|screen| screen.name())
        .collect();
    assert_eq!(
        failures,
        [
            "next-page-failed",
            "not-connected",
            "refused-key",
            "refused-certificate",
            "operator-key",
            "no-read-scope",
            "server-error",
            "detail-failed"
        ],
        "a list that could not be read, or a notice above the keys"
    );
}

#[test]
fn each_failure_screens_section_says_what_to_do() {
    for screen in Screen::ALL {
        let text = screen_section(screen);
        let needs = screen.failure() || matches!(screen, Screen::DetailGone | Screen::TooSmall);
        assert_eq!(
            text.contains("**What to do.**"),
            needs,
            "{:?}: a failure says what to do, and no other screen needs to",
            screen.title()
        );
    }
}

#[test]
fn each_screens_section_says_what_it_shows_and_how_to_get_there_and_leave() {
    for screen in Screen::ALL {
        let text = screen_section(screen);
        for part in ["**When.**", "**Shows.**", "**Leave.**"] {
            let said = text
                .split(part)
                .nth(1)
                .map_or("", |rest| rest.split("\n\n").next().unwrap_or(""));
            assert!(
                said.trim().len() >= 20,
                "{:?} has {part} with a sentence after it: {said:?}",
                screen.title()
            );
        }
    }
}

#[test]
fn each_failure_screens_section_quotes_what_the_screen_says() {
    for screen in Screen::ALL.into_iter().filter(|screen| screen.failure()) {
        let state = screen.state();
        let said = match (&state.listing, &state.notice) {
            (_, Some(notice)) => notice.clone(),
            (super::state::Listing::Failed(why), None) => why.clone(),
            other => panic!("{} is no failure: {other:?}", screen.name()),
        };
        let quoted = said.split(": ").next().expect("a first part");
        assert!(
            screen_section(screen).replace('\n', " ").contains(quoted),
            "{:?} quotes {quoted:?}",
            screen.title()
        );
    }
}

#[test]
fn the_table_at_the_top_links_every_screen_in_order() {
    let rows = table(&section(&page(), "## Every screen"), "Screen");
    assert_eq!(rows.len(), Screen::ALL.len(), "one row for each screen");
    for (row, screen) in rows.iter().zip(Screen::ALL) {
        assert_eq!(
            row.first().map(String::as_str),
            Some(format!("[{}](#{})", screen.title(), anchor(screen.title())).as_str()),
            "the screen, as a link to its section"
        );
        assert!(
            row.get(1).is_some_and(|when| when.len() >= 20),
            "{:?} says when it appears: {row:?}",
            screen.title()
        );
    }
}

#[test]
fn the_table_of_screens_stands_before_the_first_step() {
    let page = page();
    let table = page
        .find("\n## Every screen\n")
        .expect("the table's heading");
    let steps = page.find("\n## Quick start").expect("the first steps");
    assert!(table < steps, "a reader meets the list of screens first");
}

#[test]
fn the_layout_screens_are_drawn_at_their_widths() {
    let data = screen_data();
    for (screen, columns) in [
        (Screen::Wide, 120),
        (Screen::Narrow, 60),
        (Screen::Narrowest, 40),
        (Screen::TooSmall, 36),
        (Screen::List, 80),
    ] {
        assert_eq!(
            data[screen.name()]["columns"],
            columns,
            "{} is drawn in {columns} columns",
            screen.name()
        );
        assert!(
            screen_section(screen).contains(&columns.to_string()),
            "and its section names the width"
        );
    }
}

#[test]
fn the_anchor_of_a_title_is_as_the_site_makes_it() {
    assert_eq!(anchor("The list"), "the-list", "spaces");
    assert_eq!(
        anchor("A terminal of 120 columns"),
        "a-terminal-of-120-columns",
        "digits stay"
    );
    assert_eq!(anchor("Help"), "help", "one word");
}

#[test]
fn a_screen_added_to_the_code_without_a_section_would_be_found() {
    // The reader of sections fails on a heading the page lacks: this is
    // what refuses a screen that is in Screen::ALL and not on the page.
    let refused =
        std::panic::catch_unwind(|| section(&screens_section(), "### A screen nobody wrote about"));
    assert!(refused.is_err(), "a title with no section is a failure");
}