BREP_app 0.2.1

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
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
//! The persistent-storage / filesystem seam — the ONE platform exception in
//! the engine-native UI. Settings, dock layout, and model documents all use the
//! same [`ModelStore::read`] / [`ModelStore::write`] API. Only its backend differs:
//! desktop writes files; the browser mirrors an ASYNC, swappable
//! [`mirror_store::StoreBackend`] — IndexedDB today, a remote server next — into
//! memory and writes behind it, which is what keeps this whole API synchronous.

/// Reserved persistent-object names used internally for application state.
pub const SETTINGS_KEY: &str = "@settings";
pub const DOCK_LAYOUT_KEY: &str = "@dock_layout";
/// The open-document SESSION (which models are in tabs and which one is active
/// — see `crate::document`), so a reload comes back to the desk you left.
pub const SESSION_KEY: &str = "@session";
/// Pinned explorer locations (a JSON array of navigable location strings),
/// persisted through the ordinary `read`/`write` CRUD like the other reserved
/// keys so the sidebar needs no dedicated trait surface.
pub const PINNED_KEY: &str = "@pinned";

/// A file selected outside the model store. Keeping bytes verbatim allows the
/// same upload channel to carry binary STL as well as text CAD formats.
pub struct ImportedFile {
    pub name: String,
    pub bytes: Vec<u8>,
}

/// One entry exposed to the common in-application filesystem browser.
#[derive(Clone, Debug, PartialEq)]
pub struct BrowserEntry {
    pub name: String,
    pub identity: String,
    pub is_dir: bool,
    /// File size in bytes for the Size column. `None` for directories or where
    /// the backend cannot report it.
    pub size: Option<u64>,
    /// Last-modified time as whole Unix seconds for the Date column. `None` where
    /// unavailable — the browser key/value backends store values, not timestamps.
    pub modified: Option<f64>,
}

/// A quick-access destination for the explorer's left sidebar.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BrowserPlace {
    /// Human label shown in the sidebar (e.g. `"Home"`, `"Models"`, a disk name).
    pub label: String,
    /// The navigable location — pass to [`ModelStore::browser_navigate`].
    pub location: String,
    /// Which built-in glyph the widget draws for this place.
    pub kind: PlaceKind,
}

/// The category of a [`BrowserPlace`], so the widget owns the icon styling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlaceKind {
    Home,
    Documents,
    Downloads,
    Models,
    Root,
}
// A MODEL is a whole document
// (the engine-owned `HistoryRequest` JSON — one `.BREP.json` recipe), and the
// file panel needs to *enumerate*, read, and write NAMED documents, plus (in the
// browser) hand a file to / take a file from the user's real filesystem. The same
// trait also stores reserved application-state blobs. Platform-specific behavior
// remains behind two `#[cfg]`-gated implementations.
//
// The trait is deliberately a **named-document CRUD** (`list` / `read` / `write`
// / `remove`) plus a poll-based **file-interchange** side-channel. That shape is
// exactly what a later **GitHub backend** needs: `list` = a repo directory
// listing, `read` = fetch a file's contents, `write` = create/update (commit)
// a file, `remove` = delete a file — the model name is the path within the repo.
// An async backend (GitHub over HTTP, or the browser File System Access API /
// OPFS whose main-thread API is async) slots in behind the SAME trait by driving
// its request on a background task and surfacing the result through the
// `begin_import` → `take_import` poll pattern used here for uploads, so the
// synchronous panel code never changes. GitHub itself is a deferred follow-up;
// this lands the seam it plugs into.

/// The application's single persistent-storage abstraction. Reserved application
/// keys and named model documents are read and written through the same methods.
/// All methods take `&self`; mutable backend state lives behind interior mutability.
pub trait ModelStore {
    /// A short human label of where documents persist, for the panel header
    /// (e.g. `"filesystem: ~/.config/brep-app/models"` or `"browser storage"`).
    fn backend_label(&self) -> String {
        "persistent storage".into()
    }

    /// The names of the documents currently available to **Open** (bare names,
    /// no extension). May be empty on a backend that cannot enumerate — then the
    /// panel falls back to the name field / import.
    fn list(&self) -> Vec<String> {
        Vec::new()
    }

    /// Read a stored document by name, or `None` if absent/unreadable.
    fn read(&self, name: &str) -> Option<String>;

    /// Create or overwrite the document `name` with `contents`. `Err` carries a
    /// message the panel surfaces in its status line.
    fn write(&self, name: &str, contents: &str) -> Result<(), String>;

    /// Delete the document `name` (best-effort; `Ok` if it is already gone).
    fn remove(&self, _name: &str) -> Result<(), String> {
        Ok(())
    }

    /// Persistence failures that surfaced AFTER a `write` / `remove` already
    /// returned `Ok` — the price of a WRITE-BEHIND backend (see
    /// [`mirror_store`]). The app shell drains this once per frame into the toast
    /// overlay, so a save that never reached storage is never silent: the
    /// in-memory copy means nothing is lost mid-session, but the user has to know
    /// it will not survive a reload. Empty on a backend that writes synchronously
    /// (native files), which reports through `write`'s `Err` instead.
    fn take_persistence_errors(&self) -> Vec<String> {
        Vec::new()
    }

    // --- common file-browser filesystem --------------------------------------

    /// Current directory shown by the embedded explorer.
    fn browser_location(&self) -> String {
        self.backend_label()
    }

    /// Directories and matching files at the current explorer location.
    /// Directories are never filtered. The default implementation presents the
    /// backend's named model collection as a flat virtual directory.
    fn browser_entries(&self, _extensions: &[&str]) -> Vec<BrowserEntry> {
        self.list()
            .into_iter()
            .map(|name| BrowserEntry {
                identity: name.clone(),
                name,
                is_dir: false,
                size: None,
                modified: None,
            })
            .collect()
    }

    fn browser_enter(&self, _identity: &str) -> Result<(), String> {
        Err("this storage backend has no directories".into())
    }

    fn browser_up(&self) -> Result<(), String> {
        Ok(())
    }

    fn browser_home(&self) -> Result<(), String> {
        Ok(())
    }

    fn browser_root(&self) -> Result<(), String> {
        Ok(())
    }

    /// Navigate the explorer directly to `location` — a value previously returned
    /// by [`Self::browser_location`], a [`BrowserPlace::location`], a breadcrumb
    /// ancestor, or a user-typed path. `Err` if it is not a directory this backend
    /// can browse. Powers the breadcrumb, the sidebar, back/forward, and the
    /// path-edit field. Default: unsupported.
    fn browser_navigate(&self, _location: &str) -> Result<(), String> {
        Err("this storage backend cannot navigate to a path".into())
    }

    /// Quick-access places for the explorer's left sidebar (home, documents, the
    /// models root, disks…). Default: none, and the sidebar hides itself.
    fn browser_places(&self) -> Vec<BrowserPlace> {
        Vec::new()
    }

    /// Create a child directory at the current browser location.
    fn browser_create_dir(&self, _name: &str) -> Result<(), String> {
        Err("this storage backend cannot create directories".into())
    }

    /// Write a filename at the current browser location and return its stable
    /// identity for subsequent plain Save operations.
    fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
        self.write(name, contents)?;
        Ok(name.to_string())
    }

    /// Files available to the in-app explorer for a foreign-format import.
    /// Names retain their extension. Browser storage returns none and offers an
    /// Upload button instead; desktop enumerates its application files directory.
    fn list_external_files(&self, _extensions: &[&str]) -> Vec<String> {
        Vec::new()
    }

    /// Read one entry returned by [`Self::list_external_files`].
    fn read_external_file(&self, _name: &str) -> Option<Vec<u8>> {
        None
    }

    // --- real-file interchange (the platform "fallback") ----------------------
    // The browser cannot silently write to an arbitrary path; these methods let
    // it move a document to/from the user's real filesystem. Desktop instead
    // browses and writes its application files directory directly.

    /// Whether this backend can exchange files with the user's real filesystem
    /// (browser download+upload). The panel shows the Upload affordance only when
    /// this is `true`.
    fn supports_file_interchange(&self) -> bool {
        false
    }

    /// Hand `contents` to the user as a file named after `name` (browser: a
    /// download; native w/ dialog: a Save-As). Returns the saved document's
    /// identity — the full path the user chose on native (so the caller can
    /// re-save straight to it), the bare download name on the web — or `None`
    /// when the user cancelled. No-op (`None`) by default.
    fn export_file(&self, name: &str, contents: &str) -> Result<Option<String>, String> {
        let _ = (name, contents);
        Ok(None)
    }

    /// Begin importing a real file — opens the platform picker. The result is
    /// retrieved later via [`Self::take_import`] (upload/read is async in the
    /// browser). No-op by default.
    fn begin_import(&self) -> Result<(), String> {
        Ok(())
    }

    /// Poll for a completed import, consuming it.
    /// `None` until a `begin_import` finishes. Default: never any.
    fn take_import(&self) -> Option<ImportedFile> {
        None
    }

    // --- format-typed interchange (CAD / mesh) --------------------------------
    // The model lanes above trade the `.BREP.json` recipe; import/export of a
    // foreign format (STEP text, ASCII STL) needs a DIFFERENT picker filter and
    // must NOT mangle the file extension. These two methods add that lane while
    // leaving the model lanes byte-for-byte. They share the SAME `take_import`
    // pickup channel — the panel routes the result by its filename extension.

    /// Begin importing a real file behind a specific picker `filter` (a human
    /// label + dot-less extensions, e.g. `("STEP", &["step","stp"])`). The chosen
    /// file's contents + its FULL name (extension preserved, so the panel can
    /// route it) arrive via [`Self::take_import`]. Default: reuse [`Self::begin_import`].
    fn begin_import_filtered(&self, _filter: (&str, &[&str])) -> Result<(), String> {
        self.begin_import()
    }

    /// Hand `contents` to the user under EXACTLY `file_name` (extension included,
    /// no model-extension munging) — the Save-As / download for a foreign export
    /// format. Default no-op (interchange unsupported).
    fn export_file_named(&self, _file_name: &str, _contents: &str) -> Result<(), String> {
        Ok(())
    }
}

/// Construct the platform's one persistent store for application state and models.
pub fn default_model_store() -> Box<dyn ModelStore> {
    #[cfg(not(target_arch = "wasm32"))]
    {
        Box::new(native_model::FileModelStore::new())
    }
    #[cfg(target_arch = "wasm32")]
    {
        // Already built and HYDRATED by [`hydrate_web_store`] inside the async
        // wasm entry point, so this is a hand-off, not a construction.
        web_model::take_boot_store()
    }
}

/// wasm: bring up browser persistence and pull the whole key space into memory.
/// MUST be awaited before `eframe::WebRunner::start`, because everything
/// downstream of it — [`default_model_store`], every `read` in `BrepApp::new` and
/// in the frame loop — is synchronous and assumes a complete mirror.
#[cfg(target_arch = "wasm32")]
pub async fn hydrate_web_store() {
    web_model::hydrate().await;
}

/// wasm: wake the reactive frame loop when an async file upload completes (see
/// [`web_model::set_repaint_ctx`]). Re-exported here so the app shell reaches it
/// as `store::set_repaint_ctx` without knowing the platform module.
#[cfg(target_arch = "wasm32")]
pub use web_model::set_repaint_ctx;

/// The document extension for a model recipe (`<name>.BREP.json`).
pub const MODEL_EXT: &str = ".BREP.json";

/// Test-only: a native model store rooted at an explicit directory (a temp dir
/// in tests) so a round-trip test never touches the real config dir.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub fn native_test_store(dir: std::path::PathBuf) -> Box<dyn ModelStore> {
    Box::new(native_model::FileModelStore::with_dir(dir))
}

/// Test-only: an IN-MEMORY model store (no filesystem, no dialogs) shared by
/// the update-components and assembly-panel tests. `RefCell` keeps the trait's
/// `&self` shape; the read counter lets a staleness test prove a cached badge
/// re-reads the store only when its generation key changes.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) struct MemModelStore {
    docs: std::cell::RefCell<std::collections::BTreeMap<String, String>>,
    reads: std::cell::Cell<usize>,
}

#[cfg(all(test, not(target_arch = "wasm32")))]
impl MemModelStore {
    pub fn new() -> Self {
        Self {
            docs: std::cell::RefCell::new(std::collections::BTreeMap::new()),
            reads: std::cell::Cell::new(0),
        }
    }

    /// Seed/overwrite a document without going through `write`'s Result.
    pub fn put(&self, name: &str, contents: &str) {
        self.docs
            .borrow_mut()
            .insert(name.to_string(), contents.to_string());
    }

    /// How many `read` calls the store has served (staleness-cache probe).
    pub fn reads(&self) -> usize {
        self.reads.get()
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
impl ModelStore for MemModelStore {
    fn backend_label(&self) -> String {
        "in-memory test store".into()
    }
    fn list(&self) -> Vec<String> {
        self.docs.borrow().keys().cloned().collect()
    }
    fn read(&self, name: &str) -> Option<String> {
        self.reads.set(self.reads.get() + 1);
        self.docs.borrow().get(name).cloned()
    }
    fn write(&self, name: &str, contents: &str) -> Result<(), String> {
        self.put(name, contents);
        Ok(())
    }
    fn remove(&self, name: &str) -> Result<(), String> {
        self.docs.borrow_mut().remove(name);
        Ok(())
    }
}

/// Strip the model extension (and any directory) from a filename to get the
/// bare display name — shared by both platform impls (and the file panel, which
/// shows the bare name while keeping the raw identity for re-saves).
pub(crate) fn model_display_name(file_name: &str) -> String {
    let base = file_name
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(file_name);
    base.strip_suffix(MODEL_EXT)
        .or_else(|| base.strip_suffix(".json"))
        .unwrap_or(base)
        .to_string()
}

// --- Desktop: application models/files directory -------------------------------
#[cfg(not(target_arch = "wasm32"))]
mod native_model {
    use super::{
        model_display_name, BrowserEntry, BrowserPlace, ModelStore, PlaceKind, DOCK_LAYOUT_KEY,
        MODEL_EXT, PINNED_KEY, SESSION_KEY, SETTINGS_KEY,
    };
    use std::cell::RefCell;
    use std::path::{Path, PathBuf};

    /// Persist models as `<config>/brep-app/models/<name>.BREP.json` and reserved
    /// application state as files under `<config>/brep-app`. Enumerable (for the
    /// Open list) and unit-testable without a display.
    ///
    /// Open, Save As, import, and export are all driven by the application's
    /// common egui explorer; no OS-native dialog is involved.
    pub struct FileModelStore {
        app_dir: PathBuf,
        dir: PathBuf,
        browser_dir: RefCell<PathBuf>,
    }

    impl FileModelStore {
        pub fn new() -> Self {
            let base = std::env::var_os("XDG_CONFIG_HOME")
                .map(PathBuf::from)
                .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
                .unwrap_or_else(|| PathBuf::from("."));
            let app_dir = base.join("brep-app");
            Self {
                dir: app_dir.join("models"),
                browser_dir: RefCell::new(app_dir.join("models")),
                app_dir,
            }
        }

        /// A store rooted at an explicit directory — used by the round-trip test.
        /// The tests stay headless and exercise the same egui explorer path.
        #[cfg_attr(not(test), allow(dead_code))]
        pub fn with_dir(dir: PathBuf) -> Self {
            Self {
                app_dir: dir.clone(),
                browser_dir: RefCell::new(dir.clone()),
                dir,
            }
        }

        /// Resolve a name to a path. Explicit paths remain supported for existing
        /// callers; a bare name maps to `<dir>/<sanitized>.BREP.json`.
        fn resolve(&self, name: &str) -> PathBuf {
            match name {
                SETTINGS_KEY => return self.app_dir.join("settings.json"),
                DOCK_LAYOUT_KEY => return self.app_dir.join("dock_layout.json"),
                SESSION_KEY => return self.app_dir.join("session.json"),
                PINNED_KEY => return self.app_dir.join("pinned.json"),
                _ => {}
            }
            if name.contains('/') || name.contains('\\') {
                return PathBuf::from(name);
            }
            let safe: String = name
                .strip_suffix(MODEL_EXT)
                .unwrap_or(name)
                .chars()
                .map(|c| {
                    if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
                        c
                    } else {
                        '_'
                    }
                })
                .collect();
            self.dir.join(format!("{safe}{MODEL_EXT}"))
        }

        fn home_dir() -> PathBuf {
            std::env::var_os("HOME")
                .map(PathBuf::from)
                .or_else(|| std::env::current_dir().ok())
                .unwrap_or_else(|| PathBuf::from("."))
        }

        fn matches_extension(path: &Path, extensions: &[&str]) -> bool {
            extensions.is_empty()
                || extensions.iter().any(|extension| {
                    let wanted = extension.trim_start_matches('.').to_ascii_lowercase();
                    let name = path
                        .file_name()
                        .unwrap_or_default()
                        .to_string_lossy()
                        .to_ascii_lowercase();
                    name.ends_with(&format!(".{wanted}"))
                })
        }
    }

    impl ModelStore for FileModelStore {
        fn backend_label(&self) -> String {
            format!("filesystem: {}", self.dir.display())
        }

        fn list(&self) -> Vec<String> {
            let mut names: Vec<String> = std::fs::read_dir(&self.dir)
                .into_iter()
                .flatten()
                .flatten()
                .filter_map(|entry| {
                    let name = entry.file_name().to_string_lossy().into_owned();
                    name.ends_with(MODEL_EXT).then(|| model_display_name(&name))
                })
                .collect();
            names.sort();
            names
        }

        fn read(&self, name: &str) -> Option<String> {
            std::fs::read_to_string(self.resolve(name)).ok()
        }

        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
            let path = self.resolve(name);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| format!("create models dir: {e}"))?;
            }
            std::fs::write(&path, contents).map_err(|e| format!("write {}: {e}", path.display()))
        }

        fn remove(&self, name: &str) -> Result<(), String> {
            match std::fs::remove_file(self.resolve(name)) {
                Ok(()) => Ok(()),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
                Err(e) => Err(format!("remove: {e}")),
            }
        }

        fn browser_location(&self) -> String {
            self.browser_dir.borrow().display().to_string()
        }

        fn browser_entries(&self, extensions: &[&str]) -> Vec<BrowserEntry> {
            let mut entries: Vec<BrowserEntry> = std::fs::read_dir(&*self.browser_dir.borrow())
                .into_iter()
                .flatten()
                .flatten()
                .filter_map(|entry| {
                    let path = entry.path();
                    let is_dir = path.is_dir();
                    if !(is_dir || (path.is_file() && Self::matches_extension(&path, extensions))) {
                        return None;
                    }
                    let meta = entry.metadata().ok();
                    let size = meta.as_ref().filter(|m| m.is_file()).map(|m| m.len());
                    let modified = meta
                        .as_ref()
                        .and_then(|m| m.modified().ok())
                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                        .map(|d| d.as_secs_f64());
                    Some(BrowserEntry {
                        name: entry.file_name().to_string_lossy().into_owned(),
                        identity: path.to_string_lossy().into_owned(),
                        is_dir,
                        size,
                        modified,
                    })
                })
                .collect();
            entries.sort_by(|a, b| {
                b.is_dir
                    .cmp(&a.is_dir)
                    .then_with(|| a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase()))
            });
            entries
        }

        fn browser_enter(&self, identity: &str) -> Result<(), String> {
            let path = PathBuf::from(identity);
            if !path.is_dir() {
                return Err(format!("not a directory: {}", path.display()));
            }
            *self.browser_dir.borrow_mut() = path;
            Ok(())
        }

        fn browser_up(&self) -> Result<(), String> {
            let parent = self.browser_dir.borrow().parent().map(Path::to_path_buf);
            if let Some(parent) = parent {
                *self.browser_dir.borrow_mut() = parent;
            }
            Ok(())
        }

        fn browser_home(&self) -> Result<(), String> {
            *self.browser_dir.borrow_mut() = Self::home_dir();
            Ok(())
        }

        fn browser_root(&self) -> Result<(), String> {
            let current = self.browser_dir.borrow().clone();
            let root = current
                .ancestors()
                .last()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| PathBuf::from(std::path::MAIN_SEPARATOR.to_string()));
            *self.browser_dir.borrow_mut() = root;
            Ok(())
        }

        fn browser_navigate(&self, location: &str) -> Result<(), String> {
            let path = PathBuf::from(location);
            if path.is_dir() {
                *self.browser_dir.borrow_mut() = path;
                Ok(())
            } else {
                Err(format!("not a directory: {location}"))
            }
        }

        fn browser_places(&self) -> Vec<BrowserPlace> {
            let home = Self::home_dir();
            let mut places = vec![BrowserPlace {
                label: "Home".into(),
                location: home.display().to_string(),
                kind: PlaceKind::Home,
            }];
            for (label, sub, kind) in [
                ("Documents", "Documents", PlaceKind::Documents),
                ("Downloads", "Downloads", PlaceKind::Downloads),
            ] {
                let path = home.join(sub);
                if path.is_dir() {
                    places.push(BrowserPlace {
                        label: label.into(),
                        location: path.display().to_string(),
                        kind,
                    });
                }
            }
            places.push(BrowserPlace {
                label: "Models".into(),
                location: self.dir.display().to_string(),
                kind: PlaceKind::Models,
            });
            places.push(BrowserPlace {
                label: "/".into(),
                location: "/".into(),
                kind: PlaceKind::Root,
            });
            places
        }

        fn browser_create_dir(&self, name: &str) -> Result<(), String> {
            let name = PathBuf::from(name);
            if name.components().count() != 1 {
                return Err("folder name must be one path component".into());
            }
            let path = self.browser_dir.borrow().join(name);
            std::fs::create_dir(&path)
                .map_err(|e| format!("create folder {}: {e}", path.display()))
        }

        fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
            let mut file_name = PathBuf::from(name)
                .file_name()
                .ok_or("invalid file name")?
                .to_os_string();
            if !name.to_ascii_lowercase().ends_with(".json") {
                file_name.push(MODEL_EXT);
            }
            let path = self.browser_dir.borrow().join(file_name);
            std::fs::write(&path, contents)
                .map_err(|e| format!("write {}: {e}", path.display()))?;
            Ok(path.to_string_lossy().into_owned())
        }

        fn list_external_files(&self, extensions: &[&str]) -> Vec<String> {
            let wanted: Vec<String> = extensions
                .iter()
                .map(|extension| extension.trim_start_matches('.').to_ascii_lowercase())
                .collect();
            let mut names: Vec<String> = std::fs::read_dir(&self.dir)
                .into_iter()
                .flatten()
                .flatten()
                .filter_map(|entry| {
                    let path = entry.path();
                    path.is_file().then_some(path)
                })
                .filter_map(|path| {
                    let extension = path.extension()?.to_string_lossy().to_ascii_lowercase();
                    wanted.contains(&extension).then(|| {
                        path.file_name()
                            .unwrap_or_default()
                            .to_string_lossy()
                            .into_owned()
                    })
                })
                .collect();
            names.sort();
            names
        }

        fn read_external_file(&self, name: &str) -> Option<Vec<u8>> {
            let path = PathBuf::from(name);
            let path = if path.is_absolute() || path.components().count() > 1 {
                path
            } else {
                self.browser_dir.borrow().join(path)
            };
            std::fs::read(path).ok()
        }

        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
            std::fs::create_dir_all(&self.dir)
                .map_err(|e| format!("create models dir: {e}"))?;
            let name = PathBuf::from(file_name)
                .file_name()
                .ok_or("invalid export file name")?
                .to_owned();
            let path = self.dir.join(name);
            std::fs::write(&path, contents)
                .map_err(|e| format!("write {}: {e}", path.display()))
        }
    }
}

// --- The mirrored store: a synchronous facade over an ASYNC backend ------------
//
// The browser has no synchronous storage big enough for this application. The
// measured numbers that forced this module into existence: one imported STEP
// part serialises to a ~35 MB native BREP payload, and an imported assembly
// document runs 1.0x-12.8x its source STEP text — against `localStorage`'s
// ~5-10 MB per-origin quota. Every backend with room (IndexedDB today, a remote
// server tomorrow) is ASYNC, while [`ModelStore`] is synchronous and the egui
// frame loop that calls it is immediate-mode.
//
// The reconciliation is this module: an in-memory `BTreeMap` MIRROR of the whole
// key space, hydrated ONCE from the backend inside the already-async wasm entry
// point (`lib.rs::start`) BEFORE the app is constructed. Because hydration
// completes before the first `read` can happen, a synchronous read never has a
// "not loaded yet" state to represent, and none of the ~55 call sites change.
// Writes mutate the mirror synchronously (so the very next `read` sees them) and
// are pushed to the backend WRITE-BEHIND; a push that fails afterwards surfaces
// through [`ModelStore::take_persistence_errors`].
#[cfg(any(target_arch = "wasm32", test))]
pub(crate) mod mirror_store {
    use super::{
        model_display_name, BrowserEntry, BrowserPlace, ModelStore, PlaceKind, DOCK_LAYOUT_KEY,
        MODEL_EXT, PINNED_KEY, SESSION_KEY, SETTINGS_KEY,
    };
    use std::cell::{Cell, RefCell};
    use std::collections::BTreeMap;
    use std::future::Future;
    use std::pin::Pin;
    use std::rc::Rc;

    /// The persisted key scheme, VERBATIM from the `localStorage` era so an
    /// existing origin's keys keep their meaning under any backend: model
    /// documents live at `brep-app:model:<relative name>`, explorer folders at
    /// `brep-app:dir:<relative path>/`, and the three reserved application blobs
    /// at `brep-app:settings` / `:dock_layout` / `:pinned` (see [`MirrorStore::key`]).
    pub(crate) const PREFIX: &str = "brep-app:model:";
    pub(crate) const DIR_PREFIX: &str = "brep-app:dir:";

    /// How many distinct persistence failures the error log keeps before the
    /// oldest is dropped. The log is a user-facing notice channel, not telemetry.
    const MAX_ERRORS: usize = 64;

    /// The future a [`StoreBackend`] hands back. Boxed (not `async fn` in the
    /// trait) because the store is used as `dyn StoreBackend`, and deliberately
    /// NOT `Send`: every host is single-threaded (the browser main thread; the
    /// native test executor below).
    pub(crate) type BackendFuture<T> = Pin<Box<dyn Future<Output = Result<T, String>>>>;

    /// Where a [`MirrorStore`]'s bytes actually live — the swappable persistence
    /// seam.
    ///
    /// The contract is deliberately narrow and platform-free: **string keys,
    /// string values, `String` errors, async everywhere**. No `JsValue`, no
    /// `web_sys` type, no IndexedDB concept crosses it, and the mirror above it
    /// knows nothing about how a key is stored. [`IdbBackend`](super::web_model)
    /// is the only implementation today; the intended SECOND one is a remote
    /// HTTP/AJAX backend that pushes and pulls the same key space to a central
    /// server, and it must be able to land without touching this module.
    ///
    /// Two obligations an implementation carries:
    ///
    /// * **Per-key FIFO.** Two `put`s of the same key must land in call order,
    ///   whatever order their futures are polled in — the mirror issues them from
    ///   a synchronous `write` and never sequences them itself. IndexedDB gets
    ///   this for free (a `readwrite` transaction commits in creation order, and
    ///   [`IdbBackend`](super::web_model) creates the transaction and issues the
    ///   request synchronously inside `put`). An HTTP backend has no such
    ///   guarantee and will need its own per-key send queue.
    /// * **Whole-key-space `load_all`.** Hydration is all-or-nothing today.
    ///
    /// ## The known ceiling (stated, not solved)
    ///
    /// A full hydrate holds EVERY saved document resident for the session. That
    /// is a non-issue for an origin migrating off `localStorage` (its whole
    /// corpus fit in ~5 MB), but a user with ten 30 MB assemblies pays ~300 MB at
    /// boot, and a remote backend makes it untenable outright — you cannot pull a
    /// server-side library of hundreds of parts at start-up. The escape hatch,
    /// when it is needed: make the mirror's value a `{ Resident(String), OnDisk {
    /// bytes: u64 } }` enum so `list` / `browser_entries` / sizes still answer
    /// from metadata alone, add a prefetch that resolves `OnDisk` entries in the
    /// background, and give `StoreBackend` a `load_index` + `get(key)` pair
    /// beside `load_all`. All of that sits behind THIS trait and behind
    /// [`ModelStore`], so no call site moves. **Do not build it until a real
    /// corpus needs it.**
    pub(crate) trait StoreBackend {
        /// A short human label for the storage panel header (see
        /// [`ModelStore::backend_label`]).
        fn label(&self) -> String;

        /// Pull the entire key space. Called ONCE, during the async boot, before
        /// any [`MirrorStore`] exists.
        fn load_all(&self) -> BackendFuture<Vec<(String, String)>>;

        /// Persist `value` under `key`, creating or overwriting.
        fn put(&self, key: &str, value: &str) -> BackendFuture<()>;

        /// Delete `key`. Succeeding on an absent key is correct.
        fn delete(&self, key: &str) -> BackendFuture<()>;
    }

    /// The backend installed when persistence could NOT be brought up (IndexedDB
    /// blocked in a private window, storage denied, the boot hydrate never ran).
    ///
    /// There is deliberately no quiet fallback to `localStorage`: a 5 MB backend
    /// silently standing in for a hundreds-of-megabytes one is the failure mode
    /// this whole change exists to end. Instead the session stays fully usable
    /// IN MEMORY — the mirror still holds everything written this session — while
    /// every write reports, loudly and repeatedly, that nothing is being saved.
    pub(crate) struct UnavailableBackend {
        reason: String,
    }

    impl UnavailableBackend {
        pub(crate) fn new(reason: impl Into<String>) -> Self {
            Self {
                reason: reason.into(),
            }
        }
    }

    impl StoreBackend for UnavailableBackend {
        fn label(&self) -> String {
            format!("NOT SAVING — {} · use Download to keep your work", self.reason)
        }

        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
            let reason = self.reason.clone();
            Box::pin(async move { Err(reason) })
        }

        fn put(&self, _key: &str, _value: &str) -> BackendFuture<()> {
            let reason = self.reason.clone();
            Box::pin(async move { Err(reason) })
        }

        fn delete(&self, _key: &str) -> BackendFuture<()> {
            let reason = self.reason.clone();
            Box::pin(async move { Err(reason) })
        }
    }

    /// Persistence failures that happened AFTER the synchronous `write` returned
    /// `Ok` — the price of write-behind. Nothing is lost mid-session (the mirror
    /// holds it), but the user MUST learn that it did not persist, so the log is
    /// drained into the toast overlay every frame.
    ///
    /// The cursor (rather than a `Vec::drain`) keeps the full history addressable
    /// for the `__brepStoreErrors` verification hook while still handing the UI
    /// each message exactly once.
    pub(crate) struct ErrorLog {
        log: RefCell<Vec<String>>,
        drained: Cell<usize>,
        /// Wakes the reactive frame loop so a failure recorded from an async
        /// callback is toasted THIS frame instead of waiting for stray input.
        wake: Option<Rc<dyn Fn()>>,
    }

    impl ErrorLog {
        fn new(wake: Option<Rc<dyn Fn()>>) -> Self {
            Self {
                log: RefCell::new(Vec::new()),
                drained: Cell::new(0),
                wake,
            }
        }

        /// Record one failure. An identical message that is still UNDRAINED is
        /// collapsed (a burst of failing writes shows one toast, not six); once
        /// the UI has shown it, the same message can be recorded again — every
        /// failed save is reported.
        pub(crate) fn record(&self, message: String) {
            {
                let mut log = self.log.borrow_mut();
                let undrained = log.len() > self.drained.get();
                if undrained && log.last().map(|last| *last == message).unwrap_or(false) {
                    return;
                }
                log.push(message);
                if log.len() > MAX_ERRORS {
                    log.remove(0);
                    self.drained.set(self.drained.get().saturating_sub(1));
                }
            }
            if let Some(wake) = &self.wake {
                wake();
            }
        }

        /// Messages recorded since the last drain (what the UI has not shown yet).
        fn drain(&self) -> Vec<String> {
            let log = self.log.borrow();
            let from = self.drained.get().min(log.len());
            self.drained.set(log.len());
            log[from..].to_vec()
        }

        /// Every message recorded this session (verification hook).
        fn all(&self) -> Vec<String> {
            self.log.borrow().clone()
        }
    }

    /// Drive one write-behind push to completion.
    ///
    /// wasm: hand it to the browser's microtask queue, which is the whole point —
    /// the caller's `write` already returned. Native: the mirror only exists under
    /// `cfg(test)`, where the test backend's futures are already resolved, so a
    /// single poll with a no-op waker finishes them. Keeping the shape identical
    /// means the native tests exercise the REAL write-behind path (spawn, await,
    /// record the error) rather than a synchronous stand-in.
    #[cfg(target_arch = "wasm32")]
    fn spawn(task: impl Future<Output = ()> + 'static) {
        wasm_bindgen_futures::spawn_local(task);
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn spawn(task: impl Future<Output = ()> + 'static) {
        let mut task = Box::pin(task);
        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
        let _ = task.as_mut().poll(&mut cx);
    }

    /// A synchronous [`ModelStore`] over an asynchronous [`StoreBackend`]: the
    /// hydrated mirror plus write-behind. Cheap to clone — every field is shared,
    /// so a clone is another handle on the SAME session state (used by the
    /// verification hooks).
    #[derive(Clone)]
    pub(crate) struct MirrorStore {
        /// The whole key space, keyed EXACTLY as the backend keys it.
        entries: Rc<RefCell<BTreeMap<String, String>>>,
        /// The explorer's current virtual directory (`/` or `/models/...`).
        browser_dir: Rc<RefCell<String>>,
        backend: Rc<dyn StoreBackend>,
        errors: Rc<ErrorLog>,
        /// Pushes issued but not yet settled. Zero means everything written so
        /// far is durable — which is what makes a "save, reload, still there"
        /// check non-racy (see the `__brepStorePending` hook).
        pending: Rc<Cell<usize>>,
    }

    impl MirrorStore {
        /// Build the session store from an already-hydrated key space.
        /// `wake` (`None` off-browser) is called when a write-behind failure is
        /// recorded, to repaint the reactive frame loop.
        pub(crate) fn new(
            backend: Rc<dyn StoreBackend>,
            entries: Vec<(String, String)>,
            wake: Option<Rc<dyn Fn()>>,
        ) -> Self {
            Self {
                entries: Rc::new(RefCell::new(entries.into_iter().collect())),
                browser_dir: Rc::new(RefCell::new("/models".into())),
                backend,
                errors: Rc::new(ErrorLog::new(wake)),
                pending: Rc::new(Cell::new(0)),
            }
        }

        /// The persisted key for a document/reserved name. UNCHANGED from the
        /// `localStorage` implementation this replaced, so an existing origin's
        /// data keeps its identity.
        pub(crate) fn key(name: &str) -> String {
            match name {
                SETTINGS_KEY => "brep-app:settings".into(),
                DOCK_LAYOUT_KEY => "brep-app:dock_layout".into(),
                SESSION_KEY => "brep-app:session".into(),
                PINNED_KEY => "brep-app:pinned".into(),
                _ => format!("{PREFIX}{}", Self::model_relative(name)),
            }
        }

        /// A document name reduced to its store-relative form: no leading `/`, no
        /// `/models` root, no model extension.
        fn model_relative(name: &str) -> String {
            let name = name
                .trim_start_matches('/')
                .strip_prefix("models/")
                .unwrap_or_else(|| name.trim_start_matches('/'));
            name.strip_suffix(MODEL_EXT)
                .or_else(|| name.strip_suffix(".json"))
                .unwrap_or(name)
                .trim_matches('/')
                .to_string()
        }

        fn virtual_model_path(relative: &str) -> String {
            format!("/models/{}{MODEL_EXT}", relative.trim_matches('/'))
        }

        fn child_path(parent: &str, child: &str) -> String {
            if parent == "/" {
                format!("/{child}")
            } else {
                format!("{}/{child}", parent.trim_end_matches('/'))
            }
        }

        /// Hand one backend push to the executor, counting it in `pending` and
        /// routing its eventual failure to the error log.
        fn push(&self, name: &str, request: BackendFuture<()>) {
            self.pending.set(self.pending.get() + 1);
            let pending = self.pending.clone();
            let errors = self.errors.clone();
            let name = name.to_string();
            spawn(async move {
                let outcome = request.await;
                pending.set(pending.get().saturating_sub(1));
                if let Err(message) = outcome {
                    errors.record(format!("'{name}' was NOT saved: {message}"));
                }
            });
        }

        /// Seed the log with a boot-time failure so the very first frame toasts it.
        pub(crate) fn report(&self, message: String) {
            self.errors.record(message);
        }

        /// Backend pushes issued but not yet settled (verification hook).
        pub(crate) fn pending(&self) -> usize {
            self.pending.get()
        }

        /// Every persistence failure this session (verification hook).
        pub(crate) fn error_history(&self) -> Vec<String> {
            self.errors.all()
        }

        /// Byte length of a stored document, or `None` if absent (verification
        /// hook — a multi-megabyte payload is not worth marshalling into JS just
        /// to measure it).
        pub(crate) fn len_of(&self, name: &str) -> Option<usize> {
            self.entries.borrow().get(&Self::key(name)).map(|v| v.len())
        }
    }

    impl ModelStore for MirrorStore {
        fn backend_label(&self) -> String {
            self.backend.label()
        }

        fn list(&self) -> Vec<String> {
            // `BTreeMap` iterates in key order, so the names come out sorted.
            self.entries
                .borrow()
                .keys()
                .filter_map(|key| key.strip_prefix(PREFIX).map(str::to_string))
                .collect()
        }

        fn read(&self, name: &str) -> Option<String> {
            self.entries.borrow().get(&Self::key(name)).cloned()
        }

        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
            let key = Self::key(name);
            self.entries
                .borrow_mut()
                .insert(key.clone(), contents.to_string());
            // The mirror is authoritative for this session, so `Ok` is honest:
            // every subsequent read sees the new bytes. Durability is the
            // backend's job and its failure arrives via `take_persistence_errors`.
            self.push(name, self.backend.put(&key, contents));
            Ok(())
        }

        fn remove(&self, name: &str) -> Result<(), String> {
            let key = Self::key(name);
            self.entries.borrow_mut().remove(&key);
            self.push(name, self.backend.delete(&key));
            Ok(())
        }

        fn take_persistence_errors(&self) -> Vec<String> {
            self.errors.drain()
        }

        fn browser_location(&self) -> String {
            // The RAW navigable path (breadcrumb / back-forward / path-edit rely on
            // this being feed-able straight back to `browser_navigate`); the human
            // "virtual filesystem" context lives in `backend_label`.
            self.browser_dir.borrow().clone()
        }

        fn browser_entries(&self, extensions: &[&str]) -> Vec<BrowserEntry> {
            let current = self.browser_dir.borrow().clone();
            if current == "/" {
                return vec![BrowserEntry {
                    name: "models".into(),
                    identity: "/models".into(),
                    is_dir: true,
                    size: None,
                    modified: None,
                }];
            }
            let relative_dir = current
                .strip_prefix("/models")
                .unwrap_or("")
                .trim_matches('/');
            let prefix = if relative_dir.is_empty() {
                String::new()
            } else {
                format!("{relative_dir}/")
            };
            let wanted: Vec<String> = extensions
                .iter()
                .map(|extension| extension.trim_start_matches('.').to_ascii_lowercase())
                .collect();
            let mut entries: BTreeMap<String, BrowserEntry> = BTreeMap::new();
            for (key, value) in self.entries.borrow().iter() {
                let (item, is_model) = if let Some(item) = key.strip_prefix(PREFIX) {
                    (item, true)
                } else if let Some(item) = key.strip_prefix(DIR_PREFIX) {
                    (item.trim_end_matches('/'), false)
                } else {
                    continue;
                };
                let Some(rest) = item.strip_prefix(&prefix) else {
                    continue;
                };
                if rest.is_empty() {
                    continue;
                }
                if let Some((child, _)) = rest.split_once('/') {
                    entries
                        .entry(child.to_string())
                        .or_insert_with(|| BrowserEntry {
                            name: child.to_string(),
                            identity: Self::child_path(&current, child),
                            is_dir: true,
                            size: None,
                            modified: None,
                        });
                } else if is_model {
                    let name = format!("{rest}{MODEL_EXT}");
                    let lower = name.to_ascii_lowercase();
                    if wanted.is_empty()
                        || wanted
                            .iter()
                            .any(|extension| lower.ends_with(&format!(".{extension}")))
                    {
                        // Size = the mirrored JSON's byte length. `modified` stays
                        // None: the key space carries values, not timestamps.
                        entries.insert(
                            name.clone(),
                            BrowserEntry {
                                name,
                                identity: Self::virtual_model_path(item),
                                is_dir: false,
                                size: Some(value.len() as u64),
                                modified: None,
                            },
                        );
                    }
                } else {
                    entries
                        .entry(rest.to_string())
                        .or_insert_with(|| BrowserEntry {
                            name: rest.to_string(),
                            identity: Self::child_path(&current, rest),
                            is_dir: true,
                            size: None,
                            modified: None,
                        });
                }
            }
            let mut entries: Vec<_> = entries.into_values().collect();
            entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then_with(|| a.name.cmp(&b.name)));
            entries
        }

        fn browser_enter(&self, identity: &str) -> Result<(), String> {
            if identity == "/models" || identity.starts_with("/models/") {
                *self.browser_dir.borrow_mut() = identity.trim_end_matches('/').to_string();
                Ok(())
            } else {
                Err("the browser virtual filesystem is rooted at /models".into())
            }
        }

        fn browser_up(&self) -> Result<(), String> {
            let current = self.browser_dir.borrow().clone();
            if current == "/" {
                return Ok(());
            }
            let parent = current
                .rsplit_once('/')
                .map(|(parent, _)| parent)
                .unwrap_or("");
            *self.browser_dir.borrow_mut() = if parent.is_empty() {
                "/".into()
            } else {
                parent.into()
            };
            Ok(())
        }

        fn browser_home(&self) -> Result<(), String> {
            *self.browser_dir.borrow_mut() = "/models".into();
            Ok(())
        }

        fn browser_root(&self) -> Result<(), String> {
            *self.browser_dir.borrow_mut() = "/".into();
            Ok(())
        }

        fn browser_navigate(&self, location: &str) -> Result<(), String> {
            let loc = location.trim_end_matches('/');
            let loc = if loc.is_empty() { "/" } else { loc };
            if loc == "/" || loc == "/models" || loc.starts_with("/models/") {
                *self.browser_dir.borrow_mut() = loc.to_string();
                Ok(())
            } else {
                Err("the browser virtual filesystem is rooted at /models".into())
            }
        }

        fn browser_places(&self) -> Vec<BrowserPlace> {
            vec![
                BrowserPlace {
                    label: "Models".into(),
                    location: "/models".into(),
                    kind: PlaceKind::Models,
                },
                BrowserPlace {
                    label: "/".into(),
                    location: "/".into(),
                    kind: PlaceKind::Root,
                },
            ]
        }

        fn browser_create_dir(&self, name: &str) -> Result<(), String> {
            if name.is_empty()
                || name == "."
                || name == ".."
                || name.contains('/')
                || name.contains('\\')
            {
                return Err("folder name must be one path component".into());
            }
            let current = self.browser_dir.borrow().clone();
            if !current.starts_with("/models") {
                return Err("folders can only be created under /models".into());
            }
            let relative = Self::child_path(&current, name)
                .trim_start_matches("/models/")
                .to_string();
            // A folder is a zero-length marker key; the explorer derives the tree
            // from the key prefixes alone.
            let key = format!("{DIR_PREFIX}{relative}/");
            self.entries.borrow_mut().insert(key.clone(), String::new());
            self.push(name, self.backend.put(&key, ""));
            Ok(())
        }

        fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
            let file = model_display_name(name);
            if file.is_empty() {
                return Err("invalid file name".into());
            }
            let current = self.browser_dir.borrow().clone();
            if !current.starts_with("/models") {
                return Err("select a folder under /models".into());
            }
            let identity = format!("{}{MODEL_EXT}", Self::child_path(&current, &file));
            self.write(&identity, contents)?;
            Ok(identity)
        }
    }
}

// --- Browser: IndexedDB documents + download / upload interchange --------------
#[cfg(target_arch = "wasm32")]
mod web_model {
    use super::mirror_store::{BackendFuture, MirrorStore, StoreBackend, UnavailableBackend};
    use super::{
        model_display_name, BrowserEntry, BrowserPlace, ImportedFile, ModelStore, MODEL_EXT,
    };
    use std::cell::RefCell;
    use std::future::Future;
    use std::pin::Pin;
    use std::rc::Rc;
    use std::task::{Context, Poll, Waker};
    use wasm_bindgen::prelude::*;
    use wasm_bindgen::JsCast;

    // The origin-private persistent store on the web is **IndexedDB**. It replaced
    // `localStorage`, whose ~5-10 MB per-origin quota cannot hold a single native
    // BREP payload (a measured STEP import: ~35 MB), and it is the only browser
    // store that is both large and enumerable without a permission gesture (unlike
    // the File System Access API, which fails headless). Its API is ASYNC, hence
    // the mirror in [`mirror_store`](super::mirror_store); the key scheme is the
    // localStorage one, byte for byte. **Download + upload** below still bridge to
    // the user's REAL filesystem for portability.
    const DB_NAME: &str = "brep-app";
    const DB_VERSION: u32 = 1;
    /// The single key/value object store; keys are the `brep-app:*` strings.
    const STORE_NAME: &str = "kv";

    thread_local! {
        /// The single hidden `<input type=file>`, created once and reused.
        static IMPORT_INPUT: RefCell<Option<web_sys::HtmlInputElement>> = const { RefCell::new(None) };
        /// The most recent completed upload, awaiting the panel's poll.
        static IMPORTED: RefCell<Option<ImportedFile>> = const { RefCell::new(None) };
        /// The egui context, so an ASYNC callback (a `FileReader` load, a failed
        /// IndexedDB write) can wake the reactive eframe loop (the app only
        /// repaints on input events + explicit requests). Without it a completed
        /// upload — or a "your model did not save" notice — sits unshown until the
        /// user happens to move the mouse. Seeded once at boot via [`set_repaint_ctx`].
        static REPAINT_CTX: RefCell<Option<eframe::egui::Context>> = const { RefCell::new(None) };
        /// The store built by [`hydrate`] inside the async wasm entry point,
        /// waiting for `BrepApp::new` to pick it up through
        /// [`default_model_store`](super::default_model_store). The hand-off is a
        /// thread-local rather than a closure capture so the app constructor keeps
        /// its platform-free signature.
        static BOOT_STORE: RefCell<Option<IdbModelStore>> = const { RefCell::new(None) };
    }

    /// Register the egui context used to wake the frame loop when an async browser
    /// upload — or a write-behind persistence failure — completes. Called once from
    /// the app shell at construction.
    pub fn set_repaint_ctx(ctx: eframe::egui::Context) {
        REPAINT_CTX.with(|c| *c.borrow_mut() = Some(ctx));
    }

    /// Ask the reactive frame loop for a repaint. Reads `REPAINT_CTX` at CALL time,
    /// so it does not matter that the store is built (during boot) before the app
    /// shell registers the context.
    fn wake_frame_loop() {
        REPAINT_CTX.with(|c| {
            if let Some(ctx) = c.borrow().as_ref() {
                ctx.request_repaint();
            }
        });
    }

    // --- IndexedDB request/transaction -> Future ----------------------------------
    // Hand-rolled rather than pulling `indexed_db_futures`: this crate deliberately
    // keeps its wasm dependency tree thin (see the `ehttp` note in Cargo.toml about
    // the `getrandom` dep-tree problem), and the whole adapter is the ~60 lines
    // below. It owns its `Closure`s — dropping the future clears the handlers — so
    // a session of saves does not leak a pair of JS closures per write, which a
    // `Closure::forget()` sketch would.

    #[derive(Default)]
    struct Settled {
        outcome: Option<Result<JsValue, String>>,
        waker: Option<Waker>,
    }

    /// Which DOM event pair the future is listening to. Kept so `Drop` can detach
    /// the handlers (and with them the Rust closures' reference back to the target).
    enum EventSource {
        Request(web_sys::IdbRequest),
        Transaction(web_sys::IdbTransaction),
    }

    /// One IndexedDB completion, as a `Future`.
    struct IdbFuture {
        source: EventSource,
        settled: Rc<RefCell<Settled>>,
        /// Owned so the closures live exactly as long as the future.
        _handlers: Vec<Closure<dyn FnMut(web_sys::Event)>>,
    }

    fn settle(settled: &Rc<RefCell<Settled>>, outcome: Result<JsValue, String>) {
        let waker = {
            let mut settled = settled.borrow_mut();
            if settled.outcome.is_none() {
                settled.outcome = Some(outcome);
            }
            settled.waker.take()
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    }

    fn request_error(request: &web_sys::IdbRequest) -> String {
        request
            .error()
            .ok()
            .flatten()
            .map(|error| format!("{}: {}", error.name(), error.message()))
            .unwrap_or_else(|| "IndexedDB request failed".into())
    }

    fn js_error(value: &JsValue) -> String {
        value
            .as_string()
            .or_else(|| js_sys::Reflect::get(value, &JsValue::from_str("message")).ok()?.as_string())
            .unwrap_or_else(|| format!("{value:?}"))
    }

    /// Resolve when `request` succeeds, with its `result`.
    fn on_request(request: web_sys::IdbRequest) -> IdbFuture {
        let settled = Rc::new(RefCell::new(Settled::default()));
        let success = {
            let settled = settled.clone();
            let request = request.clone();
            Closure::wrap(Box::new(move |_event: web_sys::Event| {
                let value = request.result().unwrap_or(JsValue::UNDEFINED);
                settle(&settled, Ok(value));
            }) as Box<dyn FnMut(web_sys::Event)>)
        };
        let failure = {
            let settled = settled.clone();
            let request = request.clone();
            Closure::wrap(Box::new(move |_event: web_sys::Event| {
                settle(&settled, Err(request_error(&request)));
            }) as Box<dyn FnMut(web_sys::Event)>)
        };
        request.set_onsuccess(Some(success.as_ref().unchecked_ref()));
        request.set_onerror(Some(failure.as_ref().unchecked_ref()));
        IdbFuture {
            source: EventSource::Request(request),
            settled,
            _handlers: vec![success, failure],
        }
    }

    /// Resolve when `transaction` COMMITS.
    ///
    /// A write must be awaited here, not on the `put` request's `onsuccess`: the
    /// request succeeds before the transaction commits, and a page reload can abort
    /// an uncommitted `readwrite` transaction. For a multi-megabyte payload that
    /// window is real, and "the save is durable" is exactly the claim the pending
    /// counter and the reload test rest on.
    fn on_transaction(transaction: web_sys::IdbTransaction) -> IdbFuture {
        let settled = Rc::new(RefCell::new(Settled::default()));
        let complete = {
            let settled = settled.clone();
            Closure::wrap(Box::new(move |_event: web_sys::Event| {
                settle(&settled, Ok(JsValue::UNDEFINED));
            }) as Box<dyn FnMut(web_sys::Event)>)
        };
        let describe = {
            let transaction = transaction.clone();
            move |fallback: &str| {
                transaction
                    .error()
                    .map(|error| format!("{}: {}", error.name(), error.message()))
                    .unwrap_or_else(|| fallback.to_string())
            }
        };
        let failure = {
            let settled = settled.clone();
            let describe = describe.clone();
            Closure::wrap(Box::new(move |_event: web_sys::Event| {
                settle(&settled, Err(describe("IndexedDB transaction failed")));
            }) as Box<dyn FnMut(web_sys::Event)>)
        };
        let abort = {
            let settled = settled.clone();
            Closure::wrap(Box::new(move |_event: web_sys::Event| {
                settle(
                    &settled,
                    Err(describe("IndexedDB transaction aborted (quota?)")),
                );
            }) as Box<dyn FnMut(web_sys::Event)>)
        };
        transaction.set_oncomplete(Some(complete.as_ref().unchecked_ref()));
        transaction.set_onerror(Some(failure.as_ref().unchecked_ref()));
        transaction.set_onabort(Some(abort.as_ref().unchecked_ref()));
        IdbFuture {
            source: EventSource::Transaction(transaction),
            settled,
            _handlers: vec![complete, failure, abort],
        }
    }

    impl Future for IdbFuture {
        type Output = Result<JsValue, String>;

        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            let mut settled = self.settled.borrow_mut();
            if let Some(outcome) = settled.outcome.take() {
                return Poll::Ready(outcome);
            }
            settled.waker = Some(cx.waker().clone());
            Poll::Pending
        }
    }

    impl Drop for IdbFuture {
        fn drop(&mut self) {
            // Detach the handlers, breaking the target -> closure -> target cycle
            // so the closures we own are actually freed.
            match &self.source {
                EventSource::Request(request) => {
                    request.set_onsuccess(None);
                    request.set_onerror(None);
                }
                EventSource::Transaction(transaction) => {
                    transaction.set_oncomplete(None);
                    transaction.set_onerror(None);
                    transaction.set_onabort(None);
                }
            }
        }
    }

    // --- the IndexedDB backend -----------------------------------------------------

    /// [`StoreBackend`] over one IndexedDB object store. The ONLY place in the
    /// crate that knows what IndexedDB is.
    pub(super) struct IdbBackend {
        db: web_sys::IdbDatabase,
    }

    impl IdbBackend {
        /// Open (creating on first use) the application database. `Err` on any
        /// browser that blocks storage — private windows, "block all cookies"
        /// setups — which the caller turns into a loud, non-persisting session.
        async fn open() -> Result<Self, String> {
            let factory = web_sys::window()
                .ok_or("no window")?
                .indexed_db()
                .map_err(|e| js_error(&e))?
                .ok_or("no indexedDB on this window")?;
            let request = factory
                .open_with_u32(DB_NAME, DB_VERSION)
                .map_err(|e| js_error(&e))?;

            // Create the object store on first open / version bump. The request is
            // captured directly (rather than read off the event target) so no
            // `EventTarget` binding is needed.
            let upgrading = request.clone();
            let upgrade = Closure::wrap(Box::new(move |_event: web_sys::Event| {
                if let Ok(value) = upgrading.result() {
                    if let Ok(db) = value.dyn_into::<web_sys::IdbDatabase>() {
                        // Errors here mean the store already exists — harmless.
                        let _ = db.create_object_store(STORE_NAME);
                    }
                }
            }) as Box<dyn FnMut(web_sys::Event)>);
            request.set_onupgradeneeded(Some(upgrade.as_ref().unchecked_ref()));

            let opened = on_request(request.clone().unchecked_into::<web_sys::IdbRequest>()).await;
            request.set_onupgradeneeded(None);
            drop(upgrade);

            let db = opened?
                .dyn_into::<web_sys::IdbDatabase>()
                .map_err(|_| "IndexedDB open returned no database".to_string())?;
            Ok(Self { db })
        }

        /// Start a transaction and reach its object store. The transaction handle
        /// is returned so a write can await its COMMIT.
        fn transact(
            &self,
            mode: web_sys::IdbTransactionMode,
        ) -> Result<(web_sys::IdbTransaction, web_sys::IdbObjectStore), String> {
            let transaction = self
                .db
                .transaction_with_str_and_mode(STORE_NAME, mode)
                .map_err(|e| js_error(&e))?;
            let store = transaction.object_store(STORE_NAME).map_err(|e| js_error(&e))?;
            Ok((transaction, store))
        }
    }

    impl StoreBackend for IdbBackend {
        fn label(&self) -> String {
            "browser storage (IndexedDB) · download/upload for files".into()
        }

        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
            // Two whole-store requests in ONE readonly transaction rather than a
            // cursor: `getAllKeys` and `getAll` both come back in key order, so
            // zipping them reconstructs the key space in one round trip each.
            let started = (|| -> Result<(IdbFuture, IdbFuture), String> {
                let (_transaction, store) = self.transact(web_sys::IdbTransactionMode::Readonly)?;
                let keys = store.get_all_keys().map_err(|e| js_error(&e))?;
                let values = store.get_all().map_err(|e| js_error(&e))?;
                Ok((on_request(keys), on_request(values)))
            })();
            Box::pin(async move {
                let (keys, values) = started?;
                let keys = js_sys::Array::from(&keys.await?);
                let values = js_sys::Array::from(&values.await?);
                if keys.length() != values.length() {
                    return Err("IndexedDB returned mismatched keys and values".into());
                }
                let mut entries = Vec::with_capacity(keys.length() as usize);
                for i in 0..keys.length() {
                    let (Some(key), Some(value)) =
                        (keys.get(i).as_string(), values.get(i).as_string())
                    else {
                        // A non-string entry is not ours; skipping it is safer than
                        // failing the whole hydrate.
                        continue;
                    };
                    entries.push((key, value));
                }
                Ok(entries)
            })
        }

        fn put(&self, key: &str, value: &str) -> BackendFuture<()> {
            // The transaction is created and the request issued SYNCHRONOUSLY, so
            // two writes of the same key commit in call order (IndexedDB commits
            // `readwrite` transactions in creation order) no matter how the futures
            // are later polled — the per-key FIFO obligation in `StoreBackend`.
            let started = (|| -> Result<IdbFuture, String> {
                let (transaction, store) =
                    self.transact(web_sys::IdbTransactionMode::Readwrite)?;
                store
                    .put_with_key(&JsValue::from_str(value), &JsValue::from_str(key))
                    .map_err(|e| js_error(&e))?;
                Ok(on_transaction(transaction))
            })();
            Box::pin(async move {
                started?.await?;
                Ok(())
            })
        }

        fn delete(&self, key: &str) -> BackendFuture<()> {
            let started = (|| -> Result<IdbFuture, String> {
                let (transaction, store) =
                    self.transact(web_sys::IdbTransactionMode::Readwrite)?;
                store
                    .delete(&JsValue::from_str(key))
                    .map_err(|e| js_error(&e))?;
                Ok(on_transaction(transaction))
            })();
            Box::pin(async move {
                started?.await?;
                Ok(())
            })
        }
    }

    // --- boot ----------------------------------------------------------------------

    /// Bring up browser persistence and hydrate the whole key space into memory.
    ///
    /// Called from the async wasm entry point BEFORE `eframe::WebRunner::start`, so
    /// by the time any synchronous [`ModelStore::read`] can run, the mirror is
    /// complete — that ordering is the entire reason the trait stays synchronous.
    ///
    /// On failure there is NO quiet fallback: the session gets an
    /// [`UnavailableBackend`], which keeps the app usable in memory while saying so
    /// in the panel header and toasting every write that does not persist.
    pub(super) async fn hydrate() {
        let wake: Rc<dyn Fn()> = Rc::new(wake_frame_loop);
        let core = match IdbBackend::open().await {
            Ok(backend) => {
                let backend: Rc<dyn StoreBackend> = Rc::new(backend);
                match backend.load_all().await {
                    Ok(entries) => MirrorStore::new(backend, entries, Some(wake)),
                    // The database opened but would not read. Writing against a
                    // half-known key space could overwrite documents the mirror
                    // never saw, so treat it as unavailable rather than risk that.
                    Err(message) => unavailable(
                        format!("IndexedDB could not be read ({message})"),
                        Some(wake),
                    ),
                }
            }
            Err(message) => unavailable(format!("IndexedDB unavailable ({message})"), Some(wake)),
        };
        install_verification_hooks(&core);
        BOOT_STORE.with(|c| *c.borrow_mut() = Some(IdbModelStore { core }));
    }

    /// A session with no persistence: empty, in-memory, and loud about it.
    fn unavailable(reason: String, wake: Option<Rc<dyn Fn()>>) -> MirrorStore {
        let core = MirrorStore::new(
            Rc::new(UnavailableBackend::new(reason.clone())),
            Vec::new(),
            wake,
        );
        // Seed the notice channel so the FIRST frame tells the user, before they
        // have saved anything and discovered it the hard way.
        core.report(format!(
            "{reason} — this session will not be saved; use Download to keep your work"
        ));
        core
    }

    /// Hand the hydrated store to `BrepApp::new`. If boot never ran (no code path
    /// does that today), the app still starts — non-persisting and saying so.
    pub(super) fn take_boot_store() -> Box<dyn ModelStore> {
        let store = BOOT_STORE.with(|c| c.borrow_mut().take()).unwrap_or_else(|| {
            let wake: Rc<dyn Fn()> = Rc::new(wake_frame_loop);
            IdbModelStore {
                core: unavailable("storage was never initialised".into(), Some(wake)),
            }
        });
        Box::new(store)
    }

    // --- verification hooks ---------------------------------------------------------

    /// Publish `window.__brepStore*` handles onto the LIVE store, in the same
    /// spirit as the app shell's `__brep*` state globals: the headed verifier needs
    /// to write a payload far larger than any UI gesture can type, then prove it
    /// survived a reload. `__brepStorePending` is what makes that check non-racy —
    /// it reaches zero only once the backing transaction has COMMITTED.
    /// `__brepStoreRead` is the read side of the same seam: a script that saves
    /// through the UI has to be able to look at what landed.
    fn install_verification_hooks(core: &MirrorStore) {
        let Some(window) = web_sys::window() else {
            return;
        };
        let publish = |name: &str, value: &JsValue| {
            let _ = js_sys::Reflect::set(&window, &JsValue::from_str(name), value);
        };

        let store = core.clone();
        let write = Closure::wrap(Box::new(move |name: String, contents: String| -> JsValue {
            match store.write(&name, &contents) {
                Ok(()) => JsValue::NULL,
                Err(message) => JsValue::from_str(&message),
            }
        }) as Box<dyn FnMut(String, String) -> JsValue>);
        publish("__brepStoreWrite", write.as_ref());
        write.forget();

        let store = core.clone();
        let len = Closure::wrap(Box::new(move |name: String| -> f64 {
            store.len_of(&name).map(|n| n as f64).unwrap_or(-1.0)
        }) as Box<dyn FnMut(String) -> f64>);
        publish("__brepStoreLen", len.as_ref());
        len.forget();

        // The READ sibling of `__brepStoreWrite`. Without it a headed script can
        // only prove a save happened, not WHAT was saved: the assemblies sweep
        // used to read the document straight out of `localStorage`, which the
        // IndexedDB migration silently emptied.
        let store = core.clone();
        let read = Closure::wrap(Box::new(move |name: String| -> JsValue {
            match store.read(&name) {
                Some(contents) => JsValue::from_str(&contents),
                None => JsValue::NULL,
            }
        }) as Box<dyn FnMut(String) -> JsValue>);
        publish("__brepStoreRead", read.as_ref());
        read.forget();

        let store = core.clone();
        let list = Closure::wrap(Box::new(move || -> JsValue {
            JsValue::from_str(&serde_json::to_string(&store.list()).unwrap_or_default())
        }) as Box<dyn FnMut() -> JsValue>);
        publish("__brepStoreList", list.as_ref());
        list.forget();

        let store = core.clone();
        let errors = Closure::wrap(Box::new(move || -> JsValue {
            JsValue::from_str(&serde_json::to_string(&store.error_history()).unwrap_or_default())
        }) as Box<dyn FnMut() -> JsValue>);
        publish("__brepStoreErrors", errors.as_ref());
        errors.forget();

        let store = core.clone();
        let pending = Closure::wrap(Box::new(move || -> f64 { store.pending() as f64 })
            as Box<dyn FnMut() -> f64>);
        publish("__brepStorePending", pending.as_ref());
        pending.forget();
    }

    // --- real-file interchange (download / upload) ----------------------------------
    // Free functions, not methods: they are pure browser plumbing with no store
    // state, and keeping them out of the store type leaves `IdbModelStore` as a
    // thin seam between the mirror and this lane.

    /// Lazily create the reusable hidden file input, wiring its `change` handler
    /// (which reads the chosen file and stashes it for `take_import`). `accept` is
    /// (re)applied every call so the picker's filter matches the current lane (the
    /// `.BREP.json` model lane vs. a `.step` import lane).
    fn ensure_input(accept: &str) -> Option<web_sys::HtmlInputElement> {
        if let Some(existing) = IMPORT_INPUT.with(|c| c.borrow().clone()) {
            existing.set_accept(accept);
            return Some(existing);
        }
        let document = web_sys::window()?.document()?;
        let input: web_sys::HtmlInputElement =
            document.create_element("input").ok()?.dyn_into().ok()?;
        input.set_type("file");
        input.set_accept(accept);
        input.set_hidden(true);

        // Read bytes so binary STL is not corrupted at the browser boundary.
        let input_for_cb = input.clone();
        let onchange = Closure::wrap(Box::new(move |_e: web_sys::Event| {
            let Some(files) = input_for_cb.files() else { return };
            let Some(file) = files.get(0) else { return };
            let name = file.name();
            let Ok(reader) = web_sys::FileReader::new() else { return };
            let reader_for_load = reader.clone();
            let onload = Closure::wrap(Box::new(move |_e: web_sys::Event| {
                if let Ok(value) = reader_for_load.result() {
                    let bytes = js_sys::Uint8Array::new(&value).to_vec();
                    IMPORTED.with(|c| *c.borrow_mut() = Some(ImportedFile {
                        name: model_display_name(&name),
                        bytes,
                    }));
                    // Wake the reactive frame loop so the file panel polls
                    // `take_import` THIS frame, not on the next stray input event.
                    wake_frame_loop();
                }
            }) as Box<dyn FnMut(web_sys::Event)>);
            reader.set_onload(Some(onload.as_ref().unchecked_ref()));
            // One small per-import leak (the app runs for the page lifetime).
            onload.forget();
            let _ = reader.read_as_array_buffer(&file);
        }) as Box<dyn FnMut(web_sys::Event)>);
        input.set_onchange(Some(onchange.as_ref().unchecked_ref()));
        onchange.forget(); // created once — leak is bounded

        if let Some(body) = document.body() {
            let _ = body.append_child(&input);
        }
        IMPORT_INPUT.with(|c| *c.borrow_mut() = Some(input.clone()));
        Some(input)
    }

    /// Offer `contents` to the user as a download named EXACTLY `file_name`, via a
    /// Blob object-URL + a synthetic anchor click.
    fn download(file_name: &str, mime: &str, contents: &str) -> Result<(), String> {
        let document = web_sys::window()
            .and_then(|w| w.document())
            .ok_or("no document")?;
        let parts = js_sys::Array::of1(&JsValue::from_str(contents));
        let options = web_sys::BlobPropertyBag::new();
        options.set_type(mime);
        let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &options)
            .map_err(|_| "blob create failed".to_string())?;
        let url = web_sys::Url::create_object_url_with_blob(&blob)
            .map_err(|_| "object url failed".to_string())?;
        let anchor: web_sys::HtmlAnchorElement = document
            .create_element("a")
            .map_err(|_| "anchor create failed".to_string())?
            .dyn_into()
            .map_err(|_| "anchor cast failed".to_string())?;
        anchor.set_href(&url);
        anchor.set_download(file_name);
        anchor.click();
        let _ = web_sys::Url::revoke_object_url(&url);
        Ok(())
    }

    /// The browser model store: the mirrored key space (which owns every CRUD and
    /// explorer method) plus this platform's real-file interchange lane.
    pub(super) struct IdbModelStore {
        core: MirrorStore,
    }

    impl ModelStore for IdbModelStore {
        // --- delegated to the mirror ------------------------------------------
        fn backend_label(&self) -> String {
            self.core.backend_label()
        }
        fn list(&self) -> Vec<String> {
            self.core.list()
        }
        fn read(&self, name: &str) -> Option<String> {
            self.core.read(name)
        }
        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
            self.core.write(name, contents)
        }
        fn remove(&self, name: &str) -> Result<(), String> {
            self.core.remove(name)
        }
        fn take_persistence_errors(&self) -> Vec<String> {
            self.core.take_persistence_errors()
        }
        fn browser_location(&self) -> String {
            self.core.browser_location()
        }
        fn browser_entries(&self, extensions: &[&str]) -> Vec<BrowserEntry> {
            self.core.browser_entries(extensions)
        }
        fn browser_enter(&self, identity: &str) -> Result<(), String> {
            self.core.browser_enter(identity)
        }
        fn browser_up(&self) -> Result<(), String> {
            self.core.browser_up()
        }
        fn browser_home(&self) -> Result<(), String> {
            self.core.browser_home()
        }
        fn browser_root(&self) -> Result<(), String> {
            self.core.browser_root()
        }
        fn browser_navigate(&self, location: &str) -> Result<(), String> {
            self.core.browser_navigate(location)
        }
        fn browser_places(&self) -> Vec<BrowserPlace> {
            self.core.browser_places()
        }
        fn browser_create_dir(&self, name: &str) -> Result<(), String> {
            self.core.browser_create_dir(name)
        }
        fn browser_write(&self, name: &str, contents: &str) -> Result<String, String> {
            self.core.browser_write(name, contents)
        }

        // --- the browser's real-file lane -------------------------------------
        fn supports_file_interchange(&self) -> bool {
            true
        }

        /// Offer the document as a `<name>.BREP.json` download. The returned
        /// identity is the bare name (the browser owns where the download lands).
        fn export_file(&self, name: &str, contents: &str) -> Result<Option<String>, String> {
            let name = model_display_name(name);
            download(&format!("{name}{MODEL_EXT}"), "application/json", contents)?;
            Ok(Some(name))
        }

        fn begin_import(&self) -> Result<(), String> {
            let input =
                ensure_input(".json,.BREP.json,application/json").ok_or("file input unavailable")?;
            // Clear so re-selecting the same file still fires `change`.
            input.set_value("");
            input.click();
            Ok(())
        }

        fn take_import(&self) -> Option<ImportedFile> {
            IMPORTED.with(|c| c.borrow_mut().take())
        }

        // Format-typed interchange: the same hidden input, refiltered to the
        // requested extensions. The onchange handler stashes the file's real name
        // (its extension survives `model_display_name`, since that only strips
        // `.json` / `.BREP.json`), so the panel routes STEP imports by extension.
        fn begin_import_filtered(&self, filter: (&str, &[&str])) -> Result<(), String> {
            let accept = filter
                .1
                .iter()
                .map(|ext| format!(".{ext}"))
                .collect::<Vec<_>>()
                .join(",");
            let input = ensure_input(&accept).ok_or("file input unavailable")?;
            input.set_value("");
            input.click();
            Ok(())
        }

        /// Offer `contents` as a download under EXACTLY `file_name` (extension
        /// kept) — the foreign-format sibling of [`Self::export_file`].
        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
            download(file_name, "application/octet-stream", contents)
        }
    }
}


#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::native_model::FileModelStore;
    use super::{ModelStore, DOCK_LAYOUT_KEY, SETTINGS_KEY};

    #[test]
    fn native_model_store_round_trips_named_documents() {
        let dir = std::env::temp_dir().join(format!("brep-app-models-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = FileModelStore::with_dir(dir.clone());

        // Empty to start.
        assert!(store.list().is_empty());
        assert_eq!(store.read("missing"), None);

        // Write two documents, read them back verbatim, and enumerate by name.
        let doc_a = r#"{"features":[{"type":"P.CU"}]}"#;
        let doc_b = r#"{"features":[]}"#;
        store.write("alpha", doc_a).unwrap();
        store.write("beta", doc_b).unwrap();
        assert_eq!(store.read("alpha").as_deref(), Some(doc_a));
        assert_eq!(store.read("beta").as_deref(), Some(doc_b));
        assert_eq!(store.list(), vec!["alpha".to_string(), "beta".to_string()]);

        // The `.BREP.json` extension is transparent to the name.
        assert_eq!(store.read("alpha.BREP.json").as_deref(), Some(doc_a));

        // Overwrite + remove.
        store.write("alpha", doc_b).unwrap();
        assert_eq!(store.read("alpha").as_deref(), Some(doc_b));
        store.remove("alpha").unwrap();
        assert_eq!(store.read("alpha"), None);
        assert_eq!(store.list(), vec!["beta".to_string()]);
        store.remove("alpha").unwrap(); // removing an absent doc is Ok

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn native_store_uses_the_same_read_write_api_for_app_state_and_models() {
        let dir = std::env::temp_dir().join(format!(
            "brep-app-unified-store-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let store = FileModelStore::with_dir(dir.clone());

        store.write(SETTINGS_KEY, r#"{"theme":"dark"}"#).unwrap();
        store.write(DOCK_LAYOUT_KEY, r#"{"tiles":[]}"#).unwrap();
        store.write("part", r#"{"features":[]}"#).unwrap();

        assert_eq!(
            store.read(SETTINGS_KEY).as_deref(),
            Some(r#"{"theme":"dark"}"#)
        );
        assert_eq!(
            store.read(DOCK_LAYOUT_KEY).as_deref(),
            Some(r#"{"tiles":[]}"#)
        );
        assert_eq!(store.list(), vec!["part".to_string()]);
        assert!(dir.join("settings.json").is_file());
        assert!(dir.join("dock_layout.json").is_file());
        assert!(dir.join("part.BREP.json").is_file());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn native_browser_navigates_and_saves_outside_the_model_directory() {
        let root = std::env::temp_dir().join(format!(
            "brep-app-browser-navigation-{}",
            std::process::id()
        ));
        let models = root.join("models");
        let sibling = root.join("projects");
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&models).unwrap();
        std::fs::create_dir_all(&sibling).unwrap();
        let store = FileModelStore::with_dir(models.clone());

        store.browser_up().unwrap();
        let projects = store
            .browser_entries(&["BREP.json"])
            .into_iter()
            .find(|entry| entry.name == "projects")
            .expect("sibling directory should be visible");
        assert!(projects.is_dir);
        store.browser_enter(&projects.identity).unwrap();
        let identity = store
            .browser_write("assembly", r#"{"features":[]}"#)
            .unwrap();

        assert_eq!(std::path::PathBuf::from(&identity), sibling.join("assembly.BREP.json"));
        assert_eq!(store.read(&identity).as_deref(), Some(r#"{"features":[]}"#));
        assert_eq!(store.browser_location(), sibling.display().to_string());

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn native_store_exposes_foreign_files_to_the_common_explorer() {
        let dir = std::env::temp_dir().join(format!(
            "brep-app-explorer-store-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let store = FileModelStore::with_dir(dir.clone());

        store.export_file_named("bracket.step", "STEP DATA").unwrap();
        store.export_file_named("preview.stl", "solid preview").unwrap();

        assert_eq!(
            store.list_external_files(&["step", "stp"]),
            vec!["bracket.step".to_string()]
        );
        assert_eq!(
            store.read_external_file("bracket.step").as_deref(),
            Some(b"STEP DATA".as_slice())
        );
        assert!(dir.join("bracket.step").is_file());

        let _ = std::fs::remove_dir_all(&dir);
    }
}

/// The mirrored browser store, exercised WITHOUT a browser: `MirrorStore` and the
/// `StoreBackend` seam are platform-neutral, so a recording backend proves the
/// mirror semantics, the (verbatim) key scheme, the explorer's virtual tree, and
/// the write-behind error channel on the native test target. The IndexedDB
/// implementation of the same trait is what the headed `web/verify_store.mjs`
/// check covers.
#[cfg(all(test, not(target_arch = "wasm32")))]
mod mirror_tests {
    use super::mirror_store::{BackendFuture, MirrorStore, StoreBackend, UnavailableBackend};
    use super::{ModelStore, DOCK_LAYOUT_KEY, PINNED_KEY, SETTINGS_KEY};
    use std::cell::RefCell;
    use std::rc::Rc;

    /// A [`StoreBackend`] that records what the mirror asked it to persist and can
    /// be told to fail — the same seam a future HTTP backend implements.
    #[derive(Default)]
    struct RecordingBackend {
        puts: RefCell<Vec<(String, String)>>,
        deletes: RefCell<Vec<String>>,
        fail_with: RefCell<Option<String>>,
    }

    impl RecordingBackend {
        fn shared() -> Rc<Self> {
            Rc::new(Self::default())
        }

        fn put_keys(&self) -> Vec<String> {
            self.puts.borrow().iter().map(|(k, _)| k.clone()).collect()
        }

        fn outcome(&self) -> BackendFuture<()> {
            let failure = self.fail_with.borrow().clone();
            Box::pin(async move {
                match failure {
                    Some(message) => Err(message),
                    None => Ok(()),
                }
            })
        }
    }

    impl StoreBackend for RecordingBackend {
        fn label(&self) -> String {
            "recording test backend".into()
        }

        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
            Box::pin(async move { Ok(Vec::new()) })
        }

        fn put(&self, key: &str, value: &str) -> BackendFuture<()> {
            self.puts
                .borrow_mut()
                .push((key.to_string(), value.to_string()));
            self.outcome()
        }

        fn delete(&self, key: &str) -> BackendFuture<()> {
            self.deletes.borrow_mut().push(key.to_string());
            self.outcome()
        }
    }

    fn store(backend: &Rc<RecordingBackend>) -> MirrorStore {
        MirrorStore::new(backend.clone(), Vec::new(), None)
    }

    #[test]
    fn mirror_serves_reads_synchronously_and_pushes_writes_behind() {
        let backend = RecordingBackend::shared();
        let store = store(&backend);

        assert!(store.list().is_empty());
        assert_eq!(store.read("alpha"), None);

        let doc = r#"{"features":[{"type":"P.CU"}]}"#;
        // `write` returns Ok off the mirror and the read is visible IMMEDIATELY —
        // the whole point of the mirror in front of an async backend.
        store.write("alpha", doc).unwrap();
        assert_eq!(store.read("alpha").as_deref(), Some(doc));
        assert_eq!(store.list(), vec!["alpha".to_string()]);
        // ...and the backend was asked to persist it under the verbatim key.
        assert_eq!(
            backend.puts.borrow().as_slice(),
            [("brep-app:model:alpha".to_string(), doc.to_string())]
        );
        // The push settled, so nothing is outstanding and nothing failed.
        assert_eq!(store.pending(), 0);
        assert!(store.take_persistence_errors().is_empty());

        // The `.BREP.json` extension is transparent to the name, as on native.
        assert_eq!(store.read("alpha.BREP.json").as_deref(), Some(doc));

        store.remove("alpha").unwrap();
        assert_eq!(store.read("alpha"), None);
        assert!(store.list().is_empty());
        assert_eq!(
            backend.deletes.borrow().as_slice(),
            ["brep-app:model:alpha".to_string()]
        );
    }

    #[test]
    fn key_scheme_is_verbatim_from_the_local_storage_era() {
        assert_eq!(MirrorStore::key(SETTINGS_KEY), "brep-app:settings");
        assert_eq!(MirrorStore::key(DOCK_LAYOUT_KEY), "brep-app:dock_layout");
        assert_eq!(MirrorStore::key(PINNED_KEY), "brep-app:pinned");
        // Documents lose the leading slash, the `/models` root and the extension.
        assert_eq!(MirrorStore::key("part"), "brep-app:model:part");
        assert_eq!(MirrorStore::key("/models/part"), "brep-app:model:part");
        assert_eq!(
            MirrorStore::key("/models/sub/part.BREP.json"),
            "brep-app:model:sub/part"
        );
        assert_eq!(MirrorStore::key("part.json"), "brep-app:model:part");
    }

    #[test]
    fn reserved_application_blobs_share_the_document_api_and_never_list() {
        let backend = RecordingBackend::shared();
        let store = store(&backend);

        store.write(SETTINGS_KEY, r#"{"theme":"dark"}"#).unwrap();
        store.write(DOCK_LAYOUT_KEY, r#"{"tiles":[]}"#).unwrap();
        store.write("part", r#"{"features":[]}"#).unwrap();

        assert_eq!(
            store.read(SETTINGS_KEY).as_deref(),
            Some(r#"{"theme":"dark"}"#)
        );
        // Only real documents are offerable to Open.
        assert_eq!(store.list(), vec!["part".to_string()]);
        assert_eq!(
            backend.put_keys(),
            vec![
                "brep-app:settings".to_string(),
                "brep-app:dock_layout".to_string(),
                "brep-app:model:part".to_string(),
            ]
        );
    }

    #[test]
    fn hydrated_entries_are_visible_to_the_first_synchronous_read() {
        // What the boot hydrate hands over: a whole key space, already resolved.
        let store = MirrorStore::new(
            RecordingBackend::shared(),
            vec![
                ("brep-app:model:alpha".into(), "A".into()),
                ("brep-app:model:sub/beta".into(), "B".into()),
                ("brep-app:settings".into(), r#"{"theme":"dark"}"#.into()),
            ],
            None,
        );
        assert_eq!(
            store.list(),
            vec!["alpha".to_string(), "sub/beta".to_string()]
        );
        assert_eq!(store.read("alpha").as_deref(), Some("A"));
        assert_eq!(store.read("/models/sub/beta").as_deref(), Some("B"));
        assert_eq!(
            store.read(SETTINGS_KEY).as_deref(),
            Some(r#"{"theme":"dark"}"#)
        );
    }

    #[test]
    fn explorer_walks_the_virtual_tree_the_key_prefixes_describe() {
        let backend = RecordingBackend::shared();
        let store = store(&backend);
        store.write("alpha", "AAAA").unwrap();
        store.browser_create_dir("sub").unwrap();
        store.write("/models/sub/beta", "BB").unwrap();

        // The folder marker is a persisted zero-length key.
        assert!(backend.put_keys().contains(&"brep-app:dir:sub/".to_string()));

        // /models lists the folder first, then the document with its byte size.
        let entries = store.browser_entries(&["BREP.json"]);
        let names: Vec<_> = entries.iter().map(|e| e.name.clone()).collect();
        assert_eq!(names, vec!["sub".to_string(), "alpha.BREP.json".to_string()]);
        assert!(entries[0].is_dir);
        assert_eq!(entries[1].size, Some(4));
        assert_eq!(entries[1].identity, "/models/alpha.BREP.json");

        // Descend, and only the child document is in view.
        store.browser_enter("/models/sub").unwrap();
        assert_eq!(store.browser_location(), "/models/sub");
        let entries = store.browser_entries(&["BREP.json"]);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "beta.BREP.json");
        assert_eq!(entries[0].identity, "/models/sub/beta.BREP.json");

        // A Save into the current folder returns the identity to re-save to.
        let identity = store.browser_write("gamma", "G").unwrap();
        assert_eq!(identity, "/models/sub/gamma.BREP.json");
        assert_eq!(store.read(&identity).as_deref(), Some("G"));

        // The root shows the single models mount; outside it is not navigable.
        store.browser_root().unwrap();
        assert_eq!(
            store
                .browser_entries(&["BREP.json"])
                .into_iter()
                .map(|e| e.identity)
                .collect::<Vec<_>>(),
            vec!["/models".to_string()]
        );
        assert!(store.browser_navigate("/etc").is_err());
    }

    #[test]
    fn a_write_behind_failure_reaches_the_user_exactly_once() {
        let backend = RecordingBackend::shared();
        *backend.fail_with.borrow_mut() = Some("QuotaExceededError: out of room".into());
        let store = store(&backend);

        // The synchronous contract still holds: Ok, and the doc is readable.
        store.write("alpha", "A").unwrap();
        assert_eq!(store.read("alpha").as_deref(), Some("A"));

        // ...but the failure is queued for the UI, naming the document.
        let drained = store.take_persistence_errors();
        assert_eq!(drained.len(), 1);
        assert!(drained[0].contains("alpha"), "{drained:?}");
        assert!(drained[0].contains("QuotaExceededError"), "{drained:?}");
        // Drained means shown — it is not repeated.
        assert!(store.take_persistence_errors().is_empty());

        // A fresh failure of the same kind IS reported again (the collapse only
        // suppresses an identical message the user has not seen yet).
        store.write("alpha", "AA").unwrap();
        assert_eq!(store.take_persistence_errors().len(), 1);
        // Everything recorded stays addressable for the verification hook.
        assert_eq!(store.error_history().len(), 2);
    }

    #[test]
    fn an_unavailable_backend_is_usable_in_memory_and_loud_about_not_saving() {
        let backend = Rc::new(UnavailableBackend::new("IndexedDB unavailable (blocked)"));
        let store = MirrorStore::new(backend, Vec::new(), None);

        assert!(store.backend_label().contains("NOT SAVING"));
        assert!(store.backend_label().contains("blocked"));

        // The session still works — nothing is lost while the tab is open...
        store.write("alpha", "A").unwrap();
        assert_eq!(store.read("alpha").as_deref(), Some("A"));
        assert_eq!(store.len_of("alpha"), Some(1));
        // ...and every write says, in the user's face, that it did not persist.
        let drained = store.take_persistence_errors();
        assert_eq!(drained.len(), 1);
        assert!(drained[0].contains("alpha"), "{drained:?}");
    }

    #[test]
    fn recording_a_failure_wakes_the_frame_loop() {
        // The browser wires this to `ctx.request_repaint()`; without it a failure
        // recorded from an async callback would sit unshown until stray input.
        let woken = Rc::new(std::cell::Cell::new(0usize));
        let wake = {
            let woken = woken.clone();
            Rc::new(move || woken.set(woken.get() + 1)) as Rc<dyn Fn()>
        };
        let backend = RecordingBackend::shared();
        *backend.fail_with.borrow_mut() = Some("boom".into());
        let store = MirrorStore::new(backend, Vec::new(), Some(wake));

        store.write("alpha", "A").unwrap();
        assert_eq!(woken.get(), 1);
    }
}