drawbar 0.7.0

Your Nord's sounds, in a window: browse, edit and send programs, samples and pianos, in the browser or on the desktop
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
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
//! The operations, run against whichever transport the target supplies.
//!
//! Everything here is generic over [`Transport`], so the browser and the desktop run
//! the same code and only the spawn glue is cfg'd.
//!
//! ⚠️ Every operation attempts explicit session cleanup, including after an error.
//! [`Device::read`] and [`Device::destructive`] own that contract here.

use std::num::NonZeroU32;
use std::sync::mpsc::Sender;
use std::time::Duration;

use eframe::egui;
use nord_usb::device::Device;
use nord_usb::session::ReadWrite;
use nord_usb::transport::Transport;
use nord_usb::wire::{AllocationUnit, Bank, Dependency, ProgramInfo};
use nord_usb::{op, Error, Location, ObjectClass, Session};

use super::{DeviceCmd, DeviceEvent, Outgoing, Partition};
use crate::strings::shown;
use crate::workspace::Origin;

/// The event channel back to the UI thread, with the repaint that makes an event
/// visible before the next input arrives.
#[derive(Clone)]
pub struct Emit {
    tx: Sender<DeviceEvent>,
    ctx: egui::Context,
}

impl Emit {
    pub fn new(tx: Sender<DeviceEvent>, ctx: egui::Context) -> Emit {
        Emit { tx, ctx }
    }

    pub fn send(&self, event: DeviceEvent) {
        let _ = self.tx.send(event);
        self.ctx.request_repaint();
    }
}

/// Whether the worker keeps its transport after this command, and why it does not.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Flow {
    Continue,
    /// The operator asked for it back.
    Released,
    /// The byte pipe failed, so there is nothing on the other end of it any more.
    Lost,
}

/// A device status is a reply; only transport failure means detachment.
fn hung_up(e: &Error) -> bool {
    matches!(e, Error::Transport(_))
}

/// Report the classes the instrument declares, from its own partition table.
///
/// The first thing a connection does, because nothing above this can ask for a class
/// before it knows the instrument has one. The table is read once and kept, so every
/// later operation is answered out of what this read.
pub async fn announce<T: Transport>(device: &mut Device<T>, emit: &Emit) -> Flow {
    let rows = match device.geometry().await {
        Ok(geometry) => geometry
            .entries()
            .map(|(partition, _)| Partition {
                class: ObjectClass::from_raw(partition.index),
                name: partition.name.clone(),
                native: partition.native,
                unit: partition.allocation_unit().ok(),
            })
            .collect(),
        Err(e) => {
            let lost = hung_up(&e);
            emit.send(DeviceEvent::OpFailed(format!("partitions: {e}")));
            return match lost {
                true => Flow::Lost,
                false => Flow::Continue,
            };
        }
    };
    emit.send(DeviceEvent::Partitions(rows));
    Flow::Continue
}

/// Turn an error into the sentence for it, noting on the way whether the instrument is
/// still there. `at` is the slot the operation was aimed at, where it had one.
fn spoil(gone: &mut bool, at: Option<Location>) -> impl FnOnce(Error) -> String + '_ {
    move |e| {
        *gone |= hung_up(&e);
        match at {
            Some(at) => explain(e, at),
            None => e.to_string(),
        }
    }
}

/// Run one command to completion.
///
/// Emits exactly one [`DeviceEvent::Started`] and one [`DeviceEvent::Finished`], so the
/// UI's in-flight marker cannot be left set by an operation that failed halfway, and at
/// most one [`DeviceEvent::OpOk`] or [`DeviceEvent::OpFailed`]: each is one outcome of
/// one command, and a second would be put against a second entry of the send queue.
/// Steps within a command speak through [`DeviceEvent::Note`].
pub async fn run<T: Transport>(device: &mut Device<T>, cmd: DeviceCmd, emit: &Emit) -> Flow {
    if matches!(cmd, DeviceCmd::Disconnect) {
        return Flow::Released;
    }
    let what = cmd.label();
    emit.send(DeviceEvent::Started(what.clone()));

    let mut gone = false;
    let result = execute(device, cmd, emit, &mut gone).await;

    // State read during this command may already be stale, even when it failed.
    if device.take_changed() {
        emit.send(DeviceEvent::InstrumentChanged);
    }
    match result {
        Ok(Some(note)) => emit.send(DeviceEvent::OpOk(note)),
        Ok(None) => {}
        Err(e) => emit.send(DeviceEvent::OpFailed(format!("{what}: {e}"))),
    }
    emit.send(DeviceEvent::Finished);
    match gone {
        true => Flow::Lost,
        false => Flow::Continue,
    }
}

/// The command bodies. `Ok(Some(note))` is a line for the log; `Ok(None)` means the
/// command's own event already said everything.
async fn execute<T: Transport>(
    device: &mut Device<T>,
    cmd: DeviceCmd,
    emit: &Emit,
    gone: &mut bool,
) -> Result<Option<String>, String> {
    match cmd {
        // Handled by `run`; the transport is closed by the caller, which owns it.
        DeviceCmd::Disconnect => Ok(None),

        DeviceCmd::ScanBank { class, bank } => {
            let slots = scan_bank(device, class, bank)
                .await
                .map_err(spoil(gone, None))?;
            let filled = slots.iter().filter(|s| s.is_some()).count();
            let note = format!(
                "bank {bank}: {filled} of {} slots hold something",
                slots.len()
            );
            emit.send(DeviceEvent::BankScanned { class, bank, slots });
            Ok(Some(note))
        }

        DeviceCmd::ScanClass { class } => {
            let walked = scan_class(device, class, emit)
                .await
                .map_err(spoil(gone, None))?;
            Ok(Some(format!(
                "{}: {} banks, {} items, {}, one session",
                class.label(),
                walked.banks,
                walked.items,
                walked.how,
            )))
        }

        DeviceCmd::SlotInfo { class, at } => {
            let info = match slot_info(device, class, at).await {
                Ok(info) => Some(info),
                // Status 1 is a vacant slot, not a failure.
                Err(Error::DeviceStatus(1)) => None,
                Err(e) => return Err(spoil(gone, Some(at))(e)),
            };
            emit.send(DeviceEvent::SlotInfo { class, at, info });
            Ok(None)
        }

        DeviceCmd::Deps { class, at } => {
            let deps = dependencies(device, class, at)
                .await
                .map_err(spoil(gone, Some(at)))?;
            let note = format!("{}: {} dependencies", shown(at), deps.len());
            emit.send(DeviceEvent::Deps { class, at, deps });
            Ok(Some(note))
        }

        DeviceCmd::Get { class, at, why } => {
            let (info, bytes) = match read_object(device, class, at).await {
                Ok(read) => read,
                // Status 1 is a vacant slot, not a failure.
                Err(Error::DeviceStatus(1)) => {
                    emit.send(DeviceEvent::Vacant { class, at, why });
                    return Ok(None);
                }
                Err(e) => return Err(spoil(gone, Some(at))(e)),
            };
            let note = format!(
                "read {:?} from {} ({} bytes)",
                info.name,
                shown(at),
                bytes.len()
            );
            emit.send(DeviceEvent::Got {
                name: entity_name(&info),
                origin: Origin::Device { class, at },
                bytes,
                why,
            });
            Ok(Some(note))
        }

        DeviceCmd::Put {
            id,
            class,
            at,
            name,
            bytes,
        } => {
            let note = put_one(device, class, at, &name, bytes.clone(), emit, gone)
                .await
                .map_err(spoil(gone, Some(at)))??;
            // Nothing is owed to the instrument until this session has closed.
            emit.send(DeviceEvent::Sent {
                id,
                class,
                at,
                bytes,
            });
            Ok(Some(note))
        }

        DeviceCmd::SendAll { class, items } => send_all(device, class, items, emit, gone).await,

        DeviceCmd::Select { class, at } => {
            select(device, class, at)
                .await
                .map_err(spoil(gone, Some(at)))?;
            Ok(Some(format!("selected {} on the instrument", shown(at))))
        }

        DeviceCmd::Rename { class, at, name } => {
            rename(device, class, at, &name)
                .await
                .map_err(spoil(gone, Some(at)))?;
            Ok(Some(format!("renamed {} to {name:?}", shown(at))))
        }

        DeviceCmd::Move { class, from, to } => {
            move_object(device, class, from, to)
                .await
                .map_err(spoil(gone, Some(from)))?;
            Ok(Some(format!("moved {} -> {}", shown(from), shown(to))))
        }

        DeviceCmd::Duplicate { class, from, to } => {
            duplicate(device, class, from, to)
                .await
                .map_err(spoil(gone, Some(from)))?;
            Ok(Some(format!("duplicated {} -> {}", shown(from), shown(to))))
        }

        DeviceCmd::Delete { class, at } => {
            delete(device, class, at)
                .await
                .map_err(spoil(gone, Some(at)))?;
            Ok(Some(format!("deleted {}", shown(at))))
        }
    }
}

/// Replace a slot inside the caller's session. The address is the caller's to check
/// against the geometry first; this one sends frames.
///
/// ⚠️ An occupant is held in memory and restored or emitted as [`DeviceEvent::Rescued`].
async fn put<T: Transport>(
    s: &mut Session<'_, T, ReadWrite>,
    unit: AllocationUnit,
    at: Location,
    what: &str,
    bytes: Vec<u8>,
    emit: &Emit,
    gone: &mut bool,
) -> Result<Result<String, String>, Error> {
    let class = s.class();
    let timestamp = unix_now()?;

    let existing = match op::info(s, at).await {
        Ok(info) => Some(info),
        Err(Error::DeviceStatus(1)) => None,
        Err(e) => return Ok(Err(spoil(gone, Some(at))(e))),
    };
    // Confirmed on hardware.
    // Library slots take their name from `BEGIN_WRITE`; buffer classes discard it.
    let write_name = slot_label(what)
        .or_else(|| existing.as_ref().map(|info| info.name.clone()))
        .unwrap_or_default();

    // Nothing is deleted until the backup is in hand.
    let backup = match &existing {
        Some(_) => match op::read_program(s, at).await {
            Ok(file) => Some(file),
            Err(e) => {
                return Ok(Err(format!(
                    "could not read {} back before replacing it, so it was left alone: {}",
                    shown(at),
                    spoil(gone, Some(at))(e)
                )))
            }
        },
        None => None,
    };

    if backup.is_some() && !class.overwrites_in_place() {
        emit.send(DeviceEvent::Note(format!(
            "deleting {} to make room",
            shown(at)
        )));
        if let Err(e) = op::delete(s, at).await {
            return Ok(Err(format!(
                "deleting {}: {}",
                shown(at),
                spoil(gone, Some(at))(e)
            )));
        }
    }

    let written = op::write(s, unit, at, &bytes, &write_name, timestamp).await;

    Ok(match (written, backup) {
        (Ok(()), _) => Ok(wrote(class, at, what, &write_name)),
        (Err(e), None) => Err(spoil(gone, Some(at))(e)),
        // Restore the occupant before reporting the original error.
        (Err(e), Some(backup)) => {
            emit.send(DeviceEvent::Note(format!(
                "the write failed and {}; putting the original back",
                aftermath(class, at)
            )));
            let restore_name = existing
                .as_ref()
                .map(|info| info.name.as_str())
                .unwrap_or_default();
            match op::write(s, unit, at, &backup, restore_name, timestamp).await {
                Ok(()) => Err(format!(
                    "{e} ({} was restored, and is unchanged)",
                    shown(at)
                )),
                Err(restore) => {
                    *gone |= hung_up(&restore);
                    let name = rescue_name(at, &backup);
                    emit.send(DeviceEvent::Rescued {
                        at,
                        name,
                        bytes: backup,
                    });
                    Err(format!(
                        "{e} (restoring failed as well: {restore}); {}, and its former \
                         contents are now in the local list as a rescued entity — \
                         put it back",
                        aftermath(class, at)
                    ))
                }
            }
        }
    })
}

fn aftermath(class: ObjectClass, at: Location) -> String {
    match class.overwrites_in_place() {
        true => format!("{} may hold a partly written body", shown(at)),
        false => format!("{} is empty", shown(at)),
    }
}

/// Report a name only for classes that store one.
fn wrote(class: ObjectClass, at: Location, what: &str, name: &str) -> String {
    let wrote = format!("wrote {what} -> {}", shown(at));
    match class.names_its_slots() && !name.is_empty() {
        true => format!("{wrote}, named {name:?}"),
        false => wrote,
    }
}

/// Strip the format suffix from a local label, preserving the operator's text.
/// Returns `None` rather than sending a blank name.
fn slot_label(name: &str) -> Option<String> {
    // Application bound; the instrument's maximum is unknown.
    const LONGEST: usize = 64;

    let mut label = name.trim();
    if let Some((stem, tag)) = label.rsplit_once('.') {
        // A format tag, not a name that happens to hold a dot: `Bass 2.0` keeps its `0`.
        let is_tag = (2..=5).contains(&tag.len())
            && tag.chars().all(|c| c.is_ascii_alphanumeric())
            && tag.chars().any(|c| c.is_ascii_alphabetic());
        if is_tag && !stem.trim().is_empty() {
            label = stem;
        }
    }
    let label = label.trim();
    if label.is_empty() {
        return None;
    }
    // A truncated UTF-8 name must still end on a character boundary.
    let end = (0..=LONGEST.min(label.len()))
        .rev()
        .find(|end| label.is_char_boundary(*end))?;
    Some(label[..end].trim_end().to_string())
}

async fn put_one<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
    what: &str,
    bytes: Vec<u8>,
    emit: &Emit,
    gone: &mut bool,
) -> Result<Result<String, String>, Error> {
    let geometry = device.geometry().await?;
    if let Some(why) = geometry.check_address(class, at)? {
        return Ok(Err(format!("{}: {why}", shown(at))));
    }
    let unit = geometry.allocation_unit(class)?;
    device
        .destructive(class, async |s| {
            put(s, unit, at, what, bytes, emit, gone).await
        })
        .await
}

/// Send a batch until its first refusal; completed writes remain committed.
async fn send_all<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    items: Vec<Outgoing>,
    emit: &Emit,
    gone: &mut bool,
) -> Result<Option<String>, String> {
    let total = items.len();
    let mut done = 0;
    let outcome = batch(device, class, &items, total, &mut done, emit, gone).await;
    let refusal = outcome.map_err(spoil(gone, None))?;
    match refusal {
        None => Ok(Some(format!(
            "wrote {done} of {total} to {}",
            class.label()
        ))),
        Some(why) => Err(format!(
            "{why}{done} of {total} were written; the rest are still waiting"
        )),
    }
}

#[allow(clippy::too_many_arguments)]
async fn batch<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    items: &[Outgoing],
    total: usize,
    done: &mut usize,
    emit: &Emit,
    gone: &mut bool,
) -> Result<Option<String>, Error> {
    let geometry = device.geometry().await?;
    let unit = geometry.allocation_unit(class)?;
    let mut refusals = Vec::with_capacity(items.len());
    for item in items {
        refusals.push(geometry.check_address(class, item.at)?);
    }
    device
        .destructive(class, async |s| {
            for (item, refused) in items.iter().zip(&refusals) {
                emit.send(DeviceEvent::Note(format!(
                    "sending {:?} to {} ({} of {total})",
                    item.name,
                    shown(item.at),
                    *done + 1
                )));
                if let Some(why) = refused {
                    return Ok(Some(format!("{}: {why}", shown(item.at))));
                }
                match put(s, unit, item.at, &item.name, item.bytes.clone(), emit, gone).await? {
                    Ok(note) => {
                        *done += 1;
                        emit.send(DeviceEvent::Note(note));
                        emit.send(DeviceEvent::Sent {
                            id: item.id,
                            class,
                            at: item.at,
                            bytes: item.bytes.clone(),
                        });
                    }
                    Err(why) => return Ok(Some(why)),
                }
            }
            Ok(None)
        })
        .await
}

/// The sentence for an error, in terms of the slot the operation was aimed at.
// Confirmed on hardware.
fn explain(e: Error, at: Location) -> String {
    match e {
        Error::DeviceStatus(1) => format!("{} is empty", shown(at)),
        Error::DeviceStatus(3) => format!("{} is out of range for this instrument", shown(at)),
        Error::DeviceStatus(4) => format!(
            "{} is occupied, and the instrument does not overwrite in place",
            shown(at)
        ),
        other => other.to_string(),
    }
}

async fn slot_info<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
) -> Result<ProgramInfo, Error> {
    device.read(class, async |s| op::info(s, at).await).await
}

/// A shorter per-frame limit for metadata walks; transfers keep the session default.
const SCAN_READ_LIMIT: Duration = Duration::from_secs(10);

/// Host safety limit for one complete class scan, not an instrument capacity.
const MOST_OCCUPIED: u32 = op::ENUMERATION_LIMIT as u32;

/// Scan the capacity the instrument declares for this bank, or to the device boundary
/// where it declared the unbounded sentinel.
///
/// The capacity comes from the [`Device`]'s own geometry rather than from the UI's cache
/// of it: a rescan after a mutation runs before the class has necessarily been walked,
/// and walking a bounded bank as if it were open costs one `INFO` per address up to the
/// host budget.
async fn scan_bank<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    bank: u32,
) -> Result<Vec<Option<ProgramInfo>>, Error> {
    let declared = device
        .geometry()
        .await?
        .banks(class)?
        .iter()
        .find(|held| super::user_bank(held.index) == Some(bank))
        .ok_or_else(|| {
            Error::InvalidArgument(format!(
                "the instrument declares no bank {bank} in {}",
                class.label()
            ))
        })?;
    let capacity = declared.is_bounded().then_some(declared.slots);
    if capacity.is_some_and(|capacity| capacity > MOST_OCCUPIED) {
        return Err(Error::ScanLimit {
            bank: bank.saturating_sub(1),
            limit: MOST_OCCUPIED,
        });
    }
    device
        .read(class, async |s| {
            s.set_read_limit(SCAN_READ_LIMIT);
            match capacity {
                Some(capacity) => walk_bank(s, bank, capacity).await,
                None => walk_open_bank(s, bank, MOST_OCCUPIED).await,
            }
        })
        .await
}

/// One bank a walk will read.
struct Planned {
    /// The bank number the panel labels it with.
    bank: NonZeroU32,
    /// Slots the device says it holds. `None` where it reported the unbounded sentinel.
    slots: Option<u32>,
}

struct Walked {
    banks: u32,
    items: usize,
    how: &'static str,
}

/// Scan only the banks and capacities declared by the instrument.
async fn scan_class<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    emit: &Emit,
) -> Result<Walked, Error> {
    let declared = device.geometry().await?.banks(class)?.to_vec();
    let plan = planned(&declared)?;

    device
        .read(class, async |s| {
            // This also bounds the closing exchanges.
            s.set_read_limit(SCAN_READ_LIMIT);

            let status = op::status(s).await?;
            let held = status.count;
            emit.send(DeviceEvent::Geometry {
                class,
                banks: declared.clone(),
            });
            emit.send(DeviceEvent::ClassStatus {
                class,
                status,
                banks: Some(plan.len() as u32),
            });

            // Status 1 means supported but empty; other refusals mean no focus applies.
            match op::focus(s).await {
                Ok(at) => emit.send(DeviceEvent::Focus {
                    class,
                    at: Some(at),
                }),
                Err(Error::DeviceStatus(1)) => emit.send(DeviceEvent::Focus { class, at: None }),
                Err(Error::DeviceStatus(_)) => {}
                Err(e) => return Err(e),
            }

            // Cursor enumeration wins for sparse or unbounded storage.
            let capacity = plan
                .iter()
                .try_fold(0u32, |sum, planned| sum.checked_add(planned.slots?));
            let sparse = capacity.is_none_or(|capacity| worth_the_cursor(held, capacity));
            let found = match sparse {
                true => occupied(s, &declared).await?,
                false => None,
            };

            let mut remaining = MOST_OCCUPIED;
            let mut items = 0;
            let how = match &found {
                Some(_) => "by cursor",
                None => "slot by slot",
            };
            for planned in &plan {
                let slots = match &found {
                    Some(found) => shape(found, planned, remaining)?,
                    None => match planned.slots {
                        Some(capacity) if capacity <= remaining => {
                            walk_bank(s, planned.bank.get(), capacity).await?
                        }
                        Some(_) => {
                            return Err(Error::ScanLimit {
                                bank: planned.bank.get() - 1,
                                limit: MOST_OCCUPIED,
                            })
                        }
                        None => walk_open_bank(s, planned.bank.get(), remaining).await?,
                    },
                };
                let taken = u32::try_from(slots.len()).unwrap_or(u32::MAX);
                remaining = remaining.checked_sub(taken).ok_or(Error::ScanLimit {
                    bank: planned.bank.get() - 1,
                    limit: MOST_OCCUPIED,
                })?;
                items += slots.iter().filter(|slot| slot.is_some()).count();
                emit.send(DeviceEvent::BankScanned {
                    class,
                    bank: planned.bank.get(),
                    slots,
                });
            }
            Ok(Walked {
                banks: plan.len() as u32,
                items,
                how,
            })
        })
        .await
}

fn planned(declared: &[Bank]) -> Result<Vec<Planned>, Error> {
    let mut total = 0u32;
    let mut plan = Vec::with_capacity(declared.len());
    for bank in declared {
        let slots = bank.is_bounded().then_some(bank.slots);
        if let Some(slots) = slots {
            total = total.checked_add(slots).ok_or(Error::ScanLimit {
                bank: bank.index,
                limit: MOST_OCCUPIED,
            })?;
            if total > MOST_OCCUPIED {
                return Err(Error::ScanLimit {
                    bank: bank.index,
                    limit: MOST_OCCUPIED,
                });
            }
        }
        plan.push(Planned {
            bank: bank
                .index
                .checked_add(1)
                .and_then(NonZeroU32::new)
                .expect("a decoded bank index fits its panel number"),
            slots,
        });
    }
    Ok(plan)
}

/// Use cursor enumeration below half capacity, where its two exchanges per item win.
fn worth_the_cursor(held: u32, capacity: u32) -> bool {
    capacity > 0 && held.saturating_mul(2) < capacity
}

/// Return `None` when the device refuses cursor enumeration.
async fn occupied<T: Transport, C>(
    s: &mut Session<'_, T, C>,
    banks: &[Bank],
) -> Result<Option<Vec<(Location, ProgramInfo)>>, Error> {
    let found = match op::occupied_slots(s, banks).await {
        Ok(found) => found,
        Err(Error::DeviceStatus(_)) => return Ok(None),
        Err(e) => return Err(e),
    };
    if let Some(at) = found.iter().find(|at| at.slot >= MOST_OCCUPIED) {
        return Err(Error::ScanLimit {
            bank: at.bank,
            limit: MOST_OCCUPIED,
        });
    }
    let mut out = Vec::with_capacity(found.len());
    for at in found {
        match op::info(s, at).await {
            Ok(info) => out.push((at, info)),
            // A cursor hit may be emptied before INFO; keep the rest of the scan.
            Err(Error::DeviceStatus(1)) => {}
            Err(e) => return Err(e),
        }
    }
    Ok(Some(out))
}

/// Shape cursor hits to the declared capacity, or through an open bank's last item.
///
/// A hit outside a bounded bank is [`Error::Enumeration`]: the instrument answered about
/// a slot it says it does not have, and widening the bank to fit would report slots no
/// later read could reach.
fn shape(
    found: &[(Location, ProgramInfo)],
    planned: &Planned,
    limit: u32,
) -> Result<Vec<Option<ProgramInfo>>, Error> {
    let bank = planned.bank.get() - 1;
    let mine: Vec<&(Location, ProgramInfo)> =
        found.iter().filter(|(at, _)| at.bank == bank).collect();
    let len = match planned.slots {
        Some(slots) => {
            if let Some((answered, _)) = mine.iter().find(|(at, _)| at.slot >= slots) {
                return Err(Error::Enumeration {
                    bank,
                    answered: *answered,
                    slots,
                });
            }
            slots
        }
        None => mine.iter().map(|(at, _)| at.slot + 1).max().unwrap_or(0),
    };
    if len > limit {
        return Err(Error::ScanLimit {
            bank,
            limit: MOST_OCCUPIED,
        });
    }
    let mut slots = vec![None; len as usize];
    for (at, info) in mine {
        if let Some(cell) = slots.get_mut(at.slot as usize) {
            *cell = Some(info.clone());
        }
    }
    Ok(slots)
}

async fn walk_bank<T: Transport, C>(
    s: &mut Session<'_, T, C>,
    bank: u32,
    slots: u32,
) -> Result<Vec<Option<ProgramInfo>>, Error> {
    if slots == 0 {
        return Ok(Vec::new());
    }
    let mut out = Vec::new();
    for slot in 1..=slots {
        let at = Location::from_user(bank, slot);
        match op::info(s, at).await {
            Ok(info) => out.push(Some(info)),
            Err(Error::DeviceStatus(1)) => out.push(None),
            Err(Error::DeviceStatus(3)) => {
                return Err(Error::Enumeration {
                    bank: at.bank,
                    answered: at,
                    slots,
                })
            }
            Err(e) => return Err(e),
        }
    }
    Ok(out)
}

async fn walk_open_bank<T: Transport, C>(
    s: &mut Session<'_, T, C>,
    bank: u32,
    limit: u32,
) -> Result<Vec<Option<ProgramInfo>>, Error> {
    if limit == 0 {
        return Err(Error::ScanLimit {
            bank: bank.saturating_sub(1),
            limit: MOST_OCCUPIED,
        });
    }
    let mut out = Vec::new();
    for slot in 1..=limit {
        match op::info(s, Location::from_user(bank, slot)).await {
            Ok(info) => out.push(Some(info)),
            Err(Error::DeviceStatus(1)) => out.push(None),
            Err(Error::DeviceStatus(3)) => {
                while matches!(out.last(), Some(None)) {
                    out.pop();
                }
                return Ok(out);
            }
            Err(e) => return Err(e),
        }
    }
    Err(Error::ScanLimit {
        bank: bank.saturating_sub(1),
        limit: MOST_OCCUPIED,
    })
}

/// Read a slot's metadata and a complete CBIN file of what it holds.
async fn read_object<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
) -> Result<(ProgramInfo, Vec<u8>), Error> {
    device
        .read(class, async |s| {
            let info = op::info(s, at).await?;
            let file = op::read_program(s, at).await?;
            Ok((info, file))
        })
        .await
}

async fn dependencies<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
) -> Result<Vec<Dependency>, Error> {
    device
        .read(class, async |s| op::dependencies(s, at).await)
        .await
}

async fn select<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
) -> Result<(), Error> {
    device.read(class, async |s| op::select(s, at).await).await
}

async fn rename<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
    name: &str,
) -> Result<(), Error> {
    device
        .destructive(class, async |s| op::rename(s, at, name).await)
        .await
}

async fn move_object<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    from: Location,
    to: Location,
) -> Result<(), Error> {
    device
        .destructive(class, async |s| op::move_object(s, from, to).await)
        .await
}

async fn duplicate<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    from: Location,
    to: Location,
) -> Result<(), Error> {
    device
        .destructive(class, async |s| op::duplicate(s, from, to).await)
        .await
}

async fn delete<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
) -> Result<(), Error> {
    device
        .destructive(class, async |s| op::delete(s, at).await)
        .await
}

/// Unix seconds, for the timestamp word `BEGIN_WRITE` carries.
///
/// ⚠️ `SystemTime::now()` traps on `wasm32-unknown-unknown`, so the browser's own clock
/// is what the web build reads.
#[cfg(not(target_arch = "wasm32"))]
fn unix_now() -> Result<u32, Error> {
    let elapsed = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| {
            Error::InvalidArgument(format!("system clock is before the Unix epoch: {e}"))
        })?;
    u32::try_from(elapsed.as_secs())
        .map_err(|_| Error::InvalidArgument("system time does not fit the device protocol".into()))
}

#[cfg(target_arch = "wasm32")]
fn unix_now() -> Result<u32, Error> {
    let seconds = js_sys::Date::now() / 1000.0;
    if !(0.0..=f64::from(u32::MAX)).contains(&seconds) {
        return Err(Error::InvalidArgument(
            "system time does not fit the device protocol".into(),
        ));
    }
    Ok(seconds as u32)
}

/// Name a fetched entity after its slot.
fn entity_name(info: &ProgramInfo) -> String {
    let name = info.name.trim();
    match name.is_empty() {
        true => "unnamed".to_string(),
        false => name.to_string(),
    }
}

/// Name rescued bytes without requiring their last copy to pass checksum validation.
fn rescue_name(at: Location, backup: &[u8]) -> String {
    let format = backup
        .get(8..12)
        .filter(|tag| tag.iter().all(|b| b.is_ascii_alphanumeric()))
        .map(|tag| String::from_utf8_lossy(tag).into_owned())
        .unwrap_or_else(|| "bin".to_string());
    format!(
        "nord-rescued-{}-{}.{format}",
        at.user_bank(),
        at.user_slot()
    )
}

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

    #[test]
    fn a_rescued_slot_is_named_for_its_location_and_format() {
        let mut file = vec![0u8; 45];
        file[0..4].copy_from_slice(b"CBIN");
        file[4..8].copy_from_slice(&1u32.to_le_bytes());
        file[8..12].copy_from_slice(b"ne5p");
        let at = Location { bank: 6, slot: 49 };
        assert_eq!(rescue_name(at, &file), "nord-rescued-7-50.ne5p");
    }

    #[test]
    fn unparseable_bytes_still_get_rescued() {
        let at = Location { bank: 0, slot: 0 };
        assert_eq!(rescue_name(at, b"nonsense"), "nord-rescued-1-1.bin");
    }

    #[test]
    fn a_read_keeps_the_slots_name_verbatim() {
        let info = ProgramInfo {
            location: Location { bank: 6, slot: 3 },
            body_len: 121,
            format: "ne5p".into(),
            version: 4,
            crc32: Some(0),
            name: "Africa Split".into(),
        };
        assert_eq!(entity_name(&info), "Africa Split");
    }

    #[test]
    fn a_slot_is_named_what_this_computer_calls_the_object() {
        let label = |name: &str| slot_label(name);
        assert_eq!(label("Africa-Split.ne5p").as_deref(), Some("Africa-Split"));
        assert_eq!(label("Squabble B.ne5t").as_deref(), Some("Squabble B"));
        assert_eq!(label("  Rotary Fast  ").as_deref(), Some("Rotary Fast"));
        // A dot that is not a tag: a name is allowed to hold one.
        assert_eq!(label("Bass 2.0").as_deref(), Some("Bass 2.0"));
        assert_eq!(label("Mr. Hammond").as_deref(), Some("Mr. Hammond"));
        assert_eq!(
            label(".ne5p").as_deref(),
            Some(".ne5p"),
            "a tag and nothing"
        );
    }

    #[test]
    fn a_name_with_nothing_in_it_is_not_sent() {
        for nothing in ["", "   ", "\t"] {
            assert_eq!(slot_label(nothing), None, "{nothing:?}");
        }
    }

    #[test]
    fn a_long_name_is_cut_on_a_character_boundary() {
        let long = "é".repeat(200);
        let cut = slot_label(&long).expect("something is left");
        assert!(cut.len() <= 64, "{} bytes", cut.len());
        assert!(long.starts_with(&cut));
        assert_eq!(cut.chars().count(), 32, "whole characters only");
    }

    #[test]
    fn a_nameless_slot_still_gets_a_label() {
        let info = ProgramInfo {
            location: Location { bank: 0, slot: 0 },
            body_len: 121,
            format: "ne5p".into(),
            version: 4,
            crc32: None,
            name: "  ".into(),
        };
        assert_eq!(entity_name(&info), "unnamed");
    }

    #[test]
    fn a_spaced_name_survives_to_the_write() {
        assert_eq!(slot_label("Big strings").as_deref(), Some("Big strings"));
    }

    /// A cursor hit outside a bounded bank is refused rather than widening it: the bank
    /// would then report slots the instrument says it does not have. An unbounded bank
    /// has no capacity to contradict, so it is shaped through its last item.
    #[test]
    fn a_cursor_hit_past_a_declared_capacity_is_refused() {
        let at = Location { bank: 0, slot: 7 };
        let found = [(
            at,
            ProgramInfo {
                location: at,
                body_len: 121,
                format: "ne5p".into(),
                version: 4,
                crc32: None,
                name: "Africa Split".into(),
            },
        )];
        let planned = |slots| Planned {
            bank: NonZeroU32::new(1).expect("bank 1"),
            slots,
        };

        match shape(&found, &planned(Some(4)), MOST_OCCUPIED) {
            Err(Error::Enumeration {
                bank,
                answered,
                slots,
            }) => assert_eq!((bank, answered, slots), (0, at, 4)),
            other => panic!(
                "a hit at 1:8 in a bank of four: {:?}",
                other.map(|slots| slots.len())
            ),
        }
        let open = shape(&found, &planned(None), MOST_OCCUPIED).expect("an open bank takes it");
        assert_eq!(open.len(), 8, "through the last item and no further");
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod wire_tests {
    use std::collections::VecDeque;
    use std::mem::size_of;
    use std::sync::mpsc::Receiver;

    use super::*;
    use crate::device::Purpose;
    use nord_usb::wire::{cmd, ui, Message, Service};
    use nord_usb::Transport;

    /// Minimal instrument state for exercising complete worker commands.
    struct Puppet {
        heard: Vec<Message>,
        replies: VecDeque<Vec<u8>>,
        info: u32,
        deaf: bool,
        banks: Vec<(&'static str, u32)>,
        reports_geometry: bool,
        garbles_geometry: bool,
        filled: Option<Vec<(Location, &'static str)>>,
        enumerates: bool,
        focus: Option<Location>,
        refuses_first_write: bool,
        refuses_every_write: bool,
    }

    /// The Electro 5's own division, which is what an unremarkable Puppet stands for.
    const EIGHT_BANKS: [(&str, u32); 8] = [
        ("Bank 1", 50),
        ("Bank 2", 50),
        ("Bank 3", 50),
        ("Bank 4", 50),
        ("Bank 5", 50),
        ("Bank 6", 50),
        ("Bank 7", 50),
        ("Bank 8", 50),
    ];

    impl Puppet {
        fn new(info: u32) -> Puppet {
            Puppet {
                heard: Vec::new(),
                replies: VecDeque::new(),
                info,
                deaf: false,
                banks: EIGHT_BANKS.to_vec(),
                reports_geometry: true,
                garbles_geometry: false,
                filled: None,
                enumerates: true,
                focus: None,
                refuses_first_write: false,
                refuses_every_write: false,
            }
        }

        fn deaf() -> Puppet {
            Puppet {
                deaf: true,
                ..Puppet::new(1)
            }
        }

        fn stocked(banks: &[(&'static str, u32)], filled: &[(Location, &'static str)]) -> Puppet {
            Puppet {
                banks: banks.to_vec(),
                filled: Some(filled.to_vec()),
                ..Puppet::new(1)
            }
        }

        fn mute_about_geometry(mut self) -> Puppet {
            self.reports_geometry = false;
            self
        }

        fn garbling_geometry(mut self) -> Puppet {
            self.garbles_geometry = true;
            self
        }

        fn no_enumeration(mut self) -> Puppet {
            self.enumerates = false;
            self
        }

        fn focused_on(mut self, at: Location) -> Puppet {
            self.focus = Some(at);
            self
        }

        fn refusing_the_first_write(mut self) -> Puppet {
            self.refuses_first_write = true;
            self
        }

        /// Refuses the restore as well, which is what leaves an occupant with nowhere
        /// to go but the local list.
        fn refusing_every_write(mut self) -> Puppet {
            self.refuses_every_write = true;
            self
        }

        fn holds(&self, at: Location) -> Option<&'static str> {
            self.filled
                .as_ref()?
                .iter()
                .find(|(held, _)| *held == at)
                .map(|(_, name)| *name)
        }

        /// Program and UI services reuse command numbers, so only answer Program frames.
        fn answer(&self, msg: &Message) -> Option<(u32, Vec<u8>)> {
            if !matches!(msg.service, Service::Program) {
                return None;
            }
            let at = || Location {
                bank: u32::from_be_bytes(msg.args[0..4].try_into().unwrap()),
                slot: u32::from_be_bytes(msg.args[4..8].try_into().unwrap()),
            };
            match msg.command {
                cmd::BEGIN_WRITE if self.refuses_every_write => Some((4, Vec::new())),
                cmd::BEGIN_WRITE
                    if self.refuses_first_write
                        && !self.heard.iter().any(|m| m.command == cmd::BEGIN_WRITE) =>
                {
                    Some((4, Vec::new()))
                }
                cmd::PARTITIONS => Some((0, partition_table())),
                // Five words in the order `nord_usb::wire::Status` decodes them, whose
                // doc carries both this shape and the zero `dirty`/`spare` a class
                // outside the libraries reports.
                cmd::STATUS => {
                    let count = self.filled.as_ref().map_or(0, Vec::len) as u32;
                    let total: u32 = self.banks.iter().map(|(_, slots)| slots).sum();
                    // One unit per item, so `Status::slots()` answers the bank capacity
                    // total rather than a coincidence of the division.
                    Some((0, words(&[count, total.saturating_sub(count), count, 0, 0])))
                }
                cmd::BANKS if !self.reports_geometry => Some((2, Vec::new())),
                cmd::BANKS if self.garbles_geometry => Some((0, vec![0xff, 0xff])),
                cmd::BANKS => {
                    let mut p = msg.args[0..4].to_vec();
                    p.push(self.banks.len() as u8);
                    for (name, slots) in &self.banks {
                        p.extend_from_slice(&(name.len() as u32).to_be_bytes());
                        p.extend_from_slice(name.as_bytes());
                        p.extend_from_slice(&slots.to_be_bytes());
                    }
                    Some((0, p))
                }
                cmd::FOCUS => match self.focus {
                    Some(at) => Some((0, words(&[at.bank, at.slot]))),
                    None => Some((1, Vec::new())),
                },
                cmd::NEXT_SLOT if !self.enumerates => Some((op::ENUMERATION_DISABLED, Vec::new())),
                cmd::NEXT_SLOT => {
                    let from = at();
                    // Third word is the direction, which `op::next_occupied` always
                    // sends because the instrument answers its absence with
                    // `op::ENUMERATION_DISABLED`.
                    let Some(dir) = msg.args.get(8..12) else {
                        return Some((op::ENUMERATION_DISABLED, Vec::new()));
                    };
                    let backward = u32::from_be_bytes(dir.try_into().unwrap()) == 1;
                    let in_bank = self
                        .filled
                        .as_ref()
                        .into_iter()
                        .flatten()
                        .filter_map(|(held, _)| (held.bank == from.bank).then_some(held.slot));
                    let hit = if backward {
                        in_bank
                            .filter(|s| from.slot == op::SLOT_BOUNDARY || *s < from.slot)
                            .max()
                    } else {
                        in_bank
                            .filter(|s| from.slot == op::SLOT_BOUNDARY || *s > from.slot)
                            .min()
                    };
                    match hit {
                        Some(slot) => Some((0, words(&[from.bank, slot]))),
                        None => Some((1, words(&[from.bank, op::SLOT_BOUNDARY]))),
                    }
                }
                cmd::READ => {
                    let (offset, want) = (
                        u32::from_be_bytes(msg.args[8..12].try_into().unwrap()),
                        u32::from_be_bytes(msg.args[12..16].try_into().unwrap()),
                    );
                    let at = at();
                    let mut p = words(&[at.bank, at.slot, offset, want]);
                    p.resize(p.len() + want as usize, 0);
                    Some((0, p))
                }
                cmd::INFO => {
                    let at = at();
                    // Confirmed on hardware.
                    // Status 3 marks the address-space boundary for geometry-free walks.
                    let capacity = self.banks.get(at.bank as usize).map(|(_, slots)| *slots);
                    if capacity.is_none_or(|slots| at.slot >= slots) {
                        return Some((3, Vec::new()));
                    }
                    match &self.filled {
                        Some(_) => match self.holds(at) {
                            Some(name) => Some((0, info_payload(at, name))),
                            None => Some((1, Vec::new())),
                        },
                        None => match self.info {
                            0 => Some((0, info_payload(at, "something"))),
                            status => Some((status, Vec::new())),
                        },
                    }
                }
                _ => None,
            }
        }

        /// Program and UI services reuse command numbers, so return Program frames only.
        fn commands(&self) -> Vec<u32> {
            self.heard
                .iter()
                .filter(|msg| matches!(msg.service, Service::Program))
                .map(|msg| msg.command)
                .collect()
        }

        fn first(&self, command: u32) -> Option<&Message> {
            self.heard.iter().find(|msg| msg.command == command)
        }
    }

    fn words(of: &[u32]) -> Vec<u8> {
        of.iter().flat_map(|w| w.to_be_bytes()).collect()
    }

    /// Encode all class partitions with their reported allocation units.
    fn partition_table() -> Vec<u8> {
        const COUNT: u32 = 8;
        const UNREAD_FIELDS: usize = 25;

        let mut p = vec![COUNT as u8];
        for index in 0..COUNT {
            let name = format!("Partition {index}");
            p.extend_from_slice(&(name.len() as u32).to_be_bytes());
            p.extend_from_slice(name.as_bytes());
            let unit: u32 = match ObjectClass::from_raw(index).is_library() {
                true => 131_064,
                false => 1,
            };
            p.extend_from_slice(&unit.to_be_bytes());
            p.resize(p.len() + UNREAD_FIELDS, 0);
        }
        p
    }

    fn info_payload(at: Location, name: &str) -> Vec<u8> {
        let mut p = words(&[at.bank, at.slot, 121]);
        p.extend_from_slice(b"ne5p");
        p.extend_from_slice(&words(&[4, u32::MAX, u32::MAX, name.len() as u32]));
        p.extend_from_slice(name.as_bytes());
        p.extend_from_slice(&u32::MAX.to_be_bytes());
        p
    }

    impl Transport for Puppet {
        async fn write(&mut self, buf: &[u8]) -> nord_usb::Result<()> {
            let msg = Message::decode(buf)?;
            let spoken = matches!(msg.service, Service::Ui)
                && matches!(msg.command, ui::LABEL | ui::PERCENT);
            let (status, payload) = match self.answer(&msg) {
                Some(answered) => answered,
                None => (0, vec![0; 32]),
            };
            if !spoken {
                let mut args = status.to_be_bytes().to_vec();
                args.extend_from_slice(&payload);
                self.replies.push_back(
                    Message::new(msg.service, msg.subsystem, msg.command + 1, args).encode(),
                );
            }
            self.heard.push(msg);
            Ok(())
        }

        async fn read(&mut self, _max: usize) -> nord_usb::Result<Vec<u8>> {
            if self.deaf {
                return Err(Error::Transport("the device stopped answering".into()));
            }
            self.replies
                .pop_front()
                .ok_or_else(|| Error::Transport("nothing to read".into()))
        }
    }

    fn a_program() -> Vec<u8> {
        let ctx = egui::Context::default();
        let mut workspace = crate::workspace::Workspace::new(ctx);
        let mut log = crate::log::Log::default();
        let id = workspace
            .create(crate::workspace::Fresh::Program, &mut log)
            .expect("a fresh default");
        workspace.get(id).expect("just made").bytes.clone()
    }

    fn drive(puppet: &mut Puppet, cmd: DeviceCmd) -> (Flow, Receiver<DeviceEvent>) {
        let (tx, events) = std::sync::mpsc::channel();
        let emit = Emit::new(tx, egui::Context::default());
        let lent = std::mem::replace(puppet, Puppet::new(1));
        let mut device = Device::new(lent);
        let flow = nord_usb::block_on(run(&mut device, cmd, &emit));
        *puppet = device.into_transport();
        (flow, events)
    }

    fn written_names(device: &Puppet) -> Vec<String> {
        device
            .heard
            .iter()
            .filter(|msg| msg.command == cmd::BEGIN_WRITE)
            .map(|msg| {
                let name_arg = &msg.args[6 * size_of::<u32>()..];
                let (len, name) = name_arg.split_at(size_of::<u32>());
                let len = u32::from_be_bytes(len.try_into().expect("four bytes")) as usize;
                assert_eq!(name.len(), len, "the name is length-prefixed");
                String::from_utf8(name.to_vec()).expect("a name is UTF-8")
            })
            .collect()
    }

    fn written_name(device: &Puppet) -> String {
        let mut names = written_names(device);
        assert_eq!(names.len(), 1, "one write");
        names.remove(0)
    }

    /// A read of a slot the instrument reports empty is an answer, not a fault: the
    /// queue needs to hear *empty* to stop waiting on it.
    #[test]
    fn a_read_of_an_empty_slot_is_forwarded_as_vacant() {
        let at = Location { bank: 0, slot: 3 };
        let mut device = Puppet::stocked(&[("Bank 1", 50)], &[]);
        let (_, events) = drive(
            &mut device,
            DeviceCmd::Get {
                class: ObjectClass::Program,
                at,
                why: Purpose::Compare,
            },
        );

        let said: Vec<DeviceEvent> = events.try_iter().collect();
        assert!(
            said.iter().any(|event| matches!(
                event,
                DeviceEvent::Vacant {
                    at: empty,
                    why: Purpose::Compare,
                    ..
                } if *empty == at
            )),
            "the empty slot was reported"
        );
        assert!(
            !said
                .iter()
                .any(|event| matches!(event, DeviceEvent::OpFailed(_) | DeviceEvent::Got { .. })),
            "and neither failed nor handed anything back"
        );
    }

    #[test]
    fn a_put_names_the_slot_in_the_write_itself() {
        let at = Location { bank: 6, slot: 3 };
        for class in [ObjectClass::Program, ObjectClass::Sample] {
            let mut device = Puppet::new(1);
            let (flow, _) = drive(
                &mut device,
                DeviceCmd::Put {
                    id: 1,
                    class,
                    at,
                    name: "Africa-Split.ne5p".into(),
                    bytes: a_program(),
                },
            );

            assert!(flow == Flow::Continue, "the instrument is still there");
            assert_eq!(written_name(&device), "Africa-Split", "{}", class.label());
            assert_eq!(
                counted(&device, cmd::RENAME),
                0,
                "no follow-up rename for {}",
                class.label()
            );
        }
    }

    #[test]
    fn a_restore_puts_the_occupants_own_name_back() {
        let at = Location { bank: 0, slot: 3 };
        let mut device =
            Puppet::stocked(&[("Bank 1", 50)], &[(at, "Squabble B")]).refusing_the_first_write();
        let (_, events) = drive(
            &mut device,
            DeviceCmd::Put {
                id: 1,
                class: ObjectClass::Program,
                at,
                name: "Africa-Split.ne5p".into(),
                bytes: a_program(),
            },
        );

        assert_eq!(written_names(&device), ["Africa-Split", "Squabble B"]);
        let said: Vec<DeviceEvent> = events.try_iter().collect();
        assert_eq!(
            failures(&said).len(),
            1,
            "one refusal is one failure: {:?}",
            failures(&said)
        );
    }

    /// A write that fails and cannot be put back is still one failure, and the occupant
    /// it displaced reaches the local list once, under the name its bytes are filed as.
    #[test]
    fn an_occupant_that_cannot_be_restored_is_rescued_once() {
        let at = Location { bank: 0, slot: 3 };
        let mut device =
            Puppet::stocked(&[("Bank 1", 50)], &[(at, "Squabble B")]).refusing_every_write();
        let (flow, events) = drive(
            &mut device,
            DeviceCmd::Put {
                id: 1,
                class: ObjectClass::Program,
                at,
                name: "Africa-Split.ne5p".into(),
                bytes: a_program(),
            },
        );
        assert!(flow == Flow::Continue, "it said no, it did not go away");

        let said: Vec<DeviceEvent> = events.try_iter().collect();
        let rescued: Vec<&str> = said
            .iter()
            .filter_map(|event| match event {
                DeviceEvent::Rescued { name, .. } => Some(name.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(rescued, ["nord-rescued-1-4.ne5p"]);
        assert_eq!(
            failures(&said).len(),
            1,
            "one refusal is one failure: {:?}",
            failures(&said)
        );
    }

    /// A batch lands once. Every item reports its own line to the log, but the sentence
    /// that says the send is done belongs to the whole of it.
    #[test]
    fn a_batch_succeeds_once_however_many_items_it_carries() {
        let bytes = a_program();
        let item = |slot, name: &str| Outgoing {
            id: slot as u64,
            at: Location { bank: 6, slot },
            name: name.into(),
            bytes: bytes.clone(),
        };
        let mut device = Puppet::new(1);
        let (flow, events) = drive(
            &mut device,
            DeviceCmd::SendAll {
                class: ObjectClass::Program,
                items: vec![item(3, "Africa-Split.ne5p"), item(4, "Squabble-B.ne5p")],
            },
        );
        assert!(flow == Flow::Continue);

        let said: Vec<DeviceEvent> = events.try_iter().collect();
        let landed: Vec<&str> = said
            .iter()
            .filter_map(|event| match event {
                DeviceEvent::OpOk(note) => Some(note.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(landed.len(), 1, "{landed:?}");
        assert!(landed[0].contains("wrote 2 of 2"), "{}", landed[0]);
        let sent = said
            .iter()
            .filter(|event| matches!(event, DeviceEvent::Sent { .. }))
            .count();
        assert_eq!(sent, 2, "each item is owed no longer");
    }

    #[test]
    fn a_put_into_a_buffer_class_never_deletes_the_slot() {
        let at = Location { bank: 0, slot: 2 };
        let put = |class| DeviceCmd::Put {
            id: 1,
            class,
            at,
            name: "Africa-Split.ne5p".into(),
            bytes: a_program(),
        };

        let mut live = Puppet::stocked(&[("Live", 3)], &[(at, "Live 3")]);
        let (flow, _) = drive(&mut live, put(ObjectClass::Live));
        assert!(flow == Flow::Continue, "the instrument is still there");
        assert_eq!(counted(&live, cmd::DELETE), 0, "nothing was emptied");
        assert_eq!(counted(&live, cmd::BEGIN_WRITE), 1, "and the bytes went");

        let mut program = Puppet::stocked(&[("Bank 1", 50)], &[(at, "Africa")]);
        drive(&mut program, put(ObjectClass::Program));
        assert_eq!(
            counted(&program, cmd::DELETE),
            1,
            "a class that refuses an occupied slot still makes room"
        );
    }

    #[test]
    fn a_class_that_stores_no_name_is_not_reported_as_named() {
        let at = Location { bank: 0, slot: 2 };
        let mut device = Puppet::stocked(&[("Live", 3)], &[(at, "Live 3")]);
        let (flow, _) = drive(
            &mut device,
            DeviceCmd::Put {
                id: 1,
                class: ObjectClass::Live,
                at,
                name: "Africa-Split.ne5l".into(),
                bytes: a_program(),
            },
        );
        assert!(flow == Flow::Continue);
        assert!(device.first(cmd::WRITE_DATA).is_some(), "the bytes went");
        let told = wrote(ObjectClass::Live, at, "Africa-Split.ne5l", "Africa-Split");
        assert!(!told.contains("named"), "{told}");
    }

    #[test]
    fn a_nameless_asset_still_gets_its_bytes_written() {
        let mut device = Puppet::new(1);
        let (flow, _) = drive(
            &mut device,
            DeviceCmd::Put {
                id: 1,
                class: ObjectClass::Program,
                at: Location { bank: 6, slot: 3 },
                name: "   ".into(),
                bytes: a_program(),
            },
        );
        assert!(flow == Flow::Continue);
        assert!(device.first(cmd::WRITE_DATA).is_some(), "the bytes went");
        assert_eq!(written_name(&device), "", "nothing to name it");
    }

    #[test]
    fn a_nameless_asset_leaves_the_slots_name_alone() {
        let at = Location { bank: 0, slot: 3 };
        let mut device = Puppet::stocked(&[("Bank 1", 50)], &[(at, "Squabble B")]);
        drive(
            &mut device,
            DeviceCmd::Put {
                id: 1,
                class: ObjectClass::Program,
                at,
                name: "   ".into(),
                bytes: a_program(),
            },
        );

        assert_eq!(written_name(&device), "Squabble B");
    }

    #[test]
    fn every_item_of_a_batch_is_named() {
        let bytes = a_program();
        let item = |slot, name: &str| Outgoing {
            id: slot as u64,
            at: Location { bank: 6, slot },
            name: name.into(),
            bytes: bytes.clone(),
        };
        let mut device = Puppet::new(1);
        let (flow, _) = drive(
            &mut device,
            DeviceCmd::SendAll {
                class: ObjectClass::Program,
                items: vec![item(3, "Africa-Split.ne5p"), item(4, "Squabble-B.ne5p")],
            },
        );
        assert!(flow == Flow::Continue);
        assert_eq!(
            written_names(&device),
            ["Africa-Split", "Squabble-B"],
            "one name per item"
        );
        // One geometry read and one destructive session around the pair, which is what
        // a batch is for.
        let opens = device
            .commands()
            .into_iter()
            .filter(|command| *command == cmd::SESSION_OPEN)
            .count();
        assert_eq!(opens, 2);
    }

    #[test]
    fn a_transport_that_fails_is_the_instrument_going_away() {
        let (flow, _) = drive(
            &mut Puppet::deaf(),
            DeviceCmd::SlotInfo {
                class: ObjectClass::Program,
                at: Location { bank: 6, slot: 3 },
            },
        );
        assert!(flow == Flow::Lost);
    }

    fn a_small_library() -> Puppet {
        Puppet::stocked(
            &[("Grand", 50), ("Upright", 30)],
            &[
                (Location { bank: 0, slot: 0 }, "Royal Grand 3D"),
                (Location { bank: 1, slot: 2 }, "Queen Upright"),
            ],
        )
    }

    fn holdings(bank: &(u32, Vec<Option<String>>)) -> (u32, usize, Vec<(usize, &str)>) {
        let held = bank
            .1
            .iter()
            .enumerate()
            .filter_map(|(slot, name)| Some((slot, name.as_deref()?)))
            .collect();
        (bank.0, bank.1.len(), held)
    }

    fn scan(class: ObjectClass) -> DeviceCmd {
        DeviceCmd::ScanClass { class }
    }

    fn scanned(events: Receiver<DeviceEvent>) -> Vec<(u32, Vec<Option<String>>)> {
        events
            .try_iter()
            .filter_map(|event| match event {
                DeviceEvent::BankScanned { bank, slots, .. } => Some((
                    bank,
                    slots
                        .into_iter()
                        .map(|slot| slot.map(|info| info.name))
                        .collect(),
                )),
                _ => None,
            })
            .collect()
    }

    /// The failures reported for one command. `run` emits one; a second means a step
    /// inside the command reported its own, which the send queue would put against the
    /// next entry waiting.
    fn failures(said: &[DeviceEvent]) -> Vec<&str> {
        said.iter()
            .filter_map(|event| match event {
                DeviceEvent::OpFailed(why) => Some(why.as_str()),
                _ => None,
            })
            .collect()
    }

    fn refused(events: Receiver<DeviceEvent>) -> String {
        let said: Vec<DeviceEvent> = events.try_iter().collect();
        failures(&said).join(" | ")
    }

    fn counted(device: &Puppet, command: u32) -> usize {
        device
            .commands()
            .into_iter()
            .filter(|held| *held == command)
            .count()
    }

    #[test]
    fn a_scan_publishes_a_bank_before_reading_the_next_one() {
        struct ObserveProgress {
            puppet: Puppet,
            events: Receiver<DeviceEvent>,
            first_bank_arrived: bool,
        }

        impl Transport for ObserveProgress {
            async fn write(&mut self, buf: &[u8]) -> nord_usb::Result<()> {
                let msg = Message::decode(buf)?;
                if msg.service == Service::Program
                    && msg.command == cmd::INFO
                    && msg.args[..4] == 1u32.to_be_bytes()
                {
                    self.first_bank_arrived = self.events.try_iter().any(|event| {
                        matches!(event, DeviceEvent::BankScanned { class: ObjectClass::Program, bank: 1, slots }
                            if slots.first().and_then(Option::as_ref).is_some_and(|info| info.name == "First"))
                    });
                }
                self.puppet.write(buf).await
            }

            async fn read(&mut self, max: usize) -> nord_usb::Result<Vec<u8>> {
                self.puppet.read(max).await
            }
        }

        let (tx, events) = std::sync::mpsc::channel();
        let emit = Emit::new(tx, egui::Context::default());
        let puppet = Puppet::stocked(
            &[("Bank 1", 1), ("Bank 2", 1)],
            &[
                (Location { bank: 0, slot: 0 }, "First"),
                (Location { bank: 1, slot: 0 }, "Second"),
            ],
        );
        let mut device = Device::new(ObserveProgress {
            puppet,
            events,
            first_bank_arrived: false,
        });
        let flow = nord_usb::block_on(run(&mut device, scan(ObjectClass::Program), &emit));
        assert!(flow == Flow::Continue);
        assert!(
            device.transport().first_bank_arrived,
            "the first bank's names and progress were withheld until the second bank finished"
        );
    }

    #[test]
    fn a_scan_asks_only_about_the_slots_that_hold_something() {
        let mut device = a_small_library();
        let (flow, events) = drive(&mut device, scan(ObjectClass::Piano));
        assert!(flow == Flow::Continue);

        let banks = scanned(events);
        assert_eq!(
            banks.iter().map(holdings).collect::<Vec<_>>(),
            vec![
                (1, 50, vec![(0, "Royal Grand 3D")]),
                (2, 30, vec![(2, "Queen Upright")]),
            ]
        );
        assert!(counted(&device, cmd::NEXT_SLOT) > 0, "the cursor was used");
        assert_eq!(counted(&device, cmd::INFO), 2, "not the 80 addresses");
    }

    #[test]
    fn a_device_that_refuses_to_enumerate_is_walked_slot_by_slot() {
        let mut device = a_small_library().no_enumeration();
        let (flow, events) = drive(&mut device, scan(ObjectClass::Piano));
        assert!(flow == Flow::Continue, "a refusal is not a disconnection");

        let banks = scanned(events);
        assert_eq!(
            banks.iter().map(holdings).collect::<Vec<_>>(),
            vec![
                (1, 50, vec![(0, "Royal Grand 3D")]),
                (2, 30, vec![(2, "Queen Upright")]),
            ],
            "the same folder, found the long way"
        );
        assert!(counted(&device, cmd::NEXT_SLOT) > 0, "it was tried");
        assert_eq!(counted(&device, cmd::INFO), 80);
    }

    /// The instrument's own partition table is what says which classes exist, and every
    /// row of it is one — the ones this app has no name for included, so a folder the
    /// crate cannot name is still listed rather than dropped.
    #[test]
    fn a_connection_announces_the_classes_the_instrument_declares() {
        let mut puppet = Puppet::stocked(&[("Bank 1", 50)], &[]);
        let (tx, events) = std::sync::mpsc::channel();
        let emit = Emit::new(tx, egui::Context::default());
        let lent = std::mem::replace(&mut puppet, Puppet::new(1));
        let mut device = Device::new(lent);

        let flow = nord_usb::block_on(announce(&mut device, &emit));
        assert!(flow == Flow::Continue);

        let announced: Vec<Vec<Partition>> = events
            .try_iter()
            .filter_map(|event| match event {
                DeviceEvent::Partitions(rows) => Some(rows),
                _ => None,
            })
            .collect();
        let [rows] = announced.as_slice() else {
            panic!("one announcement per connection, not {}", announced.len());
        };
        assert_eq!(
            rows.iter().map(|row| row.class).collect::<Vec<_>>(),
            (0..8).map(ObjectClass::from_raw).collect::<Vec<_>>(),
            "the table's index is the class code"
        );
        assert_eq!(rows[4].name, "Partition 4", "the device's own word");
        // The libraries count blocks of net bytes; every other partition counts bytes.
        assert_eq!(
            rows.iter()
                .map(|row| row.unit.map(|unit| unit.get()))
                .collect::<Vec<_>>(),
            [1, 131_064, 1, 131_064, 1, 1, 1, 1].map(Some),
            "each partition's own unit"
        );
    }

    #[test]
    fn the_devices_own_geometry_shapes_the_scan() {
        let mut device = a_small_library();
        let (_, events) = drive(&mut device, scan(ObjectClass::Piano));

        let mut named = Vec::new();
        let mut widths = Vec::new();
        for event in events.try_iter() {
            match event {
                DeviceEvent::Geometry { banks, .. } => {
                    named = banks
                        .into_iter()
                        .map(|bank| (bank.name, bank.slots))
                        .collect()
                }
                DeviceEvent::BankScanned { slots, .. } => widths.push(slots.len()),
                _ => {}
            }
        }
        assert_eq!(
            named,
            vec![("Grand".to_string(), 50), ("Upright".to_string(), 30)],
            "the categories reach the browser by name"
        );
        assert_eq!(widths, vec![50, 30], "and its capacities");
    }

    #[test]
    fn an_oversized_geometry_is_refused_before_slot_reads() {
        let mut device = Puppet::stocked(&[("Bank 1", MOST_OCCUPIED + 1)], &[]);
        let (flow, events) = drive(&mut device, scan(ObjectClass::Program));

        assert!(flow == Flow::Continue);
        assert!(refused(events).contains("cannot be scanned completely"));
        assert_eq!(counted(&device, cmd::INFO), 0);
    }

    #[test]
    fn an_oversized_bank_scan_is_refused_before_slot_reads() {
        let mut device = Puppet::stocked(&[("Bank 1", MOST_OCCUPIED + 1)], &[]);
        let (flow, events) = drive(
            &mut device,
            DeviceCmd::ScanBank {
                class: ObjectClass::Program,
                bank: 1,
            },
        );

        assert!(flow == Flow::Continue);
        assert!(refused(events).contains("cannot be scanned completely"));
        assert_eq!(counted(&device, cmd::INFO), 0);
    }

    #[test]
    fn a_rescan_takes_the_banks_capacity_from_the_instrument() {
        let at = Location { bank: 0, slot: 1 };
        let mut device = Puppet::stocked(&[("Bank 1", 4)], &[(at, "Africa Split")]);
        let (flow, events) = drive(
            &mut device,
            DeviceCmd::ScanBank {
                class: ObjectClass::Program,
                bank: 1,
            },
        );

        assert!(flow == Flow::Continue);
        assert_eq!(
            scanned(events),
            vec![(1, vec![None, Some("Africa Split".to_string()), None, None])],
            "the declared four slots, not a walk to the host budget"
        );
        assert_eq!(counted(&device, cmd::INFO), 4);
    }

    #[test]
    fn a_bank_ending_before_its_declared_capacity_is_not_reported() {
        let mut device = Puppet::new(3);
        let (flow, events) = drive(
            &mut device,
            DeviceCmd::ScanBank {
                class: ObjectClass::Program,
                bank: 1,
            },
        );

        assert!(flow == Flow::Continue);
        let events: Vec<DeviceEvent> = events.try_iter().collect();
        assert!(events.iter().any(
            |event| matches!(event, DeviceEvent::OpFailed(why) if why.contains("became inconsistent"))
        ));
        assert!(!events
            .iter()
            .any(|event| matches!(event, DeviceEvent::BankScanned { .. })));
    }

    #[test]
    fn a_class_whose_banks_are_refused_is_not_scanned() {
        let mut device = Puppet::stocked(
            &[("Bank 1", 50)],
            &[(Location { bank: 0, slot: 1 }, "Africa Split")],
        )
        .mute_about_geometry();
        let (flow, events) = drive(&mut device, scan(ObjectClass::Program));
        assert!(flow == Flow::Continue, "a refusal is not a disconnection");

        let why = refused(events);
        assert!(
            why.contains("status 0x2"),
            "the device's own refusal: {why}"
        );
        assert_eq!(counted(&device, cmd::INFO), 0, "and nothing was walked");
    }

    #[test]
    fn a_bank_list_that_will_not_decode_stops_the_scan() {
        let mut device = Puppet::stocked(&[("Bank 1", 50)], &[]).garbling_geometry();
        let (flow, events) = drive(&mut device, scan(ObjectClass::Program));
        assert!(flow == Flow::Continue, "a bad reply is not a dead pipe");

        let why = refused(events);
        assert!(why.contains("truncated"), "{why}");
        assert_eq!(counted(&device, cmd::INFO), 0, "and nothing was walked");
    }

    #[test]
    fn an_unbounded_bank_is_read_to_its_last_item() {
        let filled: Vec<(Location, &'static str)> = (0..60)
            .map(|slot| (Location { bank: 0, slot }, "Marimba"))
            .collect();
        let mut device = Puppet::stocked(&[("Samp Lib", Bank::UNBOUNDED)], &filled);
        let (flow, events) = drive(&mut device, scan(ObjectClass::Sample));
        assert!(flow == Flow::Continue);

        let banks = scanned(events);
        assert_eq!(banks.len(), 1);
        assert_eq!(banks[0].1.len(), 60, "all of them");
        assert!(banks[0].1.iter().all(Option::is_some));
    }

    #[test]
    fn an_unbounded_bank_without_an_end_does_not_report_a_partial_scan() {
        let at = Location { bank: 0, slot: 40 };
        let mut library =
            Puppet::stocked(&[("Samp Lib", Bank::UNBOUNDED)], &[(at, "Marimba")]).no_enumeration();
        let (flow, events) = drive(&mut library, scan(ObjectClass::Sample));

        assert!(flow == Flow::Continue);
        assert!(refused(events).contains("cannot be scanned completely"));
        assert_eq!(counted(&library, cmd::INFO), MOST_OCCUPIED as usize);
    }

    #[test]
    fn a_full_class_is_read_slot_by_slot_and_a_sparse_one_by_cursor() {
        let full: Vec<(Location, &'static str)> = (0..2)
            .flat_map(|bank| (0..50).map(move |slot| (Location { bank, slot }, "Africa Split")))
            .collect();
        let banks = [("Bank 1", 50), ("Bank 2", 50)];

        let mut dense = Puppet::stocked(&banks, &full);
        drive(&mut dense, scan(ObjectClass::Program));
        assert_eq!(counted(&dense, cmd::NEXT_SLOT), 0, "the cursor was skipped");
        assert_eq!(
            counted(&dense, cmd::INFO),
            100,
            "one per address, and no more"
        );

        let mut sparse = Puppet::stocked(&banks, &full[..2]);
        drive(&mut sparse, scan(ObjectClass::Program));
        assert!(counted(&sparse, cmd::NEXT_SLOT) > 0, "the cursor earned it");
        assert!(counted(&sparse, cmd::INFO) < 100);
    }

    #[test]
    fn a_geometry_that_cannot_be_read_stops_the_write_before_any_frame_of_it() {
        let mut device = Puppet::stocked(&[("Bank 1", 50)], &[]).garbling_geometry();
        let (flow, _) = drive(
            &mut device,
            DeviceCmd::Put {
                id: 1,
                class: ObjectClass::Program,
                at: Location { bank: 0, slot: 3 },
                name: "Africa-Split.ne5p".into(),
                bytes: a_program(),
            },
        );
        assert!(flow == Flow::Continue, "not a disconnection");
        assert_eq!(counted(&device, cmd::BEGIN_WRITE), 0);
        assert_eq!(counted(&device, cmd::WRITE_DATA), 0);
    }

    #[test]
    fn a_scan_reports_the_slot_the_panel_has_loaded() {
        let panel = Location { bank: 1, slot: 2 };
        let mut device = a_small_library().focused_on(panel);
        let (_, events) = drive(&mut device, scan(ObjectClass::Piano));

        let focused: Vec<Location> = events
            .try_iter()
            .filter_map(|event| match event {
                DeviceEvent::Focus { at, .. } => at,
                _ => None,
            })
            .collect();
        assert_eq!(focused, vec![panel]);
    }

    #[test]
    fn a_write_past_the_end_is_refused_before_anything_is_deleted() {
        let mut device = a_small_library();
        let (flow, events) = drive(
            &mut device,
            DeviceCmd::Put {
                id: 1,
                class: ObjectClass::Program,
                at: Location { bank: 6, slot: 0 },
                name: "Africa-Split.ne5p".into(),
                bytes: a_program(),
            },
        );
        assert!(flow == Flow::Continue, "it said no, it did not go away");

        let why = refused(events);
        assert!(why.contains("bank 7 does not exist"), "{why}");
        assert!(
            why.contains("Grand, Upright"),
            "in the panel's own words: {why}"
        );

        assert_eq!(counted(&device, cmd::DELETE), 0, "nothing was emptied");
        assert_eq!(
            counted(&device, cmd::BEGIN_WRITE),
            0,
            "and nothing was sent"
        );
    }

    #[test]
    fn a_write_to_a_real_address_still_goes() {
        let mut device = Puppet::stocked(&[("Bank 1", 50)], &[]);
        let (flow, _) = drive(
            &mut device,
            DeviceCmd::Put {
                id: 1,
                class: ObjectClass::Program,
                at: Location { bank: 0, slot: 3 },
                name: "Africa-Split.ne5p".into(),
                bytes: a_program(),
            },
        );
        assert!(flow == Flow::Continue);
        assert_eq!(counted(&device, cmd::WRITE_DATA), 1, "the bytes went");
    }

    #[test]
    fn a_refusal_is_not_a_disconnection() {
        let (flow, _) = drive(
            &mut Puppet::new(3),
            DeviceCmd::SlotInfo {
                class: ObjectClass::Program,
                at: Location { bank: 30, slot: 3 },
            },
        );
        assert!(flow == Flow::Continue);
    }
}