datui-lib 0.4.4

Data Exploration in the Terminal (library)
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
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
//! The home screen's work: listing, probing remote places, measuring and
//! classifying rows, previews, search, catalogs and the cloud sources, and the
//! answers its workers send back.

use crate::app::background::{CacheWrites, OwedAnswer};
use crate::app::feedback::Confirm;
use crate::cache::CacheManager;
use crate::cli::FileFormat;
use crate::loading::open_options::OpenOptions;
#[cfg(feature = "cloud")]
use crate::wait_on_runtime;
use crate::{
    APP_NAME, App, AppEvent, InputMode, cloud::source, config, home, home::catalog, home::discover,
    loading, widgets,
};
use color_eyre::Result;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

/// The home screen's work in flight and what it keeps for the session: probes, listings,
/// search, previews and schemas.
#[derive(Default)]
pub struct HomeApp {
    /// Network roots being listed off-thread, so a probe is not started twice. Never
    /// removed for a root that does not answer: its thread is lost, and a retry would
    /// lose another.
    pub(crate) probes_inflight: Vec<PathBuf>,
    /// Each cloud listing's stop flag, by place: leaving the place stops it before its
    /// next page.
    pub(crate) listing_cancels: HashMap<PathBuf, Arc<std::sync::atomic::AtomicBool>>,
    /// The listing a filter asked of a cut-short cloud directory: where, the name
    /// prefix, and its stop flag.
    pub(crate) narrowing: Option<(PathBuf, String, Arc<std::sync::atomic::AtomicBool>)>,
    /// Cloud discovery has started. It costs a request per provider, so it runs once
    /// per session.
    #[cfg(feature = "cloud")]
    pub(crate) cloud_discovery_started: bool,
    /// A recursive search below the working directory is out. One at a time: a second
    /// would only compete for the disk.
    pub(crate) search_inflight: bool,
    /// The home generation the walk started in. Its batches stay its own across
    /// refreshes; the root decides whether they still apply.
    pub(crate) search_generation: u64,
    /// Why the last open failed, shown at home when the error is dismissed with nothing
    /// to fall back to.
    pub(crate) last_load_error: Option<String>,
    /// Schema reads currently out, so the same one is not requested every frame.
    pub(crate) schema_inflight: Vec<PathBuf>,
    /// Invalidates listings and measurements from a request the user has moved past.
    pub(crate) generation: u64,
    /// Rows arrived for a listing still being read; it is listed again before the next
    /// frame.
    pub(crate) refresh_owed: bool,
    /// Schema previews, memoized for the session only (persisted, they would go stale).
    pub(crate) schema_cache: HashMap<PathBuf, Option<discover::SchemaPreview>>,
    /// The home screen's `ROWS` previews, and the dataset the newest one built.
    pub previews: crate::home::home_preview::Previews,
    /// The pre-0.4.0 Ctrl+D directories in the cache have been moved to `catalog.toml`.
    pub(crate) remembered_moved: bool,
    /// Which home workers panic before starting, for tests. The jobs' own is
    /// [`Jobs::worker_dies`].
    #[cfg(test)]
    pub(crate) worker_dies: Option<crate::HomeWorkerDies>,
    /// Whether a browser opened here appears in front of the user: `o` on a doc link
    /// is offered only then (`link_open::local_desktop`).
    pub local_desktop: bool,
    /// The reads of data started this session, by kind.
    pub reads: crate::home::home_preview::ReadCounts,
}

/// Rows measured per background pass: small, so a slow filesystem shows progress.
const MEASURE_BATCH: usize = 12;

/// Rows a probe measures while it is already reading a remote directory.
const PROBE_MEASURE_LIMIT: usize = 24;

/// Rows one classification pass looks into: a cap on work in flight, the next pass
/// chosen from the viewport when this one lands. Small like [`MEASURE_BATCH`], so a
/// screen fills in rather than going silent.
pub(crate) const CLASSIFY_BATCH: usize = 16;

/// Probes allowed at once: a probe of a gone share holds its thread until exit.
pub(crate) const MAX_CONCURRENT_PROBES: usize = 4;

/// A number per home search walk, so one walk's scorings are never taken for
/// another's over the same place.
fn next_search_epoch() -> u64 {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

/// A source as a home-screen row, with the last run's buckets when they still apply.
#[cfg(feature = "cloud")]
pub(crate) fn home_cloud_source(
    source: &crate::cloud::cloud_sources::Source,
    cached: Option<&crate::cache::CloudListing>,
    listing: bool,
) -> home::CloudSource {
    let mut details: Vec<(String, String)> = vec![
        ("source".to_string(), source.id.clone()),
        ("api".to_string(), source.kind.name().to_string()),
    ];
    if let Some(endpoint) = &source.s3.endpoint {
        details.push(("endpoint".to_string(), endpoint.clone()));
    }
    if let Some(region) = &source.s3.region {
        details.push(("region".to_string(), region.clone()));
    }
    if let Some(project) = &source.project {
        details.push(("project".to_string(), project.clone()));
    }
    if let Some(profile) = &source.profile {
        details.push(("profile".to_string(), profile.clone()));
    }
    if let Some(configuration) = &source.gcloud {
        details.push(("configuration".to_string(), configuration.clone()));
    }
    if source.s3.virtual_hosted.is_some() {
        let style = if source.s3.virtual_hosted_style() {
            "virtual-hosted"
        } else {
            "path-style"
        };
        details.push(("addressing".to_string(), style.to_string()));
    }
    details.push(("login".to_string(), source.origin.clone()));

    let short = source.problem.as_deref().map(|problem| {
        if problem.starts_with("not signed in") {
            "not signed in"
        } else if problem.starts_with("unsupported login") {
            "unsupported login"
        } else {
            "not configured"
        }
    });
    // A source that cannot list says what to do where the row has room; the count
    // carries the short problem.
    let note = match (&source.problem, short) {
        (Some(problem), Some(short)) => problem
            .strip_prefix(short)
            .map(|rest| rest.trim_start_matches([':', ' ']))
            .filter(|rest| !rest.is_empty())
            .unwrap_or(problem)
            .to_string(),
        _ => [source.detail(), Some(source.origin.clone())]
            .into_iter()
            .flatten()
            .filter(|n| !n.is_empty())
            .collect::<Vec<_>>()
            .join(&format!(" {} ", crate::glyphs::get().middot)),
    };
    let mut names: Vec<String> = cached.map(|c| c.buckets.clone()).unwrap_or_default();
    for bucket in &source.buckets {
        if !names.contains(bucket) {
            names.push(bucket.clone());
        }
    }
    let status = match (&source.problem, short) {
        (Some(problem), Some(short)) => home::CloudStatus::Failed {
            short: short.to_string(),
            detail: problem.clone(),
        },
        _ if cached.is_some() => home::CloudStatus::Listed,
        _ if listing => home::CloudStatus::Listing,
        _ => home::CloudStatus::Unlisted,
    };
    home::CloudSource {
        id: source.id.clone(),
        label: source.label.clone(),
        api: source.kind,
        note,
        buckets: names
            .iter()
            .map(|b| PathBuf::from(source.bucket_url(b)))
            .collect(),
        refreshing: listing && cached.is_some() && source.problem.is_none(),
        // A source that failed before any request has nothing to ask.
        asked: listing || source.problem.is_some(),
        listed_at: cached
            .map(|c| std::time::UNIX_EPOCH + std::time::Duration::from_secs(c.listed_at)),
        status,
        details,
        place_details: Default::default(),
    }
}

/// A listing error as a word for the row and the full message for the details pane.
#[cfg(feature = "cloud")]
fn summarize_cloud_failure(error: &str) -> (String, String) {
    let lower = error.to_lowercase();
    // A missing tool is already as short as it gets: `needs the AWS CLI`.
    if let Some(start) = lower.find("needs ") {
        return (error[start..].to_string(), error.to_string());
    }
    let short = if lower.contains("403")
        || lower.contains("forbidden")
        || lower.contains("accessdenied")
        || lower.contains("access denied")
    {
        "403"
    } else if lower.contains("401")
        || lower.contains("unauthorized")
        || lower.contains("credential")
        || lower.contains("invalidaccesskeyid")
        || lower.contains("expired")
        || lower.contains("sso")
        || lower.contains("az login")
    {
        "not logged in"
    } else if lower.contains("unsupported login") {
        "unsupported login"
    } else if lower.contains("no gcp project") {
        "no project"
    } else if lower.contains("is not set") {
        "not configured"
    } else if lower.contains("timed out")
        || lower.contains("timeout")
        || lower.contains("connection")
        || lower.contains("dns")
        || lower.contains("resolve")
    {
        "unavailable"
    } else {
        "error"
    };
    (short.to_string(), error.to_string())
}

impl App {
    /// Schema for a home entry, from Parquet metadata, memoized for the session. `None`
    /// means not knowable without a scan, and the UI says so.
    pub fn home_schema(&mut self, entry: &discover::Entry) -> Option<discover::SchemaPreview> {
        // Previews read local files only: nothing in an object store is read before it is
        // opened.
        if home::is_cloud_place(&entry.path) || home::is_object_store_url(&entry.path) {
            return None;
        }
        if let Some(cached) = self.home_app.schema_cache.get(&entry.path) {
            return cached.clone();
        }
        // Opening a file, so requested from a worker; the frame never waits.
        self.request_home_schema(entry.clone());
        None
    }

    /// What a home-screen worker owes in place of its answer if it panics.
    fn owed_answer(&mut self, instead: AppEvent) -> OwedAnswer {
        OwedAnswer {
            tx: self.events.clone(),
            #[cfg(test)]
            dies: self
                .home_app
                .worker_dies
                .as_mut()
                .is_some_and(|dies| dies(&instead)),
            instead: Some(instead),
        }
    }

    /// List the directory the `~` prompt is typing, if not already listed: a URL from
    /// what the screen knows, a local directory on a worker.
    pub(crate) fn list_the_typed_directory(&mut self) {
        if !self.home.path_input_active {
            return;
        }
        let dir = home::typed_dir(&self.home.path_input).to_string();
        if self
            .home
            .path_listing
            .as_ref()
            .is_some_and(|l| l.dir == dir)
        {
            return;
        }
        if home::typed_dir_is_url(&dir) {
            self.home.path_listing = Some(home::names_under(&dir, self.home.known_urls()));
            return;
        }
        // Off the UI thread: a typed path may name a dead mount.
        let tx = self.events.clone();
        let owed = self.owed_answer(AppEvent::HomePathListed {
            listing: Box::new(home::PathListing {
                dir: dir.clone(),
                names: Vec::new(),
                failed: true,
            }),
        });
        std::thread::spawn(move || {
            owed.run(|| {
                let listing = home::list_typed_dir(&dir);
                let _ = tx.send(AppEvent::HomePathListed {
                    listing: Box::new(listing),
                });
            })
        });
    }

    /// Complete the path being typed, on a worker.
    pub(crate) fn request_path_completion(&mut self) {
        let typed = self.home.path_input.clone();
        if typed.is_empty() {
            return;
        }
        let generation = self.home_app.generation;
        let tx = self.events.clone();
        std::thread::spawn(move || {
            let (completed, candidates) = home::complete_path(&typed);
            let _ = tx.send(AppEvent::HomePathCompleted {
                generation,
                typed,
                completed,
                candidates,
            });
        });
    }

    /// A home file's first rows for its `ROWS` preview, read on a worker as its open
    /// reads them. `None` until they land or when not previewed. `screen_height` sizes
    /// the page to the table's.
    pub fn home_preview_rows(
        &mut self,
        entry: &discover::Entry,
        screen_height: u16,
    ) -> Option<Arc<crate::home::home_preview::PreviewRows>> {
        let max = self.app_config.home.preview_max.bytes();
        if !crate::home::home_preview::previewable(entry, max) {
            return None;
        }
        let stamp = crate::home::home_preview::Stamp::of_entry(entry);
        if let Some(known) = self.home_app.previews.rows(&entry.path, stamp) {
            return known;
        }
        if self.home_app.previews.inflight.is_none() {
            self.request_home_preview(entry.path.clone(), stamp, screen_height);
        }
        None
    }

    /// Whether `entry` is one the preview reads, before its rows are in.
    pub fn home_preview_pending(&self, path: &Path) -> bool {
        self.home_app.previews.reading(path)
    }

    /// Read a file's first page on a worker through the open's own scan and schema read,
    /// so the open can install the result.
    fn request_home_preview(
        &mut self,
        path: PathBuf,
        stamp: crate::home::home_preview::Stamp,
        screen_height: u16,
    ) {
        self.home_app.previews.inflight = Some(path.clone());
        self.home_app.reads.previews += 1;
        let tx = self.events.clone();
        let cloud = self.app_config.cloud.clone();
        let formats = self.formats.clone();
        let runtime = self.runtime.clone();
        let cache = self.cache.clone();
        let writes = self.cache_writes.clone();
        // The table's rows: the screen less the title, the header and the footer.
        let visible = (screen_height as usize).saturating_sub(3).max(1);
        let owed = self.owed_answer(AppEvent::HomePreviewReady {
            path: path.clone(),
            stamp,
            read_at: None,
            rows: None,
            prepared: crate::home::home_preview::Handoff::default(),
        });
        self.runtime.spawn_blocking(move || {
            owed.run(|| {
                let began = std::time::Instant::now();
                let read_at = crate::home::home_preview::Stamp::of_file(&path);
                let read = Self::read_home_preview(
                    &path, &cloud, &formats, &runtime, cache, writes, visible,
                );
                log::debug!(
                    target: "datui",
                    "home preview of {}: {:.1?}",
                    path.display(),
                    began.elapsed()
                );
                let (rows, prepared) = match read {
                    Some((rows, prepared)) => (Some(Arc::new(rows)), Some(Box::new(prepared))),
                    None => (None, None),
                };
                let _ = tx.send(AppEvent::HomePreviewReady {
                    path,
                    stamp,
                    read_at,
                    rows,
                    prepared: Arc::new(Mutex::new(prepared)),
                });
            })
        });
    }

    /// What opening `path` from home reads first: scan, schema and the page for
    /// `visible` rows, built by the open's own steps and options so the dataset is the
    /// one the open would build.
    fn read_home_preview(
        path: &Path,
        cloud: &crate::config::CloudConfig,
        formats: &crate::formats::Registry,
        runtime: &tokio::runtime::Handle,
        cache: CacheManager,
        writes: CacheWrites,
        visible: usize,
    ) -> Option<(
        crate::home::home_preview::PreviewRows,
        crate::home::home_preview::Prepared,
    )> {
        let paths = [path.to_path_buf()];
        let scanned = Self::scan_for_open(
            cloud,
            formats,
            &paths,
            OpenOptions::default(),
            Some(path.to_path_buf()),
        )
        .ok()?;
        let loading::LoadAnswer::Scanned { lf, path, options } = scanned else {
            return None;
        };
        let progress = Arc::<crate::formats::schema_union::FooterProgress>::default();
        let report = crate::loading::measurements::OpenReport {
            progress: progress.clone(),
            meter: Arc::new(crate::loading::measurements::Meter::default()),
            remembered: Some(cache),
            writes,
        };
        let read = Self::read_schema_for_open(
            *lf,
            path,
            options,
            cloud,
            runtime,
            &report,
            loading::Made::default(),
        )
        .ok()?;
        let loading::LoadAnswer::SchemaRead {
            mut state,
            options,
            debug_label,
            ..
        } = read
        else {
            return None;
        };
        // Planned as the table plans its first page, so the page is the one it wants.
        state.visible_rows = visible;
        let began = std::time::Instant::now();
        let request = state.prepare_async_collect(None)?;
        let df =
            crate::analysis::statistics::collect_lazy(request.lf, request.polars_streaming).ok()?;
        let result = request.plan.fit(df);
        let rows = crate::home::home_preview::PreviewRows::from_frame(result.rows());
        state.measurements().read_page(began.elapsed(), Some(1));
        state.apply_async_collect(result);
        Some((
            rows,
            crate::home::home_preview::Prepared {
                state,
                options,
                debug_label,
                progress,
            },
        ))
    }

    /// Whether a schema read is currently out for this path.
    pub fn home_schema_pending(&self, path: &Path) -> bool {
        self.home_app.schema_inflight.iter().any(|p| p == path)
    }

    /// Read the selected dataset's schema on a worker.
    fn request_home_schema(&mut self, entry: discover::Entry) {
        if self.home_app.schema_inflight.contains(&entry.path) {
            return;
        }
        self.home_app.schema_inflight.push(entry.path.clone());

        let generation = self.home_app.generation;
        let tx = self.events.clone();
        // Remembered as none on failure, so it is not asked again.
        let owed = self.owed_answer(AppEvent::HomeSchemaReady {
            generation,
            path: entry.path.clone(),
            preview: None,
        });
        self.runtime.spawn_blocking(move || {
            owed.run(|| {
                let preview = discover::schema_preview(&entry);
                let _ = tx.send(AppEvent::HomeSchemaReady {
                    generation,
                    path: entry.path,
                    preview,
                });
            })
        });
    }

    /// Start listing network roots that have not answered yet. Never waits: a gone
    /// share (a `hard` NFS mount) blocks its thread uninterruptibly, so the task is
    /// abandoned, not joined.
    pub(crate) fn spawn_home_probes(&mut self) {
        self.stop_listings_left_behind();
        for root in self.home.pending_probes() {
            if self.home_app.probes_inflight.contains(&root) {
                // Left and returned to before its next page: it goes on.
                if let Some(cancelled) = self.home_app.listing_cancels.get(&root) {
                    cancelled.store(false, std::sync::atomic::Ordering::Relaxed);
                }
                continue;
            }
            // Each probe of an unreachable share costs a thread forever, so they are capped.
            // The browsed directory is exempt: it is the whole screen, and the user bounds how
            // many they open.
            let browsed = self.home.browsing.as_ref() == Some(&root);
            if !browsed && self.home_app.probes_inflight.len() >= MAX_CONCURRENT_PROBES {
                continue;
            }
            self.home_app.probes_inflight.push(root.clone());
            let tx = self.events.clone();
            let cache = self.cache.clone();
            let owed = self.owed_answer(AppEvent::HomeProbeFailed {
                root: root.clone(),
                message: "Could not read it; see the log".to_string(),
            });
            #[cfg(feature = "cloud")]
            let cloud = self.app_config.cloud.clone();
            #[cfg(feature = "cloud")]
            let runtime = self.runtime.clone();
            #[cfg(feature = "cloud")]
            let cancelled = {
                let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
                self.home_app
                    .listing_cancels
                    .insert(root.clone(), flag.clone());
                flag
            };
            // A detached thread, not the runtime's blocking pool: a thread wedged on a dead
            // mount never returns, and must not eat the pool that loads data.
            std::thread::spawn(move || {
                owed.run(|| {
                    // A bucket or prefix: listed with an object-store listing, not `read_dir` (which
                    // fails on `gs://`). Metadata only: names, sizes and times for one level; no
                    // footers, schemas or counts, which would cost a paid ranged read per row.
                    #[cfg(feature = "cloud")]
                    if let Some((id, account)) = home::cloud_account(&root) {
                        let listed = wait_on_runtime(&runtime, async move {
                            crate::cloud::cloud_browse::list_account(&id, &account, &cloud).await
                        });
                        match listed {
                            Some(Ok(rows)) => {
                                let _ = tx.send(AppEvent::HomeProbeReady {
                                    root,
                                    rows: Some(rows),
                                    cut_short: false,
                                });
                            }
                            Some(Err(message)) => {
                                log::warn!(
                                    target: "datui::cloud",
                                    "listing {} failed: {message}",
                                    root.display()
                                );
                                let _ = tx.send(AppEvent::HomeProbeFailed { root, message });
                            }
                            None => {
                                let _ = tx.send(AppEvent::HomeProbeReady {
                                    root,
                                    rows: None,
                                    cut_short: false,
                                });
                            }
                        }
                        return;
                    }
                    #[cfg(feature = "cloud")]
                    if crate::cloud::cloud_browse::split_bucket_url(&root.to_string_lossy())
                        .is_some()
                        || source::azure_parts(&root.to_string_lossy()).is_some()
                    {
                        let url = root.to_string_lossy().into_owned();
                        // Each page's rows are drawn as they come; leaving the place stops the listing.
                        let watch = crate::cloud::cloud_browse::Watch {
                            progress: Some(std::sync::Arc::new({
                                let (tx, root) = (tx.clone(), root.clone());
                                move |page: &[crate::home::discover::Entry]| {
                                    let _ = tx.send(AppEvent::HomeProbeProgress {
                                        root: root.clone(),
                                        rows: page.to_vec(),
                                    });
                                }
                            })),
                            cancelled,
                            names_from: None,
                        };
                        let listed = wait_on_runtime(&runtime, async move {
                            crate::cloud::cloud_browse::list_objects_watched(&url, &cloud, &watch)
                                .await
                        });
                        // A refused listing says why, rather than reading as a place that stopped
                        // answering.
                        match listed {
                            Some(Err(message)) => {
                                log::warn!(
                                    target: "datui::cloud",
                                    "listing {} failed: {message}",
                                    root.display()
                                );
                                let _ = tx.send(AppEvent::HomeProbeFailed { root, message });
                            }
                            Some(Ok(level)) if level.cancelled => {
                                let _ = tx.send(AppEvent::HomeProbeCancelled { root });
                            }
                            other => {
                                let (rows, cut_short) = match other {
                                    Some(Ok(level)) => (Some(level.rows), level.truncated),
                                    _ => (None, false),
                                };
                                let _ = tx.send(AppEvent::HomeProbeReady {
                                    root,
                                    rows,
                                    cut_short,
                                });
                            }
                        }
                        return;
                    }
                    // No cloud feature: `read_dir` on a bucket URL would only say unavailable.
                    #[cfg(not(feature = "cloud"))]
                    if source::is_remote_url(&root) {
                        let message = "cloud support not in this build".to_string();
                        let _ = tx.send(AppEvent::HomeProbeFailed { root, message });
                        return;
                    }
                    let mut cut_short = false;
                    let rows = if std::fs::read_dir(&root).is_ok() {
                        // What has been read shows while the rest is read (seconds for thousands of files).
                        let scan = crate::home::discover::scan_dir_progressive(&root, |read| {
                            let _ = tx.send(AppEvent::HomeProbeProgress {
                                root: root.clone(),
                                rows: read.to_vec(),
                            });
                        });
                        cut_short = scan.truncated;
                        let mut rows = scan.entries;
                        // Measured here too: this thread is already the one allowed to block on the share.
                        for row in rows.iter_mut().take(PROBE_MEASURE_LIMIT) {
                            crate::home::discover::enrich(row);
                        }
                        // Remote datasets are measured nowhere else, so remember them here; otherwise a
                        // remote row is blank on every run.
                        let mounts = crate::home::locality::Mounts::current();
                        for row in rows.iter_mut() {
                            row.cost.source = Some(mounts.describe(&row.path).fstype);
                        }
                        let facts: Vec<_> = rows.iter().filter_map(home::facts_for).collect();
                        cache.record_dataset_facts(&facts);
                        Some(rows)
                    } else {
                        None
                    };
                    let _ = tx.send(AppEvent::HomeProbeReady {
                        root,
                        rows,
                        cut_short,
                    });
                })
            });
        }
    }

    /// Stop cloud listings of places no longer on screen (the browsed one, or home's
    /// roots). A place left and revisited is listed again.
    fn stop_listings_left_behind(&mut self) {
        let home = &self.home;
        for (root, cancelled) in &self.home_app.listing_cancels {
            let wanted = match &home.browsing {
                Some(dir) => dir == root,
                None => home
                    .sections
                    .iter()
                    .any(|s| s.remote_root.as_ref() == Some(root)),
            };
            if !wanted {
                cancelled.store(true, std::sync::atomic::Ordering::Relaxed);
            }
        }
        if let Some((dir, _, cancelled)) = &self.home_app.narrowing
            && home.browsing.as_ref() != Some(dir)
        {
            cancelled.store(true, std::sync::atomic::Ordering::Relaxed);
            self.home_app.narrowing = None;
        }
        if self
            .home
            .narrowed
            .as_ref()
            .is_some_and(|n| self.home.browsing.as_ref() != Some(&n.dir))
        {
            self.home.narrowed = None;
        }
    }

    /// In a cloud directory cut short at the cap, ask the server for names starting with
    /// the filter, so names past the cap can be found. Nothing when the filter is empty
    /// or what is held answers it.
    #[cfg(feature = "cloud")]
    pub(crate) fn narrow_cloud_listing(&mut self) {
        let dir = self.home.browsing.clone();
        let prefix = dir.as_ref().and_then(|dir| {
            if !self.home.probes.cut_short(dir) {
                return None;
            }
            let rows = self.home.probes.listed(dir)?;
            let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();
            crate::cloud::cloud_browse::narrowing_prefix(&self.home.filter, &names)
        });
        let (Some(dir), Some(prefix)) = (dir, prefix) else {
            if let Some((_, _, cancelled)) = self.home_app.narrowing.take() {
                cancelled.store(true, std::sync::atomic::Ordering::Relaxed);
            }
            if self.home.narrowed.take().is_some() {
                self.home_refresh();
            }
            return;
        };
        // Everything under a shorter prefix is everything under this one too.
        if self.home.narrowed.as_ref().is_some_and(|n| {
            n.dir == dir && (n.prefix == prefix || (!n.truncated && prefix.starts_with(&n.prefix)))
        }) {
            return;
        }
        if let Some((d, p, _)) = &self.home_app.narrowing
            && *d == dir
            && *p == prefix
        {
            return;
        }
        if let Some((_, _, cancelled)) = self.home_app.narrowing.take() {
            cancelled.store(true, std::sync::atomic::Ordering::Relaxed);
        }
        let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
        self.home_app.narrowing = Some((dir.clone(), prefix.clone(), cancelled.clone()));
        let tx = self.events.clone();
        let owed = self.owed_answer(AppEvent::HomeNarrowed {
            dir: dir.clone(),
            prefix: prefix.clone(),
            listed: None,
        });
        let cloud = self.app_config.cloud.clone();
        let runtime = self.runtime.clone();
        std::thread::spawn(move || {
            owed.run(|| {
                let url = dir.to_string_lossy().into_owned();
                let watch = crate::cloud::cloud_browse::Watch {
                    progress: None,
                    cancelled,
                    names_from: Some(prefix.clone()),
                };
                let listed = wait_on_runtime(&runtime, async move {
                    crate::cloud::cloud_browse::list_objects_watched(&url, &cloud, &watch).await
                });
                let listed = match listed {
                    Some(Ok(level)) if !level.cancelled => Some((level.rows, level.truncated)),
                    _ => None,
                };
                let _ = tx.send(AppEvent::HomeNarrowed {
                    dir,
                    prefix,
                    listed,
                });
            })
        });
    }

    /// Find the cloud sources this machine and the config describe, and list their
    /// buckets when `[cloud] list_on_start` asks. Once per session; Ctrl+R asks again.
    #[cfg(feature = "cloud")]
    fn spawn_cloud_discovery(&mut self) {
        if self.home_app.cloud_discovery_started {
            return;
        }
        self.home_app.cloud_discovery_started = true;
        let list = self.app_config.cloud.list_on_start;
        self.list_cloud_sources(None, list);
    }

    /// List the browsed source if not asked this session; entering a source asks.
    #[cfg(feature = "cloud")]
    fn list_browsed_cloud_source(&mut self) {
        let Some(id) = self
            .home
            .browsing
            .as_deref()
            .and_then(home::cloud_source_id)
        else {
            return;
        };
        let Some(source) = self.home.cloud.iter_mut().find(|s| s.id == id) else {
            return;
        };
        if source.asked {
            return;
        }
        source.begin_listing();
        self.list_cloud_sources(Some(id), true);
    }

    /// Send every source's rows, or list the named one's buckets. Rows go first, filled
    /// from the last run's listing when still valid. With `list`, sources are listed a
    /// few at a time and each result sent on arrival; without, nothing leaves the
    /// machine. On the runtime, not a detached thread: every call has a global timeout.
    #[cfg(feature = "cloud")]
    fn list_cloud_sources(&mut self, only: Option<String>, list: bool) {
        let tx = self.events.clone();
        let cloud = self.app_config.cloud.clone();
        let cache = self.cache.clone();
        self.runtime.spawn(async move {
            let mut hidden = cache.load_hidden_cloud_sources();
            hidden.extend(cloud.hide.iter().cloned());
            let cached_for = |source: &crate::cloud::cloud_sources::Source| {
                cache.cloud_listing(&source.id, &source.fingerprint())
            };
            // Looked for again, and kept for the opens and listings that follow.
            let found = crate::cloud::cloud_sources::rediscover(&cloud).to_vec();
            // A bucket under Recent opens with the login that listed it, shown or not, unless
            // its source is hidden (perhaps for a dead login; the default opens it then).
            // Only with the rows, so an old listing never overrides a newer one.
            if only.is_none() {
                for source in found.iter().filter(|s| !hidden.contains(&s.id)) {
                    if let Some(cached) = cached_for(source) {
                        crate::cloud::cloud_sources::remember_listed(source, &cached.buckets);
                    }
                }
            }
            let sources: Vec<crate::cloud::cloud_sources::Source> =
                crate::cloud::cloud_sources::on_home(found, &cloud)
                    .into_iter()
                    .filter(|s| !hidden.contains(&s.id))
                    .collect();

            match &only {
                None => {
                    let rows = sources
                        .iter()
                        .map(|source| home_cloud_source(source, cached_for(source).as_ref(), list))
                        .collect();
                    let _ = tx.send(AppEvent::HomeCloudSources { sources: rows });
                }
                // Gone since its row was drawn (a profile removed, a source hidden): said, so the
                // row does not wait forever.
                Some(id) if !sources.iter().any(|s| &s.id == id) => {
                    let _ = tx.send(AppEvent::HomeCloudListed {
                        id: id.clone(),
                        buckets: Vec::new(),
                        details: Vec::new(),
                        failure: Some((
                            "not found".to_string(),
                            format!("{id} is gone or hidden. Ctrl+R at the top looks again."),
                        )),
                        listed_at: std::time::SystemTime::now(),
                    });
                    return;
                }
                Some(_) => {}
            }
            if !list {
                return;
            }

            // One slow endpoint does not delay the rest, and many sources do not storm.
            const LISTING_AT_ONCE: usize = 4;
            let permits = std::sync::Arc::new(tokio::sync::Semaphore::new(LISTING_AT_ONCE));
            let mut listings = tokio::task::JoinSet::new();
            for source in sources
                .into_iter()
                .filter(|s| only.as_ref().is_none_or(|id| &s.id == id))
            {
                let permits = permits.clone();
                listings.spawn(async move {
                    let _permit = permits.acquire_owned().await;
                    let result = crate::cloud::cloud_browse::list_first_level(&source).await;
                    (source, result)
                });
            }
            while let Some(joined) = listings.join_next().await {
                let Ok((source, result)) = joined else {
                    continue;
                };
                let listed_at = std::time::SystemTime::now();
                // Buckets named in the config show whether or not the login can list them.
                let mut names = source.buckets.clone();
                let mut details = Vec::new();
                let failure = match result {
                    Ok(listed) => {
                        for item in listed {
                            crate::cloud::cloud_sources::remember_bucket(&source, &item.name);
                            if !item.details.is_empty() {
                                details.push((item.place.clone(), item.details));
                            }
                            let name = item.name;
                            if !names.contains(&name) {
                                names.push(name);
                            }
                        }
                        cache.save_cloud_listing(
                            &source.id,
                            crate::cache::CloudListing {
                                fingerprint: source.fingerprint(),
                                buckets: names.clone(),
                                listed_at: listed_at
                                    .duration_since(std::time::UNIX_EPOCH)
                                    .map(|d| d.as_secs())
                                    .unwrap_or(0),
                            },
                        );
                        None
                    }
                    Err(e) => {
                        log::warn!(target: "datui::cloud", "listing {} failed: {e}", source.id);
                        Some(summarize_cloud_failure(&e))
                    }
                };
                let _ = tx.send(AppEvent::HomeCloudListed {
                    id: source.id.clone(),
                    buckets: names
                        .iter()
                        .map(|b| PathBuf::from(source.bucket_url(b)))
                        .collect(),
                    details,
                    failure,
                    listed_at,
                });
            }
        });
    }

    /// Ask again for what is on screen, bypassing the cache: the browsed source's
    /// buckets, the browsed bucket or directory, or every source's buckets.
    pub(crate) fn home_reload(&mut self) {
        #[cfg(feature = "cloud")]
        {
            let browsing = self.home.browsing.clone();
            match browsing.as_deref().and_then(home::cloud_source_id) {
                Some(id) => {
                    if let Some(source) = self.home.cloud.iter_mut().find(|s| s.id == id) {
                        source.begin_listing();
                    }
                    self.list_cloud_sources(Some(id), true);
                }
                None if browsing.is_none() && !self.home.cloud.is_empty() => {
                    for source in &mut self.home.cloud {
                        source.begin_listing();
                    }
                    self.list_cloud_sources(None, true);
                }
                None => {}
            }
        }
        if let Some(dir) = self.home.browsing.clone() {
            // Its answer, not a listing still coming in.
            if self.home.probes.settled(&dir) {
                self.home.probes.forget(&dir);
            }
        }
        // Ctrl+R retries failed peeks and missing web files too.
        self.home.peek_failed.clear();
        for path in std::mem::take(&mut self.home.web_gone).into_keys() {
            self.home.sized.remove(&path);
        }
        self.home.status = None;
        self.home_refresh();
    }

    /// Start the recursive search below the working directory, if wanted and not
    /// running. Triggered by typing, not by opening home, so opening a recent costs no
    /// walk.
    pub(crate) fn spawn_home_search(&mut self) {
        if self.home_app.search_inflight || self.home.search.done {
            return;
        }
        let config = self.app_config.home.search.clone();
        if !config.enabled {
            return;
        }
        let Some(root) =
            crate::home::search::search_root(self.home.browsing.as_ref(), self.home.network_check)
        else {
            return;
        };

        self.home.search.reset();
        self.home.search.root = Some(root.clone());
        self.home.search.running = true;
        self.home.search.epoch = next_search_epoch();
        self.home.search_limit = config.max_results;
        self.home_app.search_inflight = true;

        let generation = self.home_app.generation;
        self.home_app.search_generation = generation;
        let tx = self.events.clone();
        let formats = self.formats.clone();
        // Ended, with what the batches already found kept.
        let owed = self.owed_answer(AppEvent::HomeSearchDone {
            generation,
            root: root.clone(),
            scanned: 0,
            limited: Some(crate::glyphs::dotted("partial · failed")),
        });
        // A detached thread, as for probes: a filesystem stall must not stop drawing.
        std::thread::spawn(move || {
            owed.run(|| {
                let walk_root = root.clone();
                let batch_tx = tx.clone();
                let batch_gen = generation;
                let batch_root = root.clone();
                let outcome = crate::home::search::walk_with_specs(
                    &walk_root,
                    &config,
                    &formats,
                    move |found, outcome| {
                        // Sent even when empty: it carries progress, and a failed send tells the walk
                        // nobody listens.
                        batch_tx
                            .send(AppEvent::HomeSearchBatch {
                                generation: batch_gen,
                                root: batch_root.clone(),
                                found,
                                scanned: outcome.scanned,
                            })
                            // A closed channel means the app is gone; stop walking.
                            .is_ok()
                    },
                );
                let _ = tx.send(AppEvent::HomeSearchDone {
                    generation,
                    root,
                    scanned: outcome.scanned,
                    limited: outcome.note().map(crate::glyphs::dotted),
                });
            })
        });
    }

    /// Score the filter against the search's files on a worker, when owed. Asked after
    /// every event; over tens of thousands of files scoring held back keystroke echo.
    /// One at a time; each answer asks for the next if the filter moved.
    pub(crate) fn home_score_search(&mut self) {
        if self.input_mode != InputMode::Home {
            return;
        }
        let Some(job) = self.home.score_job() else {
            return;
        };
        let epoch = job.epoch;
        let tx = self.events.clone();
        // A worker that dies answers with nothing.
        let owed = self.owed_answer(AppEvent::HomeSearchScored {
            epoch,
            matches: None,
        });
        self.runtime.spawn_blocking(move || {
            owed.run(move || {
                let matches = crate::home::search::score(
                    &job.results,
                    &job.query,
                    job.base.as_ref(),
                    job.limit,
                );
                let _ = tx.send(AppEvent::HomeSearchScored {
                    epoch,
                    matches: Some(Box::new(matches)),
                });
            })
        });
    }

    /// Rebuild the home listing from the filesystem.
    pub(crate) fn home_refresh(&mut self) {
        self.home_app.refresh_owed = false;
        // Every way into a source comes through here: Enter, Backspace up from a bucket,
        // a jump, and rows arriving while it is open.
        #[cfg(feature = "cloud")]
        self.list_browsed_cloud_source();
        // Listings of where the user was are pages for nobody.
        self.stop_listings_left_behind();
        self.home_app.generation = self.home_app.generation.wrapping_add(1);
        let generation = self.home_app.generation;

        self.move_remembered_places();
        let mut catalogs = home::catalogs(&self.app_config);
        // Hidden with Delete on its heading: only the bundled catalog, never a user's
        // `examples.toml`.
        if self.cache.examples_hidden() {
            catalogs.retain(|c| c.origin != crate::home::catalog::Origin::Bundled);
        }
        self.home.set_catalogs(catalogs);
        let mut request = home::ListingRequest {
            // Filled on the worker from the cache and the desktop's recents, so the first frame
            // waits on no file.
            recents: Vec::new(),
            desktop_dirs: Vec::new(),
            browsing: self.home.browsing.clone(),
            probes: self.home.probes.clone(),
            narrowed: self.home.narrowed.clone(),
            network_check: self.home.network_check,
            cloud: self.home.cloud.clone(),
            catalogs: self.home.catalogs.clone(),
            known: Default::default(),
            formats: self.formats.clone(),
        };
        let read_folds = std::mem::take(&mut self.home.folds_owed);
        let desktop = self.app_config.home.desktop_recents;
        let cache = self.cache.clone();
        let writes = self.cache_writes.clone();

        self.home.listing_in_flight = true;
        let tx = self.events.clone();
        let owed = self.owed_answer(AppEvent::HomeListingFailed);
        self.runtime.spawn_blocking(move || {
            owed.run(move || {
                // After the dataset just left is in the recents with its shape.
                writes.settle();
                // Ranked by frecency; the cursor lands on the newest, one Enter from the last file.
                let (recents, visits) = cache.load_recents_with_visits();
                let newest = recents.first().cloned();
                request.recents = crate::cache::by_frecency(recents, &visits);
                request.known = cache.load_dataset_facts();
                if desktop {
                    request.desktop_dirs = home::desktop_recent_dirs();
                }
                let listing = home::build_listing(&request);
                let mut visits = visits;
                listing.alias_visits(&mut visits);
                // A record shown is a record used: the ones eviction keeps.
                let shown: Vec<PathBuf> = listing
                    .sections
                    .iter()
                    .flat_map(|s| s.rows.iter().chain(&s.door))
                    .flat_map(|row| [row.path.clone(), home::index_key(&row.path)])
                    .filter(|key| request.known.contains_key(key))
                    .collect();
                cache.touch_dataset_facts(shown.iter().map(PathBuf::as_path));
                let _ = tx.send(AppEvent::HomeListingReady {
                    generation,
                    listing: Box::new(listing),
                    known: request.known,
                    visits,
                    newest,
                    folds: read_folds.then(|| cache.load_folds()),
                });
            })
        });
    }

    /// Ask the worker to measure on-screen rows not yet known. Opening a footer can
    /// block (a FIFO, a device, a wedged mount, a failing disk), so never on the draw
    /// thread.
    pub(crate) fn request_home_measurements(&mut self) {
        if self.home.measure_in_flight {
            return;
        }
        let wanted = self.home.unmeasured_visible(MEASURE_BATCH);
        if wanted.is_empty() {
            return;
        }

        self.home.measure_in_flight = true;
        let tx = self.events.clone();
        let cache = self.cache.clone();
        self.runtime.spawn_blocking(move || {
            home::look_into_batch(wanted, &cache, |path, m| {
                let _ = tx.send(AppEvent::HomeMeasured {
                    measured: vec![(path, m)],
                    done: false,
                });
            });
            let _ = tx.send(AppEvent::HomeMeasured {
                measured: Vec::new(),
                done: true,
            });
        });
    }

    /// Ask an HTTP(S) server the size of the file under the cursor, once a session,
    /// when unmeasured. The row shows the catalog's `~33 MB` until then; the answer is
    /// kept for the next listing.
    #[cfg(feature = "http")]
    pub(crate) fn size_selected_web_file(&mut self) {
        if !self.info.head_web_rows {
            return;
        }
        let Some(entry) = self.home.selected_entry().cloned() else {
            return;
        };
        if entry.size.is_some()
            || !matches!(
                source::input_source(&entry.path),
                source::InputSource::Http(_)
            )
            || !self.home.sized.insert(entry.path.clone())
        {
            return;
        }
        let tx = self.events.clone();
        let cache = self.cache.clone();
        self.runtime.spawn_blocking(move || {
            let size = match Self::fetch_remote_size_http(&entry.path.to_string_lossy()) {
                Ok(Some(size)) => size,
                Ok(None) => return,
                Err(gone) => {
                    let _ = tx.send(AppEvent::HomeWebGone {
                        path: entry.path,
                        gone,
                    });
                    return;
                }
            };
            let key = home::index_key(&entry.path);
            let mut facts = cache.dataset_facts(&key).unwrap_or_default();
            facts.size = size;
            cache.record_dataset_facts(&[(key, facts)]);
            let measured = home::Measured {
                rows: entry.rows,
                cols: entry.cols,
                cols_sampled: entry.cols_sampled,
                size: Some(size),
                columns: entry.columns.clone(),
                cost: entry.cost.clone(),
                kind: None,
                holds: entry.holds.clone(),
            };
            let _ = tx.send(AppEvent::HomeSized {
                path: entry.path,
                measured,
            });
        });
    }

    /// Ask a worker what the rows on screen are. Classifying reads the named directory
    /// (a round trip on a share, forever on a wedged mount), so only on-screen rows,
    /// on a detached thread, one pass at a time. It also measures remote rows, which
    /// [`crate::home::HomeState::unmeasured_visible`] leaves alone since probes return them
    /// `Unknown`.
    pub(crate) fn request_home_classifications(&mut self) {
        if self.home.classify_in_flight {
            return;
        }
        let wanted = self.home.unclassified_visible(CLASSIFY_BATCH);
        if wanted.is_empty() {
            return;
        }

        self.home.classify_in_flight = true;
        let tx = self.events.clone();
        let cache = self.cache.clone();
        std::thread::spawn(move || {
            home::look_into_batch(wanted, &cache, |path, m| {
                let _ = tx.send(AppEvent::HomeClassified {
                    measured: vec![(path, m)],
                    done: false,
                });
            });
            let _ = tx.send(AppEvent::HomeClassified {
                measured: Vec::new(),
                done: true,
            });
        });
    }

    pub fn enter_home(&mut self) {
        self.counting.pause_indexing();
        if self.return_from_quality_evidence(false) {
            self.analysis_modal.close();
        }
        self.close_overlays();
        self.stop_find();
        // A count of the dataset being left is read for nobody.
        self.stop_value_count();
        self.export_modal.forget_counts();
        self.abandon_load();
        // Nobody is watching the file any more.
        if let Some(state) = self.data_table_state.as_mut() {
            state.stop_following();
        }
        self.home.status = None;
        // The search that found the dataset comes back selected: the next character starts
        // a new one, and `~` opens the path prompt.
        self.home.filter_selected = !self.home.filter.is_empty();
        self.home.folds_owed = true;
        self.home_refresh();
        if let Some(open_path) = self.path.clone() {
            let target =
                crate::canonical::canonicalize(&open_path).unwrap_or_else(|_| open_path.clone());
            if let Some(idx) = self.home.visible().iter().position(|row| match row {
                home::Row::Entry { entry, .. } => {
                    crate::canonical::canonicalize(&entry.path)
                        .unwrap_or_else(|_| entry.path.clone())
                        == target
                }
                // Not the door: its path is the directory's, and would take the cursor from the
                // file to the whole-directory row.
                home::Row::Header { .. }
                | home::Row::Place { .. }
                | home::Row::More { .. }
                | home::Row::Hidden { .. }
                | home::Row::Up { .. }
                | home::Row::Door { .. } => false,
            }) {
                self.home.selected = idx;
            }
        }
        self.input_mode = InputMode::Home;
    }

    /// Esc backs out one layer: the filter, the directory descended into, then back to
    /// the open data. Nothing at the top level; Ctrl+C quits.
    pub(crate) fn home_escape(&mut self) -> Option<AppEvent> {
        if !self.home.filter.is_empty() {
            self.home.filter.clear();
            self.home.sync_search_section();
            // On a dataset, as at launch, not on the first section's header.
            self.home.select_first_entry();
            return None;
        }
        if self.home.browsing.is_some() {
            if self.home.below_browse_start() {
                self.home_ascend();
            } else {
                // Not past where the browse began: back to the listing it started from.
                self.home_leave_browsing(None);
            }
            return None;
        }
        if self.data_table_state.is_some() {
            self.show_table();
            // Said on arrival: one Esc too many lands here, and the next keys act on the table.
            let name = self
                .path
                .as_deref()
                .and_then(|p| p.file_name())
                .map(|n| n.to_string_lossy().into_owned());
            if let Some(name) = name {
                self.flash_note(format!("Back to {name}"));
            }
        }
        None
    }

    /// Drop the highlighted dataset from the recents list. Only from Recent: elsewhere
    /// a row is a file on disk, and forgetting it would imply a deletion.
    pub(crate) fn home_forget_selected(&mut self) {
        // A catalog's heading: Delete hides the bundled one until the cache is cleared; a
        // user's catalog is hidden by id in the config.
        if let Some(catalog) = self.home.selected_catalog() {
            if catalog.origin == crate::home::catalog::Origin::Bundled {
                let message = format!(
                    "Hide {}? It comes back after datui cache clear.",
                    catalog.label
                );
                self.confirmation_modal
                    .show_destructive(message, "Hide", Confirm::HideExamples);
            } else {
                self.home.status = Some(format!(
                    "[home] hide = [\"{}\"] in config.toml hides it",
                    catalog.id
                ));
            }
            return;
        }
        // A place row stands for every recent under it, so forgetting them asks first, as
        // Shift+Delete does.
        if let Some(home::Row::Place { path, held, .. }) = self.home.selected_row() {
            let message = format!(
                "Forget {held} recently opened {} under {}?",
                if held == 1 { "dataset" } else { "datasets" },
                home::display_path(&path)
            );
            self.confirmation_modal
                .show(message, Confirm::ForgetPlace(path.clone()));
            return;
        }
        // A row in catalog.toml's own section is removed from the file, as Ctrl+D does; the
        // same place under Recent is only forgotten as a recent.
        let in_mine = self
            .home
            .selected_section()
            .and_then(|i| self.home.sections.get(i))
            .is_some_and(|s| s.origin == Some("catalog.toml"));
        if in_mine
            && let Some((location, _)) = self.home_row_for_catalog()
            && let Some((id, name)) = self.mine_entry_at(&location)
        {
            self.home_forget_from_catalog(&id, &name);
            return;
        }
        let section_title = self
            .home
            .selected_section()
            .and_then(|i| self.home.sections.get(i))
            .map(|s| s.title.clone())
            .unwrap_or_default();
        if self.home.browsing.is_none()
            && section_title == home::HomeState::CLOUD_SECTION
            && let Some(id) = self
                .home
                .selected_entry()
                .and_then(|e| home::cloud_source_id(&e.path))
        {
            self.cache.hide_cloud_source(&id);
            self.home.cloud.retain(|s| s.id != id);
            self.home_refresh();
            return;
        }
        let in_recents = section_title == "Recent";
        if !in_recents {
            self.home.status = Some("Only recents and catalog.toml rows can be forgotten".into());
            return;
        }
        let Some(entry) = self.home.selected_entry() else {
            return;
        };
        self.cache.forget_recent(&entry.path);
        // Nothing to say: the row going is the answer.
        self.home.status = None;
        self.home_refresh();
    }

    /// The location and shown name Ctrl+D adds for the highlighted row; a heading stands
    /// for its section's directory. Tables inside files, cloud sources and non-place
    /// rows have none.
    fn home_row_for_catalog(&self) -> Option<(PathBuf, String)> {
        match self.home.selected_row()? {
            home::Row::Place { path, .. } => {
                let name = home::display_path(&path);
                Some((path, name))
            }
            home::Row::Door { entry, .. } => {
                // A local door's trailing slash goes; a URL keeps its `//`, which `components`
                // would fold.
                let path: PathBuf = if matches!(
                    source::input_source(&entry.path),
                    source::InputSource::Local(_)
                ) {
                    entry.path.components().collect()
                } else {
                    entry.path.clone()
                };
                Some((path.clone(), home::display_path(&path)))
            }
            home::Row::Entry { entry, .. } => (entry.table.is_none()
                && !home::is_cloud_place(&entry.path)
                && crate::formats::members::split(&entry.path).is_none())
            .then(|| (entry.path.clone(), entry.name.clone())),
            home::Row::Header { section, .. } => {
                let root = self.home.sections.get(section)?.root.clone()?;
                let name = home::display_path(&root);
                Some((root, name))
            }
            home::Row::More { .. } | home::Row::Hidden { .. } | home::Row::Up { .. } => None,
        }
    }

    /// `catalog.toml`'s path: beside the config file read, else in the config directory.
    fn mine_catalog_file(&self) -> Option<PathBuf> {
        let dir = match &self.app_config.catalog_dir {
            Some(dir) => dir.clone(),
            None => config::ConfigManager::new(APP_NAME)
                .ok()?
                .config_dir()
                .to_path_buf(),
        };
        Some(dir.join(catalog::MINE_FILE))
    }

    /// The id and name of the `catalog.toml` entry at `location`, when there is one.
    fn mine_entry_at(&self, location: &Path) -> Option<(String, String)> {
        self.app_config
            .read_catalogs
            .iter()
            .find(|c| c.origin == catalog::Origin::Mine)?
            .dataset_at(location)
            .map(|d| (d.id.clone(), d.name.clone()))
    }

    /// Read the catalogs again after `catalog.toml` changed, and list again.
    fn reload_catalogs(&mut self) -> Result<(), String> {
        let dir = self
            .mine_catalog_file()
            .and_then(|f| f.parent().map(Path::to_path_buf));
        self.app_config
            .read_catalog_files(dir.as_deref())
            .map_err(|e| e.to_string())?;
        // The open dataset's notes and Documentation tab follow the file.
        self.info
            .follow_catalogs(&self.app_config, self.path.as_deref());
        self.open_info_documentation();
        self.home_refresh();
        Ok(())
    }

    /// What Ctrl+D writes for `location` named `name`: a copy of another catalog's
    /// entry, or the place as is.
    fn new_catalog_dataset(&self, location: &Path, name: &str) -> catalog::NewDataset {
        if let Some((_, shown)) = self.home.catalog_dataset(location) {
            let entry = &shown.entry;
            return catalog::NewDataset {
                name: entry.name.clone(),
                path: entry.local_path().map(|p| home::display_path(&p)),
                url: entry.url.clone(),
                auth: entry.auth.clone(),
                connection: entry.connection.clone(),
                description: entry.description.clone(),
                size: entry.size,
            };
        }
        let mut new = catalog::NewDataset {
            name: name.to_string(),
            ..Default::default()
        };
        if matches!(
            source::input_source(location),
            source::InputSource::Local(_)
        ) {
            let absolute = if location.is_relative() {
                std::env::current_dir()
                    .map(|cwd| cwd.join(location))
                    .unwrap_or_else(|_| location.to_path_buf())
            } else {
                location.to_path_buf()
            };
            new.path = Some(home::display_path(&absolute));
            return new;
        }
        // A store reached through a configured source: the source becomes the connection
        // and leaves the URL.
        let text = location.to_string_lossy();
        let (id, plain) = source::split_source_id(&text);
        new.url = Some(plain.into_owned());
        if let Some(id) = id {
            new.connection = Some(id.to_string());
        }
        new
    }

    /// Ctrl+D: add the row under the cursor to `catalog.toml`, or forget it from there.
    pub(crate) fn home_toggle_catalog(&mut self) {
        let Some((location, name)) = self.home_row_for_catalog() else {
            self.home.status = Some("Move to a dataset or directory to add it".into());
            return;
        };
        if let Some((id, name)) = self.mine_entry_at(&location) {
            self.home_forget_from_catalog(&id, &name);
            return;
        }
        let Some(file) = self.mine_catalog_file() else {
            self.home.status = Some("No config directory to keep catalog.toml in".into());
            return;
        };
        let new = self.new_catalog_dataset(&location, &name);
        // A source found on the machine but not configured cannot be named in a catalog:
        // the URL would be read elsewhere.
        if let Some(connection) = &new.connection
            && !self
                .app_config
                .cloud
                .connections
                .iter()
                .any(|c| c.name == *connection)
        {
            self.home.status = Some(format!(
                "Not added: {connection} is not a [[cloud.connections]] entry in the config"
            ));
            return;
        }
        if let Err(why) = new.check() {
            self.home.status = Some(format!("Not added: {why}"));
            return;
        }
        let label = self
            .app_config
            .read_catalogs
            .iter()
            .find(|c| c.origin == catalog::Origin::Mine)
            .map(|c| c.label.clone())
            .unwrap_or_else(|| catalog::MINE_LABEL.to_string());
        match catalog::add(&file, &new) {
            Ok(_) => match self.reload_catalogs() {
                Ok(()) => self.flash_note(format!("Added {} to {label}", new.name)),
                Err(e) => self.error_modal.show(e),
            },
            Err(e) => self.error_modal.show(e.to_string()),
        }
    }

    /// Remove the entry `id` from `catalog.toml`.
    fn home_forget_from_catalog(&mut self, id: &str, name: &str) {
        let Some(file) = self.mine_catalog_file() else {
            return;
        };
        match catalog::forget(&file, id) {
            Ok(()) => match self.reload_catalogs() {
                Ok(()) => self.flash_note(format!("Forgot {name}")),
                Err(e) => self.error_modal.show(e),
            },
            Err(e) => self.error_modal.show(e.to_string()),
        }
    }

    /// Move pre-0.4.0 Ctrl+D directories from the cache into `catalog.toml`, once.
    fn move_remembered_places(&mut self) {
        if std::mem::replace(&mut self.home_app.remembered_moved, true) {
            return;
        }
        let places = self.cache.load_remembered_places();
        if places.is_empty() {
            return;
        }
        let Some(file) = self.mine_catalog_file() else {
            return;
        };
        // The cache's list goes only once all are in catalog.toml; a failure retries next
        // run.
        match catalog::move_places(&file, &places) {
            Ok(_) => self.cache.clear_remembered_places(),
            Err(e) => {
                log::warn!(target: "datui", "moving remembered places into catalog.toml: {e:#}")
            }
        }
        let dir = file.parent().map(Path::to_path_buf);
        if let Err(e) = self.app_config.read_catalog_files(dir.as_deref()) {
            log::warn!(target: "datui", "reading catalog.toml: {e:#}");
        }
    }

    /// Ctrl+E: the Documentation view of the row under the cursor.
    pub(crate) fn home_open_documentation(&mut self) {
        let Some((path, doc)) = self.home_documented_row() else {
            self.home.status =
                Some("Ctrl+E shows what a catalog or a format spec says of a row".into());
            return;
        };
        let measured = self
            .home
            .selected_entry()
            .filter(|e| {
                e.path == path
                    && doc
                        .catalog
                        .as_ref()
                        .is_some_and(|(_, entry)| entry.location() == path)
            })
            .and_then(|e| e.size);
        self.info.documentation.open(doc, measured);
        self.info.documentation.links_open = self.home_app.local_desktop;
    }

    /// What Ctrl+E documents for the row under the cursor, with its path: the catalog
    /// dataset it is or is inside, and its format spec's docs, if any.
    pub(crate) fn home_documented_row(
        &self,
    ) -> Option<(PathBuf, widgets::documentation::Documented)> {
        let row = self.home.selected_row();
        let (path, file) = match &row {
            Some(home::Row::Entry { entry, .. }) | Some(home::Row::Door { entry, .. }) => {
                (Some(entry.path.clone()), Some(*entry))
            }
            Some(home::Row::Place { path, .. }) => (Some(path.clone()), None),
            Some(home::Row::Header { section, .. }) => (
                self.home
                    .sections
                    .get(*section)
                    .and_then(|s| s.root.clone()),
                None,
            ),
            _ => (None, None),
        };
        let path = path?;
        let catalog = home::catalog_entry_for(&self.home.catalogs, &path);
        let spec = file
            .filter(|e| e.kind == discover::EntryKind::File)
            .and_then(|e| e.format_spec.as_deref())
            .and_then(|name| self.home.formats.get(name))
            .and_then(|spec| spec.docs())
            .map(std::sync::Arc::new);
        // A record type's row (`day.ord/add`) documents its file.
        let name = file
            .map(|e| {
                let text = e.path.to_string_lossy();
                text.strip_suffix(e.name.as_str())
                    .filter(|_| e.table.is_some())
                    .map(|file| file.trim_end_matches(std::path::is_separator))
                    .and_then(|file| Path::new(file).file_name())
                    .map_or_else(|| e.name.clone(), |n| n.to_string_lossy().into_owned())
            })
            .unwrap_or_default();
        let doc = widgets::documentation::Documented::new(catalog, spec, name)?;
        Some((path, doc))
    }

    /// Whether Delete on the selected row hides a catalog: the bundled one's heading.
    pub(crate) fn home_hides_catalog(&self) -> bool {
        self.home
            .selected_catalog()
            .is_some_and(|c| c.origin == crate::home::catalog::Origin::Bundled)
    }

    /// What Ctrl+D does on the row under the cursor, as the footer names it: add to
    /// `catalog.toml` or forget from it; `None` where it cannot add.
    pub(crate) fn home_catalog_action(&self) -> Option<&'static str> {
        let (location, _) = self.home_row_for_catalog()?;
        Some(if self.mine_entry_at(&location).is_some() {
            "Forget"
        } else {
            "Add"
        })
    }

    /// Fold or unfold the section under the cursor; folding moves the cursor to its
    /// header.
    pub(crate) fn home_toggle_fold(&mut self) {
        if let Some(section) = self.home.selected_section() {
            self.home.toggle_collapsed(section);
            self.home.clamp_selection();
            self.cache.save_folds(&self.home.folds);
        }
    }

    pub(crate) fn home_collapse(&mut self, collapse: bool) {
        // The browsed listing is the whole screen: it never folds, and no fold is
        // remembered for its path (see `set_collapsed`).
        if self.home.browsing.is_some() {
            return;
        }
        let Some(section) = self.home.selected_section() else {
            return;
        };
        // → on a section's more row shows it whole; ← on a row its cut would hide cuts it
        // back. Elsewhere they fold.
        if collapse && self.home.cut_again(section) {
            return;
        }
        if !collapse && matches!(self.home.selected_row(), Some(home::Row::More { .. })) {
            self.home.show_all(section);
            return;
        }
        if collapse && !self.home.is_collapsed(section) {
            self.home.set_collapsed(section, true);
            if let Some(idx) = self
                .home
                .visible()
                .iter()
                .position(|row| row.section() == section)
            {
                self.home.selected = idx;
            }
        } else if !collapse {
            self.home.set_collapsed(section, false);
        }
        self.home.clamp_selection();
        self.cache.save_folds(&self.home.folds);
    }

    /// Step out of a directory that was descended into.
    pub(crate) fn home_ascend(&mut self) {
        let Some(current) = self.home.browsing.clone() else {
            return;
        };
        let parent = self.home.parent_of(&current);
        self.home_leave_browsing(parent);
    }

    /// Move the browse up to `to`, or back to the root listing when `None`.
    fn home_leave_browsing(&mut self, to: Option<PathBuf>) {
        // What the last place said of itself no longer applies.
        self.home.status = None;
        let from = std::mem::replace(&mut self.home.browsing, to);
        // Backspace can climb above the browse start; the start follows so Esc has a place
        // to stop.
        if !self.home.below_browse_start() {
            self.home.browse_start = self.home.browsing.clone();
        }
        // The filter, search and row left here come back; the cursor returns to that row
        // when the listing lands. A search of the old place no longer applies.
        self.home.come_back(from);
        self.home.sync_search_section();
        self.home.selected = 0;
        self.home_refresh();
        if !self.home.filter.is_empty() {
            self.spawn_home_search();
        }
    }

    /// Whether a peek's answer changes what a row draws: its kind, or anything in
    /// `holds` (`truncated` turns `dir` into `dir+`). Kept answers rebuild the listing
    /// on the UI thread, so the rest become "a directory, nothing to say", still sent
    /// to clear `peeking`.
    #[cfg(feature = "cloud")]
    pub(crate) fn peek_tells_a_row_something(
        answer: &(discover::EntryKind, discover::Holds),
    ) -> bool {
        answer.0 != discover::EntryKind::Directory || !answer.1.is_empty()
    }

    /// Peek inside cloud directories at or near the cursor so datasets show `hive` or
    /// `multi` and open as one: one small listing per directory, once a session, plus
    /// up to three few-KiB footer reads for a `multi` candidate. On-screen rows a batch
    /// at a time, the highlighted first.
    #[cfg(feature = "cloud")]
    pub(crate) fn peek_cloud_directories(&mut self) {
        const PEEKS_AT_ONCE: usize = 4;
        let directories = self.home.cloud_directories_to_peek(PEEKS_AT_ONCE);
        if directories.is_empty() {
            return;
        }
        // Marked out, not answered: a second pass must not ask again, and writing an
        // answer now would claim one before the request is made.
        for directory in &directories {
            self.home.peeking.insert(directory.clone());
        }
        let tx = self.events.clone();
        let cloud = self.app_config.cloud.clone();
        self.runtime.spawn(async move {
            let permits = Arc::new(tokio::sync::Semaphore::new(PEEKS_AT_ONCE));
            let mut peeks = tokio::task::JoinSet::new();
            // By task, so a panicking peek is sent back as failed rather than spinning
            // forever.
            let mut asked = std::collections::HashMap::new();
            for directory in directories {
                let (permits, cloud) = (permits.clone(), cloud.clone());
                let task_directory = directory.clone();
                let task = peeks.spawn(async move {
                    let directory = task_directory;
                    let _permit = permits.acquire_owned().await;
                    let kind =
                        crate::cloud::cloud_browse::peek_kind(&directory.to_string_lossy(), &cloud)
                            .await;
                    (directory, kind)
                });
                asked.insert(task.id(), directory);
            }
            // Sent a few at a time so labels fill in without a rebuild per directory. Every
            // directory asked is sent back, undecided and failed ones too: that clears
            // `peeking` and keeps one request per directory.
            let mut found = Vec::new();
            let mut failed = Vec::new();
            while let Some(joined) = peeks.join_next_with_id().await {
                match joined {
                    Ok((_, (directory, Ok(answer)))) => {
                        let answer = Some(answer)
                            .filter(Self::peek_tells_a_row_something)
                            .unwrap_or((discover::EntryKind::Directory, Default::default()));
                        found.push((directory, answer));
                    }
                    Ok((_, (directory, Err(_)))) => failed.push(directory),
                    Err(error) => failed.extend(asked.remove(&error.id())),
                }
                if found.len() + failed.len() >= PEEKS_AT_ONCE {
                    let _ = tx.send(AppEvent::HomeCloudKinds {
                        kinds: std::mem::take(&mut found),
                        failed: std::mem::take(&mut failed),
                    });
                }
            }
            if !found.is_empty() || !failed.is_empty() {
                let _ = tx.send(AppEvent::HomeCloudKinds {
                    kinds: found,
                    failed,
                });
            }
        });
    }

    /// Browse into a directory or bucket, local or remote.
    pub(crate) fn home_browse_into(&mut self, path: PathBuf) {
        self.home.leave_mark();
        if self.home.browsing.is_none() {
            self.home.browse_start = Some(path.clone());
        } else if self.home.browse_start.is_none() {
            self.home.browse_start = self.home.browsing.clone();
        }
        self.home.browsing = Some(path);
        // What the last walk found and the status line describe a different place; a fresh
        // walk starts on the next keystroke. A caller with news of the new place says it
        // after this returns.
        self.home.status = None;
        self.home.search.reset();
        self.home.filter.clear();
        self.home.sync_search_section();
        self.home.selected = 0;
        self.home_refresh();
    }

    /// Whether the highlighted row is the `(all files)` door, which opens the browsed
    /// directory and so is already inside it.
    fn selection_opens_the_whole_directory(&self) -> bool {
        self.home.selection_is_the_door()
    }

    /// The highlighted row when → goes inside it: any directory, local or remote,
    /// whatever its label. Files, headers and the door are left out.
    pub(crate) fn selected_directory_to_enter(&self) -> Option<PathBuf> {
        // A place under `RECENT` has no entry, so it is answered first.
        if let Some(home::Row::Place { path, .. }) = self.home.selected_row() {
            return home::place_is_browsable(&path).then_some(path);
        }
        let entry = self.home.selected_entry()?;
        if self.selection_opens_the_whole_directory() || self.home.missing.contains(&entry.path) {
            return None;
        }
        // A SQLite database lists its tables, however many it has.
        if entry.cost.tables.is_some() {
            return Some(entry.path.clone());
        }
        (!matches!(
            entry.kind,
            discover::EntryKind::File | discover::EntryKind::Other
        ))
        .then_some(entry.path.clone())
    }

    /// Why Enter on a bucket directory's `(all files)` row reads nothing, by Enter's
    /// own rule: a hive root or one-table directory reads through its files, and one
    /// with a reader for its contents reads with that.
    #[cfg(feature = "cloud")]
    pub(crate) fn why_a_door_reads_nothing(entry: &discover::Entry) -> Option<String> {
        if !home::is_object_store_url(&entry.path)
            || matches!(
                entry.kind,
                discover::EntryKind::Hive | discover::EntryKind::MultiFile
            )
            || Self::cloud_prefix_format(&entry.holds).is_some()
        {
            return None;
        }
        Self::why_a_cloud_prefix_cannot_be_read(&entry.holds)
    }

    /// Why an object-store prefix cannot be read as one table, from its listed
    /// contents (no request). `None` when it may yet be Parquet: it holds Parquet,
    /// or no data files and perhaps data a level down.
    #[cfg(feature = "cloud")]
    pub(crate) fn why_a_cloud_prefix_cannot_be_read(holds: &discover::Holds) -> Option<String> {
        let reads_parquet =
            |name: &str| crate::FileFormat::from_name(name) == Some(crate::FileFormat::Parquet);
        if holds.formats.iter().any(|(name, _)| reads_parquet(name)) {
            return None;
        }
        match holds.formats.as_slice() {
            // Data files, none Parquet. `label()` says `mixed` for several formats, so the
            // line spells them out.
            [] => {
                // Nothing readable. A refusal only if nothing is below: sub-prefixes may hold
                // Parquet a level down.
                (holds.not_read > 0 && holds.directories == 0).then(|| {
                    "this prefix holds nothing datui can read — datui reads a directory in \
                     an object store as Parquet only."
                        .to_string()
                })
            }
            formats => {
                let held = formats
                    .iter()
                    .map(|(name, count)| format!("{count} {name}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                Some(format!(
                    "this prefix holds {held} — datui reads a directory in an object store \
                     as Parquet only. Open one of the files below instead."
                ))
            }
        }
    }

    /// The reader an object-store prefix calls for, from its listing's counts: the
    /// commonest format, ranked by `rank_formats` as on disk, Parquet included. `None`
    /// when nothing there has a multi-file reader, where the refusal belongs.
    #[cfg(feature = "cloud")]
    pub(crate) fn cloud_prefix_format(
        holds: &discover::Holds,
    ) -> Option<(FileFormat, Vec<(FileFormat, usize)>)> {
        // A saved DatasetDict: its splits are Arrow, read one at a time.
        if holds.dataset_dict {
            return Some((FileFormat::Arrow, Vec::new()));
        }
        // Model weights beside config and tokenizer JSON: the prefix is the model, and the
        // JSON is not data passed over.
        if let Some((name, _)) = holds.model_weights() {
            return FileFormat::from_name(name).map(|format| (format, Vec::new()));
        }
        let (name, _) = holds.formats.first()?;
        // A GPS log is read whole from disk; a bucket's logs open one at a time, as its
        // text files do.
        let format = FileFormat::from_name(name)
            .filter(|f| f.reads_many_files() && !f.reads_into() && !f.is_lines())?;
        // What taking the commonest passes over. Polars lists the prefix and never sees
        // other formats, so the note comes from the listing on screen.
        let left_out = holds
            .formats
            .iter()
            .skip(1)
            .filter_map(|(name, n)| FileFormat::from_name(name).map(|f| (f, *n)))
            .collect();
        Some((format, left_out))
    }

    /// Open the highlighted entry: toggle a section, descend, or load a dataset.
    pub(crate) fn home_open_selected(&mut self) -> Option<AppEvent> {
        match self.home.selected_row() {
            // Into the directory or prefix the recents under it live in.
            Some(home::Row::Place { path, .. }) => {
                if home::place_is_browsable(&path) {
                    self.home_browse_into(path);
                } else {
                    self.home.status = Some(
                        "An HTTP server has no listing to browse. Open a file under it".into(),
                    );
                }
                return None;
            }
            // The rest of `RECENT`, or of a directory, for the session.
            Some(home::Row::More { section, .. }) => {
                self.home.show_all(section);
                return None;
            }
            // Up a level: as Backspace while browsing, and above a root at the listing.
            Some(home::Row::Up { section }) => {
                if self.home.browsing.is_some() {
                    self.home_ascend();
                } else if let Some(parent) = self
                    .home
                    .sections
                    .get(section)
                    .and_then(|s| s.root.as_deref())
                    .and_then(|root| self.home.parent_of(root))
                {
                    self.home_browse_into(parent);
                }
                return None;
            }
            // What Ctrl+A shows; the cursor goes to the first, where the hidden row stood.
            Some(home::Row::Hidden { .. }) => {
                self.home.hide_unreadable = false;
                if let Some(idx) = self.home.visible().iter().position(|row| {
                    matches!(row, home::Row::Entry { entry, .. }
                        if entry.hidden_by_default())
                }) {
                    self.home.selected = idx;
                }
                return None;
            }
            _ => {}
        }
        if self.home.selection_is_header() {
            self.home_toggle_fold();
            return None;
        }
        let entry = self.home.selected_entry()?.clone();
        // A collection's local dataset that is not there: said here, where it was named.
        if self.home.missing.contains(&entry.path) {
            self.home.status = Some(format!(
                "{} does not exist",
                home::display_path(&entry.path)
            ));
            return None;
        }
        // A place a collection suggests opens as one table on Enter; → still goes in.
        if entry.kind != discover::EntryKind::File && self.home.bookmark(&entry.path).is_some() {
            #[cfg(feature = "cloud")]
            let reader = if home::is_object_store_url(&entry.path)
                && !matches!(
                    entry.kind,
                    discover::EntryKind::Hive | discover::EntryKind::MultiFile
                ) {
                Self::cloud_prefix_format(&entry.holds)
            } else {
                None
            };
            #[cfg(not(feature = "cloud"))]
            let reader = None;
            let directory = home::directory_dataset_url(&entry.path);
            return Some(self.home_open_directory_as(directory, true, None, reader));
        }
        // The `(all files)` row opens its directory whatever the label: no label can lock
        // the user out. Sent straight to the open, since `open_what_it_is` would read the
        // label and step inside again.
        if self.selection_opens_the_whole_directory() {
            // A lake table read as Parquet counts tombstoned rows and every rewritten version,
            // so the read is labeled, not refused: a note in the panel and a footer chip say
            // so, and Enter one level up explains datui does not read the table itself yet.
            let lake = entry.kind.lake_name();
            // Pick an object-store prefix's reader from its listed contents (no request), so a
            // CSV prefix is not scanned as Parquet and blamed on credentials. A prefix the
            // listing already calls a dataset is left alone: a hive root reads through its
            // partitions despite a stray `manifest.csv`.
            #[cfg(feature = "cloud")]
            let reader = if home::is_object_store_url(&entry.path)
                && !matches!(
                    entry.kind,
                    discover::EntryKind::Hive | discover::EntryKind::MultiFile
                ) {
                let reader = Self::cloud_prefix_format(&entry.holds);
                // Nothing readable: the refusal names what is there rather than blaming the
                // connection.
                if reader.is_none()
                    && let Some(what) = Self::why_a_cloud_prefix_cannot_be_read(&entry.holds)
                {
                    self.home.status = Some(what);
                    return None;
                }
                reader
            } else {
                None
            };
            #[cfg(not(feature = "cloud"))]
            let reader = None;
            // `hive: true` reads it as one and carries partition columns through the hive
            // route. The cloud route returns before the dispatch.
            let directory = home::directory_dataset_url(&entry.path);
            return Some(self.home_open_directory_as(directory, true, lake, reader));
        }
        // A row nothing has looked at is looked at first: `Unknown` is offered as openable,
        // and a lake root would otherwise read as one table.
        let mut entry = entry;
        if entry.kind == discover::EntryKind::Unknown {
            if self.looking_could_block(&entry.path) {
                return Some(AppEvent::ClassifyThenOpen {
                    path: entry.path,
                    jump: false,
                });
            }
            if entry.path.is_dir() {
                entry.kind = discover::classify_directory(&entry.path);
            }
        }
        // A database of several tables lists them; one not yet measured opens and lands on
        // its tables the same way.
        if entry.enter_lists_tables() {
            self.home_browse_into(entry.path);
            return None;
        }
        self.open_what_it_is(entry.path, entry.kind, false)
    }

    /// Browse into `path` as a jump: the browse starts here, so Esc returns to the
    /// listing rather than up through the path's parents.
    pub(crate) fn home_jump_into(&mut self, path: PathBuf) {
        // Only the listing's mark is still a way back.
        self.home.trail.retain(|mark| mark.place.is_none());
        if self.home.browsing.is_none() {
            self.home.leave_mark();
        }
        self.home.browse_start = Some(path.clone());
        self.home.browsing = Some(path);
        self.home.status = None;
        self.home.search.reset();
        self.home.filter.clear();
        self.home.sync_search_section();
        self.home.selected = 0;
        self.home_refresh();
    }

    /// Load a path from the home screen. The `Open` handler records the recent.
    pub(crate) fn home_open_path(&mut self, path: PathBuf, hive: bool) -> AppEvent {
        self.home_open_directory(path, hive, None)
    }

    /// As [`Self::home_open_path`], noting whether the directory is a lake table whose
    /// plain files are read, so the dataset can say so.
    fn home_open_directory(
        &mut self,
        path: PathBuf,
        hive: bool,
        lake: Option<&'static str>,
    ) -> AppEvent {
        self.home_open_directory_as(path, hive, lake, None)
    }

    /// As [`Self::home_open_directory`], naming the reader. For an object-store prefix
    /// the cloud scan runs before the format dispatch, so the listing's format travels
    /// with the open or the scan falls back to Parquet.
    fn home_open_directory_as(
        &mut self,
        path: PathBuf,
        hive: bool,
        lake: Option<&'static str>,
        reader: Option<(FileFormat, Vec<(FileFormat, usize)>)>,
    ) -> AppEvent {
        let (format, left_out) = match reader {
            Some((format, left_out)) => (Some(format), left_out),
            None => (None, Vec::new()),
        };
        // Told, not stat'ed: the caller knows, and a stat on a gone share would freeze the
        // key thread (also why `Open` fills in the size).
        let options = OpenOptions {
            hive,
            read_as_plain_files_of: lake,
            format,
            left_out,
            ..self.open_defaults()
        };
        self.show_table();
        // Chosen here, so a failure is reported here.
        self.announce_open(true, "Scanning input".to_string(), 10);
        // The frame drawn before `Open` runs says which file; `Open` fills in the size a
        // frame later, off this thread.
        self.name_what_is_loading(path.clone());
        AppEvent::Open(vec![path], options)
    }

    /// The home screen's worker answers.
    pub(crate) fn home_event(&mut self, event: AppEvent) -> Option<AppEvent> {
        match event {
            AppEvent::HomeListingReady {
                generation,
                listing,
                known,
                visits,
                newest,
                folds,
            } => {
                // Only the current listing's answer clears the flag; a stale one landing first
                // would say nothing is in flight.
                if generation == self.home_app.generation {
                    self.home.listing_in_flight = false;
                }
                // Read fresh from the cache, so true whichever listing carried them; only the
                // first listing after entering home carries the folds.
                self.home.known = known;
                self.home.set_visits(visits);
                self.home.newest_recent = newest;
                if let Some(folds) = folds {
                    self.home.folds = folds;
                }
                // A superseded listing describes somewhere the user has left.
                if generation != self.home_app.generation {
                    return None;
                }
                self.home.apply_listing(*listing);
                // Probes are chosen from the sections, so only once they exist.
                self.spawn_home_probes();
                #[cfg(feature = "cloud")]
                self.spawn_cloud_discovery();
                self.request_home_measurements();
                self.request_home_classifications();
                None
            }
            AppEvent::HomeListingFailed => {
                // The rows already listed stay. The panic is flashed as a raw worker's.
                self.home.listing_in_flight = false;
                None
            }
            AppEvent::HomeMeasured { measured, done } => {
                for (path, m) in measured {
                    self.home.record_measurement(path, m);
                }
                // A batch answers one file per event; they are folded in at the next frame
                // (`begin_frame`), not one list per file.
                if done {
                    self.home.measure_in_flight = false;
                    self.request_home_measurements();
                }
                None
            }
            AppEvent::HomeSized { path, measured } => {
                self.home.record_size(path, measured);
                self.home.apply_new_measurements();
                None
            }
            AppEvent::HomeWebGone { path, gone } => {
                self.home.web_gone.insert(path, gone);
                None
            }
            AppEvent::HomeClassified { measured, done } => {
                // Kept even if the listing was rebuilt since: probes and peeks rebuild it often,
                // and dropping answers would leave rows unlabeled.
                for (path, m) in measured {
                    self.home.record_measurement(path, m);
                }
                // Nothing re-sorts: kinds are written into rows in place, so the listing never
                // reshuffles under the cursor. Folded in at the next frame, as measurements.
                // The next batch comes from the viewport as it is now, not the rows scrolled past.
                if done {
                    self.home.classify_in_flight = false;
                    self.request_home_classifications();
                }
                None
            }
            AppEvent::HomePathListed { listing } => {
                // Kept only for the directory still being typed.
                if self.home.path_input_active
                    && home::typed_dir(&self.home.path_input) == listing.dir
                {
                    self.home.path_listing = Some(*listing);
                    if self.home.path_pick.is_none() {
                        self.home.pick_first_path();
                    }
                }
                None
            }
            AppEvent::HomePathCompleted {
                generation,
                typed,
                completed,
                candidates,
            } => {
                // Discard if the user typed since asking: completing would scramble their input.
                if generation != self.home_app.generation || self.home.path_input != typed {
                    return None;
                }
                if candidates == 0 {
                    self.home.status = Some("No such path".to_string());
                } else {
                    self.home.status = None;
                    if candidates > 1 {
                        self.flash_note(format!("{candidates} matches"));
                    }
                    self.home.path_input = completed;
                    self.home.pick_first_path();
                }
                None
            }
            AppEvent::HomePreviewReady {
                path,
                stamp,
                read_at,
                rows,
                prepared,
            } => {
                let prepared = prepared.lock().ok().and_then(|mut p| p.take());
                // The columns came with the rows: the pane lists them, for a CSV too.
                if let Some(prepared) = &prepared {
                    let schema = prepared
                        .state
                        .schema()
                        .iter()
                        .map(|(name, dtype)| (name.to_string(), dtype.clone()))
                        .collect();
                    self.home_app
                        .schema_cache
                        .insert(path.clone(), Some(schema));
                }
                let prepared = prepared.filter(|_| read_at.is_some());
                self.home_app.previews.landed(
                    path,
                    stamp,
                    read_at.unwrap_or(stamp),
                    rows,
                    prepared,
                );
                None
            }
            AppEvent::HomeSchemaReady {
                generation,
                path,
                preview,
            } => {
                self.home_app.schema_inflight.retain(|p| p != &path);
                // A preview's columns are not taken back by a metadata read that had none.
                let known = self
                    .home_app
                    .schema_cache
                    .get(&path)
                    .is_some_and(Option::is_some);
                if generation == self.home_app.generation && (preview.is_some() || !known) {
                    self.home_app.schema_cache.insert(path.clone(), preview);
                }
                None
            }
            AppEvent::HomeSearchBatch {
                generation,
                root,
                found,
                scanned,
            } => {
                // Batches from a walk a later navigation superseded describe a place left behind;
                // the walk is abandoned, not cancelled, so late batches are expected. A refresh of
                // the same place supersedes nothing.
                if generation == self.home_app.search_generation {
                    self.home.search_batch(&root, found, scanned);
                }
                None
            }
            AppEvent::HomeSearchScored { epoch, matches } => {
                // A scoring that died is not retried (it would die again); listed matches stand.
                if let Some(matches) = matches {
                    self.home.search_scored(epoch, *matches);
                }
                None
            }
            AppEvent::HomeSearchDone {
                generation,
                root,
                scanned,
                limited,
            } => {
                if generation == self.home_app.search_generation {
                    self.home.search_finished(&root, scanned, limited);
                }
                self.home_app.search_inflight = false;
                // A walk abandoned by a browse held up the one the filter now asks for.
                if !self.home.filter.is_empty() && self.home.search.root.is_none() {
                    self.spawn_home_search();
                }
                None
            }
            #[cfg(feature = "cloud")]
            AppEvent::HomeCloudSources { sources } => {
                self.home.cloud = sources;
                self.home_refresh();
                None
            }
            #[cfg(feature = "cloud")]
            AppEvent::HomeCloudListed {
                id,
                buckets,
                details,
                failure,
                listed_at,
            } => {
                if let Some(source) = self.home.cloud.iter_mut().find(|s| s.id == id) {
                    source.refreshing = false;
                    for (place, lines) in details {
                        source.place_details.insert(place, lines);
                    }
                    match failure {
                        // A failed refresh keeps the last buckets, and the row says it failed.
                        Some((short, detail)) => {
                            for bucket in buckets {
                                if !source.buckets.contains(&bucket) {
                                    source.buckets.push(bucket);
                                }
                            }
                            source.status = home::CloudStatus::Failed { short, detail };
                        }
                        None => {
                            source.buckets = buckets;
                            source.status = home::CloudStatus::Listed;
                            source.listed_at = Some(listed_at);
                        }
                    }
                }
                self.home_refresh();
                None
            }
            AppEvent::HomeNarrowed {
                dir,
                prefix,
                listed,
            } => {
                // Only the current request: a replaced one may answer late with a shorter prefix.
                let asked = self
                    .home_app
                    .narrowing
                    .as_ref()
                    .is_some_and(|(d, p, _)| *d == dir && *p == prefix);
                if asked {
                    self.home_app.narrowing = None;
                }
                // Only while it is still where the user is and what the filter asks.
                let wanted = asked
                    && self.home.browsing.as_ref() == Some(&dir)
                    && !self.home.filter.is_empty();
                if let (Some((rows, truncated)), true) = (listed, wanted) {
                    self.home.narrowed = Some(home::Narrowed {
                        dir,
                        prefix,
                        rows,
                        truncated,
                    });
                    self.home_refresh();
                }
                None
            }
            AppEvent::HomeProbeCancelled { root } => {
                self.home_app.probes_inflight.retain(|p| p != &root);
                self.home_app.listing_cancels.remove(&root);
                self.home.probes.stopped(&root);
                // Come back to after it had stopped: listed afresh.
                if self.home.browsing.as_ref() == Some(&root) {
                    self.home_refresh();
                }
                None
            }
            AppEvent::HomeProbeFailed { root, message } => {
                self.home_app.probes_inflight.retain(|p| p != &root);
                self.home_app.listing_cancels.remove(&root);
                self.home.probe_failed(root, Some(message));
                self.home_refresh();
                None
            }
            AppEvent::HomeProbeProgress { root, rows } => {
                // Only while that listing is out: a late batch must not paint over the answer.
                if self.home_app.probes_inflight.contains(&root) && !self.home.probes.settled(&root)
                {
                    self.home.probes.read(&root, &rows);
                    // Listed once a frame, however many batches came in it.
                    self.home_app.refresh_owed = true;
                }
                None
            }
            AppEvent::HomeProbeReady {
                root,
                rows,
                cut_short,
            } => {
                // Free the slot. The cap bounds threads wedged on dead mounts, which never send
                // this; without freeing, probing stops after MAX_CONCURRENT_PROBES roots.
                self.home_app.probes_inflight.retain(|p| p != &root);
                self.home_app.listing_cancels.remove(&root);
                let landed = rows.is_some();
                match rows {
                    Some(rows) => self.home.probe_ready(root.clone(), rows, cut_short),
                    None => self.home.probe_failed(root.clone(), None),
                }
                // A filter typed while it was listing asks the server too.
                #[cfg(feature = "cloud")]
                if cut_short && !self.home.filter.is_empty() {
                    self.narrow_cloud_listing();
                }
                // An account read with its keys (the sign-in has no data role) says so.
                #[cfg(feature = "cloud")]
                if let Some((account, _, _)) = source::azure_parts(&root.to_string_lossy())
                    && crate::cloud::azure::remembered_key(&account).is_some()
                {
                    for source in &mut self.home.cloud {
                        let place = source
                            .buckets
                            .iter()
                            .find(|b| home::cloud_account(b).is_some_and(|(_, a)| a == account))
                            .cloned();
                        if let Some(place) = place {
                            let lines = source.place_details.entry(place).or_default();
                            if !lines.iter().any(|(k, _)| k == "access") {
                                lines.push(("access".to_string(), "access key".to_string()));
                            }
                        }
                    }
                }
                // Rebuild so the listing picks up the result.
                self.home_refresh();
                // Then peek at its rows: after the rebuild, which writes the `visible()` the picker
                // reads. Here, because a listing landing under a still cursor may draw no frame to
                // notice.
                #[cfg(feature = "cloud")]
                if landed {
                    self.peek_cloud_directories();
                }
                #[cfg(not(feature = "cloud"))]
                let _ = landed;
                None
            }
            AppEvent::HomeCloudKinds { kinds, failed } => {
                for directory in failed {
                    self.home.peeking.remove(&directory);
                    self.home.peek_failed.insert(directory);
                }
                let roots: Vec<PathBuf> = self
                    .home
                    .probes
                    .answered()
                    .map(|(root, _)| root.clone())
                    .collect();
                for (directory, kind) in kinds {
                    // Answered: out of `peeking` into the set rows are labeled from; every directory
                    // comes back, so none is asked twice.
                    self.home.peeking.remove(&directory);
                    self.home.cloud_kinds.insert(directory, kind);
                }
                for root in roots {
                    self.home.apply_cloud_kinds(&root);
                }
                self.home_refresh();
                None
            }
            _ => unreachable!("not a home event"),
        }
    }
}