saturnus-host 0.12.1

Host-side pieces shared by the Saturnus emulator's front ends: the emulator with its key queue, command-line typing, hidden Kermit transfers, key layouts and skins, ROM identification
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
//! The front end's protocol (`web/protocol.md`) and its pacing, once for
//! every host: [`Engine`] takes commands and gives replies and events,
//! and runs the machine against a clock the host passes in. It has no
//! clock, timer, thread or I/O of its own; a host is a thin driver around
//! it:
//!
//! - feed it the page's messages ([`Engine::command`]) with the host's
//!   [`Clock`];
//! - after every call, deliver [`Engine::take_output`] in order (the events
//!   a command caused come before its reply) and arm one timer for
//!   [`Engine::deadline`], which calls [`Engine::timer`].
//!
//! The Web Worker (`web/worker.js`, through `saturnus-web`) drives it with
//! `performance.now()` and `setTimeout`; the native machine thread
//! (`saturnus-drive`'s runner, for the desktop app and `saturnus run`)
//! with `Instant` and its channel's `recv_timeout`. What only one host has
//! stays with it: files and dialogs natively, IndexedDB and the ROM slots
//! in the browser, the native commands (`screen`, `info`, `model`,
//! `peek`, `poke`, `keyScript`), which the runner serves around the engine
//! ([`Engine::answer`], [`Engine::exclusive`]).
//!
//! Sends (`insert`, `run`, `replace`, `typeText`) and the writes to the
//! user memory (`storeFile`, `fetchFile`, `purge`, `rename`, `createDir`,
//! `changeDir`, `setFlag`, `storeText`, `copy`, `move`, `storeScreen`: a
//! hidden Kermit transaction,
//! [`crate::transfer`]) run in
//! turns between other messages; meanwhile the commands in
//! whose [`Policy`] says `refused_while_typing` are refused, `releaseAll` stops the send or
//! the write, and a send of more than 12 characters, or any write, holds
//! the frames, keys and errors until it ends.
//!
//! The page may also hold the emulated serial port itself (`serialOpen`,
//! `serialWrite`, the `serial` event, `serialClose`): the transfer page
//! talks to the calculator over it as over a cable. The port carries one
//! conversation at a time, so while the page holds it the writes are
//! refused, and while a write runs the page cannot take it.
//!
//! A host that keeps states ([`Engine::set_auto_save`]) gets the machine's
//! state as [`Output::Save`] once it changed and settled (`protocol/autosave.rs`),
//! and boots a model with the state it kept ([`Engine::boot_restoring`]).

mod autosave;
mod command;
mod pacing;
mod recover;
mod watch;

#[cfg(test)]
mod tests;

pub use autosave::DELAY_MS as AUTO_SAVE_MS;
pub use command::{CommandKind, HttpEndpoint, Policy};
pub use pacing::{LoopState, MAX_BEHIND_MS, Pacing, Speed};
pub use watch::{EVENT_MS as MEMORY_EVENT_MS, LOOK_MS as MEMORY_LOOK_MS};

use saturnus_core::{Machine, Model};
use serde::Serialize;
use serde_json::{Value, json};

use crate::host::{Frame, KeysDown, base64_decode, model_for_rom};
use crate::transfer::{MAX_FILE_BYTES, Op, Target};
use crate::{Emulator, Error, Result};
use autosave::AutoSave;
use pacing::Loop;
use recover::{Recover, Step};
use watch::Watch;

/// The protocol version.
pub const VERSION: u64 = 1;
/// Largest state accepted (`loadState`): the largest is the 49G's, 2.6 MB
/// (its 2 MiB flash and 512 KiB RAM); 4 MiB leaves half again as much.
pub const MAX_STATE_BYTES: usize = 4 * 1024 * 1024;
/// Emulated ms one step of a send runs.
pub const TYPING_STEP_MS: f64 = 20.0;
/// Wall time a send may take in all, in ms (also the native key scripts').
/// A `run` that reaches it after ENTER replies `running` instead.
pub const WALL_LIMIT_MS: f64 = 30_000.0;
/// Steps a `run` cut short after ENTER may take to finish (reading the
/// line, closing the 49G's error box and waiting after it).
const WAIT_END_STEPS: usize = 64;
/// Most bytes waiting for the calculator's UART (`serialWrite`): at 9600
/// baud it takes about 840 a second, so this is many packets ahead.
pub const MAX_SERIAL_PENDING: usize = 16 * 1024;
/// Why a write is refused while the page holds the serial port.
pub const SERIAL_IN_USE: &str = "the serial port is in use (serialClose frees it)";
/// Least wall time between two `serial` events while the machine computes
/// in passes (a native host runs one every millisecond): about 10 bytes at
/// 9600 baud, so a Kermit packet is two or three events, not a hundred.
pub const SERIAL_EVENT_MS: f64 = 10.0;

/// The host's clock: milliseconds from any fixed start, never going back.
pub trait Clock {
    /// Now, in ms.
    fn now_ms(&self) -> f64;
}

/// The `status` event: sent whenever one of its fields changed.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename = "status", rename_all = "camelCase")]
pub struct Status {
    /// The booted model's name.
    pub model: Option<&'static str>,
    /// The ROM file's name.
    pub rom_name: String,
    /// The machine runs (booted, not paused, not halted).
    pub running: bool,
    /// Why the CPU stopped, or `None`.
    pub halted: Option<String>,
    /// The speed setting.
    pub speed: Speed,
    /// What the loop does.
    #[serde(rename = "loop")]
    pub loop_state: LoopState,
    /// A long send holds the frames.
    pub busy: bool,
    /// A cold boot's "Try To Recover Memory?" (and the 49G's "Memory
    /// Clear") is still being answered: the keyboard is not the user's
    /// yet, and a send waits for the answer.
    pub starting: bool,
}

/// The `error` event: a command without an `id` failed, or a key the
/// machine refused.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename = "error")]
pub struct ErrorEvent {
    /// For the user.
    pub message: String,
}

/// The `memoryChanged` event.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename = "memoryChanged")]
pub struct MemoryChanged {}

/// The `serial` event: bytes the calculator sent on its serial port while
/// the page holds it (`serialOpen`); base64 in JSON.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename = "serial")]
pub struct SerialEvent {
    /// The bytes, in the order they left the UART.
    #[serde(serialize_with = "crate::host::as_base64")]
    pub bytes: Vec<u8>,
}

/// An event for the page (`web/protocol.md`, "Events"); serializes as
/// the protocol's JSON object.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(untagged)]
pub enum Event {
    /// `serial`.
    Serial(SerialEvent),
    /// `frame`.
    Frame(Frame),
    /// `keys`.
    Keys(KeysDown),
    /// `status`.
    Status(Status),
    /// `error`.
    Error(ErrorEvent),
    /// `memoryChanged`.
    MemoryChanged(MemoryChanged),
    /// `menu`.
    Menu(crate::host::MenuKeys),
}

/// The reply to a command that asked for one.
#[derive(Clone, Debug, PartialEq)]
pub struct Reply {
    /// The host's tag for the command ([`Engine::command`]).
    pub tag: u64,
    /// The result, or the error's message.
    pub result: std::result::Result<Value, String>,
    /// Bytes that belong in the result's field of this name (`saveState`'s
    /// `state`): the Worker passes them as a `Uint8Array`, JSON hosts as
    /// base64.
    pub bytes: Option<(&'static str, Vec<u8>)>,
}

/// The machine's state for the host's store: it changed and has settled
/// ([`Engine::set_auto_save`]). The host keeps it in the model's auto slot,
/// apart from the user's own saved state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Saved {
    /// The model's name.
    pub model: &'static str,
    /// The ROM file's name.
    pub rom_name: String,
    /// CPU cycles since power-on.
    pub cycles: u64,
    /// The whole machine state (`saveState`'s).
    pub state: Vec<u8>,
}

/// What the engine has for the host, in order.
#[derive(Clone, Debug, PartialEq)]
pub enum Output {
    /// An event for every page.
    Event(Event),
    /// A reply for one caller.
    Reply(Reply),
    /// A state for the host's store, not for the page.
    Save(Saved),
}

/// `boot`'s result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Booted {
    /// The model booted (the ROM may have chosen another).
    pub model: &'static str,
    /// The ROM file's name.
    pub rom_name: String,
    /// The host's kept state was restored ([`Engine::boot_restoring`]);
    /// only `true` is sent.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub restored: bool,
    /// Why the kept state did not load (another ROM, an older format):
    /// the machine cold-booted instead.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub restore_error: Option<String>,
}

/// `stats`'s result: counters for tests (`web/protocol.md`).
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Stats {
    /// CPU cycles since power-on.
    pub cycles: u64,
    /// Emulated ms since power-on.
    pub emulated_ms: f64,
    /// Wall ms spent emulating (passes, wakes, sends, key scripts).
    pub work_ms: f64,
    /// Passes run.
    pub ticks: u64,
    /// Wakes from a sleep.
    pub wakes: u64,
    /// Looks at the user memory for `memoryChanged`.
    pub memory_looks: u64,
    /// Wall ms those looks took.
    pub memory_ms: f64,
    /// What the loop does.
    #[serde(rename = "loop")]
    pub loop_state: LoopState,
    /// Emulated ms owed to the wall clock: unpaid, plus the current sleep.
    pub owed_ms: f64,
    /// The host's clock.
    pub now_ms: f64,
}

/// Why a host's own run of the machine failed ([`Engine::exclusive`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunError {
    /// For the user.
    pub message: String,
    /// The CPU halted (the machine stops until a reset or a state load).
    pub halted: bool,
}

/// What the calculator sent on the page's serial port and the page has
/// not had yet: gathered between passes, so a `serial` event goes out at
/// most every [`SERIAL_EVENT_MS`] while the machine computes, and at once
/// otherwise (asleep, before a reply).
#[derive(Clone, Debug, Default)]
struct SerialOut {
    held: Vec<u8>,
    /// When the last `serial` event went out.
    last: Option<f64>,
}

impl SerialOut {
    /// The bytes to send at `t`: all held, if there are any and `now`, or
    /// [`SERIAL_EVENT_MS`] has passed since the last event (within the
    /// host timer's `slack`).
    fn take(&mut self, t: f64, slack: f64, now: bool) -> Option<Vec<u8>> {
        if self.held.is_empty()
            || (!now && self.last.is_some_and(|l| t + slack < l + SERIAL_EVENT_MS))
        {
            return None;
        }
        self.last = Some(t);
        Some(std::mem::take(&mut self.held))
    }

    /// When held bytes are due to go out.
    fn due(&self) -> Option<f64> {
        (!self.held.is_empty()).then(|| self.last.map_or(0.0, |l| l + SERIAL_EVENT_MS))
    }
}

/// A send in progress.
#[derive(Clone, Debug)]
struct Send {
    /// Where its reply goes; `None`: errors become `error` events.
    tag: Option<u64>,
    /// It holds the frames (`status` `busy`).
    freezes: bool,
    /// A write through the Kermit server rather than typing.
    transfer: bool,
    /// When it started, on the host's clock.
    started: f64,
    /// When its next turn is due.
    due: f64,
    /// A write being stopped: why (its reply), while its cleanup (the
    /// server ended, the 49G's mode set again) runs in turns.
    stopping: Option<Error>,
    /// A send or write that came while the boot's question was still
    /// being answered: started once the answer is done.
    waiting: Option<Waiting>,
}

/// What a send waiting for the boot's question starts.
#[derive(Clone, Debug)]
enum Waiting {
    /// Typing: the verb and the text.
    Typing(String, String),
    /// A write.
    Transfer(Op),
}

/// The protocol's state machine (see the module docs).
#[derive(Debug)]
pub struct Engine {
    /// The host's name in `hello` ("worker", "tauri", "http").
    host: &'static str,
    emu: Option<Emulator>,
    model: Option<Model>,
    rom_name: String,
    halted: Option<String>,
    lp: Loop,
    watch: Watch,
    send: Option<Send>,
    out: Vec<Output>,
    last_status: Option<Status>,
    /// When the last `frame` event went out.
    last_frame: Option<f64>,
    autosave: AutoSave,
    /// Whether a cold boot's "Try To Recover Memory?" is answered
    /// ([`Engine::set_answer_recover`]), and the answer pending.
    answer_recover: bool,
    recover: Option<Recover>,
    /// The page holds the serial port (`serialOpen`): what the UART sends
    /// goes out as `serial` events, and the writes are refused.
    serial: bool,
    serial_out: SerialOut,
}

/// What one look at a sleeping machine's screen does for the boot's
/// question (`recover.rs`).
enum Look {
    /// Not on the screen yet.
    Wait,
    /// It did not come in time: given up.
    GiveUp,
    /// On the screen: press the sixth menu key (the NO, then the 49G's
    /// OK, both there), then wait for this (none after the last).
    Answer(Option<Recover>),
}

fn look(e: &Emulator, r: Recover) -> Look {
    if e.emulated_ms() > r.until_ms {
        return Look::GiveUp;
    }
    let rows = &e.machine().framebuffer().pixels.pixels;
    match r.step {
        Step::Prompt if recover::is_prompt(rows) => {
            Look::Answer((e.model() == Model::Hp49g).then(|| Recover {
                step: Step::Dismiss,
                until_ms: e.emulated_ms() + recover::DISMISS_WAIT_MS,
            }))
        }
        Step::Dismiss if recover::is_memory_clear(rows) => Look::Answer(None),
        _ => Look::Wait,
    }
}

/// One step of a send waiting for the boot's question: run the machine
/// [`TYPING_STEP_MS`], answering the question as [`Engine::timer`] would
/// (a look whenever the CPU sleeps). True once it is answered (or given
/// up) and the ROM has settled after the last key, so typing can begin.
fn answer_boot(e: &mut Emulator, recover: &mut Option<Recover>) -> Result<bool> {
    if pacing::asleep(e) {
        match recover.map(|r| look(e, r)) {
            None => return Ok(true),
            Some(Look::Wait) => {}
            Some(Look::GiveUp) => *recover = None,
            // Not a change to keep: a reload boots cold and is answered
            // again.
            Some(Look::Answer(next)) => {
                e.type_keys("f");
                *recover = next;
            }
        }
    }
    e.run_slice(TYPING_STEP_MS, true)?;
    Ok(false)
}

/// The string field `name` of `msg`.
fn str_field<'a>(msg: &'a Value, name: &str) -> Result<&'a str> {
    msg.get(name)
        .and_then(Value::as_str)
        .ok_or_else(|| format!("missing string field {name:?}").into())
}

/// The `text` of a send or `storeText`. With `codes` true (the AI
/// tools' text) the 48's translation codes (`\GS`, `\v/`, `\->`, `\\` for
/// a backslash) are read as their characters first, as an ASCII transfer
/// reads them (`charset::from_trigraphs`); without it the text is the
/// calculator's own (the editor's, which may hold a backslash in a string)
/// and stays as it is.
fn text_field(msg: &Value) -> Result<String> {
    let text = str_field(msg, "text")?;
    Ok(if msg.get("codes").and_then(Value::as_bool) == Some(true) {
        saturnus_objects::charset::from_trigraphs(text)
    } else {
        text.to_string()
    })
}

/// A typed answer as the reply's JSON value.
fn value_of<T: Serialize>(v: &T) -> Result<Value> {
    serde_json::to_value(v).map_err(|e| e.to_string().into())
}

fn unknown_key(e: &Emulator, key: &str) -> Error {
    format!("no key {key:?} on the {}", e.model().name()).into()
}

/// What a command handler answers: a reply now (with bytes for a field),
/// or later (a send).
enum Answer {
    Now(Value, Option<(&'static str, Vec<u8>)>),
    Later,
}

impl From<Value> for Answer {
    fn from(v: Value) -> Self {
        Answer::Now(v, None)
    }
}

impl Engine {
    /// An engine with no machine yet, for the host called `host`, paced
    /// as `pacing` says.
    pub fn new(host: &'static str, pacing: Pacing) -> Engine {
        Engine {
            host,
            emu: None,
            model: None,
            rom_name: String::new(),
            halted: None,
            lp: Loop::new(pacing),
            watch: Watch::default(),
            send: None,
            out: Vec::new(),
            last_status: None,
            last_frame: None,
            autosave: AutoSave::default(),
            answer_recover: false,
            recover: None,
            serial: false,
            serial_out: SerialOut::default(),
        }
    }

    /// Whether a cold boot's "Try To Recover Memory?" (48SX, 48GX, 49G)
    /// is answered NO for the user, and the 49G's "Memory Clear" after it
    /// dismissed (`recover.rs`): a host that keeps the user's calculator
    /// (off by default; key scripts and tests answer it themselves).
    pub fn set_answer_recover(&mut self, on: bool) {
        self.answer_recover = on;
        if !on {
            self.recover = None;
        }
    }

    /// An answer to the boot's question is still pending.
    pub fn answering_recover(&self) -> bool {
        self.recover.is_some()
    }

    /// Whether the host keeps states: then the machine's state comes out
    /// as [`Output::Save`] once it changed and settled (off by default).
    pub fn set_auto_save(&mut self, on: bool) {
        self.autosave.on = on;
        if !on {
            self.autosave.clear();
        }
    }

    /// Saves handed to the host so far.
    pub fn auto_saves(&self) -> u64 {
        self.autosave.saves
    }

    /// A change is waiting to be saved.
    pub fn save_owed(&self) -> bool {
        self.autosave.owed()
    }

    /// Hand out the owed save now, without the delay, if the machine has
    /// settled (a computing one is not saved: its last settled state is
    /// in the store). A host calls it before a boot, and stores what it
    /// gives before it reads or clears the slot: a model switch keeps the
    /// machine it leaves, a reboot of the same model restores the newest
    /// state, and a fresh start deletes the slot after this save, so the
    /// old machine never comes back.
    pub fn save_now(&mut self) {
        if self.autosave.owed() && self.settled() {
            self.emit_save();
        }
    }

    /// The protocol version check and the command's name, refused while a
    /// send is typing if its [`Policy`] says so: what every command
    /// passes first, also those a host serves itself.
    pub fn admit<'a>(&self, msg: &'a Value) -> Result<&'a str> {
        match msg.get("v") {
            Some(v) if v.as_u64() == Some(VERSION) => {}
            Some(v) => {
                return Err(format!(
                    "protocol version {v} not supported (this host speaks {VERSION})"
                )
                .into());
            }
            None => {
                return Err(
                    format!("protocol version missing (this host speaks {VERSION})").into(),
                );
            }
        }
        let cmd = str_field(msg, "cmd")?;
        match self.refusal(cmd) {
            Some(e) => Err(e),
            None => Ok(cmd),
        }
    }

    /// Why `cmd` is refused now, or `None` (an unknown name never is):
    /// the page holds the serial port and it is a write or a question to
    /// the server; a send is typing and it is `refused_while_typing`; a
    /// write runs and it uses the serial port.
    pub fn refusal(&self, cmd: &str) -> Option<Error> {
        let policy = cmd.parse::<CommandKind>().ok()?.policy();
        if self.serial && (policy.write || policy.server) {
            return Some(SERIAL_IN_USE.into());
        }
        let send = self.send.as_ref()?;
        let refused = policy.refused_while_typing || (send.transfer && policy.serial);
        refused.then(|| {
            if send.transfer {
                "a transfer is in progress (releaseAll stops it)".into()
            } else {
                "typing is in progress (releaseAll stops it)".into()
            }
        })
    }

    /// One protocol message. `bytes` are its *bytes* field when the host
    /// has them apart from the JSON (the Worker's `rom` and `state`);
    /// without them a `state` field is base64. With a `reply` tag the
    /// reply comes out as [`Output::Reply`] after the events the command
    /// caused (a send's when it is done); without one an error comes out
    /// as an `error` event.
    pub fn command(
        &mut self,
        clock: &dyn Clock,
        msg: &Value,
        bytes: Option<Vec<u8>>,
        reply: Option<u64>,
    ) {
        let answer = self
            .admit(msg)
            .and_then(|cmd| self.handle(clock, cmd, msg, bytes, reply));
        match answer {
            Ok(Answer::Later) => self.flush(clock, true),
            Ok(Answer::Now(v, b)) => self.respond(clock, reply, Ok(v), b),
            Err(e) => self.respond(clock, reply, Err(e), None),
        }
    }

    /// Answer a command the host served itself: the events so far, then
    /// the reply (or, without a `reply` tag, an `error` event for an
    /// error).
    pub fn answer(&mut self, clock: &dyn Clock, reply: Option<u64>, result: Result<Value>) {
        self.respond(clock, reply, result, None);
    }

    fn respond(
        &mut self,
        clock: &dyn Clock,
        reply: Option<u64>,
        result: Result<Value>,
        bytes: Option<(&'static str, Vec<u8>)>,
    ) {
        self.flush(clock, true);
        self.reply_to(reply, result, bytes);
    }

    fn reply_to(
        &mut self,
        reply: Option<u64>,
        result: Result<Value>,
        bytes: Option<(&'static str, Vec<u8>)>,
    ) {
        match (reply, result) {
            (Some(tag), result) => self.out.push(Output::Reply(Reply {
                tag,
                result: result.map_err(|e| e.to_string()),
                bytes,
            })),
            (None, Err(e)) => self.event(Event::Error(ErrorEvent {
                message: e.to_string(),
            })),
            (None, Ok(_)) => {}
        }
    }

    fn event(&mut self, e: Event) {
        self.out.push(Output::Event(e));
    }

    /// The replies and events so far, in order.
    pub fn take_output(&mut self) -> Vec<Output> {
        std::mem::take(&mut self.out)
    }

    /// When [`Engine::timer`] is due on the host's clock; `None` while
    /// only a message can change anything (paused, idle with nothing to
    /// watch).
    pub fn deadline(&self) -> Option<f64> {
        [
            self.send.as_ref().map(|s| s.due),
            self.lp.due(),
            self.watch.due,
            self.serial_out.due(),
            // A busy machine's own timers bring it to the save.
            self.settled().then(|| self.autosave.due()).flatten(),
        ]
        .into_iter()
        .flatten()
        .reduce(f64::min)
    }

    /// The host's timer fired: run what is due (a send's turn, a pass, a
    /// wake, a look at the memory).
    pub fn timer(&mut self, clock: &dyn Clock) {
        let now = clock.now_ms();
        let slack = self.lp.pacing.timer_slack_ms;
        if self.send.as_ref().is_some_and(|s| s.due <= now + slack) {
            self.typing_turn(clock);
        }
        if let Some(e) = self.emu.as_mut()
            && let Err(err) = self.lp.fire(e, clock, now)
        {
            self.halt(clock, err);
        }
        if self.watch.due.is_some_and(|d| d <= now + slack) {
            self.watch.due = None;
        }
        // Between passes a frame waits for the throttle; otherwise it
        // goes now.
        self.flush(clock, !self.lp.passing());
        self.poll_recover(clock);
    }

    /// Answer the boot's question once it is on the screen and the ROM
    /// waits for a key (`recover.rs`); give up when it does not come.
    fn poll_recover(&mut self, clock: &dyn Clock) {
        let Some(r) = self.recover else {
            return;
        };
        if !self.settled() {
            return;
        }
        let Some(e) = self.emu.as_mut() else {
            self.recover = None;
            return;
        };
        match look(e, r) {
            Look::Wait => {}
            Look::GiveUp => self.recover = None,
            Look::Answer(next) => {
                e.type_keys("f");
                self.recover = next;
                self.after_keys(clock);
            }
        }
    }

    /// Bytes arrived for the machine from outside (the serial bridge): a
    /// sleeping CPU first runs the time that passed, then sees when the
    /// UART wakes it.
    pub fn input(&mut self, clock: &dyn Clock) {
        self.autosave.touch(clock.now_ms());
        if self.lp.sleeping() {
            self.wake(clock);
            self.flush(clock, !self.lp.passing());
        }
    }

    /// The page holds the serial port (`serialOpen`).
    pub fn serial_open(&self) -> bool {
        self.serial
    }

    /// The page lets go of the serial port: bytes not yet on the wire to
    /// the calculator are dropped, and so is what it sent and the page
    /// did not get.
    fn close_serial(&mut self) {
        self.serial_out = SerialOut::default();
        if std::mem::take(&mut self.serial)
            && let Some(e) = self.emu.as_mut()
        {
            let m = e.machine_mut();
            m.serial_clear_inbound();
            m.serial_drain();
        }
    }

    /// A write through the Kermit server runs (a `/v1/memory` write, a
    /// server probe): it owns the calculator's UART, so a host's own serial
    /// bridge leaves it alone until it ends.
    pub fn transferring(&self) -> bool {
        self.send.as_ref().is_some_and(|s| s.transfer)
    }

    /// The tag of the send in progress, if it has one.
    pub fn sending(&self) -> Option<u64> {
        self.send.as_ref().and_then(|s| s.tag)
    }

    /// Stop the send in progress; its reply is the error `why`.
    pub fn cancel_send(&mut self, clock: &dyn Clock, why: &str) {
        if self.send.is_some() {
            self.end_typing(clock, Some(why.into()));
        }
    }

    /// What `status` says now.
    pub fn status(&self) -> Status {
        Status {
            model: self.model.map(Model::name),
            rom_name: self.rom_name.clone(),
            running: self.lp.running,
            halted: self.halted.clone(),
            speed: self.lp.speed,
            loop_state: self.lp.state(),
            busy: self.send.as_ref().is_some_and(|s| s.freezes),
            // Only answered while the machine runs: paused or halted at
            // the question, the keyboard is the user's to take.
            starting: self.recover.is_some() && self.lp.running && self.halted.is_none(),
        }
    }

    /// The machine, for what a host does beside the protocol (the serial
    /// bridge); `None` before a boot.
    pub fn emulator_mut(&mut self) -> Option<&mut Emulator> {
        self.emu.as_mut()
    }

    /// The machine, for the commands a host serves itself.
    pub fn emulator(&self) -> Result<&Emulator> {
        self.emu.as_ref().ok_or_else(|| "no ROM loaded".into())
    }

    /// The machine, once the host is done with the engine.
    pub fn into_emulator(self) -> Option<Emulator> {
        self.emu
    }

    /// Start running `emu`, a machine the host built (and perhaps ran)
    /// from the ROM file `rom_name`.
    pub fn start(&mut self, clock: &dyn Clock, emu: Emulator, rom_name: &str) {
        self.serial = false;
        self.serial_out = SerialOut::default();
        self.model = Some(emu.model());
        self.emu = Some(emu);
        self.rom_name = rom_name.to_string();
        // A machine the host built and perhaps ran: its screen is its own.
        self.recover = None;
        self.halted = None;
        self.watch.force = true;
        self.autosave.clear();
        self.set_running(clock, true);
        self.flush(clock, true);
    }

    /// Write `nibbles` from `address` on as CPU writes would (`poke`):
    /// the display may show it, the user memory may have changed, a
    /// sleeping CPU may see it.
    pub fn poke(&mut self, clock: &dyn Clock, address: u32, nibbles: &[u8]) -> Result<()> {
        if let Some(e) = self.refusal("poke") {
            return Err(e);
        }
        let e = self.emu.as_mut().ok_or("no ROM loaded")?;
        self.recover = None;
        for (a, &n) in (address..).zip(nibbles) {
            e.machine_mut().poke(a, n);
        }
        e.reshow();
        self.watch.force = true;
        if self.send.is_none() {
            self.lp.schedule(&*e, clock.now_ms());
        }
        self.autosave.touch(clock.now_ms());
        Ok(())
    }

    /// Run `f` on the machine outside the pacing, as fast as the host can
    /// (a native key script), with every key released first; then follow
    /// the wall clock again from where it left the machine. `f` gets the
    /// machine and gives it back with its result. Refused during a send,
    /// as `keyScript`.
    pub fn exclusive<T>(
        &mut self,
        clock: &dyn Clock,
        f: impl FnOnce(Machine) -> (Machine, std::result::Result<T, RunError>),
    ) -> Result<T> {
        if let Some(e) = self.refusal("keyScript") {
            return Err(e);
        }
        // A sleeping machine first catches up the time that passed.
        self.wake_running(clock)?;
        let mut emu = self.emu.take().ok_or("no ROM loaded")?;
        emu.release_keys();
        self.recover = None;
        let start = clock.now_ms();
        let (machine, result) = f(emu.into_machine());
        self.lp.work_ms += clock.now_ms() - start;
        self.emu = Some(Emulator::from_machine(machine));
        self.autosave.touch(clock.now_ms());
        match result {
            Ok(t) => {
                self.set_running(clock, self.lp.running);
                Ok(t)
            }
            Err(e) => {
                if e.halted {
                    self.halted = Some(e.message.clone());
                    self.set_running(clock, false);
                } else {
                    self.set_running(clock, self.lp.running);
                }
                Err(e.message.into())
            }
        }
    }

    /// Build `model` (a preference: a ROM that only fits another model
    /// boots that one) from `rom` and run it; the machine before keeps
    /// running if this one cannot be built.
    pub fn boot(
        &mut self,
        clock: &dyn Clock,
        model: &str,
        rom: &[u8],
        rom_name: &str,
    ) -> Result<Booted> {
        self.boot_restoring(clock, model, rom, rom_name, None)
    }

    /// [`Engine::boot`], then restore `kept`, the state the host kept for
    /// this model, before the machine runs a cycle: the calculator is as
    /// it was, with no "Try To Recover Memory?". A state that does not
    /// load (another ROM, another model, an older format) leaves the cold
    /// boot, and `restore_error` says why. The machine it replaces is not
    /// saved here: the host calls [`Engine::save_now`] and stores that
    /// save before it reads or clears the slot, so the slot it reads is
    /// the newest and a fresh start's stays empty. An owed save left now
    /// is dropped.
    pub fn boot_restoring(
        &mut self,
        clock: &dyn Clock,
        model: &str,
        rom: &[u8],
        rom_name: &str,
        kept: Option<&[u8]>,
    ) -> Result<Booted> {
        if let Some(e) = self.refusal("boot") {
            return Err(e);
        }
        let model = model_for_rom(rom, model.parse()?);
        let mut emu = Emulator::new(model, rom)?;
        let mut restored = false;
        let mut restore_error = None;
        if let Some(state) = kept {
            if state.len() > MAX_STATE_BYTES {
                restore_error = Some(format!("state is larger than {MAX_STATE_BYTES} bytes"));
            } else {
                match emu.load_state(state) {
                    Ok(()) => restored = true,
                    Err(e) => restore_error = Some(e.to_string()),
                }
            }
        }
        // A cold boot of a model that asks: the question is answered once it is up.
        self.recover =
            (self.answer_recover && !restored && recover::asks(model)).then(|| Recover {
                step: Step::Prompt,
                until_ms: emu.emulated_ms() + recover::PROMPT_WAIT_MS,
            });
        // Another calculator: the page's link to the old one is gone.
        self.serial = false;
        self.serial_out = SerialOut::default();
        self.emu = Some(emu);
        self.model = Some(model);
        self.rom_name = rom_name.to_string();
        self.halted = None;
        self.watch.force = true;
        self.autosave.clear();
        self.set_running(clock, true);
        self.flush(clock, true);
        Ok(Booted {
            model: model.name(),
            rom_name: self.rom_name.clone(),
            restored,
            restore_error,
        })
    }

    /// The whole machine state (`saveState`).
    pub fn save_state(&self) -> Result<Vec<u8>> {
        if let Some(e) = self.refusal("saveState") {
            return Err(e);
        }
        Ok(self.emulator()?.save_state())
    }

    /// Restore a saved state of the same model and ROM (`loadState`);
    /// the host's queued and held keys go with the old machine
    /// ([`Emulator::load_state`]). A state that does not load changes
    /// nothing, the keys held included.
    pub fn load_state(&mut self, clock: &dyn Clock, state: &[u8]) -> Result<()> {
        if let Some(e) = self.refusal("loadState") {
            return Err(e);
        }
        if state.len() > MAX_STATE_BYTES {
            return Err(format!("state is larger than {MAX_STATE_BYTES} bytes").into());
        }
        let e = self.emu.as_mut().ok_or("no ROM loaded")?;
        e.load_state(state)?;
        e.reshow();
        // Another machine's screen: nothing of the boot's to answer.
        self.recover = None;
        self.halted = None;
        self.watch.force = true;
        self.autosave.touch(clock.now_ms());
        self.set_running(clock, self.lp.running);
        self.flush(clock, true);
        Ok(())
    }

    /// Stats now.
    pub fn stats(&self, clock: &dyn Clock) -> Stats {
        let now = clock.now_ms();
        Stats {
            cycles: self.emu.as_ref().map_or(0, |e| e.machine().cycles()),
            emulated_ms: self.emu.as_ref().map_or(0.0, Emulator::emulated_ms),
            work_ms: self.lp.work_ms,
            ticks: self.lp.ticks,
            wakes: self.lp.wakes,
            memory_looks: self.watch.looks,
            memory_ms: self.watch.spent_ms,
            loop_state: self.lp.state(),
            owed_ms: self.lp.owed_ms(now),
            now_ms: now,
        }
    }

    fn emu(&mut self) -> Result<&mut Emulator> {
        self.emu.as_mut().ok_or_else(|| "no ROM loaded".into())
    }

    /// One admitted command.
    fn handle(
        &mut self,
        clock: &dyn Clock,
        cmd: &str,
        msg: &Value,
        bytes: Option<Vec<u8>>,
        reply: Option<u64>,
    ) -> Result<Answer> {
        // The user's own keys answer whatever the screen asks: the boot's
        // question is theirs then. (A machine replaced, reset, poked or
        // run by a key script ends it in those methods, for every host.)
        let kind: CommandKind = cmd.parse()?;
        use CommandKind as C;
        if matches!(kind, C::KeyDown | C::TypeLetter | C::TypeKeys) {
            self.recover = None;
        }
        Ok(match kind {
            C::Hello => {
                // A (re)loaded page starts from nothing: the status, the
                // keys down and the current frame go out again, before
                // this reply. The page fetches the model's skin itself.
                self.last_status = None;
                self.watch.on = false;
                self.close_serial();
                if let Some(e) = self.emu.as_mut() {
                    e.reshow();
                }
                let models: Vec<&str> = crate::skins::hosted_models().map(|m| m.name()).collect();
                // The release (the workspace's version): the page shows it in About.
                json!({
                    "protocol": VERSION,
                    "host": self.host,
                    "models": models,
                    "version": env!("CARGO_PKG_VERSION"),
                })
                .into()
            }
            C::Skin => {
                let m: Model = str_field(msg, "model")?.parse()?;
                let view = crate::skins::skin_view(m)
                    .ok_or_else(|| format!("no drawn keyboard for the {} yet", m.name()))?;
                value_of(&view)?.into()
            }
            C::Layout => {
                let m: Model = str_field(msg, "model")?.parse()?;
                value_of(&crate::layout::grid(m))?.into()
            }
            C::Boot => {
                let model = str_field(msg, "model")?;
                let rom = bytes.ok_or("missing bytes field \"rom\"")?;
                let name = msg.get("romName").and_then(Value::as_str).unwrap_or("");
                value_of(&self.boot(clock, model, &rom, name)?)?.into()
            }
            C::KeyDown => {
                let key = str_field(msg, "key")?;
                let shift = msg.get("shift").and_then(Value::as_str);
                let e = self.emu()?;
                let queued = match shift {
                    None => e.press(key),
                    Some(shift) => {
                        if !e.has_key(shift) {
                            return Err(unknown_key(e, shift));
                        }
                        e.press_shifted(key, shift)
                    }
                };
                if !queued {
                    if let Some(shift) = shift.filter(|_| e.has_key(key)) {
                        return Err(format!("{shift:?} is not a shift key").into());
                    }
                    return Err(unknown_key(e, key));
                }
                self.autosave.touch(clock.now_ms());
                self.after_keys(clock);
                Value::Null.into()
            }
            C::KeyUp => {
                let key = str_field(msg, "key")?;
                let e = self.emu()?;
                if !e.has_key(key) {
                    return Err(unknown_key(e, key));
                }
                e.release(key);
                e.pump();
                self.autosave.touch(clock.now_ms());
                Value::Null.into()
            }
            C::KeyUpAll => {
                // The window lost the focus during a send: the send holds
                // no queued key, and its own key comes up when its press
                // ends.
                if self.send.is_none()
                    && let Some(e) = self.emu.as_mut()
                {
                    e.release_held();
                    e.pump();
                }
                Value::Null.into()
            }
            C::TypeLetter => {
                let letter = str_field(msg, "letter")?;
                let Some(e) = self.emu.as_mut() else {
                    return Ok(Value::Bool(false).into());
                };
                let ok = e.type_letter(letter);
                self.autosave.touch(clock.now_ms());
                self.after_keys(clock);
                Value::Bool(ok).into()
            }
            C::TypeKeys => {
                let keys = msg
                    .get("keys")
                    .and_then(Value::as_array)
                    .ok_or("missing array field \"keys\"")?;
                // As long as the longest text a send types.
                if keys.len() > crate::typing::MAX_CHARS {
                    return Err(format!(
                        "\"keys\" holds more than {} keys",
                        crate::typing::MAX_CHARS
                    )
                    .into());
                }
                let keys: Vec<&str> = keys
                    .iter()
                    .map(Value::as_str)
                    .collect::<Option<_>>()
                    .ok_or("\"keys\" must hold key names (strings)")?;
                let e = self.emu()?;
                // All or nothing: one unknown name refuses the sequence.
                if let Some(k) = keys.iter().find(|k| !e.has_key(k)) {
                    return Err(unknown_key(e, k));
                }
                e.queue().type_keys(&keys);
                self.autosave.touch(clock.now_ms());
                self.after_keys(clock);
                Value::Null.into()
            }
            C::ReleaseAll => {
                // Also stops a send in progress (its reply is an error).
                self.cancel_send(clock, "cancelled");
                if let Some(e) = self.emu.as_mut() {
                    e.release_keys();
                }
                Value::Null.into()
            }
            C::SetSpeed => {
                // Asleep, emulated time runs at 1x at any speed: only the
                // passes change.
                self.lp.speed = Speed::parse(str_field(msg, "speed")?);
                Value::Null.into()
            }
            C::Pause => {
                // Anything but `paused: false` pauses.
                let paused = msg.get("paused").and_then(Value::as_bool).unwrap_or(true);
                self.set_running(clock, !paused);
                Value::Null.into()
            }
            C::Unload => {
                // Its ROM was removed: no machine, as before the first
                // boot (the page shows the empty state). A change not yet
                // saved is saved first, as saved states stay (the page
                // deletes a 49G's after, with its ROM).
                if self.autosave.owed() {
                    self.emit_save();
                }
                self.serial = false;
                self.serial_out = SerialOut::default();
                self.emu = None;
                self.model = None;
                self.rom_name.clear();
                self.halted = None;
                self.recover = None;
                self.watch.on = false;
                self.autosave.clear();
                self.set_running(clock, false);
                self.send_status();
                Value::Null.into()
            }
            C::Reset => {
                self.recover = None;
                let e = self.emu()?;
                e.release_keys();
                e.reset();
                self.halted = None;
                self.autosave.touch(clock.now_ms());
                self.set_running(clock, true);
                Value::Null.into()
            }
            C::SaveState => {
                let state = self.save_state()?;
                let cycles = self.emulator()?.machine().cycles();
                Answer::Now(json!({"cycles": cycles}), Some(("state", state)))
            }
            C::LoadState => {
                let state = match bytes {
                    Some(b) => b,
                    None => {
                        let b64 = str_field(msg, "state")?;
                        if b64.len() > MAX_STATE_BYTES.div_ceil(3) * 4 {
                            return Err(
                                format!("state is larger than {MAX_STATE_BYTES} bytes").into()
                            );
                        }
                        base64_decode(b64).map_err(|e| format!("state: {e}"))?
                    }
                };
                self.load_state(clock, &state)?;
                json!({}).into()
            }
            C::Visibility => {
                let hidden = msg.get("hidden").and_then(Value::as_bool).unwrap_or(false);
                // The last moment a phone's page may run: an unsaved
                // change is saved now, or once a send, a write or a
                // computation has settled. In the browser a computation
                // stops while hidden, so its save waits until the page is
                // shown again.
                if hidden {
                    self.autosave.hide();
                }
                let idle = self.send.is_none();
                self.lp
                    .set_hidden(hidden, self.emu.as_ref(), idle, clock.now_ms());
                Value::Null.into()
            }
            C::Stats => value_of(&self.stats(clock))?.into(),
            C::WatchMemory => {
                let on = msg.get("on").and_then(Value::as_bool).unwrap_or(false);
                self.watch.subscribe(on, self.emu.as_ref());
                let Some(e) = &self.emu else {
                    return Ok(json!({"supported": null, "reason": null}).into());
                };
                let reason = e.memory_refusal();
                json!({"supported": reason.is_none(), "reason": reason}).into()
            }
            C::MemoryTree => value_of(&self.emu()?.memory_tree()?)?.into(),
            C::Stack => Value::Array(self.emu()?.stack()?).into(),
            C::StackTop => self.emu()?.stack_top()?.into(),
            C::Flags => value_of(&self.emu()?.flags()?)?.into(),
            C::ObjectAt => {
                let address = msg
                    .get("address")
                    .and_then(Value::as_u64)
                    .ok_or("missing number field \"address\"")?;
                let address = u32::try_from(address)
                    .ok()
                    .filter(|&a| a <= 0xF_FFFF)
                    .ok_or("address is outside the address space")?;
                self.emu()?.object_at(address)?.into()
            }
            C::CommandLine => value_of(&self.emu()?.command_line()?)?.into(),
            C::EntryModes => value_of(&crate::typing::entry_modes(self.emu()?.machine())?)?.into(),
            C::UiState => value_of(&self.emu()?.ui_state()?)?.into(),
            C::SerialOpen => {
                let serial = self.serial;
                let e = self.emu()?;
                if !e.machine().has_serial() {
                    return Err(format!(
                        "the {} has no serial port",
                        e.model().name().to_uppercase()
                    )
                    .into());
                }
                // What the calculator sent before is not the page's; once
                // open, what it sent since is (a second open keeps it).
                if !serial {
                    e.machine_mut().serial_drain();
                    self.serial = true;
                }
                Value::Null.into()
            }
            C::SerialWrite => {
                // The calculator and the port first, then the bytes.
                self.emu()?;
                if !self.serial {
                    return Err("the serial port is not open (serialOpen first)".into());
                }
                let too_many =
                    || format!("more than {MAX_SERIAL_PENDING} bytes for the serial port");
                let data = match bytes {
                    Some(b) => b,
                    None => {
                        let b64 = str_field(msg, "bytes")?;
                        if b64.len() > MAX_SERIAL_PENDING.div_ceil(3) * 4 {
                            return Err(too_many().into());
                        }
                        base64_decode(b64).map_err(|e| format!("bytes: {e}"))?
                    }
                };
                if data.len() > MAX_SERIAL_PENDING {
                    return Err(too_many().into());
                }
                let m = self.emu()?.machine_mut();
                let waiting = m.serial_pending();
                if waiting + data.len() > MAX_SERIAL_PENDING {
                    return Err(format!(
                        "the serial port's input is full ({waiting} bytes still waiting)"
                    )
                    .into());
                }
                m.serial_push(&data);
                self.input(clock);
                Value::Null.into()
            }
            C::SerialClose => {
                self.close_serial();
                Value::Null.into()
            }
            C::EditText => {
                let (dir, target) = self.text_target(msg)?;
                let (text, was) = self.emu()?.edit_text(&dir, &target)?;
                json!({"text": text, "was": was}).into()
            }
            C::Insert | C::TypeText => self.start_typing(clock, "insert", msg, reply)?,
            C::Run => self.start_typing(clock, "run", msg, reply)?,
            C::ProbeServer | C::EndServer => {
                // No server possible: answered at once, the machine
                // untouched (a boot's check is no change to save).
                let m = self.emu()?.machine();
                if !crate::transfer::may_serve(m) && m.has_serial() {
                    return Ok(json!({"server": false, "emulatedMs": 0.0, "keys": false}).into());
                }
                let op = Op::Server {
                    end: kind == C::EndServer,
                };
                self.start_transfer(clock, op, reply)?
            }
            C::StoreFile
            | C::FetchFile
            | C::Purge
            | C::Rename
            | C::CreateDir
            | C::ChangeDir
            | C::SetFlag
            | C::Copy
            | C::Move
            | C::StoreScreen
            | C::StoreText
            | C::Backup => {
                let op = self.write_op(kind, msg, bytes)?;
                self.start_transfer(clock, op, reply)?
            }
            C::Replace => self.start_typing(clock, "replace", msg, reply)?,
            C::SetClock => self.set_clock(clock, msg, reply)?,
            // Served by the hosts themselves (the native commands, the ROM
            // slots, the hub's), or by none: unknown here.
            C::Screen
            | C::Info
            | C::Model
            | C::Peek
            | C::Poke
            | C::KeyScript
            | C::StateSlot
            | C::OpenState
            | C::SaveFile
            | C::RomSlots
            | C::BootModel
            | C::ChooseRom
            | C::DownloadRom
            | C::ForgetRom
            | C::RomSettings
            | C::Join
            | C::Ping
            | C::Attach
            | C::Leave => return Err(format!("unknown command {cmd:?}").into()),
        })
    }

    /// Commands queued keys: wake a sleeping machine (its time first, then
    /// the keys; the wake starts passes for the queue), then feed the
    /// queue.
    fn after_keys(&mut self, clock: &dyn Clock) {
        self.wake(clock);
        if let Some(e) = self.emu.as_mut() {
            e.pump();
        }
    }

    /// Leave a sleep now (a halt on the way stops the machine).
    fn wake(&mut self, clock: &dyn Clock) {
        if let Some(e) = self.emu.as_mut()
            && let Err(err) = self.lp.wake(e, clock)
        {
            self.halt(clock, err);
        }
    }

    /// [`Engine::wake`] for work that needs a running CPU: refused if it
    /// is halted, before the wake or by it (the time it caught up ran into
    /// the halt).
    fn wake_running(&mut self, clock: &dyn Clock) -> Result<()> {
        if self.halted.is_none() {
            self.wake(clock);
        }
        match &self.halted {
            Some(h) => Err(format!("the CPU is halted: {h}").into()),
            None => Ok(()),
        }
    }

    fn halt(&mut self, clock: &dyn Clock, err: Error) {
        self.halted = Some(err.to_string());
        self.set_running(clock, false);
    }

    /// The Run/Pause switch, and the restart after anything that changed
    /// the machine under the loop.
    fn set_running(&mut self, clock: &dyn Clock, on: bool) {
        self.lp.running = on && self.emu.is_some() && self.halted.is_none();
        self.lp.stop();
        // A send drives the machine itself; the loop resumes when it ends.
        if self.send.is_some() {
            return;
        }
        if let Some(e) = &self.emu {
            self.lp.start(e, clock.now_ms());
        }
    }

    /// Start a send of `msg`'s `text` with `verb`: the loop stops and the
    /// send runs in turns ([`Engine::timer`]) until it is done.
    fn start_typing(
        &mut self,
        clock: &dyn Clock,
        verb: &str,
        msg: &Value,
        reply: Option<u64>,
    ) -> Result<Answer> {
        let text = &text_field(msg)?;
        self.emu()?;
        // A sleeping machine first catches up the time that passed.
        self.wake_running(clock)?;
        // Right after a cold boot the question still has the keyboard
        // (and the 49G's RAM may not hold a command line yet): the send
        // waits, in emulated time, until it is answered, then types.
        let waiting = self.recover.is_some() && self.lp.running;
        let freezes = if waiting {
            self.emu()?.check_typing(verb, text)?
        } else {
            self.emu()?.start_typing(verb, text)?
        };
        self.lp.stop();
        let now = clock.now_ms();
        self.autosave.touch(now);
        self.send = Some(Send {
            tag: reply,
            freezes,
            transfer: false,
            started: now,
            due: now,
            stopping: None,
            waiting: waiting.then(|| Waiting::Typing(verb.to_string(), text.to_string())),
        });
        Ok(Answer::Later)
    }

    /// The write a command asks for: `dir` (the current directory when
    /// absent), `name`, `to`, `flag`, `on`, and `storeFile`'s file
    /// (`bytes`, else the base64 field `data`).
    fn write_op(&mut self, cmd: CommandKind, msg: &Value, bytes: Option<Vec<u8>>) -> Result<Op> {
        let given = match msg.get("dir") {
            None | Some(Value::Null) => None,
            Some(v) => Some(
                v.as_array()
                    .and_then(|a| {
                        a.iter()
                            .map(|s| s.as_str().map(str::to_string))
                            .collect::<Option<Vec<_>>>()
                    })
                    .ok_or("\"dir\" must be an array of directory names")?,
            ),
        };
        let name = || str_field(msg, "name").map(str::to_string);
        let dir = Vec::new();
        if cmd == CommandKind::StoreText {
            let text = text_field(msg)?;
            let (dir, target) = self.text_target(msg)?;
            // What the editor opened must still be there: a save never
            // replaces what it did not show. Compared by the object
            // (`editText`'s `was`: size and checksum), not its text, which
            // follows the display mode.
            if let Some(was) = msg.get("was").and_then(Value::as_str) {
                self.emu()?.check_unchanged(&dir, &target, was)?;
            }
            return Ok(Op::StoreText { dir, target, text });
        }
        if cmd == CommandKind::StoreScreen {
            let name = match msg.get("name") {
                None | Some(Value::Null) => None,
                Some(_) => Some(name()?),
            };
            let screen = self.screen_of(msg)?;
            let dir = match (given, &name) {
                (Some(d), _) => d,
                (None, Some(_)) => self.emu()?.memory_tree()?.path,
                (None, None) => Vec::new(),
            };
            return Ok(Op::StoreScreen {
                dir,
                name,
                replace: msg.get("replace").and_then(Value::as_bool).unwrap_or(false),
                screen,
            });
        }
        if cmd == CommandKind::Backup {
            return Ok(Op::Backup);
        }
        let mut op = match cmd {
            CommandKind::StoreFile => {
                let data = match bytes {
                    Some(b) => b,
                    None => {
                        let b64 = str_field(msg, "data")?;
                        if b64.len() > MAX_FILE_BYTES.div_ceil(3) * 4 {
                            return Err(
                                format!("the file is larger than {MAX_FILE_BYTES} bytes").into()
                            );
                        }
                        base64_decode(b64).map_err(|e| format!("data: {e}"))?
                    }
                };
                Op::Store {
                    dir,
                    name: name()?,
                    data,
                    replace: msg.get("replace").and_then(Value::as_bool),
                }
            }
            CommandKind::FetchFile => Op::Fetch {
                dir,
                name: name()?,
                text: msg.get("text").and_then(Value::as_bool).unwrap_or(false),
            },
            CommandKind::Purge => Op::Purge { dir, name: name()? },
            CommandKind::Rename => Op::Rename {
                dir,
                name: name()?,
                to: str_field(msg, "to")?.to_string(),
            },
            CommandKind::CreateDir => Op::CreateDir { dir, name: name()? },
            CommandKind::Copy | CommandKind::Move => Op::Copy {
                dir,
                name: name()?,
                to: msg
                    .get("to")
                    .and_then(Value::as_array)
                    .and_then(|a| {
                        a.iter()
                            .map(|s| s.as_str().map(str::to_string))
                            .collect::<Option<Vec<_>>>()
                    })
                    .ok_or("\"to\" must be an array of directory names")?,
                replace: msg.get("replace").and_then(Value::as_bool).unwrap_or(false),
                remove: cmd == CommandKind::Move,
            },
            CommandKind::ChangeDir if given.is_none() => {
                return Err("missing array field \"dir\"".into());
            }
            CommandKind::ChangeDir => Op::ChangeDir { dir },
            _ => {
                let flag = msg
                    .get("flag")
                    .and_then(Value::as_i64)
                    .and_then(|f| i32::try_from(f).ok())
                    .ok_or("missing number field \"flag\"")?;
                let on = msg
                    .get("on")
                    .and_then(Value::as_bool)
                    .ok_or("missing boolean field \"on\"")?;
                Op::SetFlag { flag, on }
            }
        };
        // The fields first, then the calculator.
        if let Op::Store { dir, .. }
        | Op::Fetch { dir, .. }
        | Op::Purge { dir, .. }
        | Op::Rename { dir, .. }
        | Op::CreateDir { dir, .. }
        | Op::Copy { dir, .. }
        | Op::ChangeDir { dir } = &mut op
        {
            *dir = match given {
                Some(d) => d,
                None => self.emu()?.memory_tree()?.path,
            };
        }
        Ok(op)
    }

    /// The screen `storeScreen` stores: `pixels` (base64, packed as the
    /// `frame` event's, the display's size: the frame the page showed),
    /// or else the display as it is now.
    fn screen_of(&mut self, msg: &Value) -> Result<saturnus_objects::Graphic> {
        let lcd = self.emu()?.machine().lcd();
        let (width, height) = (lcd.width(), lcd.height());
        let packed = match msg.get("pixels") {
            None | Some(Value::Null) => crate::host::pack_bits(&lcd.pixels),
            Some(_) => {
                let b64 = str_field(msg, "pixels")?;
                let given =
                    |k: &str, d: usize| msg.get(k).and_then(Value::as_u64).unwrap_or(d as u64);
                if given("width", width) != width as u64 || given("height", height) != height as u64
                {
                    return Err(format!("the screen is {width} by {height} pixels").into());
                }
                let bytes = base64_decode(b64).map_err(|e| format!("pixels: {e}"))?;
                if bytes.len() != crate::host::packed_row_bytes(width) * height {
                    return Err(format!("pixels: not {width} by {height} pixels").into());
                }
                bytes
            }
        };
        saturnus_objects::Graphic::from_packed(width as u32, height as u32, &packed)
            .map_err(Into::into)
    }

    /// The directory and the target of `editText` and `storeText`: `dir`
    /// (the current directory when absent) and `name`, or `level`.
    fn text_target(&mut self, msg: &Value) -> Result<(Vec<String>, Target)> {
        let target = match (msg.get("name"), msg.get("level")) {
            (Some(_), None) => Target::Variable(str_field(msg, "name")?.to_string()),
            (None, Some(l)) => Target::Level(
                l.as_u64()
                    .and_then(|n| usize::try_from(n).ok())
                    .filter(|&n| n >= 1)
                    .ok_or("\"level\" must be a stack level (1 or more)")?,
            ),
            _ => return Err("give either \"name\" or \"level\"".into()),
        };
        let dir = match msg.get("dir") {
            None | Some(Value::Null) => self.emu()?.memory_tree()?.path,
            Some(v) => v
                .as_array()
                .and_then(|a| {
                    a.iter()
                        .map(|s| s.as_str().map(str::to_string))
                        .collect::<Option<Vec<_>>>()
                })
                .ok_or("\"dir\" must be an array of directory names")?,
        };
        Ok((dir, target))
    }

    /// `setClock`: the 48 and 49 type `→TIME` and `→DATE` as a write
    /// (replied when done); the other models with a clock get its keys
    /// queued (replied at once). Either way the set is rehearsed on a
    /// copy of the machine first and the time keyed ahead (or behind) by
    /// what that showed, so the clock reads the wall clock once the set is
    /// done (`crate::clock`). Refused while the boot's question is being
    /// answered, and when the calculator is off, busy or has a command
    /// line open.
    fn set_clock(&mut self, clock: &dyn Clock, msg: &Value, reply: Option<u64>) -> Result<Answer> {
        let wall_ms = clock.now_ms();
        let time = crate::clock::ClockTime::from_json(msg)?;
        let ms = match msg.get("millisecond") {
            None | Some(Value::Null) => 0.0,
            Some(v) => v
                .as_f64()
                .filter(|ms| (0.0..1000.0).contains(ms))
                .ok_or("\"millisecond\" must be a number from 0 to 999")?,
        };
        let now = crate::clock::Now { time, ms, wall_ms };
        if let Some(h) = &self.halted {
            return Err(format!("the CPU is halted: {h}").into());
        }
        if self.recover.is_some() {
            return Err(crate::clock::BUSY.into());
        }
        if let Some(why) = self.emu()?.clock_refusal() {
            return Err(why.into());
        }
        // Time the CPU slept is run first, so the rehearsal starts from
        // the machine the keys will play on. A wake may halt the CPU; one
        // that could not catch up leaves time owed, which the first pass
        // would run with the keys, faster than the rehearsal: refused.
        self.wake_running(clock)?;
        if self.lp.behind_ms() > 0.0 {
            return Err(crate::clock::BUSY.into());
        }
        let e = self.emu()?;
        if crate::clock::by_command(e.model()) {
            // A write runs as fast as the host can, whatever the speed.
            let (op, _) = e.clock_write(&now, &crate::clock::Pace::UNBOUNDED, clock)?;
            return self.start_transfer(clock, op, reply);
        }
        let pace = self.lp.clock_pace();
        let e = self.emu()?;
        e.set_clock_by_keys(&now, &pace, clock)?;
        self.autosave.touch(clock.now_ms());
        self.after_keys(clock);
        Ok(Value::Null.into())
    }

    /// Start the write `op`: the loop stops and it runs in turns, the
    /// screen held, until it is done.
    fn start_transfer(&mut self, clock: &dyn Clock, op: Op, reply: Option<u64>) -> Result<Answer> {
        self.emu()?;
        self.wake_running(clock)?;
        // As a send: right after a cold boot it waits for the question's
        // answer (the memory is not set up before).
        let waiting = if self.recover.is_some() && self.lp.running {
            Some(Waiting::Transfer(op))
        } else {
            self.emu()?.start_transfer(op)?;
            None
        };
        self.lp.stop();
        let now = clock.now_ms();
        self.autosave.touch(now);
        self.send = Some(Send {
            tag: reply,
            freezes: true,
            transfer: true,
            started: now,
            due: now,
            stopping: None,
            waiting,
        });
        Ok(Answer::Later)
    }

    /// One turn of the send: steps until it is done or the turn's wall
    /// time is used up.
    fn typing_turn(&mut self, clock: &dyn Clock) {
        let (Some(send), Some(e)) = (self.send.as_mut(), self.emu.as_mut()) else {
            return;
        };
        let started = send.started;
        let transfer = send.transfer;
        let start = clock.now_ms();
        let mut result = Ok(false);
        while matches!(result, Ok(false)) && clock.now_ms() - start < self.lp.pacing.typing_tick_ms
        {
            result = if send.waiting.is_some() {
                match answer_boot(e, &mut self.recover) {
                    Ok(true) => match send.waiting.take() {
                        Some(Waiting::Typing(verb, text)) => {
                            e.start_typing(&verb, &text).map(|_| false)
                        }
                        Some(Waiting::Transfer(op)) => e.start_transfer(op).map(|_| false),
                        None => Ok(false),
                    },
                    other => other.map(|_| false),
                }
            } else if transfer {
                e.transfer_step(TYPING_STEP_MS)
            } else {
                e.typing_step(TYPING_STEP_MS)
            };
        }
        let now = clock.now_ms();
        self.lp.work_ms += now - start;
        // Out of wall time after ENTER: the wait ends as at its emulated
        // cap, and the reply says `running` (the error is for typing).
        if matches!(result, Ok(false))
            && now - started > WALL_LIMIT_MS
            && !transfer
            && send.waiting.is_none()
            && e.typing_end_wait()
        {
            for _ in 0..WAIT_END_STEPS {
                result = e.typing_step(TYPING_STEP_MS);
                if !matches!(result, Ok(false)) {
                    break;
                }
                e.typing_end_wait();
            }
        }
        match result {
            Ok(false) if now - started > WALL_LIMIT_MS => self.end_typing(
                clock,
                Some(
                    format!(
                        "{} ran out of wall-clock time ({} s)",
                        if transfer { "the transfer" } else { "typing" },
                        WALL_LIMIT_MS / 1000.0
                    )
                    .into(),
                ),
            ),
            Ok(false) => {
                if let Some(s) = self.send.as_mut() {
                    s.due = now;
                }
                self.flush(clock, true);
            }
            Ok(true) => self.end_typing(clock, None),
            Err(err) => self.end_typing(clock, Some(err)),
        }
    }

    /// Finish the send: its result, or `error` (the send is stopped). A
    /// write that is stopped first runs its cleanup in turns
    /// ([`Send::stopping`]); its reply is then `error`, with what the
    /// cleanup could not do.
    fn end_typing(&mut self, clock: &dyn Clock, error: Option<Error>) {
        let Some(mut send) = self.send.take() else {
            return;
        };
        if let (Some(err), Some(e)) = (&error, self.emu.as_mut())
            && send.transfer
            && e.transferring()
        {
            if send.stopping.is_none() && !matches!(err, Error::Halted(_)) {
                e.stop_transfer();
                let now = clock.now_ms();
                send.stopping = Some(err.clone());
                send.started = now;
                send.due = now;
                self.send = Some(send);
                return;
            }
            // Its cleanup ran out of time too: given up.
            e.abandon_transfer();
        }
        let error = match (send.stopping.take(), error) {
            (Some(why), None) => Some(match self.emu.as_mut().map(Emulator::transfer_result) {
                Some(Err(e)) if e.to_string() != crate::transfer::STOPPED => {
                    format!("{why}; {e}").into()
                }
                _ => why,
            }),
            (Some(why), Some(e)) => Some(format!("{why}; {e}").into()),
            (None, e) => e,
        };
        // The delay counts from its end.
        self.autosave.touch(clock.now_ms());
        let mut bytes = None;
        let result = match (error, self.emu.as_mut()) {
            (_, None) => Err("no ROM loaded".into()),
            (None, Some(e)) if send.transfer => e.transfer_result().and_then(|(r, file)| {
                bytes = file.map(|f| ("data", f));
                value_of(&r)
            }),
            (None, Some(e)) => e.typing_result().and_then(|r| value_of(&r)),
            (Some(err), Some(e)) => {
                e.stop_typing();
                e.stop_transfer();
                Err(err)
            }
        };
        if send.transfer {
            // What the server drew is gone; the memory changed.
            if let Some(e) = self.emu.as_mut() {
                e.reshow();
            }
            self.watch.force = true;
        }
        // The status says the screen is live again before its frame.
        if send.freezes {
            self.send_status();
        }
        match &result {
            Err(e @ Error::Halted(_)) => {
                let e = e.clone();
                self.halt(clock, e);
            }
            _ => self.set_running(clock, self.lp.running),
        }
        self.respond(clock, send.tag, result, bytes);
    }

    /// Send what the calculator sent on a serial port the page holds, the
    /// status if it changed, the errors, the keys and a frame if
    /// they changed (none of these while a long send holds them; a frame
    /// between passes only every [`Pacing::frame_ms`] unless `now`), and
    /// look at the user memory if that is due.
    fn flush(&mut self, clock: &dyn Clock, now: bool) {
        // The serial port is not the screen: a send does not hold it.
        // Gathered between passes, as frames are.
        if self.serial
            && let Some(e) = self.emu.as_mut()
        {
            self.serial_out.held.extend(e.machine_mut().serial_drain());
            let slack = self.lp.pacing.timer_slack_ms;
            if let Some(bytes) = self.serial_out.take(clock.now_ms(), slack, now) {
                self.event(Event::Serial(SerialEvent { bytes }));
            }
        }
        let frozen = self.send.as_ref().is_some_and(|s| s.freezes);
        if !frozen && let Some(e) = self.emu.as_mut() {
            let errors = e.take_errors();
            let keys = e.keys_if_changed();
            let t = clock.now_ms();
            let due = now
                || self
                    .last_frame
                    .is_none_or(|f| t - f >= self.lp.pacing.frame_ms);
            let frame = if due { e.frame_if_changed() } else { None };
            for err in errors {
                self.event(Event::Error(ErrorEvent {
                    message: err.to_string(),
                }));
            }
            if let Some(k) = keys {
                self.event(Event::Keys(k));
            }
            if let Some(f) = frame {
                self.last_frame = Some(t);
                self.event(Event::Frame(f));
            }
            // The menu keys while the ROM waits for a key, no send
            // typing or writing (its RAM is whole then).
            if self.send.is_none()
                && let Some(e) = self.emu.as_mut()
                && pacing::asleep(e)
                && let Some(m) = e.menu_if_changed()
            {
                self.event(Event::Menu(m));
            }
        }
        self.send_status();
        self.poll_memory(clock);
        self.poll_save(clock);
    }

    /// The machine is in a state worth keeping: no send or write in
    /// progress, the CPU asleep with no key down or queued, not halted.
    fn settled(&self) -> bool {
        self.send.is_none()
            && self.halted.is_none()
            && self.emu.as_ref().is_some_and(pacing::asleep)
    }

    /// Hand the state to the host if a save is due and the machine has
    /// settled (`protocol/autosave.rs`).
    fn poll_save(&mut self, clock: &dyn Clock) {
        let settled = self.settled();
        if self
            .autosave
            .poll(clock.now_ms(), self.lp.pacing.timer_slack_ms, settled)
        {
            self.emit_save();
        }
    }

    fn emit_save(&mut self) {
        let Some(e) = self.emu.as_ref() else {
            return;
        };
        let saved = Saved {
            model: e.model().name(),
            rom_name: self.rom_name.clone(),
            cycles: e.machine().cycles(),
            state: e.save_state(),
        };
        self.autosave.clear();
        self.autosave.saves += 1;
        self.out.push(Output::Save(saved));
    }

    fn send_status(&mut self) {
        let status = self.status();
        if self.last_status.as_ref() != Some(&status) {
            self.last_status = Some(status.clone());
            self.event(Event::Status(status));
        }
    }

    /// Tell a watching page that the user memory changed, if a look is
    /// due and shows it (see [`watch`]): not while the machine computes,
    /// nor while a send types.
    fn poll_memory(&mut self, clock: &dyn Clock) {
        let quiet = self.send.is_none()
            && self
                .emu
                .as_ref()
                .is_none_or(|e| !self.lp.running || pacing::asleep(e));
        if self.watch.poll(self.emu.as_ref(), quiet, clock) {
            self.event(Event::MemoryChanged(MemoryChanged {}));
        }
    }
}