ashlar-app 0.2.0

ashlar runtime: App builder, frame scheduler, crash guard, logging, telemetry, agent control
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
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
//! The runtime: one frame of an app (control requests, jobs, autosave, menus, keys, the view,
//! dialogs), the repaint policy, and the eframe glue.
//!
//! Repaints happen only for: input (egui/eframe), a store revision change made during a frame, a
//! job's wake, a control request, toasts and egui animations, injected agent input, the text
//! caret's blink for a while after input ([`crate::caret`]), and pending
//! work that asks for its own frame (settings and autosave wake hooks when a save is due, the
//! autosave writer when a write finished). Every request goes through [`crate::wake`] with a
//! reason (`app.stats` → `wakes`). An idle app, clean or dirty, requests nothing and draws no
//! frames.

use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::mpsc::Receiver;
use std::time::Duration;

use ashlar_command::shortcut::{Platform, format_list};
use ashlar_command::{CommandError, CommandInfo, Keymap, Registry};
use ashlar_control::{AppInfo, Reply, Request, Server};
use ashlar_fs::{ConfigStore, DirConfig, MemoryConfig, Settings};
use ashlar_jobs::Jobs;
use ashlar_store::{Autosave, AutosaveConfig, RecoveryCandidate, Revision};
use ashlar_ui::automation;
use ashlar_ui::commands::keys::works_while_typing;
use ashlar_ui::commands::{CommandPalette, KeymapChange, KeymapEditor, MenuSpec, dispatch, menu_bar};
use ashlar_ui::devtools;
use ashlar_ui::dialog::{Dialog, DialogButton, DialogOutcome};
use ashlar_ui::toasts::Toasts;
use ashlar_ui::tokens::{self, ThemeMode};
use ashlar_ui::wake::{self, Reason, Scheduler, WakeStats};
use serde_json::{Value, json};

use crate::app::{App, Error, SetupFn, Shared, ViewFn};
use crate::caret::Caret;
use crate::control::UiQueue;
use crate::crash::{self, LaunchGuard, PreviousLaunch};
use crate::open::Inbox;
use crate::session::{Document, Effect, Origin, Session, now};
use crate::stats::FrameStats;
use crate::telemetry::Telemetry;
use crate::window_state::{self, WindowState};
use ashlar_native::session_end::{self, EndKind, EndRequest};

/// Wakes for a quit, logout or shutdown request from the OS (IMP-6.7).
const SESSION_END: Reason = Reason("session_end");

mod prefs;

pub use ashlar_motion::MotionPrefs;
pub use ashlar_native::system::Preferences;

/// Top-level menus in this order; menus the app adds follow in first-seen order.
pub const MENU_ORDER: &[&str] = &["File", "Edit", "View"];

/// What `run()` found out before the window opened.
#[derive(Default)]
pub struct Launch {
    /// Start without restoring view settings (after a crash during startup, or `--safe-mode`).
    pub safe_mode: bool,
    pub previous: Option<PreviousLaunch>,
    /// A file named on the command line; it opens after the first frame.
    pub open: Option<PathBuf>,
    pub control_port: Option<u16>,
    pub(crate) guard: Option<LaunchGuard>,
    pub(crate) telemetry: Telemetry,
    /// Files from the OS and later launches, set up before the window opened.
    pub(crate) inbox: Option<Inbox>,
    /// Held while this is the app's only instance ([`App::single_instance`]).
    #[cfg(not(target_arch = "wasm32"))]
    #[allow(dead_code, reason = "held for its drop, which stops listening")]
    pub(crate) instance: Option<ashlar_native::single_instance::PrimaryGuard>,
    /// The first line of `run()`, and when eframe had built the window (native only).
    pub(crate) process_start: Option<std::time::Instant>,
    pub(crate) window_at: Option<std::time::Instant>,
    /// `<PREFIX>_READY_FILE`: gets `{pid, ready_ms}` once the first frame is presented.
    pub(crate) ready_file: Option<PathBuf>,
    /// The first present was recorded.
    pub(crate) presented: bool,
    /// A scene to apply once the session is set up (`--scene`).
    pub(crate) scene: Option<String>,
}

/// Which file dialog a command asked for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pick {
    Open,
    SaveAs,
}

/// Picks a file for [`Pick`]; `None` = cancelled. The default shows the native dialog.
pub type FilePicker = Box<dyn FnMut(Pick) -> Option<PathBuf>>;

/// What the view gets each frame: the session, commands, jobs, toasts and settings.
pub struct Cx<'a, D: Document> {
    session: &'a mut Session<D>,
    registry: &'a Registry<Session<D>>,
    /// Background work; a job's apply runs on the session (each edit there is an undo step).
    pub jobs: &'a mut Jobs<Session<D>>,
    pub toasts: &'a mut Toasts,
    /// App settings (debounced, saved in the config folder).
    pub settings: &'a mut Settings,
    queued: &'a mut Vec<(String, Value)>,
    dropped: &'a [PathBuf],
    ctx: egui::Context,
    /// Who changed the document since the view last drew (`None`: unchanged).
    origin: Option<Origin>,
}

impl<D: Document> Cx<'_, D> {
    /// The design tokens of the current theme (`cx.tokens().space.md`).
    pub fn tokens(&self) -> tokens::Tokens {
        tokens::current(&self.ctx)
    }

    /// Who changed the document since the view last drew; `None` when it did not change (or
    /// changed without an edit: opened, replaced).
    pub fn origin(&self) -> Option<Origin> {
        self.origin
    }

    /// The value to draw for `id`, moving toward `target` along `curve`
    /// ([`ashlar_ui::motion::value`], [`Class::Other`](ashlar_motion::Class::Other)). When the
    /// document changed by the user's own hand since the last frame ([`Origin::animates`] is
    /// false) it jumps to `target` instead ([`ashlar_ui::motion::set`]): typing and drags show at
    /// once, while undo, agent and job changes animate.
    pub fn motion<T>(&self, id: impl egui::AsId, target: T, curve: impl Into<ashlar_motion::Curve>) -> T
    where
        T: ashlar_motion::Animatable + Send + Sync + 'static,
    {
        let id = egui::Id::new(id);
        if self.origin.is_some_and(|o| !o.animates()) {
            ashlar_ui::motion::set(&self.ctx, id, target);
            return target;
        }
        ashlar_ui::motion::value(&self.ctx, id, target, ashlar_motion::Class::Other, curve)
    }

    /// The current document.
    pub fn doc(&self) -> &D {
        self.session.doc()
    }

    /// The current document as an `Arc` (to keep while calling `&mut self` methods).
    pub fn snapshot(&self) -> Arc<D> {
        self.session.snapshot()
    }

    /// The revision of the current document (key caches by it).
    pub fn revision(&self) -> Revision {
        self.session.revision()
    }

    pub fn session(&self) -> &Session<D> {
        self.session
    }

    pub fn session_mut(&mut self) -> &mut Session<D> {
        self.session
    }

    pub fn ctx(&self) -> &egui::Context {
        &self.ctx
    }

    /// Files dropped on the window this frame that the runtime did not open as the document
    /// (another extension, or a second document). Empty with [`App::accept_drops`] off.
    pub fn dropped_files(&self) -> &[PathBuf] {
        self.dropped
    }

    /// Run a command after the view returns (menus, buttons). Errors are shown as toasts.
    pub fn dispatch(&mut self, id: &str, params: Value) {
        self.queued.push((id.to_string(), params));
    }

    /// Run a command now and get its result.
    pub fn execute(&mut self, id: &str, params: Value) -> Result<Value, CommandError> {
        self.registry.execute(self.session, id, params)
    }

    /// An undoable change made directly by the view (one step called `label`).
    pub fn edit<R>(&mut self, label: &str, f: impl FnOnce(&mut D) -> R) -> R {
        self.session.edit(label, f)
    }

    /// An undoable change folded into the previous one with the same label and key (a drag).
    pub fn edit_merged<R>(&mut self, label: &str, merge_key: &str, f: impl FnOnce(&mut D) -> R) -> R {
        self.session.edit_merged(label, merge_key, f)
    }

    /// View state (not in the document; `ui.set` changes it too).
    pub fn view<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
        self.session.view(key)
    }

    pub fn view_or<T: serde::de::DeserializeOwned>(&self, key: &str, default: T) -> T {
        self.session.view_or(key, default)
    }

    pub fn set_view<T: serde::Serialize + ?Sized>(&mut self, key: &str, value: &T) {
        self.session.set_view(key, value);
    }
}

#[derive(Default)]
struct InfoCache {
    key: Option<(Revision, u64, u64, u64)>,
    seq: u64,
    infos: Vec<CommandInfo>,
    menu: MenuSpec,
}

enum Modal {
    Recovery,
    SafeMode,
    Confirm { quit: bool, command: Option<(String, Value)> },
}

struct AutosaveState {
    autosave: Autosave,
    #[cfg(not(target_arch = "wasm32"))]
    writer: Option<ashlar_store::BackgroundWriter>,
    file_gen: u64,
}

/// One app instance's frame loop. Built by [`App::runtime`] (tests, benches) or `App::run`.
pub struct Runtime<D: Document> {
    shared: Arc<Shared<D>>,
    session: Session<D>,
    jobs: Jobs<Session<D>>,
    toasts: Toasts,
    settings: Settings,
    view: Option<ViewFn<D>>,
    setup: Option<SetupFn>,
    keymap: Keymap,
    keymap_gen: u64,
    palette: CommandPalette,
    keymap_editor: KeymapEditor,
    keymap_open: bool,
    cache: InfoCache,
    control: Option<(Server, Receiver<Request>)>,
    injected_requests: Vec<Request>,
    /// The revision the view last drew ([`Cx::origin`]).
    view_rev: Option<Revision>,
    autosave: Option<AutosaveState>,
    recovery: Vec<RecoveryCandidate>,
    modals: Vec<Modal>,
    stats: FrameStats,
    wakes: Scheduler,
    launch: Launch,
    queued: Vec<(String, Value)>,
    created: Option<std::time::Instant>,
    started: bool,
    first_frame_done: bool,
    view_error: Option<String>,
    allow_close: bool,
    quit_after_save: bool,
    /// Quit, logout and shutdown requests from the OS (native only) and where answering them is.
    session_end: Option<Receiver<EndRequest>>,
    end_state: session_end::State,
    /// The last answer given to the OS: `Some(true)` allowed the end.
    end_reply: Option<bool>,
    /// A command the confirm dialog's Save holds back until the save (maybe through Save As)
    /// is done.
    after_save: Option<(String, Value)>,
    /// A file dialog a command asked for, shown at the start of the next frame (IMP-6.5).
    pending_pick: Option<Pick>,
    /// The window placement written to the settings (IMP-6.4).
    window: window_state::Tracker,
    shown_title: String,
    /// (dirty, file generation) the title was made for.
    title_key: Option<(bool, u64)>,
    /// The view generation last written to the settings.
    persisted_view: Option<u64>,
    picker: Option<FilePicker>,
    passes: u64,
    /// Times each pass for the perf warnings (`None`: nothing uses it).
    probe: Option<crate::perf_warn::Probe>,
    /// `ASHLAR_RECORD`: input and control requests appended for replay ([`crate::record`]).
    recorder: Option<crate::record::Recorder>,
    probe_installed: bool,
    /// `app.stats` → `process`.
    process: crate::stats::ProcessProbe,
    /// The wake counts at the probe's previous frame (their growth is the frame's reasons).
    probe_wakes: ashlar_ui::wake::WakeStats,
    caret: Caret,
    /// `app.clock`: the time frames see (pause, step, resume).
    clock: crate::clock::Clock,
    /// Running in a real window (not the headless driver): OS menus may be installed.
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    pub(crate) native: bool,
    #[cfg(all(feature = "native-menu", any(target_os = "macos", target_os = "windows")))]
    native_menu: Option<crate::native_menu::NativeMenu>,
    /// The OS menu bar was tried (installed and attached, or refused) on the first frame.
    #[cfg_attr(not(all(feature = "native-menu", any(target_os = "macos", target_os = "windows"))), allow(dead_code))]
    native_menu_tried: bool,
    /// The tray icon ([`App::tray`](crate::App::tray)), installed with the OS menu bar.
    #[cfg(all(feature = "tray", not(target_arch = "wasm32")))]
    tray: Option<ashlar_native::tray::Tray>,
    #[cfg(all(feature = "tray", not(target_arch = "wasm32")))]
    tray_tried: bool,
    #[cfg(all(feature = "hotkey", not(target_arch = "wasm32")))]
    global_shortcuts: Option<ashlar_native::hotkey::GlobalShortcuts>,
    #[cfg(all(feature = "hotkey", not(target_arch = "wasm32")))]
    global_shortcuts_tried: bool,
    /// Dock reopen requests (macOS), listened for after the first frame.
    #[cfg(target_os = "macos")]
    reopen: Option<std::sync::mpsc::Receiver<ashlar_native::mac_shell::Reopen>>,
    #[cfg(target_os = "macos")]
    mac_shell_tried: bool,
    /// Bring the window to the front on the next frame (a forwarded launch, a tray click, a
    /// global shortcut), through the OS where the focus request alone may be refused.
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    bring_front: bool,
    /// Ids picked in the OS menu bar, run by [`Runtime::logic`] (also fed by
    /// [`crate::Driver::native_menu_pick`]).
    native_picks: Vec<String>,
    os_prefs: prefs::OsPrefs,
    /// Files from the OS and later launches.
    inbox: Inbox,
    /// Paths dropped since the last [`Runtime::logic`] (when drops are accepted).
    drops: Vec<PathBuf>,
    /// Dropped files left for the view this frame ([`Cx::dropped_files`]).
    dropped: Vec<PathBuf>,
    /// A file from outside waiting for open dialogs to close; a newer one replaces it.
    open_next: Option<PathBuf>,
}

fn panic_text(payload: &(dyn std::any::Any + Send)) -> String {
    payload
        .downcast_ref::<&str>()
        .map(|s| (*s).to_string())
        .or_else(|| payload.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "unknown error".into())
}

impl<D: Document> Runtime<D> {
    pub(crate) fn new(shared: Arc<Shared<D>>, view: Option<ViewFn<D>>, setup: Option<SetupFn>, mut launch: Launch) -> Self {
        // `system_locales()` also reads the OS's language list (desktop launches have no `LANG`)
        ashlar_i18n::set_native_languages(ashlar_native::system::preferred_languages);
        let inbox = launch.inbox.take().unwrap_or_default();
        let mut session = Session::new(Arc::clone(&shared.format));
        session.set_windowed(true);
        session.telemetry = launch.telemetry.clone();
        let config: Arc<dyn ConfigStore> = match &shared.dirs {
            Some(d) => Arc::new(DirConfig::new(d.config.clone())),
            None => Arc::new(MemoryConfig::new()),
        };
        let settings = Settings::load(config, "settings.json", &[]);
        let mut keymap = Keymap::from_registry(&shared.registry, Platform::current());
        if let Some(o) = settings.get_value("keymap") {
            keymap.apply_overrides_json(o);
        }
        if !launch.safe_mode
            && let Some(Value::Object(view)) = settings.get_value("view")
        {
            for (k, v) in view {
                session.set_view_value(k, v.clone());
            }
        }
        let mut rt = Runtime {
            session,
            jobs: Jobs::new(),
            toasts: Toasts::new(),
            settings,
            view,
            setup,
            keymap,
            keymap_gen: 0,
            palette: CommandPalette::new(),
            keymap_editor: KeymapEditor::new(),
            keymap_open: false,
            cache: InfoCache::default(),
            control: None,
            injected_requests: Vec::new(),
            view_rev: None,
            autosave: None,
            recovery: Vec::new(),
            modals: Vec::new(),
            stats: FrameStats::default(),
            wakes: Scheduler::default(),
            queued: Vec::new(),
            created: now(),
            started: false,
            first_frame_done: false,
            view_error: None,
            allow_close: false,
            quit_after_save: false,
            session_end: None,
            end_state: session_end::State::Idle,
            end_reply: None,
            after_save: None,
            pending_pick: None,
            window: window_state::Tracker::default(),
            shown_title: String::new(),
            title_key: None,
            persisted_view: None,
            picker: None,
            passes: 0,
            probe: crate::perf_warn::Probe::from_env(),
            recorder: crate::record::Recorder::from_env(),
            probe_installed: false,
            process: crate::stats::ProcessProbe::default(),
            probe_wakes: ashlar_ui::wake::WakeStats::default(),
            caret: Caret::default(),
            clock: crate::clock::Clock::default(),
            native: false,
            #[cfg(all(feature = "native-menu", any(target_os = "macos", target_os = "windows")))]
            native_menu: None,
            native_menu_tried: false,
            #[cfg(all(feature = "tray", not(target_arch = "wasm32")))]
            tray: None,
            #[cfg(all(feature = "tray", not(target_arch = "wasm32")))]
            tray_tried: false,
            #[cfg(all(feature = "hotkey", not(target_arch = "wasm32")))]
            global_shortcuts: None,
            #[cfg(all(feature = "hotkey", not(target_arch = "wasm32")))]
            global_shortcuts_tried: false,
            bring_front: false,
            #[cfg(target_os = "macos")]
            reopen: None,
            #[cfg(target_os = "macos")]
            mac_shell_tried: false,
            native_picks: Vec::new(),
            os_prefs: prefs::OsPrefs::new(shared.follow_system_accent, shared.motion),
            inbox,
            drops: Vec::new(),
            dropped: Vec::new(),
            open_next: None,
            launch,
            shared,
        };
        if let (Some(s), Some(w)) = (rt.launch.process_start, rt.launch.window_at) {
            rt.stats.set_to_window(w.saturating_duration_since(s));
        }
        rt.start_autosave();
        // `launch.open` waits for the first frame (open_from_outside): the window shows first
        if rt.launch.safe_mode {
            rt.modals.push(Modal::SafeMode);
        }
        // with a command-line document, the scene waits for it (open_from_outside)
        if rt.launch.open.is_none() {
            rt.apply_launch_scene();
        }
        rt
    }

    /// The `--scene` named at launch, once.
    fn apply_launch_scene(&mut self) {
        if let Some(name) = self.launch.scene.take()
            && let Err(e) = self.apply_scene(&name)
        {
            log::error!("{e}");
            self.toasts.error(e);
        }
    }

    /// Run the scene called `name` ([`crate::App::scene`]) on the session. Its effects run on
    /// the next frame.
    pub fn apply_scene(&mut self, name: &str) -> Result<(), String> {
        let shared = Arc::clone(&self.shared);
        let Some(scene) = shared.scene(name) else {
            return Err(format!("no scene `{name}` (scenes: {})", shared.scene_names().join(", ")));
        };
        let session = &mut self.session;
        catch_unwind(AssertUnwindSafe(|| scene(session))).map_err(|p| format!("scene `{name}` panicked: {}", panic_text(p.as_ref())))
    }

    fn start_autosave(&mut self) {
        let (Some(every), Some(dirs)) = (self.shared.autosave, &self.shared.dirs) else { return };
        let mut cfg = AutosaveConfig::new(dirs.data.join("Recovery"));
        cfg.interval = every;
        match Autosave::start(cfg) {
            Ok((autosave, candidates)) => {
                self.recovery = candidates;
                if !self.recovery.is_empty() {
                    self.modals.insert(0, Modal::Recovery);
                }
                self.autosave = Some(AutosaveState {
                    autosave,
                    #[cfg(not(target_arch = "wasm32"))]
                    writer: ashlar_store::BackgroundWriter::start().ok(),
                    file_gen: u64::MAX,
                });
            }
            Err(e) => log::warn!("autosave is off: {e}"),
        }
    }

    // ------------------------------------------------------------------ public API

    pub fn session(&self) -> &Session<D> {
        &self.session
    }

    pub fn session_mut(&mut self) -> &mut Session<D> {
        &mut self.session
    }

    pub fn settings(&self) -> &Settings {
        &self.settings
    }

    pub fn toasts(&self) -> &Toasts {
        &self.toasts
    }

    /// Write one JSON line per frame to `path` (what `ASHLAR_FRAME_LOG=path` does; see
    /// [`crate::frame_log`]), from the next frame on. Replaces an earlier log.
    pub fn log_frames(&mut self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        let log = crate::frame_log::FrameLog::create(path.as_ref(), crate::frame_log::MAX_BYTES)?;
        self.probe.get_or_insert_with(crate::perf_warn::Probe::default).set_log(log);
        Ok(())
    }

    /// Record every frame's input and time, and every control request, to `path` (what
    /// `ASHLAR_RECORD=path` does; see [`crate::record`]), from the next frame on. Replaces an
    /// earlier recording. [`crate::Driver::replay`] plays it back.
    pub fn record_to(&mut self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        self.recorder = Some(crate::record::Recorder::create(path.as_ref(), crate::record::MAX_BYTES)?);
        Ok(())
    }

    /// Watch frames with these warning meters instead of the environment's (tests).
    #[cfg(test)]
    pub(crate) fn watch_frames(&mut self, warn: crate::perf_warn::PerfWarn) -> crate::perf_warn::Probe {
        let p = crate::perf_warn::Probe::with_warn(warn);
        self.probe = Some(p.clone());
        p
    }

    /// Frame-time statistics (`app.stats`).
    pub fn stats(&self) -> &FrameStats {
        &self.stats
    }

    pub fn stats_mut(&mut self) -> &mut FrameStats {
        &mut self.stats
    }

    /// Frames and wake requests per [`Reason`] (`app.stats` → `wakes`).
    pub fn wakes(&self) -> WakeStats {
        self.wakes.stats()
    }

    /// Passes run so far (frames, plus egui's occasional extra layout pass).
    pub fn passes(&self) -> u64 {
        self.passes
    }

    /// Replace the OS preferences (reduced motion, accent, contrast) with `source` (tests). Call
    /// it before the first frame; it is read again whenever the window gains focus.
    pub fn set_preferences(&mut self, source: impl FnMut() -> Preferences + 'static) {
        self.os_prefs.source = Some(Box::new(source));
    }

    /// Replace the native file dialogs (tests, scripted runs).
    pub fn set_file_picker(&mut self, picker: impl FnMut(Pick) -> Option<PathBuf> + 'static) {
        self.picker = Some(Box::new(picker));
    }

    /// Run a command through the chokepoint now.
    pub fn execute(&mut self, id: &str, params: Value) -> Result<Value, CommandError> {
        self.shared.registry.execute(&mut self.session, id, params)
    }

    /// Hand a control request to the runtime as if it came from the control port (tests).
    pub fn inject_request(&mut self, req: Request) {
        self.injected_requests.push(req);
    }

    /// The control port, when one is serving.
    pub fn control_port(&self) -> Option<u16> {
        self.control.as_ref().map(|(s, _)| s.port())
    }

    /// Whether the app has decided to close (the window should go away).
    pub fn is_closing(&self) -> bool {
        self.allow_close
    }

    /// The error that suspended the view, if one did.
    pub fn view_error(&self) -> Option<&str> {
        self.view_error.as_deref()
    }

    fn info(&self) -> AppInfo {
        AppInfo::new(self.shared.name.clone(), self.shared.version.clone())
    }

    // ------------------------------------------------------------------ start

    fn ensure_started(&mut self, ctx: &egui::Context) {
        if self.started {
            return;
        }
        self.started = true;
        devtools::install(ctx);
        // without eframe's AccessKit adapter no screen reader can turn AccessKit on
        if !cfg!(feature = "accesskit") {
            devtools::set_platform_accesskit(ctx, false);
        }
        self.inbox.set_ctx(ctx);
        let mode = if self.launch.safe_mode { ThemeMode::System } else { self.settings.get::<ThemeMode>("theme").unwrap_or_default() };
        // OS accent, contrast and reduced motion; tokens the setup below installs win
        let (light, dark) = self.os_prefs.startup(ctx);
        tokens::install(ctx, &light, &dark, mode);
        if let Some(setup) = self.setup.take()
            && let Err(p) = catch_unwind(AssertUnwindSafe(|| setup(ctx)))
        {
            log::error!("app setup panicked: {}", panic_text(p.as_ref()));
        }
        let w = wake::waker(ctx, Reason::JOB);
        self.jobs.set_wake(move || w.wake());
        let w = wake::waker(ctx, Reason::SETTINGS);
        self.settings.set_wake(move |d| w.reschedule(d));
        if let Some(a) = &mut self.autosave {
            let w = wake::waker(ctx, Reason::AUTOSAVE);
            a.autosave.set_wake(move |d| w.reschedule(d));
            #[cfg(not(target_arch = "wasm32"))]
            if let Some(writer) = &a.writer {
                let w = wake::waker(ctx, Reason::AUTOSAVE);
                writer.set_wake(move || w.wake());
            }
        }
        let port = self.launch.control_port.or(self.shared.control_port);
        // A launcher may say where the key goes (`ashlar-debug open`); otherwise the settings folder.
        let key_dir = ashlar_control::key::key_dir_from_env().or_else(|| self.shared.dirs.as_ref().map(|d| d.config.clone()));
        if let (Some(port), Some(key_dir)) = (port, key_dir) {
            let w = wake::waker(ctx, Reason::CONTROL);
            match Server::start(ashlar_control::Config::new(port, key_dir), move || w.wake()) {
                Ok((server, rx)) => {
                    self.control = Some((server, rx));
                }
                Err(e) => {
                    log::error!("control port {port}: {e}");
                    self.toasts.error(format!("Agent control is off: {e}"));
                }
            }
        }
        // the event loop runs by now, so winit's application delegate exists
        if self.native {
            match session_end::listen(Arc::new({
                let w = wake::waker(ctx, SESSION_END);
                move || w.wake()
            })) {
                Ok(rx) => self.session_end = Some(rx),
                Err(e) => log::debug!("quit requests from the OS: {e}"),
            }
        }
    }

    // ------------------------------------------------------------------ the frame

    /// Work that needs no drawing: control requests, finished jobs, effects, autosave, settings.
    /// eframe calls it before every frame (and while the window is hidden).
    pub fn logic(&mut self, ctx: &egui::Context) {
        self.launch.telemetry.begin_turn();
        self.ensure_started(ctx);
        self.os_prefs.poll(ctx);
        self.serve_control(ctx);
        self.show_pending_pick(ctx, None);
        let outer = self.session.swap_source(Some(Origin::Job));
        let done = self.jobs.drain_ready(&mut self.session);
        self.session.swap_source(outer);
        for rec in done {
            if rec.status == ashlar_jobs::Status::Failed {
                self.toasts.error(format!("{}: {}", rec.label, rec.message));
            }
        }
        self.apply_effects(ctx);
        self.open_from_outside(ctx);
        #[cfg(all(feature = "native-menu", any(target_os = "macos", target_os = "windows")))]
        if let Some(m) = &self.native_menu {
            self.native_picks.extend(m.drain());
        }
        #[cfg(all(feature = "tray", not(target_arch = "wasm32")))]
        self.drain_tray(ctx);
        #[cfg(all(feature = "hotkey", not(target_arch = "wasm32")))]
        if let Some(g) = &self.global_shortcuts {
            let pressed = g.drain();
            if !pressed.is_empty() {
                self.show_window(ctx);
            }
            self.native_picks.extend(pressed);
        }
        self.run_native_picks(ctx);
        self.launch.telemetry.end_turn();
    }

    /// eframe runs no UI pass while the window is minimized or covered. While debugger work waits
    /// (ui input, snapshots, waits, screenshots), run one here, after [`Runtime::logic`]: what it
    /// draws is not presented (screenshots render off screen) and nothing raises the window, so
    /// agents drive a covered window without taking the focus. Its window commands go to the
    /// context; the output is returned for the caller to hand its texture changes to the renderer.
    /// `time` and `events` are for the pass (eframe gives none: the wall clock goes on; the
    /// headless driver passes its virtual clock and delivers its screenshots this way).
    pub fn hidden_pass(&mut self, ctx: &egui::Context, time: Option<f64>, events: Vec<egui::Event>) -> Option<egui::FullOutput> {
        if ctx.input(|i| i.viewport().visible()) != Some(false) || !devtools::has_pending(ctx) {
            return None;
        }
        let mut raw = ctx.input(|i| i.raw.clone());
        raw.events = events;
        raw.hovered_files.clear();
        raw.dropped_files.clear();
        raw.viewport_id = egui::ViewportId::ROOT;
        // eframe hands no time to a hidden window: go on from the last pass on the wall clock
        // (host time: `app.clock` turns it into the app's in `raw_input_hook`)
        let last = self.clock.host_time();
        raw.time = Some(time.unwrap_or_else(|| self.created.map_or(last, |c| c.elapsed().as_secs_f64())).max(last));
        if raw.screen_rect.is_none()
            && let Some(r) = raw.viewports.get(&egui::ViewportId::ROOT).and_then(|v| v.inner_rect)
        {
            raw.screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, r.size()));
        }
        self.raw_input_hook(ctx, &mut raw);
        let out = ctx.run_ui(raw, |ui| self.ui(ui));
        for (id, vo) in &out.viewport_output {
            for c in &vo.commands {
                ctx.send_viewport_cmd_to(*id, c.clone());
            }
            if *id == egui::ViewportId::ROOT && vo.repaint_delay < Duration::from_secs(3600) {
                wake::wake_after(ctx, Reason::CONTROL, vo.repaint_delay);
            }
        }
        if !out.platform_output.commands.is_empty() {
            let commands = out.platform_output.commands.clone();
            ctx.output_mut(|o| o.commands.extend(commands));
        }
        Some(out)
    }

    /// The start of a frame (eframe's `raw_input_hook`, before [`Runtime::logic`]): set the
    /// frame's time (`app.clock` may hold it), then credit the frame to the wake reasons that were
    /// due. (Injected agent input is handed to egui by the debugger's plugin.)
    pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
        // the host's time and input, before `app.clock` changes them: what replay hands back
        if let Some(r) = &mut self.recorder
            && !r.frame(raw)
        {
            self.recorder = None;
        }
        self.clock.begin_frame(raw);
        // installed every frame: an app may reset egui's memory, which holds the scheduler
        self.wakes.install(ctx);
        self.wakes.begin_frame(raw.time.unwrap_or_else(|| ctx.input(|i| i.time)));
        if let Some(p) = &self.probe {
            // before egui's pass begins, so the plugin times the first frame too
            if !self.probe_installed {
                ctx.add_plugin(p.plugin());
                self.probe_installed = true;
            }
            let now = self.wakes.stats();
            p.begin_frame(crate::perf_warn::credited(&self.probe_wakes, &now));
            self.probe_wakes = now;
        }
        // on the web a dropped file has no path to open: the view reads it from egui's input
        #[cfg(not(target_arch = "wasm32"))]
        if self.shared.accept_drops {
            self.drops.extend(raw.dropped_files.iter().map(|f| f.path().to_path_buf()));
        }
    }

    /// Open what the OS, a later launch or a drop asked for: one document at a time, after any
    /// open dialog, through `file.open` (a dirty document asks to save first). A forwarded launch
    /// brings the window to the front.
    fn open_from_outside(&mut self, ctx: &egui::Context) {
        let (items, focus) = self.inbox.drain();
        if focus {
            ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
            ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
            self.bring_front = true;
        }
        let mut files = items.into_iter().filter_map(|item| match item {
            ashlar_native::open_files::Opened::File(p) => Some(p),
            ashlar_native::open_files::Opened::Url(u) => {
                log::info!("asked to open {u}: URLs are not handled");
                None
            }
        });
        if let Some(p) = files.next() {
            self.open_next = Some(p);
        }
        // the command-line document, once the first frame is up (a slow load no longer delays it)
        if self.first_frame_done
            && let Some(path) = self.launch.open.take()
        {
            self.run_ui_command(ctx, "file.open", json!({"path": path.to_string_lossy(), "discard": true}));
            self.apply_launch_scene();
        }
        let skipped = files.count();
        if skipped > 0 {
            log::info!("{skipped} more file(s) to open ignored: one document at a time");
        }
        if !self.drops.is_empty() {
            let (open, rest) = crate::open::split_drops(std::mem::take(&mut self.drops), &self.shared.extensions);
            if open.is_some() {
                self.open_next = open;
            }
            self.dropped = rest;
        }
        if self.modal_open() {
            return;
        }
        if let Some(p) = self.open_next.take() {
            self.run_ui_command(ctx, "file.open", json!({"path": p.to_string_lossy()}));
        }
    }

    /// Called at the start of every native frame: the frame after the first one finds that frame
    /// presented. Records `launch_to_present_ms` and writes the ready file.
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    pub(crate) fn note_presented(&mut self) {
        if !self.first_frame_done || std::mem::replace(&mut self.launch.presented, true) {
            return;
        }
        let Some(start) = self.launch.process_start else { return };
        let took = start.elapsed();
        self.stats.set_presented(took);
        let t = self.stats.launch();
        let f = |v: Option<f64>| v.map_or_else(|| "-".to_owned(), |v| format!("{v:.1}"));
        log::info!(
            "launch: window {} ms, first frame {} ms (runtime {} ms), presented {} ms",
            f(t.to_window_ms),
            f(t.to_first_frame_ms),
            f(self.stats.summary().first_frame_ms),
            f(t.launch_to_present_ms)
        );
        if let Some(path) = self.launch.ready_file.take() {
            let body = json!({"pid": std::process::id(), "ready_ms": took.as_secs_f64() * 1000.0}).to_string();
            // off the UI thread; a launcher polls for the file
            let spawned = std::thread::Builder::new().name("ashlar-ready".into()).spawn(move || {
                let r = catch_unwind(AssertUnwindSafe(|| ashlar_fs::atomic_write(&path, body.as_bytes())));
                match r {
                    Ok(Ok(())) => {}
                    Ok(Err(e)) => log::warn!("ready file {}: {e}", path.display()),
                    Err(_) => log::warn!("ready file {}: the writer panicked", path.display()),
                }
            });
            if let Err(e) = spawned {
                log::warn!("ready file: {e}");
            }
        }
    }

    /// Queue a later launch's arguments, as [`App::single_instance`] receives them (tests).
    pub(crate) fn forwarded(&self, f: ashlar_native::single_instance::Forwarded) {
        self.inbox.forward(f);
    }

    /// Draw the frame.
    pub fn ui(&mut self, ui: &mut egui::Ui) {
        let ctx = ui.ctx().clone();
        let started = now();
        self.launch.telemetry.begin_turn();
        self.ensure_started(&ctx);
        self.passes = self.passes.saturating_add(1);
        // timed wakes not yet due when this frame ran (input came first) stay scheduled
        self.wakes.rearm(&ctx);
        // before anything consumes this frame's input events
        self.caret.begin(&ctx);
        let (focused, active) = ctx.input(|i| (i.focused, !i.events.is_empty()));
        self.launch.telemetry.input(focused, active);

        self.refresh_infos();
        if !self.modal_open()
            && let Some(id) = dispatch(&ctx, &self.keymap)
        {
            self.run_ui_command(&ctx, &id, json!({}));
            // the command may have changed what the menus show
            self.refresh_infos();
        }
        // nothing is drawn yet: changes made so far (control requests, jobs, a key command) show
        // in this frame; only changes made from here on need another
        let rev_before = self.session.revision();
        self.update_title(&ctx);
        if !self.native_menu_active() {
            let spec = &self.cache.menu;
            let chosen = egui::Panel::top("ashlar.menu_bar").show(ui, |ui| menu_bar(ui, spec, Platform::current())).inner;
            if let Some(id) = chosen {
                self.run_ui_command(&ctx, &id, json!({}));
            }
        }
        self.draw_view(ui);
        self.dropped.clear();
        for (id, params) in std::mem::take(&mut self.queued) {
            self.run_ui_command(&ctx, &id, params);
        }
        self.apply_effects(&ctx);
        self.draw_modals(&ctx);
        self.draw_tools(&ctx);
        self.toasts.show(&ctx);
        self.run_toast_actions(&ctx);
        self.handle_close(&ctx);
        self.poll_session_end(&ctx);
        self.apply_effects(&ctx);
        self.persist_view();
        self.track_window(&ctx);
        self.tick_storage(&ctx);
        self.feed_devtools(&ctx);

        // the frame changed the document: draw once more so everything shows the new state
        if self.session.revision() != rev_before {
            wake::wake(&ctx, Reason::DOCUMENT);
        }
        self.caret.end(&ctx);
        let took = started.map(|s| s.elapsed());
        if let Some(took) = took {
            self.stats.record(took);
            self.launch.telemetry.frame(took);
        }
        self.process.tick();
        let ran = self.session.take_ran();
        if let Some(p) = &self.probe {
            p.end_ui(took, ran);
        }
        if !self.first_frame_done {
            self.first_frame_done = true;
            if let Some(g) = &mut self.launch.guard {
                g.started();
            }
            if let Some(c) = self.created {
                self.stats.set_first_frame(c.elapsed());
            }
            if let Some(s) = self.launch.process_start {
                self.stats.set_to_first_frame(s.elapsed());
            }
            // one more frame: it opens the command-line document and records the present
            if self.native || self.launch.open.is_some() {
                wake::wake(&ctx, Reason::STARTUP);
            }
            self.launch.telemetry.first_frame();
        }
        self.launch.telemetry.end_turn();
    }

    fn draw_view(&mut self, ui: &mut egui::Ui) {
        let Runtime { session, shared, jobs, toasts, settings, queued, view, view_error, dropped, view_rev, .. } = self;
        let rev = session.revision();
        let origin = if *view_rev == Some(rev) { None } else { session.origin() };
        *view_rev = Some(rev);
        egui::CentralPanel::default().show(ui, |ui| {
            if let Some(err) = view_error.as_deref() {
                ui.centered_and_justified(|ui| ui.label(format!("This view stopped after an internal error:\n{err}")));
                return;
            }
            let Some(view) = view.as_mut() else { return };
            let mut cx = Cx { session, registry: &shared.registry, jobs, toasts, settings, queued, dropped, ctx: ui.ctx().clone(), origin };
            let r = catch_unwind(AssertUnwindSafe(|| view(ui, &mut cx)));
            if let Err(p) = r {
                let msg = crash::last_panic().map_or_else(|| panic_text(p.as_ref()), |r| format!("{} ({})", r.message, r.location));
                log::error!("the view panicked: {msg}");
                *view_error = Some(msg);
            }
        });
    }

    fn native_menu_active(&self) -> bool {
        #[cfg(all(feature = "native-menu", any(target_os = "macos", target_os = "windows")))]
        {
            self.native_menu.is_some()
        }
        #[cfg(not(all(feature = "native-menu", any(target_os = "macos", target_os = "windows"))))]
        {
            false
        }
    }

    /// After the first frame, install the OS menu bar and attach it to the window. Until it is
    /// attached (and when that fails) the in-window bar shows.
    #[cfg(not(target_arch = "wasm32"))]
    fn install_native_menu(&mut self, ctx: &egui::Context, window: &eframe::Frame) {
        #[cfg(all(feature = "native-menu", any(target_os = "macos", target_os = "windows")))]
        if self.native && self.first_frame_done && !self.native_menu_tried {
            self.native_menu_tried = true;
            self.native_menu = crate::native_menu::NativeMenu::install(&self.cache.infos, ctx, window);
            // the in-window bar goes (or stays) with the next frame
            wake::wake(ctx, Reason::MENU);
        }
        #[cfg(all(feature = "tray", not(target_arch = "wasm32")))]
        if self.native && self.first_frame_done && !self.tray_tried {
            self.tray_tried = true;
            if let Some(spec) = self.shared.tray.clone() {
                let wake = ashlar_ui::wake::waker(ctx, Reason::MENU);
                match ashlar_native::tray::Tray::new(spec, std::sync::Arc::new(move || wake.wake())) {
                    Ok(t) => self.tray = Some(t),
                    Err(e) => log::warn!("no tray icon: {e}"),
                }
            }
        }
        #[cfg(all(feature = "hotkey", not(target_arch = "wasm32")))]
        if self.native && self.first_frame_done && !self.global_shortcuts_tried {
            self.global_shortcuts_tried = true;
            if !self.shared.global_shortcuts.is_empty() {
                let wake = ashlar_ui::wake::waker(ctx, Reason::MENU);
                match ashlar_native::hotkey::GlobalShortcuts::new(std::sync::Arc::new(move || wake.wake())) {
                    Ok(mut g) => {
                        for (command, chord) in &self.shared.global_shortcuts {
                            let done = ashlar_command::shortcut::Chord::parse(chord)
                                .map_err(|e| ashlar_native::NativeError::Invalid(e.0))
                                .and_then(|c| g.register(command.clone(), &c));
                            if let Err(e) = done {
                                log::warn!("global shortcut `{chord}` for `{command}` skipped: {e}");
                            }
                        }
                        self.global_shortcuts = Some(g);
                    }
                    Err(e) => log::warn!("no global shortcuts: {e}"),
                }
            }
        }
        #[cfg(target_os = "macos")]
        if self.native && self.first_frame_done && !self.mac_shell_tried {
            self.mac_shell_tried = true;
            if let Err(e) = ashlar_native::mac_shell::guard_appearance() {
                log::debug!("appearance guard: {e}");
            }
            let wake = ashlar_ui::wake::waker(ctx, Reason::MENU);
            match ashlar_native::mac_shell::listen_reopen(std::sync::Arc::new(move || wake.wake())) {
                Ok(rx) => self.reopen = Some(rx),
                Err(e) => log::debug!("Dock reopen: {e}"),
            }
        }
        #[cfg(target_os = "macos")]
        if self.reopen.as_ref().is_some_and(|rx| rx.try_iter().count() > 0) {
            self.show_window(ctx);
        }
        if std::mem::take(&mut self.bring_front)
            && let Err(e) = ashlar_native::system::bring_to_front(window)
            && !e.is_unsupported()
        {
            log::debug!("bring to front: {e}");
        }
        let _ = (ctx, window);
    }

    /// Show, restore and focus the window, now through the viewport and on the next frame
    /// through the OS.
    #[cfg_attr(any(target_arch = "wasm32", not(any(target_os = "macos", feature = "tray", feature = "hotkey"))), allow(dead_code))]
    fn show_window(&mut self, ctx: &egui::Context) {
        ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
        ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
        ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
        self.bring_front = true;
        wake::wake(ctx, Reason::MENU);
    }

    /// Tray menu picks run like OS menu picks; a click on the icon shows the window.
    #[cfg(all(feature = "tray", not(target_arch = "wasm32")))]
    fn drain_tray(&mut self, ctx: &egui::Context) {
        let Some(t) = &self.tray else { return };
        for e in t.events() {
            match e {
                ashlar_native::tray::TrayEvent::Menu(id) => self.native_picks.push(id),
                ashlar_native::tray::TrayEvent::Activate => self.show_window(ctx),
            }
        }
    }

    /// Run the ids picked in the OS menu bar, under the rules key presses follow: nothing runs
    /// while a dialog or the palette is open, and while a text field has the keyboard a command
    /// whose shortcut belongs to the field ([`works_while_typing`]) is skipped. The OS reports a
    /// click and a key equivalent the same way, so a click on such an item while typing is
    /// skipped too; text-editing shortcuts have no key equivalent (see `native_menu`), so this
    /// mostly affects clicks on Undo / Redo while a text field is focused, which then belong to
    /// the field anyway.
    fn run_native_picks(&mut self, ctx: &egui::Context) {
        if self.native_picks.is_empty() {
            return;
        }
        let picks = std::mem::take(&mut self.native_picks);
        let typing = ctx.egui_wants_keyboard_input();
        for id in picks {
            if self.modal_open() {
                log::debug!("menu pick `{id}` ignored: a dialog is open");
                continue;
            }
            if typing && self.keymap.keys_for(&id).first().is_some_and(|c| !works_while_typing(c)) {
                log::debug!("menu pick `{id}` ignored: a text field has the keyboard");
                continue;
            }
            self.run_ui_command(ctx, &id, json!({}));
        }
    }

    /// Queue an OS menu pick (the headless driver's stand-in for the OS menu bar).
    pub(crate) fn push_native_pick(&mut self, id: impl Into<String>) {
        self.native_picks.push(id.into());
    }

    pub(crate) fn modal_open(&self) -> bool {
        !self.modals.is_empty() || self.palette.is_open() || self.view_error.is_some()
    }

    // ------------------------------------------------------------------ commands

    fn refresh_infos(&mut self) {
        let key = (self.session.revision(), self.session.view_generation(), self.session.file_generation(), self.keymap_gen);
        if self.cache.key == Some(key) {
            return;
        }
        // only the document changed (typing): what the menus show moves only if a command's
        // enabled state did, and checking that is far cheaper than rebuilding every info
        if let Some(old) = self.cache.key
            && (old.1, old.2, old.3) == (key.1, key.2, key.3)
            && self.enabled_unchanged()
        {
            self.cache.key = Some(key);
            return;
        }
        let mut infos = self.shared.registry.infos(&self.session);
        for info in &mut infos {
            let keys = self.keymap.keys_for(&info.id);
            info.shortcut = if keys.is_empty() { None } else { Some(format_list(keys)) };
        }
        self.cache.menu = MenuSpec::from_commands(&infos, MENU_ORDER);
        self.cache.infos = infos;
        self.cache.key = Some(key);
        self.cache.seq = self.cache.seq.wrapping_add(1);
        #[cfg(all(feature = "native-menu", any(target_os = "macos", target_os = "windows")))]
        if let Some(m) = &mut self.native_menu {
            m.update(&self.cache.infos);
        }
    }

    /// Every command's enabled state (and reason) is what the cached infos say.
    fn enabled_unchanged(&self) -> bool {
        let specs = self.shared.registry.specs();
        specs.len() == self.cache.infos.len()
            && specs.iter().zip(&self.cache.infos).all(|(spec, info)| match (spec.enabled)(&self.session) {
                Ok(()) => info.enabled,
                Err(reason) => !info.enabled && info.disabled_reason.as_deref() == Some(reason.as_str()),
            })
    }

    /// With [`App::run_toast_actions`](crate::App::run_toast_actions) on: run the clicked toast
    /// actions that name a registered command.
    fn run_toast_actions(&mut self, ctx: &egui::Context) {
        if !self.shared.toast_commands {
            return;
        }
        let shared = Arc::clone(&self.shared);
        for a in self.toasts.take_actions_where(|a| shared.registry.find(&a.command).is_some()) {
            self.run_ui_command(ctx, &a.command, json!({}));
        }
    }

    /// Run a command the user chose (menu, key, palette, button): errors become toasts.
    fn run_ui_command(&mut self, ctx: &egui::Context, id: &str, params: Value) {
        if let Err(e) = self.execute(id, params) {
            match e {
                CommandError::Disabled { .. } => log::debug!("{e}"),
                _ => {
                    self.toasts.error(e.to_string());
                }
            }
        }
        self.apply_effects(ctx);
    }

    fn apply_effects(&mut self, ctx: &egui::Context) {
        // effects can run commands that request more effects: bounded rounds
        for _ in 0..8 {
            let effects = self.session.take_effects();
            if effects.is_empty() {
                return;
            }
            for e in effects {
                self.apply_effect(ctx, e);
            }
        }
    }

    fn apply_effect(&mut self, ctx: &egui::Context, e: Effect) {
        match e {
            Effect::Toast { level, text } => {
                self.toasts.push(ashlar_ui::toasts::Toast::new(level, text));
            }
            Effect::OpenPalette => self.palette.open(),
            Effect::OpenKeymap => self.keymap_open = true,
            Effect::Theme(mode) => {
                tokens::set_mode(ctx, mode);
                let _ = self.settings.set("theme", &mode);
            }
            Effect::PickOpen => self.request_pick(ctx, Pick::Open),
            Effect::PickSaveAs => self.request_pick(ctx, Pick::SaveAs),
            Effect::ConfirmDiscard { command, params } => self.modals.push(Modal::Confirm { quit: false, command: Some((command, params)) }),
            Effect::Quit { discard } => {
                if self.session.is_dirty() && !discard {
                    self.modals.push(Modal::Confirm { quit: true, command: None });
                } else {
                    self.close(ctx, discard);
                }
            }
        }
    }

    fn report(&mut self, r: Result<Value, CommandError>) {
        if let Err(e) = r {
            self.toasts.error(e.to_string());
        }
    }

    /// Ask for a file dialog. It is not shown inside this frame (a blocking dialog would freeze
    /// it half drawn, menus open): the next frame shows it first and acts on the pick.
    fn request_pick(&mut self, ctx: &egui::Context, kind: Pick) {
        if let Some(open) = self.pending_pick {
            log::debug!("a {kind:?} dialog was asked for while a {open:?} dialog waits: ignored");
            return;
        }
        self.pending_pick = Some(kind);
        wake::wake(ctx, Reason("dialog"));
    }

    /// Show the dialog asked for last frame, over `parent` when there is a window, and act on the
    /// pick: called before the frame's work, by [`Runtime::logic`] and (with the window) by eframe.
    pub(crate) fn show_pending_pick(&mut self, ctx: &egui::Context, parent: Option<&eframe::Frame>) {
        let Some(kind) = self.pending_pick.take() else { return };
        let picked = match &mut self.picker {
            Some(p) => p(kind),
            None => {
                // the dialog blocks the event loop: not a hang
                self.launch.telemetry.pause_hangs();
                let r = native_pick(&self.shared, &self.session, kind, parent);
                self.launch.telemetry.resume_hangs();
                r
            }
        };
        self.deliver_pick(ctx, kind, picked);
        self.apply_effects(ctx);
        wake::wake(ctx, Reason("dialog"));
    }

    fn deliver_pick(&mut self, ctx: &egui::Context, kind: Pick, picked: Option<PathBuf>) {
        match (kind, picked) {
            (Pick::Open, Some(path)) => {
                let r = self.execute("file.open", json!({"path": path.to_string_lossy(), "discard": true}));
                self.report(r);
            }
            (Pick::Open, None) => {}
            (Pick::SaveAs, Some(path)) => {
                let r = self.execute("file.save_as", json!({"path": path.to_string_lossy()}));
                self.report(r);
                self.continue_after_save(ctx);
            }
            (Pick::SaveAs, None) => {
                self.quit_after_save = false;
                self.after_save = None;
                if self.answering_end() {
                    self.end_step(ctx, session_end::Event::SaveFailed);
                }
            }
        }
    }

    /// The save the confirm dialog started is over: quit, or run the command it held back.
    fn continue_after_save(&mut self, ctx: &egui::Context) {
        self.continue_quit(ctx);
        let next = self.after_save.take();
        if let Some((id, params)) = next
            && !self.session.is_dirty()
        {
            self.run_ui_command(ctx, &id, params);
        }
    }

    // ------------------------------------------------------------------ closing

    fn handle_close(&mut self, ctx: &egui::Context) {
        let requested = ctx.input(|i| i.viewport().close_requested());
        if !requested || self.allow_close {
            return;
        }
        if self.session.is_dirty() {
            ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
            if !self.modals.iter().any(|m| matches!(m, Modal::Confirm { quit: true, .. })) {
                self.modals.push(Modal::Confirm { quit: true, command: None });
            }
        } else {
            self.shutdown(false);
        }
    }

    fn poll_session_end(&mut self, ctx: &egui::Context) {
        let requests: Vec<EndRequest> = self.session_end.as_ref().map(|rx| rx.try_iter().collect()).unwrap_or_default();
        for r in requests {
            self.end_requested(ctx, r.kind, session_end::CAN_WAIT);
        }
    }

    /// The OS asks the app to end (Dock Quit, logout, shutdown): the same dirty check and
    /// cleanup as closing the window, answered through `session_end::step`.
    fn end_requested(&mut self, ctx: &egui::Context, kind: EndKind, can_wait: bool) {
        let dirty = self.session.is_dirty();
        self.end_step(ctx, session_end::Event::Requested { kind, dirty, can_wait });
    }

    /// Whether the confirm dialog on screen answers an OS end request.
    fn answering_end(&self) -> bool {
        matches!(self.end_state, session_end::State::Asking(_) | session_end::State::Saving(_))
    }

    fn end_step(&mut self, ctx: &egui::Context, event: session_end::Event) {
        let (state, effects) = session_end::step(self.end_state, event);
        self.end_state = state;
        for effect in effects {
            match effect {
                session_end::Effect::Ask => {
                    if !self.modals.iter().any(|m| matches!(m, Modal::Confirm { quit: true, .. })) {
                        self.modals.push(Modal::Confirm { quit: true, command: None });
                    }
                }
                session_end::Effect::Save => {
                    self.quit_after_save = true;
                    self.after_save = None;
                    let r = self.execute("file.save", json!({}));
                    self.report(r);
                    self.apply_effects(ctx);
                    // saved in place (or failed); a Save As answers when its dialog closes
                    if self.pending_pick.is_none() {
                        self.quit_after_save = false;
                        let next = if self.session.is_dirty() { session_end::Event::SaveFailed } else { session_end::Event::Saved };
                        self.end_step(ctx, next);
                    }
                }
                session_end::Effect::Shutdown { keep_recovery } => self.shutdown_inner(keep_recovery),
                session_end::Effect::Allow => {
                    self.end_reply = Some(true);
                    session_end::reply(true);
                    // macOS ends the process from the reply; elsewhere close the window too
                    if !cfg!(target_os = "macos") || self.session_end.is_none() {
                        ctx.send_viewport_cmd(egui::ViewportCommand::Close);
                    }
                }
                session_end::Effect::Refuse => {
                    self.end_reply = Some(false);
                    session_end::reply(false);
                }
            }
        }
    }

    fn close(&mut self, ctx: &egui::Context, discarded: bool) {
        self.shutdown(discarded);
        ctx.send_viewport_cmd(egui::ViewportCommand::Close);
    }

    /// Settle everything before the process ends: stop jobs, flush settings, end autosave.
    pub fn shutdown(&mut self, _discarded: bool) {
        self.shutdown_inner(false);
    }

    /// `keep_recovery`: unsaved changes the user wasn't asked about (a logout that can't wait)
    /// stay in the autosave files for the next launch to offer.
    #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
    fn shutdown_inner(&mut self, keep_recovery: bool) {
        if self.allow_close {
            return;
        }
        self.allow_close = true;
        self.jobs.cancel_all();
        self.persist_view();
        if let Err(e) = self.settings.flush() {
            log::warn!("settings not saved: {e}");
        }
        if let Some(mut a) = self.autosave.take() {
            #[cfg(not(target_arch = "wasm32"))]
            if let Some(w) = a.writer.take() {
                for e in w.shutdown(&mut a.autosave) {
                    log::warn!("autosave: {e}");
                }
            }
            // a clean exit (saved, or the user chose not to keep the changes), unless the
            // changes were never offered for saving
            if let Err(e) = a.autosave.close(keep_recovery && self.session.is_dirty()) {
                log::warn!("autosave cleanup: {e}");
            }
        }
        self.launch.telemetry.flush(Duration::from_millis(500));
        log::info!("{} closed", self.shared.name);
    }

    /// End without any cleanup, as if the process had died: autosave files stay for the next
    /// launch to recover, settings are not flushed. For crash-recovery tests.
    #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
    pub fn abandon(mut self) {
        self.allow_close = true;
        if let Some(mut a) = self.autosave.take() {
            #[cfg(not(target_arch = "wasm32"))]
            if let Some(w) = a.writer.take() {
                let _ = w.shutdown(&mut a.autosave);
            }
            // dropping (not closing) releases the lock and keeps the session's files
            drop(a);
        }
    }

    fn continue_quit(&mut self, ctx: &egui::Context) {
        if self.quit_after_save {
            self.quit_after_save = false;
            if self.answering_end() {
                let next = if self.session.is_dirty() { session_end::Event::SaveFailed } else { session_end::Event::Saved };
                self.end_step(ctx, next);
            } else if !self.session.is_dirty() {
                self.close(ctx, false);
            }
        }
    }

    // ------------------------------------------------------------------ storage

    /// Keep the settings' `"window"` placement current: written only when the viewport info
    /// changes it (the settings debounce the file; closing flushes it). Once the window shows,
    /// a restored placement that no monitor shows moves back onto the screen.
    fn track_window(&mut self, ctx: &egui::Context) {
        if !self.native || !self.shared.remember_window || self.shared.dirs.is_none() {
            return;
        }
        let settings = &self.settings;
        let tracker = &mut self.window;
        let update = ctx.input(|i| tracker.update(i.viewport(), || settings.get::<WindowState>(window_state::KEY).unwrap_or_default()));
        if let Some(pos) = update.move_to {
            ctx.send_viewport_cmd(egui::ViewportCommand::OuterPosition(pos.into()));
        }
        if let Some(state) = update.save
            && let Err(e) = self.settings.set(window_state::KEY, &state)
        {
            log::warn!("window placement not saved: {e}");
        }
    }

    /// Write the view state to the settings when it changed (keyed by its generation: no copy
    /// or comparison on frames that did not change it).
    fn persist_view(&mut self) {
        let generation = self.session.view_generation();
        if self.persisted_view == Some(generation) {
            return;
        }
        self.persisted_view = Some(generation);
        let view = Value::Object(self.session.view_state().clone());
        if self.settings.get_value("view") != Some(&view) {
            self.settings.set_value("view", view);
        }
    }

    fn tick_storage(&mut self, ctx: &egui::Context) {
        // host time: saves go on while `app.clock` holds the app's time
        let t = self.clock.host_time().max(ctx.input(|i| i.time)).max(0.0);
        let now = Duration::from_secs_f64(t);
        // a pending save asks for its own frame through the settings' wake hook
        if let Err(e) = self.settings.tick(now) {
            log::warn!("settings not saved: {e}");
        }
        let Some(a) = &mut self.autosave else { return };
        if a.file_gen != self.session.file_generation() {
            a.file_gen = self.session.file_generation();
            let _ = a.autosave.set_document(&self.session.display_name(), self.session.path());
        }
        let dirty = self.session.is_dirty();
        let rev = self.session.revision();
        if !dirty {
            if a.autosave.meta().dirty {
                let _ = a.autosave.mark_clean();
            }
            return;
        }
        // an autosave not yet due asks for its frame through the autosave's wake hook, a finished
        // background write through the writer's
        let snap = self.session.store().snapshot();
        let format = Arc::clone(&self.shared.format);
        #[cfg(not(target_arch = "wasm32"))]
        let wrote = match &mut a.writer {
            Some(w) => {
                for e in w.pump(&mut a.autosave) {
                    log::warn!("autosave: {e}");
                }
                w.tick(&mut a.autosave, now, rev, dirty, move || format.encode(&snap).unwrap_or_default())
            }
            None => a.autosave.tick(now, rev, dirty, || format.encode(&snap).unwrap_or_default()).ok().flatten().is_some(),
        };
        #[cfg(target_arch = "wasm32")]
        let wrote = a.autosave.tick(now, rev, dirty, || format.encode(&snap).unwrap_or_default()).ok().flatten().is_some();
        if wrote {
            log::debug!("autosaved revision {}", rev.0);
        }
    }

    /// Set the window title when what it shows changed: the dirty mark, or the file (the
    /// display name changes only with the file generation).
    fn update_title(&mut self, ctx: &egui::Context) {
        let key = (self.session.is_dirty(), self.session.file_generation());
        if self.title_key == Some(key) {
            return;
        }
        self.title_key = Some(key);
        let dirty = if key.0 { " •" } else { "" };
        let title = format!("{}{dirty} — {}", self.session.display_name(), self.shared.title);
        if title != self.shown_title {
            ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));
            self.shown_title = title;
        }
    }

    /// The window title the runtime last set (`name • — App` when there are unsaved changes).
    pub fn title(&self) -> &str {
        &self.shown_title
    }

    // ------------------------------------------------------------------ dialogs and tools

    fn draw_modals(&mut self, ctx: &egui::Context) {
        if let Some(err) = self.view_error.clone() {
            let buttons = [DialogButton::new("Save As…"), DialogButton::new("Try Again").default()];
            let file = crash::last_panic().and_then(|p| p.log_file);
            match Dialog::new("ashlar.view_error", "Something went wrong", &buttons).width(460.0).show(ctx, |ui| {
                ui.label("The view hit an internal error and was stopped. Your document is safe: save it, then try again.");
                ui.add_space(6.0);
                ui.monospace(&err);
                if let Some(f) = &file {
                    ui.small(format!("Crash log: {}", f.display()));
                }
            }) {
                Some(DialogOutcome::Button(0)) => {
                    let r = self.execute("file.save_as", json!({}));
                    self.report(r);
                    self.apply_effects(ctx);
                }
                Some(_) => {
                    self.view_error = None;
                    crash::take_last_panic();
                }
                None => {}
            }
            return;
        }
        let Some(modal) = self.modals.first_mut() else { return };
        let done = match modal {
            Modal::Recovery => self.recovery_dialog(ctx),
            Modal::SafeMode => {
                let buttons = [DialogButton::new("Keep Settings"), DialogButton::new("Reset View Settings").default()];
                let title = format!("{} started in safe mode", self.shared.title);
                match Dialog::new("ashlar.safe_mode", &title, &buttons).show(ctx, |ui| {
                    ui.label("The last launch did not finish starting. Saved view settings (layout, theme) were not loaded this time.");
                }) {
                    Some(DialogOutcome::Button(1)) => {
                        self.settings.remove("view");
                        self.persisted_view = None;
                        self.settings.remove("theme");
                        ctx.memory_mut(|m| *m = egui::Memory::default());
                        self.wakes.install(ctx);
                        true
                    }
                    Some(_) => true,
                    None => false,
                }
            }
            Modal::Confirm { quit, command } => {
                let (quit, command) = (*quit, command.clone());
                self.confirm_dialog(ctx, quit, command)
            }
        };
        if done && !self.modals.is_empty() {
            self.modals.remove(0);
        }
    }

    fn confirm_dialog(&mut self, ctx: &egui::Context, quit: bool, command: Option<(String, Value)>) -> bool {
        let buttons = [DialogButton::cancel("Cancel"), DialogButton::destructive("Don't Save"), DialogButton::new("Save").default()];
        let title = format!("Save changes to “{}”?", self.session.display_name());
        let out = Dialog::new("ashlar.confirm_discard", &title, &buttons).show(ctx, |ui| {
            ui.label("Your changes will be lost if you don't save them.");
        });
        if quit && self.answering_end() {
            let event = match out {
                Some(DialogOutcome::Button(1)) => session_end::Event::Discard,
                Some(DialogOutcome::Button(2)) => session_end::Event::Save,
                Some(_) => session_end::Event::Cancel,
                None => return false,
            };
            self.end_step(ctx, event);
            return true;
        }
        match out {
            Some(DialogOutcome::Button(1)) => {
                if quit {
                    self.close(ctx, true);
                } else if let Some((id, params)) = command {
                    self.run_ui_command(ctx, &id, params);
                }
                true
            }
            Some(DialogOutcome::Button(2)) => {
                self.quit_after_save = quit;
                self.after_save = if quit { None } else { command };
                let r = self.execute("file.save", json!({}));
                self.report(r);
                self.apply_effects(ctx);
                if self.pending_pick.is_none() {
                    // saved in place (or failed): no Save As to wait for
                    if self.session.is_dirty() {
                        self.quit_after_save = false;
                        self.after_save = None;
                    } else {
                        self.continue_after_save(ctx);
                    }
                }
                true
            }
            Some(_) => true,
            None => false,
        }
    }

    fn recovery_dialog(&mut self, ctx: &egui::Context) -> bool {
        let Some(c) = self.recovery.first() else { return true };
        let buttons = [DialogButton::destructive("Discard"), DialogButton::new("Later"), DialogButton::new("Recover").default()];
        let label = if c.meta.label.is_empty() { "Untitled".to_string() } else { c.meta.label.clone() };
        let ago = (ashlar_store::autosave::unix_now() - c.meta.saved_unix).max(0);
        let out = Dialog::new("ashlar.recovery", "Recover unsaved work?", &buttons).width(440.0).show(ctx, |ui| {
            ui.label(format!("“{label}” had unsaved changes when {} last closed (autosaved {} ago).", self.shared.title, human_age(ago)));
        });
        let Some(out) = out else { return false };
        let c = self.recovery.remove(0);
        match out {
            DialogOutcome::Button(2) => match c.latest().map(|p| self.shared.format.load(p)) {
                Some(Ok(loaded)) => {
                    let path = c.meta.doc_path.as_ref().map(PathBuf::from);
                    self.session.replace(D::default(), path, None);
                    self.session.replace_as_edit("Recover Unsaved Work", loaded.doc);
                    if let Err(e) = c.discard() {
                        log::warn!("recovery files not removed: {e}");
                    }
                    self.toasts.success(format!("Recovered “{label}”. Save it to keep it."));
                }
                Some(Err(e)) => {
                    self.toasts.error(format!("Could not recover “{label}”: {e}"));
                }
                None => {
                    let _ = c.discard();
                }
            },
            DialogOutcome::Button(0) => {
                if let Err(e) = c.discard() {
                    log::warn!("recovery files not removed: {e}");
                }
            }
            _ => {}
        }
        self.recovery.is_empty()
    }

    fn draw_tools(&mut self, ctx: &egui::Context) {
        if self.palette.is_open()
            && let Some(id) = self.palette.show(ctx, &self.cache.infos, self.cache.seq, Platform::current())
        {
            self.run_ui_command(ctx, &id, json!({}));
        }
        if self.keymap_open {
            let mut open = true;
            let mut change = None;
            let (keymap, editor, infos, seq) = (&mut self.keymap, &mut self.keymap_editor, &self.cache.infos, self.cache.seq);
            egui::Window::new("Keyboard Shortcuts").id(egui::Id::new("ashlar.keymap")).open(&mut open).default_size([520.0, 420.0]).show(ctx, |ui| {
                change = editor.show(ui, keymap, infos, seq);
            });
            self.keymap_open = open;
            if let Some(c) = change {
                log::info!("keymap changed: {c:?}");
                let _ = self.settings.set("keymap", &self.keymap.overrides());
                self.keymap_gen = self.keymap_gen.wrapping_add(1);
                if matches!(c, KeymapChange::Bound { .. } | KeymapChange::Reset { .. }) {
                    self.cache.key = None;
                }
            }
        }
    }

    // ------------------------------------------------------------------ agent control

    fn serve_control(&mut self, ctx: &egui::Context) {
        let mut reqs: Vec<Request> = std::mem::take(&mut self.injected_requests);
        if let Some((_, rx)) = &self.control {
            reqs.extend(rx.try_iter().take(256));
        }
        if reqs.is_empty() {
            return;
        }
        let info = self.info();
        let mut queue = UiQueue { scenes: !self.shared.scenes.is_empty(), ..UiQueue::default() };
        for req in reqs {
            if let Some(r) = &mut self.recorder
                && !r.request(req.method(), req.params())
            {
                self.recorder = None;
            }
            let outer = self.session.swap_source(Some(Origin::Agent));
            let mut bound = self.shared.registry.bind(&mut self.session);
            ashlar_control::handle(req, &mut bound, &mut queue, &info);
            self.session.swap_source(outer);
            self.apply_effects(ctx);
        }
        for req in std::mem::take(&mut queue.pending) {
            self.answer_ui(ctx, req);
        }
        // No wake after answering: the port's waker asked for this frame, and requests are served
        // in `logic`, before the view draws, so this frame already draws what they changed.
        // Debugger requests that need later frames (input, screenshots, waits) ask for them in
        // `devtools`, and effects ask for their own.
    }

    fn answer_ui(&mut self, ctx: &egui::Context, req: Request) {
        let p = req.params().clone();
        let visible = ctx.input(|i| i.viewport().visible()).unwrap_or(true);
        if devtools::handles(req.method()) {
            // on a minimized or covered window, [`Runtime::hidden_pass`] runs the frames these need
            if let devtools::Outcome::NotMine(req) = devtools::handle(ctx, req) {
                req.unknown();
            }
            return;
        }
        match req.method() {
            "ui.inspect" => {
                let ins = automation::inspect(ctx);
                req.ok(json!({
                    "pass": ins.pass,
                    "elements": ins.elements,
                    "title": self.shown_title,
                    "document": {"name": self.session.display_name(), "dirty": self.session.is_dirty(), "revision": self.session.revision().0, "path": self.session.path().map(|p| p.to_string_lossy().into_owned())},
                    "view": self.session.view_state(),
                    "palette_open": self.palette.is_open(),
                    "keymap_open": self.keymap_open,
                    "dialogs": self.modals.len(),
                    "view_error": self.view_error,
                    "toasts": self.toasts.texts().collect::<Vec<_>>(),
                    "visible": visible,
                }));
            }
            "ui.menu.list" => {
                self.refresh_infos();
                req.ok(serde_json::to_value(&self.cache.menu).unwrap_or(Value::Null));
            }
            "ui.menu.invoke" => {
                let Some(id) = p.get("id").and_then(Value::as_str) else { return req.fail("ui.menu.invoke needs `id`") };
                self.refresh_infos();
                // menu item ids are command ids
                let command = self.cache.menu.find(id).map(|i| i.id.clone());
                match command {
                    Some(c) => {
                        let r = self.execute(&c, json!({}));
                        self.apply_effects(ctx);
                        req.reply(Reply::from_command(r));
                    }
                    None => req.fail(format!("no menu item `{id}` (see ui.menu.list)")),
                }
            }
            "ui.set" => {
                let Some(obj) = p.as_object() else { return req.fail("ui.set needs an object") };
                for (k, v) in obj {
                    if k == "theme" {
                        let mode: Option<ThemeMode> = serde_json::from_value(v.clone()).ok();
                        match mode {
                            Some(m) => {
                                self.session.set_view("theme", &m);
                                self.apply_effect(ctx, Effect::Theme(m));
                            }
                            None => return req.fail("theme is light, dark or system"),
                        }
                    } else {
                        self.session.set_view_value(k, v.clone());
                    }
                }
                req.ok(json!({}));
            }
            "app.quit" => {
                let discard = p.get("discard").and_then(Value::as_bool).unwrap_or(false);
                let dirty = self.session.is_dirty();
                self.apply_effect(ctx, Effect::Quit { discard });
                req.ok(json!({"closing": !dirty || discard}));
            }
            "app.stats" => {
                let mut v = serde_json::to_value(self.stats.summary()).unwrap_or(Value::Null);
                if let Some(o) = v.as_object_mut() {
                    o.insert("passes".into(), json!(self.passes));
                    o.insert("jobs".into(), self.jobs.to_json());
                    o.insert("log_lines_dropped".into(), json!(crate::logging::dropped()));
                    o.insert("wakes".into(), serde_json::to_value(self.wakes.stats()).unwrap_or(Value::Null));
                    o.insert("process".into(), serde_json::to_value(self.process.read()).unwrap_or(Value::Null));
                }
                if p.get("reset").and_then(Value::as_bool) == Some(true) {
                    self.stats.reset_window();
                }
                req.ok(v);
            }
            ashlar_control::APP_CLOCK => {
                let op = match ashlar_control::ClockOp::from_params(&p) {
                    Ok(op) => op,
                    Err(e) => return req.fail(e),
                };
                let (now, predicted_dt) = ctx.input(|i| (i.time, i.predicted_dt));
                match op {
                    ashlar_control::ClockOp::Read => {}
                    ashlar_control::ClockOp::Pause => self.clock.pause(now, predicted_dt),
                    ashlar_control::ClockOp::Step { ms } => {
                        self.clock.step(now, predicted_dt, ms / 1000.0);
                        // the frame at the new time
                        wake::wake(ctx, Reason::CONTROL);
                    }
                    ashlar_control::ClockOp::Resume => {
                        self.clock.resume();
                        wake::wake(ctx, Reason::CONTROL);
                    }
                }
                req.ok(json!({"paused": self.clock.is_paused(), "time": self.clock.time(now)}));
            }
            ashlar_control::UI_SCENE => match p.get("name").and_then(Value::as_str) {
                None => req.ok(json!({"scenes": self.shared.scene_names()})),
                Some(name) => match self.apply_scene(name) {
                    Ok(()) => {
                        self.apply_effects(ctx);
                        wake::wake(ctx, Reason::CONTROL);
                        req.ok(json!({"scene": name}));
                    }
                    Err(e) => req.fail(e),
                },
            },
            "app.logs" => {
                let limit = p.get("limit").and_then(Value::as_u64).unwrap_or(200).min(crate::logging::RING_LINES as u64) as usize;
                let level = p.get("level").and_then(Value::as_str).and_then(crate::logging::level_of).unwrap_or(log::Level::Trace);
                req.ok(json!({"lines": crate::logging::recent(limit, level)}));
            }
            _ => req.unknown(),
        }
    }

    /// The inspector's panels and the app's pending work for `ui.wait {for: "idle"}`. The panels
    /// are built only while the inspector is open.
    fn feed_devtools(&mut self, ctx: &egui::Context) {
        devtools::set_busy(ctx, self.jobs.is_busy());
        devtools::section(ctx, "Logs", || {
            crate::logging::recent(200, log::Level::Trace).into_iter().map(|l| format!("{:<5} {}: {}", l.level, l.target, l.message)).collect()
        });
        let history = self.session.store().history();
        devtools::section(ctx, "Undo", || {
            let mut lines: Vec<String> = history.undo_labels().map(|l| format!("  {l}")).collect();
            lines.push("── now ──".into());
            lines.extend(history.redo_labels().map(|l| format!("  {l} (redo)")));
            lines
        });
    }
}

impl<D: Document> Drop for Runtime<D> {
    fn drop(&mut self) {
        self.shutdown(false);
    }
}

fn human_age(secs: i64) -> String {
    match secs {
        s if s < 90 => format!("{s} s"),
        s if s < 90 * 60 => format!("{} min", s / 60),
        s if s < 48 * 3600 => format!("{} h", s / 3600),
        s => format!("{} days", s / 86_400),
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn native_pick<D: Document>(shared: &Shared<D>, session: &Session<D>, kind: Pick, parent: Option<&eframe::Frame>) -> Option<PathBuf> {
    use ashlar_native::dialogs::FileDialog;
    let exts: Vec<&str> = shared.extensions.iter().map(String::as_str).collect();
    let mut d = FileDialog::new();
    if !exts.is_empty() {
        d = d.filter(shared.title.clone(), &exts);
    }
    if let Some(dir) = session.path().and_then(std::path::Path::parent) {
        d = d.directory(dir);
    }
    let d = match kind {
        Pick::Open => d.title("Open"),
        Pick::SaveAs => {
            let name = match exts.first() {
                Some(e) if session.path().is_none() => format!("Untitled.{e}"),
                _ => session.display_name(),
            };
            d.title("Save As").file_name(name)
        }
    };
    let r = match (kind, parent) {
        (Pick::Open, Some(w)) => d.parent(w).open_file(),
        (Pick::Open, None) => d.open_file(),
        (Pick::SaveAs, Some(w)) => d.parent(w).save_file(),
        (Pick::SaveAs, None) => d.save_file(),
    };
    match r {
        Ok(p) => Some(p),
        Err(ashlar_native::NativeError::Cancelled) => None,
        Err(e) => {
            log::warn!("file dialog: {e}");
            None
        }
    }
}

#[cfg(target_arch = "wasm32")]
fn native_pick<D: Document>(_shared: &Shared<D>, _session: &Session<D>, _kind: Pick, _parent: Option<&eframe::Frame>) -> Option<PathBuf> {
    None
}

// ---------------------------------------------------------------------------------------------
// eframe
// ---------------------------------------------------------------------------------------------

struct EframeApp<D: Document> {
    rt: Runtime<D>,
    /// The debugger renders screenshots on eframe's wgpu device (set on the first frame).
    offscreen: bool,
}

impl<D: Document> EframeApp<D> {
    /// Hand the debugger its off-screen renderer once eframe's wgpu device is known.
    fn install_offscreen(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {
        if std::mem::replace(&mut self.offscreen, true) {
            return;
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Some(rs) = frame.wgpu_render_state() {
            devtools::set_offscreen(ctx, Some(crate::offscreen::renderer(rs.clone())));
        }
        #[cfg(target_arch = "wasm32")]
        let _ = (ctx, frame);
    }
}

impl<D: Document> eframe::App for EframeApp<D> {
    fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
        self.rt.note_presented();
        // before the frame's work: the last frame is on screen, the dialog opens over the window
        self.rt.show_pending_pick(ctx, Some(frame));
        self.rt.logic(ctx);
        self.install_offscreen(ctx, frame);
        let Some(mut out) = self.rt.hidden_pass(ctx, None, Vec::new()) else { return };
        #[cfg(not(target_arch = "wasm32"))]
        if let Some(rs) = frame.wgpu_render_state() {
            let mut r = rs.renderer.write();
            for (id, deltas) in &out.textures_delta.set {
                for delta in deltas {
                    r.update_texture(&rs.device, &rs.queue, *id, delta);
                }
            }
            for id in &out.textures_delta.free {
                r.free_texture(id);
            }
        }
        // handed to the renderer (or, with no wgpu device, nowhere to hand them)
        out.textures_delta.clear();
    }

    fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
        self.install_offscreen(ui.ctx(), frame);
        // the previous frame's whole CPU time, painting included
        if let Some(d) = frame.info().cpu_usage.and_then(|s| Duration::try_from_secs_f32(s).ok()) {
            self.rt.stats.record_frame_cpu(d);
        }
        self.rt.ui(ui);
        #[cfg(not(target_arch = "wasm32"))]
        self.rt.install_native_menu(ui.ctx(), frame);
    }

    fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
        self.rt.raw_input_hook(ctx, raw_input);
    }

    fn on_exit(&mut self) {
        self.rt.shutdown(false);
    }
}

#[cfg(not(target_arch = "wasm32"))]
struct Args {
    control: Option<u16>,
    scene: Option<String>,
    safe_mode: bool,
    open: Option<PathBuf>,
}

#[cfg(not(target_arch = "wasm32"))]
fn parse_args(env_prefix: &str) -> Args {
    let mut a = Args { control: None, scene: None, safe_mode: false, open: None };
    let mut it = std::env::args().skip(1);
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "--control" => a.control = it.next().and_then(|p| p.parse().ok()),
            s if s.starts_with("--control=") => a.control = s.trim_start_matches("--control=").parse().ok(),
            "--safe-mode" => a.safe_mode = true,
            "--scene" => a.scene = it.next(),
            s if s.starts_with("--scene=") => a.scene = Some(s.trim_start_matches("--scene=").to_string()),
            s if !s.starts_with('-') && a.open.is_none() => a.open = Some(PathBuf::from(s)),
            _ => {}
        }
    }
    if a.control.is_none() {
        a.control = std::env::var(format!("{env_prefix}_CONTROL_PORT")).ok().and_then(|p| p.trim().parse().ok());
    }
    a
}

/// On the web: run in the `<canvas>` [`App::canvas_id`] names (default: the app's name, then
/// `ashlar`). Returns at once; the app runs in the browser's event loop. When it cannot start, a
/// visible error is put next to the canvas (or at the top of the page) and logged to the console.
#[cfg(target_arch = "wasm32")]
pub(crate) fn run_native<D: Document>(app: App<D>) -> Result<(), Error> {
    use wasm_bindgen::JsCast;
    let (shared, view, setup) = app.split();
    let level = log::LevelFilter::Info;
    let console: crate::logging::Output = Box::new(|line| web_sys::console::log_1(&line.into()));
    crate::logging::install(Box::new(crate::logging::Logger::new(&shared.name, None, level, false).with_output(console)), level);
    // the browser console sees every panic: ashlar's hook runs first, then chains to this one
    static CONSOLE_HOOK: std::sync::Once = std::sync::Once::new();
    CONSOLE_HOOK.call_once(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            web_sys::console::error_1(&format!("panic: {info}").into());
            previous(info);
        }));
    });
    crash::install(None, &shared.name, &shared.version);
    let document = web_sys::window().and_then(|w| w.document()).ok_or_else(|| Error::Window("no document".into()))?;
    let ids: Vec<String> = shared.canvas_id.iter().cloned().chain([shared.name.clone(), "ashlar".to_string()]).collect();
    let canvas = ids.iter().find_map(|id| document.get_element_by_id(id).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()));
    let Some(canvas) = canvas else {
        let wanted = ids.first().map_or("ashlar", String::as_str);
        let msg = format!("{} could not start: the page has no <canvas id=\"{wanted}\">.", shared.title);
        show_web_error(&document, None, &msg);
        return Err(Error::Window(msg));
    };
    let title = shared.title.clone();
    wasm_bindgen_futures::spawn_local(async move {
        let creator: eframe::AppCreator<'static> =
            Box::new(move |_cc| Ok(Box::new(EframeApp { rt: Runtime::new(shared, view, setup, Launch::default()), offscreen: false })));
        let target = canvas.clone();
        if let Err(e) = eframe::WebRunner::new().start(canvas, eframe::WebOptions::default(), creator).await {
            log::error!("the app could not start: {e:?}");
            let detail = e.as_string().unwrap_or_else(|| "the browser may not support WebGL or WebGPU".to_string());
            show_web_error(&document, Some(&target), &format!("{title} could not start: {detail}"));
        }
    });
    Ok(())
}

/// Put `msg` in a visible box right after `canvas` (or first in the page's body), replacing an
/// earlier one; screen readers announce it (`role="alert"`). Errors here are only logged.
#[cfg(target_arch = "wasm32")]
fn show_web_error(document: &web_sys::Document, canvas: Option<&web_sys::HtmlCanvasElement>, msg: &str) {
    const ID: &str = "ashlar-start-error";
    let shown = (|| -> Result<(), wasm_bindgen::JsValue> {
        if let Some(old) = document.get_element_by_id(ID) {
            old.remove();
        }
        let div = document.create_element("div")?;
        div.set_id(ID);
        div.set_attribute("role", "alert")?;
        div.set_attribute(
            "style",
            "margin:12px;padding:12px 16px;border:1px solid #c62828;border-radius:6px;background:#fdecea;\
             color:#5f2120;font:14px/1.4 system-ui,sans-serif;max-width:640px",
        )?;
        div.set_text_content(Some(msg));
        match canvas.and_then(|c| c.parent_node().map(|p| (p, c.next_sibling()))) {
            Some((parent, next)) => drop(parent.insert_before(&div, next.as_ref())?),
            None => match document.body() {
                Some(body) => drop(body.insert_before(&div, body.first_child().as_ref())?),
                None => return Err("no <body>".into()),
            },
        }
        Ok(())
    })();
    if let Err(e) = shown {
        log::error!("could not show the start error in the page: {e:?}");
    }
}

/// The window as the app describes it, at the placement it had last time (kept on screen), with
/// the app's icon and its own changes last.
#[cfg(not(target_arch = "wasm32"))]
fn window_builder<D: Document>(shared: &Shared<D>, window: crate::app::WindowSpec, safe_mode: bool) -> egui::ViewportBuilder {
    let mut b =
        egui::ViewportBuilder::default().with_title(shared.title.clone()).with_inner_size(shared.window_size).with_app_id(shared.name.clone());
    if shared.remember_window
        && !safe_mode
        && let Some(d) = &shared.dirs
    {
        let settings = Settings::load(Arc::new(DirConfig::new(d.config.clone())), "settings.json", &[]);
        if let Some(saved) = settings.get::<WindowState>(window_state::KEY) {
            // checked against the monitors the OS lists now (macOS, Windows); where it lists none,
            // sizes and coordinates are only bounded and the first frame moves a window no monitor
            // shows
            b = window_state::apply(b, &window_state::clamp(saved, &window_state::monitors_now()));
        }
    }
    if let Some(png) = window.icon {
        match catch_unwind(AssertUnwindSafe(|| eframe::icon_data::from_png_bytes(&png))) {
            Ok(Ok(icon)) => b = b.with_icon(icon),
            Ok(Err(e)) => log::warn!("the app icon is not a PNG ashlar can read: {e}"),
            Err(_) => log::warn!("the app icon could not be decoded"),
        }
    }
    let Some(f) = window.viewport else { return b };
    let fallback = b.clone();
    catch_unwind(AssertUnwindSafe(move || f(b))).unwrap_or_else(|p| {
        log::error!("App::viewport panicked: {}", panic_text(p.as_ref()));
        fallback
    })
}

/// eframe's wgpu setup with `latency` frames queued at most (IMP-2.10: one swapchain image fewer).
#[cfg(not(target_arch = "wasm32"))]
fn wgpu_options(latency: u32) -> eframe::egui_wgpu::WgpuConfiguration {
    let surface = eframe::egui_wgpu::SurfaceConfig {
        present_mode: eframe::egui_wgpu::wgpu::PresentMode::AutoVsync,
        desired_maximum_frame_latency: Some(latency),
    };
    eframe::egui_wgpu::WgpuConfiguration { surface, ..Default::default() }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn run_native<D: Document>(app: App<D>) -> Result<(), Error> {
    // launch timings count from here (IMP-6.9)
    let process_start = now();
    let mut app = app;
    let window = app.take_window();
    let (shared, view, setup) = app.split();
    let args = parse_args(&shared.env_prefix);
    let logs = shared.dirs.as_ref().map(|d| d.logs.clone());
    if let Some(d) = &shared.dirs
        && let Err(e) = d.ensure()
    {
        eprintln!("{}: could not create its folders: {e}", shared.name);
    }
    // before anything else: a second launch hands its files to the first and exits
    let inbox = Inbox::default();
    let mut instance = None;
    if shared.single_instance {
        let launch_args: Vec<String> = std::env::args().skip(1).collect();
        match ashlar_native::single_instance::SingleInstance::new(&shared.name).claim(&launch_args, inbox.forwarder()) {
            Ok(ashlar_native::single_instance::Launch::Forwarded) => return Ok(()),
            Ok(ashlar_native::single_instance::Launch::Primary(g)) => instance = Some(g),
            Err(e) => eprintln!("{}: running without the single-instance check: {e}", shared.name),
        }
    }
    let env_var = format!("{}_LOG", shared.env_prefix);
    let filter = crate::logging::filter_from_env(&[env_var.as_str(), "RUST_LOG"], "info");
    let level = filter.max_level();
    let telemetry = match (&shared.telemetry, &shared.dirs) {
        (Some(cfg), Some(d)) => Telemetry::start(cfg, &shared.name, &shared.version, &d.data, true),
        _ => Telemetry::default(),
    };
    let logger = crate::logging::Logger::new(&shared.name, logs.as_deref(), level, true).with_filter(filter);
    crate::logging::install(telemetry.wrap_logger(Box::new(logger)), level);
    // after the tracer's hook: ours runs first, then chains to it
    crash::install(logs.as_deref(), &shared.name, &shared.version);
    log::info!("{} {} starting", shared.name, shared.version);
    // before the window: in a window station Windows never shows, wgpu panics configuring the
    // window's surface (ashlar_native::display)
    if let Err(e) = ashlar_native::display::check() {
        log::error!("{} cannot open its window: {e}", shared.name);
        return Err(Error::NoDesktop(e.0));
    }

    let (guard, previous) = match &shared.dirs {
        Some(d) => {
            let (g, p) = LaunchGuard::begin(&d.data);
            (Some(g), p)
        }
        None => (None, PreviousLaunch::Clean),
    };
    let safe_mode = args.safe_mode || matches!(previous, PreviousLaunch::CrashedAtStartup { .. });
    if safe_mode {
        log::warn!("starting in safe mode ({previous:?})");
    }
    // main thread, before the event loop: Finder's launch documents arrive as Apple events
    #[cfg(target_os = "macos")]
    inbox.listen_os();
    let ready_file = std::env::var_os(format!("{}_READY_FILE", shared.env_prefix)).filter(|v| !v.is_empty()).map(PathBuf::from);
    let mut launch = Launch {
        safe_mode,
        previous: Some(previous),
        open: args.open,
        control_port: args.control,
        guard,
        telemetry,
        inbox: Some(inbox),
        instance,
        process_start,
        window_at: None,
        ready_file,
        presented: false,
        scene: args.scene,
    };
    let mut options = eframe::NativeOptions {
        viewport: window_builder(&shared, window, safe_mode),
        wgpu_options: wgpu_options(shared.frame_latency),
        ..Default::default()
    };
    // `<PREFIX>_QUIET`: open without taking the focus (agents relaunching after each build)
    if ashlar_native::mac_shell::quiet_requested(&shared.env_prefix) {
        options.viewport = options.viewport.with_active(false);
        #[cfg(target_os = "macos")]
        {
            options.event_loop_builder = Some(Box::new(|b| {
                use winit::platform::macos::EventLoopBuilderExtMacOS;
                b.with_activate_ignoring_other_apps(false);
            }));
        }
    }
    let title = shared.title.clone();
    eframe::run_native(
        &title,
        options,
        Box::new(move |_cc| {
            // eframe has built the window and its wgpu surface by now
            launch.window_at = now();
            let mut rt = Runtime::new(shared, view, setup, launch);
            rt.native = true;
            Ok(Box::new(EframeApp { rt, offscreen: false }))
        }),
    )
    .map_err(|e| Error::Window(e.to_string()))
}

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

    #[test]
    fn ages_read_well() {
        assert_eq!(human_age(5), "5 s");
        assert_eq!(human_age(600), "10 min");
        assert_eq!(human_age(7200), "2 h");
        assert_eq!(human_age(300_000), "3 days");
    }

    /// A runtime as `run()` builds it, with `launch` filled in.
    fn launched(app: crate::App<i64>, launch: Launch) -> Runtime<i64> {
        let (shared, view, setup) = app.split();
        let mut rt = Runtime::new(shared, view, setup, launch);
        rt.set_preferences(Preferences::default);
        rt
    }

    #[test]
    fn launch_times_and_the_ready_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let ready = dir.path().join("ready.json");
        let start = std::time::Instant::now().checked_sub(Duration::from_millis(5));
        let launch = Launch { process_start: start, window_at: now(), ready_file: Some(ready.clone()), ..Default::default() };
        let mut d = crate::Driver::new(launched(crate::App::new("launchtest", "0.0.0"), launch));
        d.runtime.note_presented();
        assert_eq!(d.runtime.stats().launch().launch_to_present_ms, None, "nothing is presented before a frame");
        d.frame();
        d.runtime.note_presented();
        let t = d.runtime.stats().summary().launch;
        let (w, f, p) = (t.to_window_ms.unwrap(), t.to_first_frame_ms.unwrap(), t.launch_to_present_ms.unwrap());
        assert!(w >= 5.0 && w <= f && f <= p, "window {w}, first frame {f}, present {p}");
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        let body = loop {
            if let Ok(text) = std::fs::read_to_string(&ready) {
                break text;
            }
            assert!(std::time::Instant::now() < deadline, "no ready file");
            std::thread::sleep(Duration::from_millis(5));
        };
        let v: Value = serde_json::from_str(&body).unwrap();
        assert_eq!(v["pid"].as_u64(), Some(u64::from(std::process::id())));
        assert_eq!(v["ready_ms"].as_f64(), Some(p));
    }

    #[test]
    fn headless_runs_report_no_launch_times() {
        let mut d = crate::Driver::new(crate::App::<i64>::new("launchtest", "0.0.0").runtime());
        d.frame();
        d.runtime.note_presented();
        assert_eq!(d.runtime.stats().launch(), crate::LaunchTimes::default());
    }

    #[test]
    fn the_command_line_document_opens_after_the_first_frame() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("a.num");
        let mut h = crate::App::<i64>::new("launchtest", "0.0.0").headless();
        h.session_mut().edit("set", |n| *n = 7);
        h.session_mut().save_as(&path).unwrap();
        let app = crate::App::<i64>::new("launchtest", "0.0.0").file_extension("num");
        let mut d = crate::Driver::new(launched(app, Launch { open: Some(path.clone()), ..Default::default() }));
        assert_eq!(d.runtime.session().path(), None, "nothing loads before the window");
        d.frame();
        assert!(d.runtime.stats().summary().first_frame_ms.is_some(), "the first frame is drawn");
        assert_eq!(d.runtime.session().path(), None, "with the empty document");
        d.settle(10);
        assert_eq!(d.runtime.session().path(), Some(path.as_path()), "the next frame opens the file");
        assert_eq!(*d.runtime.session().doc(), 7);
    }

    #[test]
    fn menus_follow_enabled_state_but_typing_rebuilds_nothing() {
        let mut rt = crate::App::<i64>::new("runtimetest", "0.0.0").runtime();
        let undo = |rt: &Runtime<i64>| rt.cache.infos.iter().find(|i| i.id == "app.undo").map(|i| i.enabled);
        rt.refresh_infos();
        assert_eq!(undo(&rt), Some(false), "nothing to undo yet");
        rt.session_mut().edit("bump", |n| *n += 1);
        rt.refresh_infos();
        assert_eq!(undo(&rt), Some(true), "an edit enables Undo");
        assert_eq!(rt.cache.menu.find("app.undo").map(|i| i.enabled), Some(true), "and the menu shows it");
        let seq = rt.cache.seq;
        rt.session_mut().edit("bump", |n| *n += 1);
        rt.refresh_infos();
        assert_eq!(rt.cache.seq, seq, "another edit changes no command's state: the infos stay");
        assert_eq!(rt.cache.key.map(|k| k.0), Some(rt.session().revision()), "and are current");
        rt.session_mut().undo();
        rt.session_mut().undo();
        rt.refresh_infos();
        assert_eq!(undo(&rt), Some(false), "undoing everything disables Undo again");
    }

    fn enter() -> egui::Event {
        egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }
    }

    /// A driver whose dialogs answer from `answers` and log what they were asked.
    fn picking(answers: Vec<(Pick, PathBuf)>) -> (crate::Driver<i64>, std::rc::Rc<std::cell::RefCell<Vec<Pick>>>) {
        let app = crate::App::<i64>::new("picktest", "0.0.0").file_extension("num");
        let mut rt = launched(app, Launch::default());
        let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
        let log = asked.clone();
        rt.set_file_picker(move |kind| {
            log.borrow_mut().push(kind);
            answers.iter().find(|(k, _)| *k == kind).map(|(_, p)| p.clone())
        });
        let mut d = crate::Driver::new(rt);
        d.frame();
        (d, asked)
    }

    #[test]
    fn the_pick_arrives_on_the_next_frame() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("a.num");
        let (mut d, asked) = picking(vec![(Pick::SaveAs, path.clone())]);
        d.runtime.session_mut().edit("set", |n| *n = 3);
        let r = d.runtime.execute("file.save_as", json!({})).unwrap();
        assert_eq!(r["pending"], "dialog");
        d.frame();
        assert!(asked.borrow().is_empty(), "no dialog inside the frame that asked for it");
        assert_eq!(d.runtime.pending_pick, Some(Pick::SaveAs));
        d.frame();
        assert_eq!(*asked.borrow(), vec![Pick::SaveAs], "the next frame shows it");
        assert_eq!(d.runtime.session().path(), Some(path.as_path()), "and saves there");
        assert!(!d.runtime.session().is_dirty());
    }

    #[test]
    fn quitting_a_dirty_untitled_document_saves_through_the_dialog_then_closes() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("q.num");
        let (mut d, asked) = picking(vec![(Pick::SaveAs, path.clone())]);
        d.runtime.session_mut().edit("set", |n| *n = 9);
        d.request_close();
        d.frame();
        assert!(d.runtime.modal_open(), "the confirm dialog asks first");
        d.settle(10);
        d.push_event(enter());
        d.frame();
        d.settle(10);
        assert_eq!(*asked.borrow(), vec![Pick::SaveAs]);
        assert_eq!(d.runtime.session().path(), Some(path.as_path()));
        assert!(d.runtime.is_closing(), "the quit goes on once saved");
    }

    #[test]
    fn a_cancelled_save_as_keeps_the_window_open() {
        let (mut d, asked) = picking(Vec::new());
        d.runtime.session_mut().edit("set", |n| *n = 9);
        d.request_close();
        d.frame();
        d.settle(10);
        d.push_event(enter());
        d.frame();
        d.settle(10);
        assert_eq!(*asked.borrow(), vec![Pick::SaveAs]);
        assert!(!d.runtime.is_closing(), "cancelled: nothing closes");
        assert!(!d.runtime.quit_after_save, "and a later save does not quit");
    }

    /// An OS end request (Dock Quit, logout) answered in the next frame.
    fn os_end(d: &mut crate::Driver<i64>, kind: EndKind, can_wait: bool) {
        let ctx = d.ctx().clone();
        d.runtime.end_requested(&ctx, kind, can_wait);
        d.frame();
    }

    #[test]
    fn a_dock_quit_of_a_clean_document_cleans_up_and_allows_at_once() {
        let (mut d, _) = picking(Vec::new());
        os_end(&mut d, EndKind::Quit, true);
        assert_eq!(d.runtime.end_reply, Some(true));
        assert!(d.runtime.is_closing(), "shut down before answering");
        assert!(!d.runtime.modal_open());
    }

    #[test]
    fn a_dock_quit_of_a_dirty_document_asks_then_saves_then_allows() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("q.num");
        let (mut d, asked) = picking(vec![(Pick::SaveAs, path.clone())]);
        d.runtime.session_mut().edit("set", |n| *n = 9);
        os_end(&mut d, EndKind::Quit, true);
        assert!(d.runtime.modal_open(), "the confirm dialog asks first");
        assert_eq!(d.runtime.end_reply, None, "no answer to the OS yet");
        d.settle(10);
        d.push_event(enter());
        d.frame();
        d.settle(10);
        assert_eq!(*asked.borrow(), vec![Pick::SaveAs]);
        assert_eq!(d.runtime.session().path(), Some(path.as_path()));
        assert_eq!(d.runtime.end_reply, Some(true), "saved: the quit goes on");
        assert!(d.runtime.is_closing());
    }

    #[test]
    fn a_cancelled_save_as_refuses_the_os_quit() {
        let (mut d, asked) = picking(Vec::new());
        d.runtime.session_mut().edit("set", |n| *n = 9);
        os_end(&mut d, EndKind::Logout, true);
        d.settle(10);
        d.push_event(enter());
        d.frame();
        d.settle(10);
        assert_eq!(*asked.borrow(), vec![Pick::SaveAs]);
        assert_eq!(d.runtime.end_reply, Some(false), "the logout is cancelled");
        assert!(!d.runtime.is_closing());
        assert_eq!(d.runtime.end_state, session_end::State::Idle, "a later quit asks again");
    }

    #[test]
    fn a_logout_that_cant_wait_allows_and_keeps_the_changes_for_recovery() {
        let (mut d, asked) = picking(Vec::new());
        d.runtime.session_mut().edit("set", |n| *n = 9);
        os_end(&mut d, EndKind::Logout, false);
        assert!(asked.borrow().is_empty() && !d.runtime.modal_open(), "nothing is asked");
        assert_eq!(d.runtime.end_reply, Some(true));
        assert!(d.runtime.is_closing());
    }

    #[test]
    fn opening_over_a_dirty_untitled_document_saves_then_shows_the_open_dialog() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (saved, other) = (dir.path().join("s.num"), dir.path().join("o.num"));
        let mut h = crate::App::<i64>::new("picktest", "0.0.0").headless();
        h.session_mut().edit("set", |n| *n = 42);
        h.session_mut().save_as(&other).unwrap();
        let (mut d, asked) = picking(vec![(Pick::SaveAs, saved.clone()), (Pick::Open, other.clone())]);
        d.runtime.session_mut().edit("set", |n| *n = 5);
        let r = d.runtime.execute("file.open", json!({})).unwrap();
        assert_eq!(r["pending"], "confirm");
        d.frame();
        d.settle(10);
        d.push_event(enter());
        d.frame();
        d.settle(10);
        assert_eq!(*asked.borrow(), vec![Pick::SaveAs, Pick::Open], "save first, then pick the file to open");
        assert!(saved.exists(), "the changes were saved");
        assert_eq!(d.runtime.session().path(), Some(other.as_path()));
        assert_eq!(*d.runtime.session().doc(), 42);
    }
}