BREP_app 0.13.0

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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
//! 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.
//!
//! Desktop reads the real filesystem on every call. The browser CANNOT: IndexedDB
//! has no synchronous read on the main thread, so "go to the live filesystem every
//! time" is not implementable there — the mirror is not a convenience, it is the
//! only way this API can be synchronous at all. What the mirror owes in exchange
//! is that it never falls behind the storage it stands for, and the key space has
//! MORE than one writer: every other tab of the same origin. So each tab announces
//! the key it committed and re-reads the keys it is told about
//! (`mirror_store::MirrorStore::refresh_key`, over the `brep-app:store` broadcast
//! in `web_model`). Save a part in one tab and the tab holding the assembly can
//! insert it — no reload.

/// Reserved persistent-object names used internally for application state.
pub const SETTINGS_KEY: &str = "@settings";
pub const FEATURE_PALETTE_DISPLAY_KEY: &str = "@feature_palette_display";
pub const DOCK_LAYOUT_KEY: &str = "@dock_layout";
/// 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";
/// The AUTOSAVE blob: every open document that had unsaved changes the last
/// time the shell's autosave fired (see `crate::recovery`), so a crash, a
/// closed tab or a reload can offer that work back. Written debounced, removed
/// the moment nothing is dirty; never listed as a document.
pub const RECOVERY_KEY: &str = "@recovery";
/// The KiCad library folders the KiCad import last used (`panels::kicad_import`).
/// Desktop only: the web build cannot read a KiCad library, so it never writes it.
pub const KICAD_LIBRARY_KEY: &str = "@kicad_library";
/// The adoption importer's ledgers (`plm::adoption::ImportLedgers`), per PLM
/// server and per imported folder: what a stopped import resumes from. It
/// never leaves the machine — it records THIS machine's runs against a
/// server, and the source tree it describes is on this machine.
pub const PLM_IMPORT_KEY: &str = "@plm_import";
/// Explicitly installed executable packages stay on this machine, including in PLM mode.
pub const PLUGINS_KEY: &str = "@plugins";
/// Explicitly saved JavaScript editor source, local even in PLM mode.
pub const JAVASCRIPT_DRAFT_KEY: &str = "@javascript_draft";
/// Recent document identities, shared through the user preference store.
pub const RECENT_DOCUMENTS_KEY: &str = "@recent_documents";
/// The File menu's recent-document thumbnails (`plm::thumbnail::recent`): ONE
/// JSON map, store name → base64 PNG, pruned to [`RECENT_DOCUMENTS_KEY`]'s
/// names, so it is bounded by the recent list. Local, not a preference: a
/// picture cache of this machine's saves, never sent to a PLM server (which
/// keeps its own thumbnail per revision). One reserved name rather than a key
/// derived per document, because a derived name would fall through
/// [`KeySpace::of`] to `Documents` — listed by Open, written as a model file,
/// routed to the PLM server.
pub const RECENT_THUMBNAILS_KEY: &str = "@recent_thumbnails";

/// The reserved names that are a user's PREFERENCES (plm-cad-integration-todo
/// D1): state that follows the user, not the machine. A file backend keeps them
/// where it always has; a PLM backend serves them from its per-user store (P5).
///
/// `@pinned` is listed here as what it IS — explorer FOLDER locations, not
/// document identities — so in PLM mode it pins workspace folders (S14), never
/// `part/…/rev/…` keys.
pub const PREFERENCE_KEYS: &[&str] = &[
    SETTINGS_KEY,
    DOCK_LAYOUT_KEY,
    PINNED_KEY,
    FEATURE_PALETTE_DISPLAY_KEY,
    KICAD_LIBRARY_KEY,
    RECENT_DOCUMENTS_KEY,
];

/// The reserved names that never have to leave the machine to be safe: the
/// local-first copy of `@recovery` — a PLM session MIRRORS it to the server
/// after the local write (D1, S1's composition); the local copy is what a
/// network drop cannot take away — and `@plm_import`, which is never
/// mirrored.
///
/// The CAM workbench's user tool library (`panels::cam_library`) is LOCAL
/// too: a preference key is served per user by a PLM, whose server
/// allow-lists the preference names (`BREP_plm` `api::preferences::KEYS`),
/// so a new preference would be refused by every deployed server and the
/// sign-in's preference load fails on the first refused key. The library
/// stays on the machine until the PLM gains the key and the backend
/// tolerates a server that lacks it.
pub const LOCAL_KEYS: &[&str] = &[
    RECOVERY_KEY,
    PLM_IMPORT_KEY,
    PLUGINS_KEY,
    JAVASCRIPT_DRAFT_KEY,
    RECENT_THUMBNAILS_KEY,
    crate::panels::cam_library::CAM_TOOL_LIBRARY_KEY,
];

/// Which of the three key spaces a store name belongs to (D1, the round 10
/// answer). Every name is exactly one of them:
///
/// * **Documents** — model documents; the PLM's store routes
///   (`part/<part>/rev/<revision>`), a file path or a browser `/models/...`
///   name on the file backends.
/// * **Preferences** — [`PREFERENCE_KEYS`].
/// * **Local** — [`LOCAL_KEYS`].
///
/// The browser's explorer DIRECTORY rows are none of the three: they belong to
/// the file backends only (a PLM user's folders are the workspace, S14), so they
/// never reach this classifier — see `mirror_store::key_space`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeySpace {
    Documents,
    Preferences,
    Local,
}

impl KeySpace {
    /// The key space of a store NAME (what callers pass to
    /// [`ModelStore::read`] / [`ModelStore::write`]).
    pub fn of(name: &str) -> Self {
        if PREFERENCE_KEYS.contains(&name) {
            KeySpace::Preferences
        } else if LOCAL_KEYS.contains(&name) {
            KeySpace::Local
        } else {
            KeySpace::Documents
        }
    }
}

/// How much of a document a store holds right now — the synchronous answer to
/// "can `read` give me this?" that a store with an index-only hydrate owes.
///
/// A store that holds everything it lists (the native filesystem, a browser
/// origin hydrated whole) only ever answers `Absent` or `Resident`. A store
/// hydrated from an INDEX (the mirror's `OnDisk` entries — the PLM catalog is
/// the corpus that needs it) also answers `OnDisk`: the name exists and its
/// size is known, but its bytes are still on the backend, and a `read` of it
/// returns `None` while it asks for them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Residency {
    Absent,
    OnDisk,
    Resident,
}

/// A document as a caller can use it this frame: its bytes, still loading,
/// or not there ([`read_now`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ReadNow {
    Ready(String),
    Loading,
    Absent,
}

/// Read `name`, telling "not loaded yet" from "gone".
///
/// Not simply `read` then `residency`: a `read` of an `OnDisk` entry asks the
/// backend for the bytes, and a backend that answers at once (an in-process
/// router, a local cache) lands them INSIDE that read. `read` has already
/// said `None`, and `residency` now says `Resident`. Read naively, that is a
/// document reported missing that is there. So a `None` that turned resident
/// is read again.
pub fn read_now(store: &dyn ModelStore, name: &str) -> ReadNow {
    if let Some(contents) = store.read(name) {
        return ReadNow::Ready(contents);
    }
    match store.residency(name) {
        Residency::Resident => store.read(name).map_or(ReadNow::Absent, ReadNow::Ready),
        Residency::OnDisk => ReadNow::Loading,
        Residency::Absent => ReadNow::Absent,
    }
}

/// 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 `.nbrep` 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 media type an exported file is handed to the user with, from its own
/// extension.
///
/// A browser download IS its media type: the type on the `Blob` is what decides
/// whether the file opens in a viewer, is offered as a download, or is mailed on
/// correctly — the name alone is a hint. So the two export doors below take it
/// from here rather than each hard-coding one, which is what they used to do
/// (`model/gltf-binary` on everything the byte lane carried, because GLB was the
/// only thing it carried, and `application/octet-stream` on every text export).
///
/// Unknown extensions fall back to `application/octet-stream`, which is the
/// correct "some bytes, download them" answer.
///
/// It is also the type a file is UPLOADED to the PLM with (attachments and
/// workspace files), so a model stored there comes back down as the same
/// opaque bytes and keeps its name.
pub fn media_type(file_name: &str) -> &'static str {
    let extension = std::path::Path::new(file_name)
        .extension()
        .map(|extension| extension.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default();
    match extension.as_str() {
        "pdf" => "application/pdf",
        "svg" => "image/svg+xml",
        "glb" => "model/gltf-binary",
        // The 3MF Consortium's registered type for the package.
        "3mf" => "model/3mf",
        "json" => "application/json",
        // The PCB's fabrication bundle.
        "zip" => "application/zip",
        // A model document is JSON inside, but typed as opaque bytes: a browser
        // that sees a JSON type on a download may "correct" the name to
        // `bracket.nbrep.json`, and the name is the only thing that routes it.
        "nbrep" | "fbrep" | "tbrep" => "application/octet-stream",
        // The CAD text formats. `model/step+zip` is the registered type for a
        // zipped STEP; a plain `.step` file is `model/step`.
        "step" | "stp" => "model/step",
        "iges" | "igs" => "model/iges",
        "stl" => "model/stl",
        "obj" => "model/obj",
        "dxf" => "image/vnd.dxf",
        "csv" => "text/csv",
        "txt" => "text/plain",
        "md" => "text/markdown",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        _ => "application/octet-stream",
    }
}

/// Write `bytes` to `path` so that a crash or a full disk mid-save never leaves
/// a short or empty file where the last good one was: a temporary beside
/// `path` (`<name>.<pid>-<n>.tmp`, unique per write, never a sibling's name),
/// written, flushed to disk, then renamed over `path`; on any failure the
/// temporary is removed and `path` is untouched. `secret` creates the
/// temporary owner-only (0600 on unix) from the first byte. The app's one
/// atomic write: model saves, exports and the PLM config/token (I4).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn write_atomic(path: &std::path::Path, bytes: &[u8], secret: bool) -> std::io::Result<()> {
    use std::io::Write;
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(0);
    let name = path
        .file_name()
        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "no file name"))?;
    let mut temp_name = name.to_os_string();
    temp_name.push(format!(".{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
    let temp = path.with_file_name(temp_name);
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    if secret {
        use std::os::unix::fs::OpenOptionsExt;
        // Created 0600, never chmod-ed down afterwards: there is no instant at
        // which a secret sits in a file another user could open.
        options.mode(0o600);
    }
    #[cfg(not(unix))]
    let _ = secret;
    let written = options
        .open(&temp)
        .and_then(|mut file| {
            file.write_all(bytes)?;
            file.sync_all()
        })
        .and_then(|()| std::fs::rename(&temp, path));
    if written.is_err() {
        let _ = std::fs::remove_file(&temp);
    }
    written
}

/// 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 {
    /// Bounded file management over this host's persistent file store.
    #[cfg(feature = "automation")]
    fn files(&self, _request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> {
        Err("files is unsupported by this store backend".into())
    }
    /// None while persistence is in flight; otherwise the operation's result.
    #[cfg(feature = "automation")]
    fn files_settled(&self, _request: &brep_mcp_core::files::Request) -> Option<Result<(), String>> { Some(Ok(())) }

    /// 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(())
    }

    /// A monotonic count of this store's MUTATIONS — every `write`, `remove`
    /// and `browser_write` that landed, WHOEVER made it. A read never moves
    /// it; two reads that agree mean nothing was written in between.
    ///
    /// This is a cache-invalidation key, which is why it is REQUIRED rather
    /// than defaulted: a default would let a new backend (the GitHub one this
    /// trait is shaped for) compile while silently never invalidating
    /// anything, which is the failure it exists to stop. The outdated-parts
    /// badge (`panels::update_components`) used to key on the file dialog's
    /// own save counter, which counts Save / Save As / native Save-As and
    /// NOTHING else — so a KiCad re-import (`panels::kicad_bulk::write_part`)
    /// or the explorer's delete row could change a part's source under an open
    /// assembly, move no other generation, and leave the badge dark.
    fn mutation_generation(&self) -> u64;

    /// Whether `name` is absent, listed but not yet loaded, or readable now
    /// (see [`Residency`]). The default answers from `read`, which is exact for
    /// every store that holds what it lists; only an index-hydrated store
    /// overrides it. No caller branches on `OnDisk` yet — it is here so one
    /// CAN tell "not loaded yet" from "gone" without a second store API.
    fn residency(&self, name: &str) -> Residency {
        match self.read(name) {
            Some(_) => Residency::Resident,
            None => Residency::Absent,
        }
    }

    /// What kind of identity `identity` is on THIS store (see
    /// [`DocumentIdentity`] and the enumeration above it). Every file backend
    /// keys by path, so the default never parses: a browser folder named
    /// `part/7/rev` holds a document, not a revision.
    fn identity(&self, identity: &str) -> DocumentIdentity {
        DocumentIdentity::Path(identity.to_string())
    }

    /// The name a person sees for `identity`: the tab title, the name field.
    /// The default is the file rule, `model_display_name`; a PLM store knows
    /// the part number and revision label from its index, which the key alone
    /// does not carry.
    fn display_name(&self, identity: &str) -> String {
        model_display_name(identity)
    }

    /// The identity of `file_name` beside the document `identity` — or `None`
    /// on a store with no folders to be beside (the PLM, where a family member
    /// or a spun-out part is a new part instead, S7 / S9). The default is the
    /// file rule, [`sibling_identity`].
    fn sibling_of(&self, identity: &str, file_name: &str) -> Option<String> {
        Some(sibling_identity(identity, file_name))
    }

    /// The ONE spelling of the document `name` resolves to, as the explorer
    /// spells it (`BrowserEntry::identity`), so two names for one document
    /// compare equal: a bare `bolt` and `/home/u/.config/brep-app/models/bolt.nbrep`
    /// on the desktop, `sub/bolt` and `/models/sub/bolt.nbrep` in the browser.
    ///
    /// The adoption importer (S13) needs it. An assembly's `sourceKey`s are
    /// whatever name the part was inserted by, and the importer must match
    /// each one to the file it walked. The default is `name` unchanged, which
    /// is right for a store with one spelling per document (a PLM store's
    /// revision keys).
    fn canonical_identity(&self, name: &str) -> String {
        name.to_string()
    }

    /// [`Self::canonical_identity`] as a function that outlives the borrow:
    /// what the open documents compare identities with (a tab is named by the
    /// explorer's spelling, a `sourceKey` by whatever the part was inserted
    /// by — `crate::document::live_link`).
    fn canonicalizer(&self) -> Canonicalizer {
        std::rc::Rc::new(str::to_string)
    }

    /// 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()
    }

    /// The documents (as named to `write`) whose write failed AFTER `write`
    /// returned `Ok`, each once. The frame loop marks their tabs unsaved again:
    /// a Save that never reached the server must not leave a clean tab, or
    /// closing it loses the edit without a question. Empty on a backend that
    /// writes synchronously, whose `write` returns the `Err` itself.
    fn take_failed_writes(&self) -> Vec<String> {
        Vec::new()
    }

    /// The last write of `name` failed after it returned: what [`Self::read`]
    /// gives is this session's, not the backend's. A Save that would skip the
    /// write because the store "already holds" the text must write it.
    fn write_failed(&self, name: &str) -> bool {
        let _ = name;
        false
    }

    /// For a [`Self::write_failed`] key: the content hash of the document the
    /// failed write was based on (empty: unknown).
    fn failed_write_base(&self, name: &str) -> Option<String> {
        let _ = name;
        None
    }

    /// [`Self::write`], but only over the document whose content hash is
    /// `expected` (a PLM revision's `If-Match`): a backend holding a newer one
    /// refuses it, and the failure says so. A store with no such check writes.
    fn write_if(&self, name: &str, contents: &str, expected: &str) -> Result<(), String> {
        let _ = expected;
        self.write(name, contents)
    }

    /// The PLM this session is on, or is configured for and not on (why, when
    /// known): what the Settings PLM tab shows (plan S1 part 3). `None` is the
    /// file-based app, and the tab is absent.
    fn plm_session(&self) -> Option<crate::plm::connection::Session> {
        None
    }

    /// Where this session's PLM server URL is kept: the Settings PLM tab's
    /// Server URL field reads it, in every native session (file or PLM).
    /// `None` where no `plm.json` exists to write — the browser, whose PLM is
    /// the server that serves its page, and the in-memory stores.
    fn plm_url_setting(&self) -> Option<crate::plm::connection::UrlSetting> {
        None
    }

    /// Save the Server URL to `plm.json` as `--plm-configure` does
    /// ([`crate::plm::config::repoint`]: a malformed URL is refused, and a
    /// different server drops this machine's token). A file session that was
    /// on `plm.json` reports the new server from here on (signed out), so the
    /// tab's sign-in reaches it at once; a PLM session stays on its server
    /// until the next start.
    fn save_plm_url(&self, url: &str) -> Result<crate::plm::connection::UrlSaved, String> {
        let _ = url;
        Err("this session keeps no PLM settings".into())
    }

    /// The signed-in PLM client of a session whose store IS the PLM, for the
    /// calls that are not store reads and writes (Generate, spin-out, the
    /// lifecycle verbs). `None` on every file store, and on a PLM configured
    /// but not connected.
    fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
        None
    }

    /// What the PLM's store index says of revision `key` (`part/…/rev/…`):
    /// its part number, label, lifecycle and lock, as the session last read
    /// them. `None` on every file store and for a key the index does not list.
    /// No request: this is the index the session already holds.
    fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
        let _ = key;
        None
    }

    /// This session's checkout of the PLM revision `key` just landed: its
    /// index row reads it as checked out to us now, before the change feed
    /// says so (a Save planned meanwhile must not ask to check it out again).
    /// A no-op on every file store.
    fn note_checked_out(&self, key: &str) {
        let _ = key;
    }

    /// Whether the index row of the PLM revision `key` lists our own last
    /// write of it, with nothing newer listed since: what the change feed
    /// names for it is our own save, which a reader need not read back.
    /// `false` on every file store.
    fn plm_written_by_us(&self, key: &str) -> bool {
        let _ = key;
        false
    }

    /// Bring the held index up to date after the change feed moved: `keys`
    /// are the revisions the feed named, `stale` means it could not say. A
    /// no-op on every file store.
    fn refresh_plm_index(&self, keys: &[String], stale: bool) {
        let _ = (keys, stale);
    }

    /// Remember a document that has already been durably written through a PLM
    /// request. Update the session mirror without issuing a second write.
    fn remember_saved_document(&self, name: &str, contents: &str) {
        let _ = (name, contents);
    }

    /// This machine's own files, browsable, for the file chooser (any file,
    /// any folder): the native file store itself, or the file store a PLM
    /// session keeps beside the server. `None` in the browser, which picks
    /// through [`Self::begin_pick_file`] instead.
    fn local_files(&self) -> Option<&dyn ModelStore> {
        None
    }

    /// The browser's file chooser for ANY file (not the model lane's
    /// `.nbrep` input): the choice arrives later through
    /// [`Self::take_picked_file`], under the file's own name.
    fn begin_pick_file(&self) -> Result<(), String> {
        Err("this platform has no file chooser".into())
    }

    /// The file [`Self::begin_pick_file`]'s chooser delivered, once.
    fn take_picked_file(&self) -> Option<ImportedFile> {
        None
    }

    /// Writes handed to a WRITE-BEHIND backend that have not settled yet — the
    /// status bar's working indicator reports them ("Saving to browser
    /// storage"). Always 0 on a backend that writes synchronously.
    fn pending_writes(&self) -> usize {
        0
    }

    /// [`Self::pending_writes`], leaving out the writes of the documents
    /// stored under `names`: what `settle` on one document waits for while
    /// other tabs save. A store that cannot tell its writes apart counts all.
    fn pending_writes_except(&self, names: &[&str]) -> usize {
        let _ = names;
        self.pending_writes()
    }

    // --- 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())
    }

    /// Write `contents` under EXACTLY `file_name` (extension kept: no model
    /// extension munging, unlike [`Self::browser_write`]) at the current
    /// browser location, and return the written file's full identity. The
    /// Save-file chooser's door: on desktop every export goes through it once
    /// the user has chosen the folder in the explorer. Default: unsupported —
    /// the browser has no folders to choose and downloads instead
    /// ([`Self::export_file_named_bytes`]).
    fn browser_write_bytes(&self, _file_name: &str, _contents: &[u8]) -> Result<String, String> {
        Err("this storage backend cannot write a file at a location".into())
    }

    /// 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 `.nbrep` 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. The file's media type comes from its extension
    /// ([`media_type`]). Default no-op (interchange unsupported).
    fn export_file_named(&self, _file_name: &str, _contents: &str) -> Result<(), String> {
        Ok(())
    }

    /// [`Self::export_file_named`] for a BINARY format (GLB, a sheet PDF). Every
    /// text export could go through this one — text is bytes — but the text
    /// method stays because the browser's `Blob` takes a string directly and
    /// routing UTF-8 through a `Uint8Array` for every STEP file would be a copy
    /// for nothing. Both lanes type the file the same way, from its extension,
    /// so which lane an export takes is a question about copies and never about
    /// what the user receives. Default no-op, like its text sibling.
    fn export_file_named_bytes(&self, _file_name: &str, _contents: &[u8]) -> Result<(), String> {
        Ok(())
    }
}

/// Construct the platform's one persistent store for application state and models.
/// A native file store rooted at `dir` — the seam an automation host uses to keep
/// a session's settings, autosave and recovery blob out of the user's own config
/// directory.
///
/// Laid out the way the SHIPPED app lays out its own config directory: models
/// in `<dir>/models`, reserved application state beside them in `<dir>`. A
/// session whose store collapsed the two would show the app its own
/// `dock_layout.json` and `recovery.json` as documents in the Open dialog —
/// rows a user never sees, in the one place automation exists to drive.
///
/// A `plm.json` in `dir` (what the test-mcp PLM fixture writes) makes the
/// session a PLM session instead: see [`boot_native_store`]. Only the files
/// count here — never `BREP_PLM_URL` — so a host's own environment cannot leak
/// into a session it isolated. No `plm.json` is exactly the file store of
/// before the PLM existed.
#[cfg(not(target_arch = "wasm32"))]
pub fn native_store_at(dir: std::path::PathBuf) -> Box<dyn ModelStore> {
    match crate::plm::config::resolve(&dir, &|_| None, &Default::default()) {
        Ok(None) => Box::new(native_model::FileModelStore::rooted_at(dir)),
        Ok(Some(config)) => boot_native_store(dir, config),
        Err(e) => file_store_with_notice(dir, format!("PLM config: {e}")),
    }
}

/// The file store at `root`, saying on its first frame why it is not the PLM.
#[cfg(not(target_arch = "wasm32"))]
pub fn file_store_with_notice(root: std::path::PathBuf, reason: String) -> Box<dyn ModelStore> {
    Box::new(
        native_model::FileModelStore::rooted_at(root)
            .with_notice(format!("{reason} — this session uses the file stores"))
            .with_plm_reason(reason),
    )
}

#[cfg(not(target_arch = "wasm32"))]
pub use native_boot::{boot_native_store, check_native_plm, NativeFileBackend, BOOT_TIMEOUT};

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;

/// Ask for a frame from anywhere, any thread: an async answer has landed that
/// the frame loop should pick up. Browser: the egui context registered at boot.
/// Native: the PLM executor's wake hook (the frame loop's `request_repaint`).
pub(crate) fn wake_ui() {
    #[cfg(target_arch = "wasm32")]
    web_model::wake_frame_loop();
    #[cfg(not(target_arch = "wasm32"))]
    crate::plm::native::request_wake();
}

/// Run a background task (a PLM request, a store write, a thumbnail upload) and
/// wake the frame loop whenever it makes progress. The app repaints only on
/// input and explicit requests, so an answer that lands while the user is not
/// moving the mouse is otherwise not shown, and a step that waits for the next
/// frame does not run, until they do. Natively the PLM executor's waker already
/// wakes the loop; in the browser the task is wrapped so each poll (after the
/// I/O it was waiting on) requests a repaint.
pub(crate) fn spawn_waking(task: impl std::future::Future<Output = ()> + 'static) {
    #[cfg(target_arch = "wasm32")]
    wasm_bindgen_futures::spawn_local(web_model::WakeOnPoll(Box::pin(task)));
    #[cfg(not(target_arch = "wasm32"))]
    crate::plm::native::spawn(task);
}

/// The document extension for a model recipe (`<name>.nbrep`) — the NORMAL
/// part's. A bare name with no class extension means this one; a family
/// (`.fbrep`) or template (`.tbrep`) keeps its extension in its name, so its
/// class survives every round trip (see [`crate::document_class`]).
pub const MODEL_EXT: &str = ".nbrep";

/// Every model document extension, dot-less, for the explorer's filters.
pub const MODEL_EXTENSIONS: &[&str] = &["nbrep", "fbrep", "tbrep"];

/// A document file name with its class extension made lowercase, and
/// `.nbrep` added when it has none: `Bolt` -> `Bolt.nbrep`,
/// `Bolt.FBREP` -> `Bolt.fbrep`.
pub fn model_file_name(name: &str) -> String {
    let class = crate::document_class::DocumentClass::of_name(name).unwrap_or_default();
    class.file_name(name)
}

// --- Desktop: the PLM session store ---------------------------------------------
/// The native half of plan S2: the mirror over a remote backend, hydrated
/// before the first frame, exactly as the wasm entry point hydrates IndexedDB
/// before `WebRunner::start`. Built ONLY when a PLM is configured; the
/// file-based app never reaches this module.
#[cfg(not(target_arch = "wasm32"))]
mod native_boot {
    use super::mirror_store::{BackendFuture, MirrorStore, StoreBackend, DIR_PREFIX, PREFIX};
    use super::native_model::FileModelStore;
    use super::{BrowserEntry, BrowserPlace, ModelStore, Residency};
    use crate::plm::config::PlmConfig;
    use crate::plm::PlmFuture;
    use std::path::{Path, PathBuf};
    use std::rc::Rc;

    /// How long the boot waits for sign-in and the index before giving up and
    /// starting on the file stores. The window is blank while it waits, so this
    /// is a bound on a hung server, not an expected duration.
    pub const BOOT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);

    /// Every reserved name this backend stores: exactly the user's preferences
    /// and the machine's local keys (D1's split, `PREFERENCE_KEYS` ∪
    /// `LOCAL_KEYS`). DERIVED, not listed: a hand-kept copy once lacked
    /// `@plm_import`, and every PLM session refused to keep its import ledger.
    fn reserved() -> impl Iterator<Item = &'static str> {
        super::PREFERENCE_KEYS.iter().chain(super::LOCAL_KEYS).copied()
    }

    /// A `StoreBackend` over the native file store: the mirror's keys mapped
    /// back to the names `FileModelStore` has always used, so `@recovery` lands
    /// in `<root>/recovery.json` in a PLM session exactly as it does in a file
    /// session. It is the PLM session's LOCAL key space (D1: the local-first
    /// copy of `@recovery`), handed to the PLM client to compose.
    ///
    /// Every call is synchronous file I/O answered with a resolved future, so
    /// it lands writes of one key in call order by itself.
    pub struct NativeFileBackend {
        files: FileModelStore,
    }

    impl NativeFileBackend {
        pub fn rooted_at(root: PathBuf) -> Self {
            Self { files: FileModelStore::rooted_at(root) }
        }

        /// The store name a mirror key stands for; `None` for an explorer
        /// directory row, which this backend does not hold.
        fn name_of(key: &str) -> Option<String> {
            if let Some(name) = reserved().find(|name| MirrorStore::key(name) == key) {
                return Some(name.to_string());
            }
            if key.starts_with(DIR_PREFIX) {
                return None;
            }
            key.strip_prefix(PREFIX).map(str::to_string)
        }
    }

    fn ready<T: 'static>(value: Result<T, String>) -> BackendFuture<T> {
        Box::pin(std::future::ready(value))
    }

    impl StoreBackend for NativeFileBackend {
        fn label(&self) -> String {
            self.files.backend_label()
        }

        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
            let reserved = reserved().map(|name| name.to_string());
            let documents = self.files.list();
            let all = reserved
                .chain(documents)
                .filter_map(|name| self.files.read(&name).map(|value| (MirrorStore::key(&name), value)))
                .collect();
            ready(Ok(all))
        }

        fn orders_writes_per_key(&self) -> bool {
            true
        }

        fn get(&self, key: &str) -> BackendFuture<Option<String>> {
            ready(Ok(Self::name_of(key).and_then(|name| self.files.read(&name))))
        }

        fn put(&self, key: &str, value: &str) -> BackendFuture<()> {
            ready(match Self::name_of(key) {
                Some(name) => self.files.write(&name, value),
                None => Err(format!("{key}: the local store keeps no explorer folders")),
            })
        }

        fn delete(&self, key: &str) -> BackendFuture<()> {
            ready(match Self::name_of(key) {
                Some(name) => self.files.remove(&name),
                None => Ok(()),
            })
        }
    }

    /// Connect to the configured PLM: sign in, check versions, and hand back
    /// the composed backend (documents and preferences on the server, `local`
    /// on this machine): S1's `plm::client::open_session`. A refusal is a
    /// sentence, and the session starts on the file stores saying it.
    fn plm_connect(config: PlmConfig, local: Rc<dyn StoreBackend>) -> PlmFuture<Rc<dyn StoreBackend>> {
        crate::plm::client::open_session(config, local)
    }

    /// The session store for a configured PLM, hydrated before this returns.
    /// Any failure — refused sign-in, a version the server does not serve, an
    /// index that will not load, no answer within [`BOOT_TIMEOUT`] — starts the
    /// session on the file stores at `root` instead, saying why on the first
    /// frame. A PLM never makes the app fail to start.
    pub fn boot_native_store(root: PathBuf, config: PlmConfig) -> Box<dyn ModelStore> {
        let (url, source) = (config.url.clone(), config.url_source);
        match boot_with(&root, config, plm_connect, BOOT_TIMEOUT) {
            Ok(store) => Box::new(store),
            Err(reason) => {
                let reason = format!("PLM at {url}: {reason}");
                Box::new(
                    FileModelStore::rooted_at(root)
                        .with_plm_launch(url, source)
                        .with_notice(format!("{reason} — this session uses the file stores"))
                        .with_plm_reason(reason),
                )
            }
        }
    }

    /// `brep-app --plm-check`: the boot's own sign-in and version check, and
    /// nothing else — no index, no store.
    pub fn check_native_plm(root: PathBuf, config: PlmConfig) -> Result<(), String> {
        let local: Rc<dyn StoreBackend> = Rc::new(NativeFileBackend::rooted_at(root));
        crate::plm::native::block_on_for(plm_connect(config, local), BOOT_TIMEOUT)
            .ok_or_else(|| format!("no answer within {} s", BOOT_TIMEOUT.as_secs()))?
            .map(|_| ())
    }

    /// [`boot_native_store`] with the connector and the time limit passed in,
    /// so a test can boot against a backend of its own.
    pub(super) fn boot_with(
        root: &Path,
        config: PlmConfig,
        connect: impl FnOnce(PlmConfig, Rc<dyn StoreBackend>) -> PlmFuture<Rc<dyn StoreBackend>>,
        timeout: std::time::Duration,
    ) -> Result<NativeMirrorStore, String> {
        use crate::plm::native::block_on_for;
        let late = || format!("no answer within {} s", timeout.as_secs());
        let files = FileModelStore::rooted_at(root.to_path_buf()).with_plm_launch(config.url.clone(), config.url_source);
        let local: Rc<dyn StoreBackend> = Rc::new(NativeFileBackend::rooted_at(root.to_path_buf()));
        let backend = block_on_for(connect(config, local), timeout).ok_or_else(late)??;
        // The index, not the documents: a catalog of thousands of parts must
        // not load at boot or stream into memory behind the first frame.
        // Document bodies remain OnDisk until read on demand.
        let entries = block_on_for(backend.load_index(), timeout)
            .ok_or_else(late)?
            .map_err(|e| format!("the store index would not load ({e})"))?;
        let wake: Rc<dyn Fn()> = Rc::new(crate::plm::native::request_wake);
        let core = MirrorStore::from_index(backend, entries, Some(wake));
        Ok(NativeMirrorStore { core, files })
    }

    /// The native PLM session store: the mirror (every CRUD and explorer
    /// method) plus this machine's real-file lane — a STEP or PDF export still
    /// lands in `<root>/models` and an external file is still read from disk,
    /// as in a file session.
    pub(super) struct NativeMirrorStore {
        pub(super) core: MirrorStore,
        files: FileModelStore,
    }

    impl ModelStore for NativeMirrorStore {
        #[cfg(feature = "automation")]
        fn files(&self, request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> { self.files.files(request) }

        // --- delegated to the mirror ------------------------------------------
        fn backend_label(&self) -> String {
            self.core.backend_label()
        }
        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
            self.core.plm_client()
        }
        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
            self.core.plm_revision(key)
        }
        fn note_checked_out(&self, key: &str) {
            self.core.note_checked_out(key)
        }
        fn plm_written_by_us(&self, key: &str) -> bool {
            self.core.plm_written_by_us(key)
        }
        fn refresh_plm_index(&self, keys: &[String], stale: bool) {
            self.core.refresh_plm_index(keys, stale)
        }
        fn remember_saved_document(&self, name: &str, contents: &str) {
            self.core.remember_saved_document(name, contents)
        }
        fn list(&self) -> Vec<String> {
            self.core.list()
        }
        fn read(&self, name: &str) -> Option<String> {
            self.core.read(name)
        }
        fn residency(&self, name: &str) -> Residency {
            self.core.residency(name)
        }
        fn canonical_identity(&self, name: &str) -> String {
            self.core.canonical_identity(name)
        }
        fn canonicalizer(&self) -> super::Canonicalizer {
            self.core.canonicalizer()
        }
        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 mutation_generation(&self) -> u64 {
            self.core.mutation_generation()
        }
        // The native queue these failures come from is run by the frame loop
        // itself (`BrepApp::ui`'s first line), not here: a store call behind an
        // early return would stall it.
        fn take_persistence_errors(&self) -> Vec<String> {
            self.core.take_persistence_errors()
        }
        fn take_failed_writes(&self) -> Vec<String> {
            self.core.take_failed_writes()
        }
        fn write_failed(&self, name: &str) -> bool {
            self.core.write_failed(name)
        }
        fn failed_write_base(&self, name: &str) -> Option<String> {
            self.core.failed_write_base(name)
        }
        fn write_if(&self, name: &str, contents: &str, expected: &str) -> Result<(), String> {
            self.core.write_if(name, contents, expected)
        }
        fn plm_session(&self) -> Option<crate::plm::connection::Session> {
            use crate::plm::connection::{parse_label, Keep, Session, Status};
            let (url, username) = parse_label(&self.core.backend_label())?;
            Some(Session { status: Status::Connected { url, username }, keep: Keep::Files(self.files.root().to_path_buf()) })
        }
        // The URL lives in the local file lane: `files` was told this
        // launch's URL and where it came from.
        fn plm_url_setting(&self) -> Option<crate::plm::connection::UrlSetting> {
            self.files.plm_url_setting()
        }
        fn save_plm_url(&self, url: &str) -> Result<crate::plm::connection::UrlSaved, String> {
            self.files.save_plm_url(url)
        }
        fn pending_writes(&self) -> usize {
            self.core.pending_writes()
        }
        fn pending_writes_except(&self, names: &[&str]) -> usize {
            self.core.pending_writes_except(names)
        }
        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 Save-file chooser browses the LOCAL files (`local_files`), so a
        // write at its location is the file store's; delegated like its
        // export siblings below rather than to the PLM's document mirror.
        fn browser_write_bytes(&self, file_name: &str, contents: &[u8]) -> Result<String, String> {
            self.files.browser_write_bytes(file_name, contents)
        }

        // --- this machine's real files ----------------------------------------
        fn local_files(&self) -> Option<&dyn ModelStore> {
            Some(&self.files)
        }
        fn list_external_files(&self, extensions: &[&str]) -> Vec<String> {
            self.files.list_external_files(extensions)
        }
        fn read_external_file(&self, name: &str) -> Option<Vec<u8>> {
            self.files.read_external_file(name)
        }
        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
            self.files.export_file_named(file_name, contents)
        }
        fn export_file_named_bytes(&self, file_name: &str, contents: &[u8]) -> Result<(), String> {
            self.files.export_file_named_bytes(file_name, contents)
        }
    }

}






// --- Document identity -----------------------------------------------------------
//
// A document's IDENTITY is the raw string the app keys it by: the name handed
// to `read` / `write`, kept on the open tab, and copied into everything that
// has to find the document again. On the file backends it is a path (native),
// a `/models/...` path (browser) or a bare name (the models folder). On a PLM
// store it is `part/<part id>/rev/<revision id>` — always a concrete revision,
// since the CAD app has no floating occurrences (D3).
//
// Every place the app keys a document by identity (plm-cad-integration-todo
// S0, enumerated 2026-09-25 by grep, not recalled):
//
// MINTED (a new identity comes into being):
//  1. `BrowserEntry.identity` — `browser_entries` rows; `browser_write`'s
//     return value (Save As, the STEP-to-part lane `panels/step_parts.rs`).
//  2. `Document::name` (`document.rs`) — the open tab's identity, set by Open
//     / Save / Save As (`panels/file.rs` `save_to`, `save_as`, the open path)
//     and by recovery. The ROOT: items 3 and 5 are copies of it.
//  3. The recovery blob's per-entry `name` (`recovery.rs` `RecoveryEntry`),
//     copied from `Document::name`, read back by `already_saved` and restored
//     onto the tab.
//  4. `sibling_identity` — a document beside another: a family's members
//     (`family_table.rs` `member_identity`, `generate_family`'s
//     `file_name_of`) and a spun-out part (`panels/file.rs`
//     `spin_out_target`). There are no folders on a PLM store: S7 / S9
//     replace these with a new part.
//  5. The ACOMP occurrence chain's `sourceKey` — `partsLibrary.<part>.sourceKey`
//     in an assembly document, written at insert (`panels/file.rs`
//     `insert_component_document`, `panels/step_parts.rs`) from the part's
//     identity; RESOLVED by `store.read(sourceKey)` in
//     `panels/update_components.rs`, `panels/parts_library.rs`
//     (`write_through`), `panels/component_actions.rs` (`part_source_key`,
//     Edit Part), `panels/bom.rs`, `panels/ecad_parts.rs` (open requests) and
//     `app.rs`. S13 rewrites file-path sourceKeys to revision keys.
//
// DERIVED (read off an identity's shape):
//  6. `model_display_name` (tab title, name field, duplicate-open check in
//     `panels/file.rs` `name_is_free`), `file_name_of`, and
//     `DocumentClass::of_name` (a document's class from its EXTENSION) — a
//     revision key has neither a file name nor an extension; on a PLM store
//     the class comes from the index (P3 / S7).
//
// NOT identities, though the plan's first draft listed them:
//  * `@pinned` holds explorer FOLDER locations, never documents — in PLM mode
//    it pins workspace folders (S14) and stays a Preferences key.
// `@recent_documents` holds document identities in most-recent-first order;
// it is a user preference and opens through the same file-dialog door.
//
// The seam: `ModelStore::identity`, `ModelStore::display_name` and
// `ModelStore::sibling_of`, whose defaults are exactly the path rules below,
// so a file backend is unchanged and a PLM backend supplies its own.

/// [`ModelStore::canonicalizer`]'s answer.
pub type Canonicalizer = std::rc::Rc<dyn Fn(&str) -> String>;

/// A document identity read for its shape — see the enumeration above.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DocumentIdentity {
    /// A native path, a browser `/models/...` path, or a bare name.
    Path(String),
    /// A PLM document key, `part/<part id>/rev/<revision id>`.
    Revision { part: String, revision: String },
}

impl DocumentIdentity {
    /// Read `key` as a PLM revision key — `part/<id>/rev/<id>`, both halves
    /// non-empty and slash-free, the same split the server's store routes make.
    ///
    /// Only a PLM-backed store may call this on its identities: the SHAPE is
    /// not proof, since a browser document at `models/part/7/rev/3.nbrep`
    /// lists as `part/7/rev/3`. That is why the file backends never parse.
    pub fn parse_revision_key(key: &str) -> Option<Self> {
        match key.split('/').collect::<Vec<_>>().as_slice() {
            ["part", part, "rev", revision] if !part.is_empty() && !revision.is_empty() => {
                Some(DocumentIdentity::Revision {
                    part: crate::plm::identity::unsegment(part)?,
                    revision: crate::plm::identity::unsegment(revision)?,
                })
            }
            _ => None,
        }
    }

    /// The raw string this identity is keyed by.
    pub fn key(&self) -> String {
        match self {
            DocumentIdentity::Path(path) => path.clone(),
            DocumentIdentity::Revision { part, revision } => crate::plm::identity::document_key(part, revision),
        }
    }
}

/// The identity of the file `file_name` in the same folder as the document
/// `identity`: a native path, a browser `/models/...` path, or — for a
/// document known only by a bare name — the bare `file_name`, which both
/// stores resolve into their models folder.
pub fn sibling_identity(identity: &str, file_name: &str) -> String {
    match identity.rfind(['/', '\\']) {
        Some(cut) => format!("{}{file_name}", &identity[..=cut]),
        None => file_name.to_string(),
    }
}

/// The last path component of a document identity (`/a/b/bolt.fbrep` ->
/// `bolt.fbrep`), extension kept.
pub fn file_name_of(identity: &str) -> String {
    identity.rsplit(['/', '\\']).next().unwrap_or(identity).to_string()
}

/// 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);
    // Only the NORMAL extension is implied: a family or template keeps its
    // extension in its name, which is what carries its class.
    match crate::document_class::DocumentClass::of_name(base) {
        Some(crate::document_class::DocumentClass::Normal) => {
            crate::document_class::strip_class_extension(base).to_string()
        }
        _ => 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, Residency, DOCK_LAYOUT_KEY,
        FEATURE_PALETTE_DISPLAY_KEY, KICAD_LIBRARY_KEY, PINNED_KEY, PLM_IMPORT_KEY, RECOVERY_KEY,
        SETTINGS_KEY,
    };
    use std::cell::{Cell, RefCell};
    use std::path::{Path, PathBuf};

    /// Persist models as `<config>/brep-app/models/<name>.nbrep` 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.
    /// The PLM a config root names (D5's files only: what this machine keeps),
    /// as "not connected, reason unknown". A file that cannot be read is
    /// reported the same way, with the reason.
    fn configured_plm(root: &std::path::Path) -> Option<crate::plm::connection::Session> {
        use crate::plm::connection::{Keep, Session, Status};
        let status = match crate::plm::config::resolve(root, &|_| None, &Default::default()) {
            Ok(None) => return None,
            Ok(Some(config)) => Status::NotConnected { url: config.url, reason: None },
            Err(e) if root.join("plm.json").exists() => Status::NotConnected { url: String::new(), reason: Some(e) },
            Err(_) => return None,
        };
        Some(Session { status, keep: Keep::Files(root.to_path_buf()) })
    }

    pub struct FileModelStore {
        app_dir: PathBuf,
        dir: PathBuf,
        browser_dir: RefCell<PathBuf>,
        /// See [`ModelStore::mutation_generation`]. A plain `Cell` — this store
        /// is built once and held behind one `Box`, never cloned.
        mutations: Cell<u64>,
        /// Said once, on the first frame: why a session that asked for a PLM is
        /// on the file stores instead. Empty in every file-only session.
        notices: RefCell<Vec<String>>,
        /// The PLM configured in `app_dir` (read once, when the store is
        /// built) and why this session is not on it: the PLM tab's status.
        plm: RefCell<Option<crate::plm::connection::Session>>,
        /// Where `plm`'s URL came from: `plm.json`, unless the launch named
        /// it by switch or variable ([`Self::with_plm_launch`]).
        plm_source: Cell<crate::plm::config::Source>,
    }

    impl FileModelStore {
        pub fn new() -> Self {
            // The one config-directory rule, shared with the PLM's two files.
            let app_dir = crate::plm::config::app_config_dir();
            let plm = configured_plm(&app_dir);
            Self {
                dir: app_dir.join("models"),
                browser_dir: RefCell::new(app_dir.join("models")),
                app_dir,
                mutations: Cell::new(0),
                notices: RefCell::new(Vec::new()),
                plm: RefCell::new(plm),
                plm_source: Cell::new(crate::plm::config::Source::File),
            }
        }

        /// A store rooted at an explicit directory — used by the round-trip test.
        /// The tests stay headless and exercise the same egui explorer path.
        ///
        /// COLLAPSES the two directories [`Self::new`] keeps apart: models and
        /// reserved state land together. That is what a unit test wants and
        /// what a session must not have — see [`Self::rooted_at`].
        #[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,
                mutations: Cell::new(0),
                notices: RefCell::new(Vec::new()),
                plm: RefCell::new(None),
                plm_source: Cell::new(crate::plm::config::Source::File),
            }
        }

        /// A store rooted at `root` with the SAME split [`Self::new`] makes
        /// under the user's config directory: models in `<root>/models`,
        /// reserved application state in `<root>`. The models directory is
        /// created now, so the explorer opens on a real location rather than on
        /// a path that does not exist yet.
        pub fn rooted_at(root: PathBuf) -> Self {
            let models = root.join("models");
            let _ = std::fs::create_dir_all(&models);
            let plm = configured_plm(&root);
            Self {
                app_dir: root,
                browser_dir: RefCell::new(models.clone()),
                dir: models,
                mutations: Cell::new(0),
                notices: RefCell::new(Vec::new()),
                plm: RefCell::new(plm),
                plm_source: Cell::new(crate::plm::config::Source::File),
            }
        }

        /// Queue `notice` for the first frame's notice drain (see
        /// [`ModelStore::take_persistence_errors`]).
        pub fn with_notice(self, notice: String) -> Self {
            self.notices.borrow_mut().push(notice);
            self
        }

        /// The PLM this launch resolved — `url` from `source`, which may be
        /// `--plm-url` or `BREP_PLM_URL` rather than this root's `plm.json` —
        /// as the session the PLM tab shows (not connected, reason unknown).
        pub fn with_plm_launch(self, url: String, source: crate::plm::config::Source) -> Self {
            use crate::plm::connection::{Keep, Session, Status};
            *self.plm.borrow_mut() = Some(Session { status: Status::NotConnected { url, reason: None }, keep: Keep::Files(self.app_dir.clone()) });
            self.plm_source.set(source);
            self
        }

        /// Keep why this session is not on its configured PLM, for the PLM
        /// tab (the notice above is drained on the first frame).
        pub fn with_plm_reason(self, reason: String) -> Self {
            if let Some(session) = self.plm.borrow_mut().as_mut() {
                if let crate::plm::connection::Status::NotConnected { url, reason: kept } = &mut session.status {
                    // The boot's sentence names the server first; the tab
                    // already does.
                    let own = format!("PLM at {url}: ");
                    *kept = Some(reason.strip_prefix(&own).map(str::to_string).unwrap_or(reason));
                }
            }
            self
        }

        /// The root D5's files live in.
        pub(crate) fn root(&self) -> &std::path::Path {
            &self.app_dir
        }

        /// Record that a write or a delete LANDED (see
        /// [`ModelStore::mutation_generation`]).
        fn bump(&self) {
            self.mutations.set(self.mutations.get().wrapping_add(1));
        }

        /// Resolve a name to a path. Explicit paths remain supported for existing
        /// callers; a bare name maps to `<dir>/<sanitized>.nbrep`.
        fn resolve(&self, name: &str) -> PathBuf {
            Self::resolve_in(&self.app_dir, &self.dir, name)
        }

        fn resolve_in(app_dir: &Path, dir: &Path, name: &str) -> PathBuf {
            match name {
                SETTINGS_KEY => return app_dir.join("settings.json"),
                FEATURE_PALETTE_DISPLAY_KEY => return app_dir.join("feature_palette_display.json"),
                DOCK_LAYOUT_KEY => return app_dir.join("dock_layout.json"),
                PINNED_KEY => return app_dir.join("pinned.json"),
                RECOVERY_KEY => return app_dir.join("recovery.json"),
                KICAD_LIBRARY_KEY => return app_dir.join("kicad_library.json"),
                crate::panels::cam_library::CAM_TOOL_LIBRARY_KEY => return app_dir.join("cam_tools.json"),
                super::RECENT_DOCUMENTS_KEY => return app_dir.join("recent_documents.json"),
                super::RECENT_THUMBNAILS_KEY => return app_dir.join("recent_thumbnails.json"),
                PLM_IMPORT_KEY => return app_dir.join("plm_import.json"),
                super::PLUGINS_KEY => return app_dir.join("plugins.json"),
                super::JAVASCRIPT_DRAFT_KEY => return app_dir.join("javascript_draft.js"),
                _ => {}
            }
            if name.contains('/') || name.contains('\\') {
                return PathBuf::from(name);
            }
            let class = crate::document_class::DocumentClass::of_name(name).unwrap_or_default();
            let safe: String = crate::document_class::strip_class_extension(name)
                .chars()
                .map(|c| {
                    if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
                        c
                    } else {
                        '_'
                    }
                })
                .collect();
            dir.join(class.file_name(&safe))
        }

        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 {
        #[cfg(feature = "automation")]
        fn files(&self, request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> {
            std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;
            let backend = brep_mcp_core::files::native::NativeFiles::new([
                ("documents".into(), self.dir.clone()), ("workspace".into(), self.dir.clone()),
            ])?;
            let reply = brep_mcp_core::files::execute(&backend, request)?;
            if !request.operation.annotations().read_only { self.mutations.set(self.mutations.get().wrapping_add(1)); }
            Ok(reply)
        }

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

        fn local_files(&self) -> Option<&dyn ModelStore> {
            Some(self)
        }

        // Writes are synchronous here, so nothing fails after `write` returned;
        // the only thing this lane ever carries is a boot notice.
        fn take_persistence_errors(&self) -> Vec<String> {
            std::mem::take(&mut *self.notices.borrow_mut())
        }

        fn plm_session(&self) -> Option<crate::plm::connection::Session> {
            self.plm.borrow().clone()
        }

        fn plm_url_setting(&self) -> Option<crate::plm::connection::UrlSetting> {
            use crate::plm::connection::{Status, UrlSetting};
            let plm = self.plm.borrow();
            let url = plm.as_ref().map(|session| match &session.status {
                Status::Connected { url, .. } | Status::NotConnected { url, .. } => url.clone(),
            });
            Some(UrlSetting {
                dir: self.app_dir.clone(),
                url: url.filter(|url| !url.is_empty()),
                source: plm.as_ref().map(|_| self.plm_source.get()),
            })
        }

        fn save_plm_url(&self, url: &str) -> Result<crate::plm::connection::UrlSaved, String> {
            let (url, token_dropped) = crate::plm::config::repoint(&self.app_dir, url)?;
            // A session on plm.json moves to the new server now (signed out:
            // the tab's sign-in reaches it). One a switch or variable named
            // keeps that URL for this launch; plm.json is for the next.
            if self.plm_source.get() == crate::plm::config::Source::File {
                *self.plm.borrow_mut() = configured_plm(&self.app_dir);
            }
            Ok(crate::plm::connection::UrlSaved { url, token_dropped })
        }

        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();
                    crate::document_class::DocumentClass::of_name(&name)
                        .is_some()
                        .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()
        }

        // A stat, not a read: an assembly's Save asks this of every part it places.
        fn residency(&self, name: &str) -> Residency {
            if self.resolve(name).is_file() { Residency::Resident } else { Residency::Absent }
        }

        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}"))?;
            }
            super::write_atomic(&path, contents.as_bytes(), false).map_err(|e| format!("write {}: {e}", path.display()))?;
            self.bump();
            Ok(())
        }

        fn mutation_generation(&self) -> u64 {
            self.mutations.get()
        }

        fn remove(&self, name: &str) -> Result<(), String> {
            match std::fs::remove_file(self.resolve(name)) {
                // A delete that found nothing changed nothing, so it does not
                // count: the generation tracks CONTENT, not calls.
                Ok(()) => {
                    self.bump();
                    Ok(())
                }
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
                Err(e) => Err(format!("remove: {e}")),
            }
        }

        fn canonical_identity(&self, name: &str) -> String {
            // `resolve` is where every read and write goes, so it IS the
            // document a name means; the explorer spells paths the same way.
            self.resolve(name).to_string_lossy().into_owned()
        }

        fn canonicalizer(&self) -> super::Canonicalizer {
            let (app_dir, dir) = (self.app_dir.clone(), self.dir.clone());
            std::rc::Rc::new(move |name| Self::resolve_in(&app_dir, &dir, name).to_string_lossy().into_owned())
        }

        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> {
            // Rebuilt from its components: a typed `C:\models/sub` (or
            // `/models//sub/`) is the folder the walker lists as
            // `C:\models\sub`, and a file written there must carry the same
            // identity, or one file reads as two.
            let path: PathBuf = PathBuf::from(location).components().collect();
            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 file_name = PathBuf::from(name)
                .file_name()
                .ok_or("invalid file name")?
                .to_string_lossy()
                .into_owned();
            let file_name = super::model_file_name(&file_name);
            let path = self.browser_dir.borrow().join(file_name);
            super::write_atomic(&path, contents.as_bytes(), false)
                .map_err(|e| format!("write {}: {e}", path.display()))?;
            // This door writes the file ITSELF rather than going through
            // `write`, so it has to move the generation itself.
            self.bump();
            Ok(path.to_string_lossy().into_owned())
        }

        fn browser_write_bytes(&self, file_name: &str, contents: &[u8]) -> Result<String, String> {
            let file_name = PathBuf::from(file_name)
                .file_name()
                .ok_or("invalid file name")?
                .to_owned();
            let folder = self.browser_dir.borrow().clone();
            // The folder the explorer shows normally exists; the models folder
            // of a fresh store may not yet (the export lane made it too).
            std::fs::create_dir_all(&folder).map_err(|e| format!("create {}: {e}", folder.display()))?;
            let path = folder.join(file_name);
            super::write_atomic(&path, contents, false)
                .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> {
            self.export_file_named_bytes(file_name, contents.as_bytes())
        }

        fn export_file_named_bytes(&self, file_name: &str, contents: &[u8]) -> 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);
            super::write_atomic(&path, contents, false)
                .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 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`].
//
// Hydration is the only WHOLE-key-space read, not the only read. It cannot be:
// the backend is shared with every other tab of the origin, and a mirror that
// only ever loaded at boot goes stale the moment someone else saves — which is
// what made a part saved in one tab un-insertable in another until the user hit
// reload. [`MirrorStore::refresh_key`] re-reads ONE key through
// [`StoreBackend::get`] and folds it in, so the correction costs a single record
// rather than the corpus; what drives it is platform business, and lives in
// [`web_model`](super::web_model).
pub(crate) mod mirror_store {
    use super::{
        model_display_name, BrowserEntry, BrowserPlace, KeySpace, ModelStore, PlaceKind,
        Residency, DOCK_LAYOUT_KEY, FEATURE_PALETTE_DISPLAY_KEY, KICAD_LIBRARY_KEY, PINNED_KEY,
        PLM_IMPORT_KEY, RECOVERY_KEY, SETTINGS_KEY,
    };
    use std::cell::{Cell, RefCell};
    use std::collections::{BTreeMap, BTreeSet, VecDeque};
    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:";
    /// Ordinary binary/text files stay separate from model documents.
    pub(crate) const FILE_PREFIX: &str = "brep-app:file:";

    #[cfg(feature = "automation")]
    mod files { include!("store_files.rs"); }


    /// 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>>>>;

    /// One hydrated key's value in the mirror: the bytes themselves, or only
    /// the fact that they exist and how many there are.
    ///
    /// `OnDisk` is what makes an index-only hydrate possible: `list`,
    /// `browser_entries` and sizes answer from it with no bytes in memory, and
    /// the bytes arrive later — on the first `read`, or from
    /// [`MirrorStore::prefetch`] in the background.
    #[derive(Clone, Debug, PartialEq, Eq)]
    // `OnDisk` is built only by an index-only backend: the tests' today, the
    // PLM's in S1.
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) enum Entry {
        Resident(String),
        OnDisk { bytes: u64 },
    }

    /// One row of a PLM index answer: the mirror key, its size and the hash
    /// of the document the server holds (sha256, hex — what
    /// [`crate::plm::content_hash`] computes of the same bytes).
    pub(crate) struct IndexRow {
        pub(crate) key: String,
        pub(crate) bytes: u64,
        pub(crate) content_hash: String,
    }

    impl Entry {
        /// The value's size in bytes, whether or not it is loaded.
        pub(crate) fn len(&self) -> u64 {
            match self {
                Entry::Resident(value) => value.len() as u64,
                Entry::OnDisk { bytes } => *bytes,
            }
        }
    }

    /// The key space a BACKEND key belongs to (see [`KeySpace`]), or `None` for
    /// an explorer directory row (`brep-app:dir:`), which only the file backends
    /// hold — a PLM user's folders are the workspace (S14), not store keys.
    /// A key this module did not mint counts as a document.
    #[cfg_attr(not(test), allow(dead_code))] // routed by S1's PLM session
    pub(crate) fn key_space(key: &str) -> Option<KeySpace> {
        if key.starts_with(DIR_PREFIX) || key.starts_with(FILE_PREFIX) {
            return None;
        }
        for name in super::PREFERENCE_KEYS.iter().chain(super::LOCAL_KEYS) {
            if key == MirrorStore::key(name) {
                return Some(KeySpace::of(name));
            }
        }
        Some(KeySpace::Documents)
    }

    /// 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.
    ///
    /// The obligations an implementation carries:
    ///
    /// * **Per-key FIFO — the mirror's, unless the backend says it is its own.**
    ///   Two `put`s of the same key must land in call order, whatever order
    ///   their futures are polled in. 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`), and says so through
    ///   [`Self::orders_writes_per_key`]. Every other backend — an HTTP one has
    ///   no such guarantee — gets the mirror's per-key send queue: a key's next
    ///   `put`/`delete` is not even ISSUED until its previous one has settled.
    /// * **`load_index` or `load_all` hydrates the whole key space** — every key
    ///   is present in the answer; `load_index` may leave values
    ///   [`Entry::OnDisk`].
    /// * **`get` sees other clients' writes.** The mirror calls it to correct
    ///   itself after someone else wrote the key, and to load an `OnDisk`
    ///   entry, so it must read THROUGH any per-connection cache of the
    ///   implementation's own.
    ///
    /// ## Index hydration
    ///
    /// A full hydrate holds EVERY saved document resident for the session: a
    /// non-issue for a browser origin (IndexedDB is local, and still hydrates
    /// whole through the `load_index` default), untenable for a remote catalog
    /// of thousands of parts. So the mirror's value is an [`Entry`], a backend
    /// may answer [`Self::load_index`] with sizes instead of bytes, and the
    /// bytes arrive on demand ([`ModelStore::read`] asks for them) or in the
    /// background ([`MirrorStore::prefetch`]). All of it sits behind THIS trait
    /// and behind [`ModelStore`], so no call site moved.
    pub(crate) trait StoreBackend {
        /// A short human label for the storage panel header (see
        /// [`ModelStore::backend_label`]).
        fn label(&self) -> String;

        /// The signed-in client of a backend that talks to a PLM (see
        /// [`ModelStore::plm_client`]). `None` for every local backend.
        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
            None
        }

        /// See [`ModelStore::plm_revision`]. `None` for every local backend.
        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
            let _ = key;
            None
        }

        /// See [`ModelStore::note_checked_out`].
        fn note_checked_out(&self, key: &str) {
            let _ = key;
        }

        /// See [`ModelStore::plm_written_by_us`].
        fn plm_written_by_us(&self, key: &str) -> bool {
            let _ = key;
            false
        }

        /// See [`ModelStore::refresh_plm_index`].
        fn refresh_plm_index(&self, keys: &[String], stale: bool) {
            let _ = (keys, stale);
        }

        /// The index rows of `keys` (store keys, `part/<p>/rev/<r>`), as the
        /// LAZY entries the mirror reconciles on a feed move: `(mirror key,
        /// [`Entry::OnDisk`], content hash)`. A key the server no longer
        /// lists is absent from the answer. `Err` from a backend that keeps no
        /// index: the mirror then leaves its entries alone.
        fn index_rows(&self, keys: &[String]) -> BackendFuture<Vec<IndexRow>> {
            let _ = keys;
            Box::pin(async { Err("this store keeps no index".to_string()) })
        }

        /// The whole index as [`Self::index_rows`] answers it, for a stale
        /// feed (a resync): every document the server lists.
        fn index_all(&self) -> BackendFuture<Vec<IndexRow>> {
            Box::pin(async { Err("this store keeps no index".to_string()) })
        }

        /// Pull the entire key space, values included.
        fn load_all(&self) -> BackendFuture<Vec<(String, String)>>;

        /// Pull the entire key space as METADATA: every key, with its bytes
        /// where they are cheap and only its size ([`Entry::OnDisk`]) where they
        /// are not. Called ONCE, during the async boot, before any
        /// [`MirrorStore`] exists.
        ///
        /// The default is [`Self::load_all`] with every value resident — exactly
        /// the hydrate a local backend has always done. A remote backend
        /// overrides it (the PLM's `GET /api/store/index` IS this call).
        fn load_index(&self) -> BackendFuture<Vec<(String, Entry)>> {
            let all = self.load_all();
            Box::pin(async move {
                Ok(all
                    .await?
                    .into_iter()
                    .map(|(key, value)| (key, Entry::Resident(value)))
                    .collect())
            })
        }

        /// `true` when this backend ALREADY lands two writes of one key in call
        /// order without help (IndexedDB), so the mirror issues every write
        /// the moment it is made. The default, `false`, puts the backend behind
        /// the mirror's per-key send queue — the safe answer for a backend that
        /// has not thought about it.
        fn orders_writes_per_key(&self) -> bool {
            false
        }

        /// Read ONE key's CURRENT value straight from the backend — `None` when
        /// it is absent.
        ///
        /// This is the LIVE read, and it exists because the mirror is not the
        /// only writer of its key space: a SECOND TAB of the same origin holds
        /// its own mirror over the same IndexedDB (and a remote backend would
        /// have other clients still). Hydration alone therefore goes stale the
        /// moment someone else saves — the user's "I saved a part in one tab and
        /// the other tab cannot insert it until I reload". [`MirrorStore::refresh_key`]
        /// answers that by re-reading exactly the key that changed. It is also
        /// how an [`Entry::OnDisk`] value is loaded.
        ///
        /// REQUIRED rather than defaulted, for the reason
        /// [`ModelStore::mutation_generation`] is: a `None`-returning default
        /// would let a new backend compile while silently making every external
        /// change look like a deletion.
        fn get(&self, key: &str) -> BackendFuture<Option<String>>;

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

        /// [`Self::put`] only over the document whose content hash is
        /// `expected`. A backend that can tell refuses a newer one with an
        /// error starting [`CHANGED_ELSEWHERE`]; one that cannot just puts.
        fn put_if(&self, key: &str, value: &str, expected: &str) -> BackendFuture<()> {
            let _ = expected;
            self.put(key, value)
        }

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

        /// Commit a bounded file rename as one transaction. A failure must
        /// preserve the source keys; stores without this primitive refuse it.
        #[cfg(feature = "automation")]
        fn move_files(&self, _entries: Vec<(String, String, String)>) -> BackendFuture<()> {
            Box::pin(async { Err("atomic file moves are unsupported by this backend".into()) })
        }

    }

    /// A [`StoreBackend`] that sends each [`KeySpace`] to its own backend — the
    /// shape D1 gives a PLM session: documents to the store routes, preferences
    /// to the per-user store (P5), `@recovery` to the machine. Explorer
    /// directory rows travel with the documents, since only a file backend
    /// holds them; a documents backend with no folders refuses them itself.
    ///
    /// Hydration is the union of the three indexes. A key one backend returns
    /// that belongs to ANOTHER space is dropped rather than trusted: a backend
    /// is authoritative for its own space only.
    #[cfg_attr(not(test), allow(dead_code))] // composed by S1's PLM session
    pub(crate) struct KeySpaceRouter {
        pub(crate) documents: Rc<dyn StoreBackend>,
        pub(crate) preferences: Rc<dyn StoreBackend>,
        pub(crate) local: Rc<dyn StoreBackend>,
    }

    #[cfg_attr(not(test), allow(dead_code))]
    impl KeySpaceRouter {
        fn route(&self, key: &str) -> &Rc<dyn StoreBackend> {
            match key_space(key) {
                Some(KeySpace::Preferences) => &self.preferences,
                Some(KeySpace::Local) => &self.local,
                Some(KeySpace::Documents) | None => &self.documents,
            }
        }

        fn serves(space: KeySpace, key: &str) -> bool {
            match key_space(key) {
                Some(found) => found == space,
                None => space == KeySpace::Documents,
            }
        }

        fn spaces(&self) -> [(KeySpace, &Rc<dyn StoreBackend>); 3] {
            [
                (KeySpace::Documents, &self.documents),
                (KeySpace::Preferences, &self.preferences),
                (KeySpace::Local, &self.local),
            ]
        }
    }

    impl StoreBackend for KeySpaceRouter {
        fn label(&self) -> String {
            self.documents.label()
        }

        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
            self.documents.plm_client()
        }

        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
            self.documents.plm_revision(key)
        }
        fn note_checked_out(&self, key: &str) {
            self.documents.note_checked_out(key)
        }
        fn plm_written_by_us(&self, key: &str) -> bool {
            self.documents.plm_written_by_us(key)
        }

        fn refresh_plm_index(&self, keys: &[String], stale: bool) {
            self.documents.refresh_plm_index(keys, stale)
        }
        fn index_rows(&self, keys: &[String]) -> BackendFuture<Vec<IndexRow>> {
            self.documents.index_rows(keys)
        }
        fn index_all(&self) -> BackendFuture<Vec<IndexRow>> {
            self.documents.index_all()
        }

        fn load_all(&self) -> BackendFuture<Vec<(String, String)>> {
            let requests: Vec<_> = self
                .spaces()
                .into_iter()
                .map(|(space, backend)| (space, backend.load_all()))
                .collect();
            Box::pin(async move {
                let mut all = Vec::new();
                for (space, request) in requests {
                    all.extend(
                        request
                            .await?
                            .into_iter()
                            .filter(|(key, _)| Self::serves(space, key)),
                    );
                }
                Ok(all)
            })
        }

        fn load_index(&self) -> BackendFuture<Vec<(String, Entry)>> {
            let requests: Vec<_> = self
                .spaces()
                .into_iter()
                .map(|(space, backend)| (space, backend.load_index()))
                .collect();
            Box::pin(async move {
                let mut all = Vec::new();
                for (space, request) in requests {
                    all.extend(
                        request
                            .await?
                            .into_iter()
                            .filter(|(key, _)| Self::serves(space, key)),
                    );
                }
                Ok(all)
            })
        }

        fn orders_writes_per_key(&self) -> bool {
            self.spaces()
                .iter()
                .all(|(_, backend)| backend.orders_writes_per_key())
        }

        fn get(&self, key: &str) -> BackendFuture<Option<String>> {
            self.route(key).get(key)
        }

        fn put(&self, key: &str, value: &str) -> BackendFuture<()> {
            self.route(key).put(key, value)
        }

        fn put_if(&self, key: &str, value: &str, expected: &str) -> BackendFuture<()> {
            self.route(key).put_if(key, value, expected)
        }

        fn delete(&self, key: &str) -> BackendFuture<()> {
            self.route(key).delete(key)
        }
    }

    /// 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.
    // Built by the browser's boot today; a native session falls back to the file stores instead.
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    pub(crate) struct UnavailableBackend {
        reason: String,
    }

    // See `UnavailableBackend`.
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    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 get(&self, _key: &str) -> BackendFuture<Option<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) })
        }
    }

    /// What a backend's refusal starts with when it holds a newer document
    /// than the one a conditional write ([`StoreBackend::put_if`]) was based on.
    pub(crate) const CHANGED_ELSEWHERE: &str = "changed elsewhere: ";

    /// 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>,
        /// The documents whose write failed, not yet taken by the frame loop,
        /// which marks their tabs unsaved again ([`ModelStore::take_failed_writes`]).
        failed_writes: RefCell<Vec<String>>,
        /// Keys whose LAST write failed: the mirror holds what was sent (this
        /// session reads it), the backend does not ([`ModelStore::write_failed`]);
        /// with the content hash of the backend's document that write was
        /// based on (empty: unknown), for the retry's `If-Match`.
        unsynced: RefCell<BTreeMap<String, String>>,
        /// Per key, the base of the write last issued.
        bases: RefCell<BTreeMap<String, String>>,
        /// 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),
                failed_writes: RefCell::new(Vec::new()),
                unsynced: RefCell::new(BTreeMap::new()),
                bases: RefCell::new(BTreeMap::new()),
                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();
            }
        }

        /// The write of document `name` failed: besides its message, the frame
        /// loop learns WHICH document, so its tab reads unsaved again.
        pub(crate) fn record_failed_write(&self, name: &str) {
            let mut failed = self.failed_writes.borrow_mut();
            if !failed.iter().any(|n| n == name) {
                failed.push(name.to_string());
            }
        }

        fn take_failed_writes(&self) -> Vec<String> {
            std::mem::take(&mut *self.failed_writes.borrow_mut())
        }

        /// A write of `key` is issued, based on the backend's document with
        /// content hash `base` (empty: unknown).
        fn note_base(&self, key: &str, base: String) {
            self.bases.borrow_mut().insert(key.to_string(), base);
        }

        /// A write of `key` settled. Failed, the key is unsynced, keeping the
        /// base of its FIRST failed write (the backend's document before this
        /// session's unconfirmed writes); landed, or refused because the
        /// backend holds a newer document (`refused`), it is not.
        fn mark_unsynced(&self, key: &str, failed: bool) {
            let mut unsynced = self.unsynced.borrow_mut();
            if failed {
                let base = self.bases.borrow().get(key).cloned().unwrap_or_default();
                unsynced.entry(key.to_string()).or_insert(base);
            } else {
                unsynced.remove(key);
            }
        }

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

        /// 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).
        // The browser's `__brepStoreErrors` verification hook.
        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
        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 frame-driven executor
    /// ([`crate::plm::native`]), the same shape — polled once at once (so a
    /// backend whose futures are already resolved finishes inside `write`, as
    /// every test that does not care about timing assumes), parked if still
    /// pending, and polled again once its waker fires and the frame loop (or a
    /// test's [`test_executor::drive`]) runs the queue. 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 — and
    /// the parking is what lets a test hold one write open and watch what the
    /// per-key queue does with the next.
    #[cfg(target_arch = "wasm32")]
    fn spawn(task: impl Future<Output = ()> + 'static) {
        super::spawn_waking(task);
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn spawn(task: impl Future<Output = ()> + 'static) {
        crate::plm::native::spawn(task);
    }

    /// [`spawn`] for one document's write: natively the task is tagged with
    /// the document's store name, so `settle` on another document can leave
    /// it out (`plm::native::pending_except`).
    fn spawn_for(name: &str, task: impl Future<Output = ()> + 'static) {
        #[cfg(not(target_arch = "wasm32"))]
        crate::plm::native::tagged(name, || spawn(task));
        #[cfg(target_arch = "wasm32")]
        {
            let _ = name;
            spawn(task);
        }
    }


    /// 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. A value
        /// is [`Entry::OnDisk`] until something asks for its bytes.
        entries: Rc<RefCell<BTreeMap<String, Entry>>>,
        /// 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>>,
        /// See [`ModelStore::mutation_generation`]. SHARED like every other
        /// field: a clone is another handle on the same session state, and the
        /// `__brepStoreWrite` verification hook holds one — a write through
        /// that hook has to move the generation the app reads.
        mutations: Rc<Cell<u64>>,
        /// How many of our OWN pushes are still in flight, PER KEY. Used by
        /// [`Self::refresh_key`] to leave a key alone while this session is
        /// mid-write on it: pulling another tab's value in on top of a save we
        /// have already returned `Ok` for would show the user someone else's
        /// bytes under their own file name.
        in_flight: Rc<RefCell<BTreeMap<String, usize>>>,
        /// Repaint the reactive frame loop. The `ErrorLog` holds this for write
        /// failures; the store needs its own handle because an EXTERNAL change
        /// arrives on an async callback too, and a list that updates only when
        /// the user happens to move the mouse is the stale list all over again.
        wake: Option<Rc<dyn Fn()>>,
        /// `OnDisk` keys whose bytes have been asked of the backend and not yet
        /// answered, so a second `read` of one does not ask again.
        loading: Rc<RefCell<BTreeSet<String>>>,
        /// The per-key send queue (see [`StoreBackend::orders_writes_per_key`]):
        /// for each key with a write in flight, the writes made after it, not
        /// yet issued. A key is present exactly while its drain task runs.
        queues: Rc<RefCell<BTreeMap<String, VecDeque<QueuedWrite>>>>,
        /// A monotonic clock of authority: every local mutation of a key and
        /// every index request issued takes the next tick.
        clock: Rc<Cell<u64>>,
        /// Per key, the tick of the authority that last set it here — a local
        /// write, delete, remembered save, loaded body, or the ISSUE tick of
        /// the index answer applied to it. An index answer applies to a key
        /// only if it was issued after that tick (see [`Self::reconcile`]).
        freshness: Rc<RefCell<BTreeMap<String, u64>>>,
        /// A whole-index answer also speaks for keys never seen locally.
        full_index_authority: Rc<Cell<u64>>,
        /// The explorer's last listing and what it was taken from: an open
        /// Insert or Open dialog lists the folder every frame, and walking a
        /// 5,000-part key space each time was the dialog's frame cost.
        listing: Rc<RefCell<Option<(ListingKey, Vec<BrowserEntry>)>>>,
    }

    /// What a folder listing of [`MirrorStore`] depends on: the folder, the
    /// extensions asked for, and the key space as its mutation count, its
    /// size and its byte total say (a body that loads keeps its count but
    /// may move its size).
    #[derive(Clone, PartialEq)]
    struct ListingKey {
        dir: String,
        extensions: Vec<String>,
        mutations: u64,
        keys: usize,
        bytes: u64,
    }

    /// A write the per-key queue holds back: the document name its failure is
    /// reported under, and the backend call, made only when its turn comes.
    type QueuedWrite = (String, Box<dyn FnOnce() -> BackendFuture<()>>);

    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.
        // The browser's boot and the tests; the native boot hydrates from an index.
        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
        pub(crate) fn new(
            backend: Rc<dyn StoreBackend>,
            entries: Vec<(String, String)>,
            wake: Option<Rc<dyn Fn()>>,
        ) -> Self {
            Self::from_index(
                backend,
                entries
                    .into_iter()
                    .map(|(key, value)| (key, Entry::Resident(value)))
                    .collect(),
                wake,
            )
        }

        /// Build the session store from an INDEX ([`StoreBackend::load_index`]):
        /// every key present, some values only [`Entry::OnDisk`].
        pub(crate) fn from_index(
            backend: Rc<dyn StoreBackend>,
            entries: Vec<(String, Entry)>,
            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.clone())),
                pending: Rc::new(Cell::new(0)),
                mutations: Rc::new(Cell::new(0)),
                in_flight: Rc::new(RefCell::new(BTreeMap::new())),
                wake,
                loading: Rc::new(RefCell::new(BTreeSet::new())),
                queues: Rc::new(RefCell::new(BTreeMap::new())),
                clock: Rc::new(Cell::new(0)),
                freshness: Rc::new(RefCell::new(BTreeMap::new())),
                full_index_authority: Rc::new(Cell::new(0)),
                listing: Rc::new(RefCell::new(None)),
            }
        }
        /// The next tick of the authority clock.
        fn tick(&self) -> u64 {
            let next = self.clock.get() + 1;
            self.clock.set(next);
            next
        }
        /// A local authority over `key` now: later index answers that were
        /// issued before this cannot touch it.
        fn stamp_local(&self, key: &str) {
            let tick = self.tick();
            self.freshness.borrow_mut().insert(key.to_string(), tick);
        }

        /// 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(),
                FEATURE_PALETTE_DISPLAY_KEY => "brep-app:feature_palette_display".into(),
                DOCK_LAYOUT_KEY => "brep-app:dock_layout".into(),
                PINNED_KEY => "brep-app:pinned".into(),
                RECOVERY_KEY => "brep-app:recovery".into(),
                // Desktop-only today (the web build cannot read a KiCad
                // library), but a reserved name that fell through to the
                // document arm would key as `brep-app:model:@kicad_library` and
                // LIST as a document the day anything wrote it here.
                KICAD_LIBRARY_KEY => "brep-app:kicad_library".into(),
                crate::panels::cam_library::CAM_TOOL_LIBRARY_KEY => "brep-app:cam_tools".into(),
                super::RECENT_DOCUMENTS_KEY => "brep-app:recent_documents".into(),
                super::RECENT_THUMBNAILS_KEY => "brep-app:recent_thumbnails".into(),
                PLM_IMPORT_KEY => "brep-app:plm_import".into(),
                super::PLUGINS_KEY => "brep-app:plugins".into(),
                super::JAVASCRIPT_DRAFT_KEY => "brep-app:javascript_draft".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('/'));
            // The key drops ONLY the normal extension (an existing origin's
            // keys keep their identity); a family or template keeps its own,
            // lowercased, so `bolt` the part and `bolt.fbrep` the family are
            // two keys.
            let name = name.trim_matches('/');
            match crate::document_class::DocumentClass::of_name(name) {
                Some(crate::document_class::DocumentClass::Normal) => {
                    crate::document_class::strip_class_extension(name).to_string()
                }
                Some(_) => super::model_file_name(name),
                None => name.to_string(),
            }
        }

        fn virtual_model_path(relative: &str) -> String {
            format!("/models/{}", super::model_file_name(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 write to the executor, counting it in `pending` (and
        /// under its KEY in `in_flight`) and routing its eventual failure to the
        /// error log.
        ///
        /// `request` is the backend call itself, not its future: behind the
        /// per-key send queue it is made only once every earlier write of the
        /// same key has SETTLED, which is the FIFO an HTTP backend cannot give
        /// itself. A backend that orders its own writes
        /// ([`StoreBackend::orders_writes_per_key`]) has it called at once, so
        /// IndexedDB creates its transaction inside `write` exactly as before.
        fn push(
            &self,
            name: &str,
            key: &str,
            request: impl FnOnce() -> BackendFuture<()> + 'static,
        ) {
            self.pending.set(self.pending.get() + 1);
            *self.in_flight.borrow_mut().entry(key.to_string()).or_insert(0) += 1;
            if self.backend.orders_writes_per_key() {
                let settle = self.settler(key);
                let tag = name;
                let name = name.to_string();
                let request = request();
                spawn_for(tag, async move { settle(&name, request.await) });
                return;
            }
            {
                let mut queues = self.queues.borrow_mut();
                if let Some(queue) = queues.get_mut(key) {
                    // A write of this key is still open: this one waits its turn.
                    queue.push_back((name.to_string(), Box::new(request)));
                    return;
                }
                queues.insert(key.to_string(), VecDeque::new());
            }
            // Nothing ahead of it: issue now, then drain whatever queues behind.
            let settle = self.settler(key);
            let queues = self.queues.clone();
            let key = key.to_string();
            let first = (name.to_string(), request());
            spawn_for(name, async move {
                let (name, request) = first;
                settle(&name, request.await);
                loop {
                    let next = {
                        let mut queues = queues.borrow_mut();
                        let next = queues.get_mut(&key).and_then(VecDeque::pop_front);
                        if next.is_none() {
                            queues.remove(&key);
                        }
                        next
                    };
                    let Some((name, request)) = next else {
                        break;
                    };
                    // A failed write does not cancel the next: each is its own
                    // save, and each failure is reported under its own name.
                    settle(&name, request().await);
                }
            });
        }

        /// What one settled write does to the session's books: out of
        /// `pending` and `in_flight`, and into the error log if it failed.
        fn settler(&self, key: &str) -> impl Fn(&str, Result<(), String>) + 'static {
            let pending = self.pending.clone();
            let in_flight = self.in_flight.clone();
            let errors = self.errors.clone();
            let entries = self.entries.clone();
            let key = key.to_string();
            move |name, outcome| {
                pending.set(pending.get().saturating_sub(1));
                {
                    let mut in_flight = in_flight.borrow_mut();
                    if let Some(count) = in_flight.get_mut(&key) {
                        *count -= 1;
                        if *count == 0 {
                            in_flight.remove(&key);
                        }
                    }
                }
                match outcome {
                    Err(message) if message.starts_with(CHANGED_ELSEWHERE) => {
                        // The backend refused it because it holds a newer
                        // document than the one this write was based on: not
                        // ours any more. The mirror forgets what was sent, so
                        // the next read takes the newer document and a Save
                        // asks as for any document changed elsewhere.
                        errors.mark_unsynced(&key, false);
                        if let Some(entry) = entries.borrow_mut().get_mut(&key) {
                            let bytes = match entry {
                                Entry::Resident(text) => text.len() as u64,
                                Entry::OnDisk { bytes } => *bytes,
                            };
                            *entry = Entry::OnDisk { bytes };
                        }
                        errors.record_failed_write(name);
                        errors.record(format!("'{name}' was NOT saved: {}", &message[CHANGED_ELSEWHERE.len()..]));
                    }
                    Err(message) => {
                        errors.record_failed_write(name);
                        errors.mark_unsynced(&key, true);
                        errors.record(format!("'{name}' was NOT saved: {message}"));
                    }
                    Ok(()) => errors.mark_unsynced(&key, false),
                }
            }
        }

        /// Fold ONE externally-changed key into the mirror: `Some` is the value
        /// the backend now holds, `None` means it is gone.
        ///
        /// A change that is not a change (the value we already had) stops here —
        /// no generation bump, no repaint — so an echo costs nothing. A real one
        /// moves [`ModelStore::mutation_generation`], which is exactly what that
        /// counter promises ("every mutation that landed, WHOEVER made it") and
        /// what relights the outdated-components badge on an assembly whose part
        /// was just re-saved in another tab.
        // The browser's other-tab channel today; natively, the PLM change feed (S1).
        /// Fold an index answer into the entries. `asked`: the mirror keys a
        /// feed move named (a key missing from the answer was deleted on the
        /// server); `None`: the answer is the WHOLE index (a stale-feed
        /// resync), so every model key it does not list was deleted.
        ///
        /// The ordering policy, per key: an answer applies only if it was
        /// ISSUED (`issued`, the clock tick taken before the request left)
        /// after the authority that last set the key here — a local write or
        /// delete, a remembered save, a loaded body, or a newer answer. So an
        /// answer that left before a save and lands after it cannot evict the
        /// saved copy or delete the saved key, even with nothing in flight
        /// any more; and two answers landing out of order leave the newer
        /// one's result standing. A key with a write in flight or queued is
        /// skipped as well. A resident entry whose bytes hash to the row's
        /// content hash is left alone (the server holds what this app holds).
        /// Everything else becomes the server's row, lazily: a resident copy
        /// the server has moved on from is re-read on its next `read` (no
        /// body is fetched here), and an open document's unsaved edits live in
        /// its tab, not here. Returns whether anything changed.
        pub(crate) fn reconcile(&self, asked: Option<&[String]>, rows: Vec<IndexRow>, issued: u64) -> bool {
            let busy = |key: &str| {
                self.in_flight.borrow().contains_key(key)
                    || self.queues.borrow().contains_key(key)
                    || self.full_index_authority.get() >= issued
                    || self.freshness.borrow().get(key).is_some_and(|&tick| tick >= issued)
            };
            let listed: BTreeSet<&str> = rows.iter().map(|row| row.key.as_str()).collect();
            let mut changed = false;
            {
                let mut entries = self.entries.borrow_mut();
                let gone: Vec<String> = match asked {
                    Some(asked) => asked.iter().filter(|key| !listed.contains(key.as_str())).cloned().collect(),
                    None => entries
                        .keys()
                        .filter(|key| key.starts_with(PREFIX) && !listed.contains(key.as_str()))
                        .cloned()
                        .collect(),
                };
                for key in gone {
                    if busy(&key) {
                        continue;
                    }
                    self.freshness.borrow_mut().insert(key.clone(), issued);
                    changed |= entries.remove(&key).is_some();
                }
                for row in rows {
                    if busy(&row.key) {
                        continue;
                    }
                    self.freshness.borrow_mut().insert(row.key.clone(), issued);
                    let same = match entries.get(&row.key) {
                        Some(Entry::Resident(held)) => {
                            crate::plm::content_hash(held.as_bytes()) == row.content_hash
                        }
                        Some(Entry::OnDisk { bytes }) => *bytes == row.bytes,
                        None => false,
                    };
                    if same {
                        continue;
                    }
                    entries.insert(row.key, Entry::OnDisk { bytes: row.bytes });
                    changed = true;
                }
            }
            if asked.is_none() {
                self.full_index_authority.set(self.full_index_authority.get().max(issued));
            }
            if changed {
                self.mutations.set(self.mutations.get().wrapping_add(1));
                if let Some(wake) = &self.wake {
                    wake();
                }
            }
            changed
        }

        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
        pub(crate) fn apply_external(&self, key: &str, value: Option<String>) {
            self.stamp_local(key);
            let changed = {
                let mut entries = self.entries.borrow_mut();
                match value {
                    Some(value) => {
                        let same = matches!(entries.get(key), Some(Entry::Resident(held)) if *held == value);
                        if same {
                            false
                        } else {
                            entries.insert(key.to_string(), Entry::Resident(value));
                            true
                        }
                    }
                    None => entries.remove(key).is_some(),
                }
            };
            if !changed {
                return;
            }
            self.mutations.set(self.mutations.get().wrapping_add(1));
            if let Some(wake) = &self.wake {
                wake();
            }
        }

        /// Re-read `key` from the backend and fold the result in — the LIVE read
        /// behind the mirror, driven by whatever tells this session that someone
        /// else wrote (on the web, the `brep-app:store` broadcast in
        /// [`web_model`](super::web_model)).
        ///
        /// A key this session is itself mid-write on is left ALONE: our own
        /// `write` already returned `Ok` against the mirror, and racing another
        /// tab's older bytes in on top of it would replace the user's save with a
        /// stranger's under the same name. Skipping costs no correctness. Which
        /// of two simultaneous saves of one file wins is settled by the backend's
        /// own ordering (IndexedDB commits same-store transactions in creation
        /// order), and it settles the same way for the mirror: if our put was
        /// created last it lands last, so the mirror already holds what the
        /// backend ends up holding — and the OTHER tab hears our commit and
        /// corrects itself.
        // See `apply_external`.
        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
        pub(crate) fn refresh_key(&self, key: String) {
            if self.in_flight.borrow().contains_key(&key) {
                return;
            }
            let store = self.clone();
            let request = self.backend.get(&key);
            spawn(async move {
                match request.await {
                    Ok(value) => store.apply_external(&key, value),
                    // A failed re-read leaves the mirror as it was. It is NOT a
                    // persistence failure — nothing of the user's was lost — so it
                    // does not go to the toast channel; the stale row is the cost,
                    // and the next write to that key notifies again.
                    Err(_) => {}
                }
            });
        }

        /// Seed the log with a boot-time failure so the very first frame toasts it.
        // The browser's boot notice; the native boot reports through the file store it falls back to.
        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
        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).
        // Browser verification hooks.
        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
        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).
        // Browser verification hooks.
        #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
        pub(crate) fn len_of(&self, name: &str) -> Option<usize> {
            self.entries.borrow().get(&Self::key(name)).map(|v| v.len() as usize)
        }

        /// Ask the backend for ONE `OnDisk` key's bytes, unless that is already
        /// asked. The answer lands through [`Self::resolve`].
        fn load(&self, key: &str) {
            if !self.loading.borrow_mut().insert(key.to_string()) {
                return;
            }
            let store = self.clone();
            let key = key.to_string();
            let issued = self.tick();
            let request = self.backend.get(&key);
            spawn(async move {
                let outcome = request.await;
                store.loading.borrow_mut().remove(&key);
                store.resolve(&key, outcome, issued);
            });
        }

        /// Fold a loaded `OnDisk` value in — ONLY if the entry is still
        /// `OnDisk`. A write or a remove that happened while the bytes were on
        /// their way is newer than them, and wins.
        ///
        /// A failed load leaves the entry `OnDisk`, so the next `read` asks
        /// again. Like a failed refresh it does not toast: nothing of the
        /// user's was lost (S1 owns how a transport failure is shown).
        fn resolve(&self, key: &str, outcome: Result<Option<String>, String>, issued: u64) {
            let Ok(value) = outcome else {
                return;
            };
            // An index answered after this body request may name a newer
            // document while leaving the entry OnDisk (even at the same size).
            // Its authority also outranks this response; discard it so a next
            // demand read can fetch the current body.
            if self.full_index_authority.get() > issued
                || self.freshness.borrow().get(key).is_some_and(|&tick| tick > issued) {
                return;
            }
            {
                let mut entries = self.entries.borrow_mut();
                if !matches!(entries.get(key), Some(Entry::OnDisk { .. })) {
                    return;
                }
                self.stamp_local(key);
                match value {
                    Some(value) => entries.insert(key.to_string(), Entry::Resident(value)),
                    // Listed, then gone before we read it: the backend is
                    // authoritative, the listing was stale.
                    None => entries.remove(key),
                };
            }
            self.mutations.set(self.mutations.get().wrapping_add(1));
            if let Some(wake) = &self.wake {
                wake();
            }
        }

        /// Load every `OnDisk` entry in the background, ONE at a time, so a
        /// catalog of thousands of parts streams in behind the first frame
        /// instead of in front of it (or all at once in front of the user's own
        /// saves). A key a `read` already asked for is not asked twice, and a
        /// key written meanwhile is skipped.
        pub(crate) fn prefetch(&self) {
            let keys: Vec<String> = self
                .entries
                .borrow()
                .iter()
                .filter(|(_, entry)| matches!(entry, Entry::OnDisk { .. }))
                .map(|(key, _)| key.clone())
                .collect();
            if keys.is_empty() {
                return;
            }
            let store = self.clone();
            spawn(async move {
                for key in keys {
                    let wanted = matches!(store.entries.borrow().get(&key), Some(Entry::OnDisk { .. }));
                    if !wanted || !store.loading.borrow_mut().insert(key.clone()) {
                        continue;
                    }
                    let issued = store.tick();
                    let outcome = store.backend.get(&key).await;
                    store.loading.borrow_mut().remove(&key);
                    store.resolve(&key, outcome, issued);
                }
            });
        }
    }

    impl MirrorStore {
        /// The explorer's listing of the current folder, read from the whole key
        /// space ([`ModelStore::browser_entries`] caches it).
        fn list_folder(&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 = super::model_file_name(rest);
                    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()),
                                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
        }
    }

    impl ModelStore for MirrorStore {
        #[cfg(feature = "automation")]
        fn files(&self, request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> {
            brep_mcp_core::files::execute(self, request)
        }
        #[cfg(feature = "automation")]
        fn files_settled(&self, request: &brep_mcp_core::files::Request) -> Option<Result<(), String>> { self.file_settlement(request) }

        fn backend_label(&self) -> String {
            self.backend.label()
        }

        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
            self.backend.plm_client()
        }

        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
            self.backend.plm_revision(key)
        }
        fn note_checked_out(&self, key: &str) {
            self.backend.note_checked_out(key)
        }
        fn plm_written_by_us(&self, key: &str) -> bool {
            self.backend.plm_written_by_us(key)
        }

        /// A feed move: what the server now lists for `keys` — or, `stale`,
        /// for everything — is folded into the entries as LAZY `OnDisk`
        /// rows, so a document another client, the web app or Generate made
        /// after this app booted is listed and opens without a reload (bodies
        /// load on demand, as at boot). See [`Self::reconcile`] for what is
        /// never touched.
        fn refresh_plm_index(&self, keys: &[String], stale: bool) {
            // A backend that keeps no index answers `Err` and nothing moves.
            if !stale && keys.is_empty() {
                return;
            }
            let store = self.clone();
            // The answer speaks for the server AS OF NOW: ticked before the
            // request leaves, so anything local that happens while it is on
            // the wire outranks it.
            let issued = self.tick();
            if stale {
                let request = self.backend.index_all();
                spawn(async move {
                    if let Ok(rows) = request.await {
                        store.reconcile(None, rows, issued);
                    }
                });
            } else {
                let asked: Vec<String> = keys.iter().map(|key| format!("{PREFIX}{key}")).collect();
                let request = self.backend.index_rows(keys);
                spawn(async move {
                    if let Ok(rows) = request.await {
                        store.reconcile(Some(&asked), rows, issued);
                    }
                });
            }
        }
        fn remember_saved_document(&self, name: &str, contents: &str) {
            let key = Self::key(name);
            self.stamp_local(&key);
            self.entries.borrow_mut().insert(key, Entry::Resident(contents.into()));
            self.mutations.set(self.mutations.get().wrapping_add(1));
        }

        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> {
            let key = Self::key(name);
            let held = self.entries.borrow().get(&key).cloned();
            match held {
                Some(Entry::Resident(value)) => Some(value),
                // Listed but not loaded: ask for it and answer `None` NOW — the
                // API is synchronous. The bytes land through `resolve`, which
                // moves the generation and wakes the frame, so a caller keyed on
                // the generation reads again. `residency` tells the two `None`s
                // apart.
                Some(Entry::OnDisk { .. }) => {
                    self.load(&key);
                    None
                }
                None => None,
            }
        }

        fn canonical_identity(&self, name: &str) -> String {
            // The explorer's spelling of a document key (`browser_entries`);
            // a reserved name has no other spelling.
            match Self::key(name).strip_prefix(PREFIX) {
                Some(relative) => Self::virtual_model_path(relative),
                None => name.to_string(),
            }
        }

        fn canonicalizer(&self) -> super::Canonicalizer {
            std::rc::Rc::new(|name| match Self::key(name).strip_prefix(PREFIX) {
                Some(relative) => Self::virtual_model_path(relative),
                None => name.to_string(),
            })
        }

        fn residency(&self, name: &str) -> Residency {
            match self.entries.borrow().get(&Self::key(name)) {
                Some(Entry::Resident(_)) => Residency::Resident,
                Some(Entry::OnDisk { .. }) => Residency::OnDisk,
                None => Residency::Absent,
            }
        }

        fn write(&self, name: &str, contents: &str) -> Result<(), String> {
            let key = Self::key(name);
            // What the backend holds as this write leaves (a PLM revision's
            // content hash): the base a retry sends if the write fails.
            let base = crate::plm::bom::revision_of_document(name)
                .and_then(|(part, revision)| self.plm_revision(&crate::plm::identity::document_key(&part, &revision)))
                .map(|row| row.content_hash)
                .unwrap_or_default();
            self.errors.note_base(&key, base);
            self.stamp_local(&key);
            self.entries
                .borrow_mut()
                .insert(key.clone(), Entry::Resident(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`.
            let backend = self.backend.clone();
            let (put_key, contents) = (key.clone(), contents.to_string());
            self.push(name, &key, move || backend.put(&put_key, &contents));
            self.mutations.set(self.mutations.get().wrapping_add(1));
            Ok(())
        }

        fn write_if(&self, name: &str, contents: &str, expected: &str) -> Result<(), String> {
            let key = Self::key(name);
            self.errors.note_base(&key, expected.to_string());
            self.stamp_local(&key);
            self.entries
                .borrow_mut()
                .insert(key.clone(), Entry::Resident(contents.to_string()));
            let backend = self.backend.clone();
            let (put_key, contents, expected) = (key.clone(), contents.to_string(), expected.to_string());
            self.push(name, &key, move || backend.put_if(&put_key, &contents, &expected));
            self.mutations.set(self.mutations.get().wrapping_add(1));
            Ok(())
        }

        fn remove(&self, name: &str) -> Result<(), String> {
            let key = Self::key(name);
            self.stamp_local(&key);
            // The backend delete is pushed either way (the mirror may be
            // ahead of it), but only a delete that found something COUNTS —
            // the same rule `FileModelStore::remove` keeps.
            let existed = self.entries.borrow_mut().remove(&key).is_some();
            let backend = self.backend.clone();
            let delete_key = key.clone();
            self.push(name, &key, move || backend.delete(&delete_key));
            if existed {
                self.mutations.set(self.mutations.get().wrapping_add(1));
            }
            Ok(())
        }

        // `browser_write` needs no bump of its own: it routes through `write`.
        fn mutation_generation(&self) -> u64 {
            self.mutations.get()
        }

        fn pending_writes(&self) -> usize {
            self.pending()
        }

        fn pending_writes_except(&self, names: &[&str]) -> usize {
            let skip: Vec<String> = names.iter().map(|name| Self::key(name)).collect();
            self.in_flight.borrow().iter().filter(|(key, _)| !skip.contains(key)).map(|(_, count)| *count).sum()
        }

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

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

        fn write_failed(&self, name: &str) -> bool {
            self.errors.unsynced(&Self::key(name)).is_some()
        }

        fn failed_write_base(&self, name: &str) -> Option<String> {
            self.errors.unsynced(&Self::key(name))
        }

        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 key = {
                let entries = self.entries.borrow();
                ListingKey {
                    dir: self.browser_dir.borrow().clone(),
                    extensions: extensions.iter().map(|e| e.to_string()).collect(),
                    mutations: self.mutations.get(),
                    keys: entries.len(),
                    bytes: entries.values().map(Entry::len).sum(),
                }
            };
            if let Some((cached, listing)) = self.listing.borrow().as_ref() {
                if *cached == key {
                    return listing.clone();
                }
            }
            let listing = self.list_folder(extensions);
            *self.listing.borrow_mut() = Some((key, listing.clone()));
            listing
        }


        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(), Entry::Resident(String::new()));
            let backend = self.backend.clone();
            let put_key = key.clone();
            self.push(name, &key, move || backend.put(&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 = Self::child_path(&current, &super::model_file_name(&file));
            self.write(&identity, contents)?;
            Ok(identity)
        }
    }
}

#[cfg(target_arch = "wasm32")]
#[path = "store_host.rs"]
mod host;

// --- Browser: IndexedDB documents + download / upload interchange --------------
#[cfg(target_arch = "wasm32")]
mod web_model {
    use super::mirror_store::{
        BackendFuture, MirrorStore, StoreBackend, UnavailableBackend, DIR_PREFIX, FILE_PREFIX, PREFIX,
    };
    use super::{
        model_display_name, BrowserEntry, BrowserPlace, ImportedFile, ModelStore,
    };
    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";
    /// The cross-tab change channel. IndexedDB is shared by every tab of the
    /// origin but says NOTHING when another connection writes it, so each tab's
    /// hydrated mirror would sit at its boot-time contents until reloaded — save a
    /// part in one tab, and the tab holding the assembly cannot insert it. Every
    /// tab posts the key it just committed here and re-reads the keys it is told
    /// about; a [`BroadcastChannel`](web_sys::BroadcastChannel) never echoes to
    /// the object that sent the message, so a tab hears only the others.
    const CHANNEL_NAME: &str = "brep-app:store";

    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 file chooser's own input and slot ([`ModelStore::begin_pick_file`]):
        /// a picked attachment must never be taken by the model-import lane.
        static PICK_INPUT: RefCell<Option<web_sys::HtmlInputElement>> = const { RefCell::new(None) };
        static PICKED: 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) };
        /// Why a page the PLM serves is on IndexedDB instead (the PLM refused
        /// its session), shown once on the first frame.
        static BOOT_NOTICE: RefCell<Option<String>> = const { RefCell::new(None) };
        /// The same reason, kept for the PLM tab after the notice is drained.
        static BOOT_REASON: RefCell<Option<String>> = const { RefCell::new(None) };
    }

    fn set_boot_notice(notice: String) {
        BOOT_REASON.with(|r| *r.borrow_mut() = Some(notice.clone()));
        BOOT_NOTICE.with(|n| *n.borrow_mut() = Some(format!("{notice} — this page uses the browser's storage")));
    }

    /// 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.
    /// A task that asks for a frame after every poll; see [`super::spawn_waking`].
    pub(crate) struct WakeOnPoll(pub(crate) std::pin::Pin<Box<dyn Future<Output = ()>>>);

    impl Future for WakeOnPoll {
        type Output = ();
        fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<()> {
            let poll = self.0.as_mut().poll(cx);
            wake_frame_loop();
            poll
        }
    }

    pub(crate) 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,
        /// The cross-tab notification channel (see [`CHANNEL_NAME`]), or `None`
        /// where the browser does not offer one — then this tab still saves and
        /// still reads, it just will not hear about another tab's saves.
        channel: Option<web_sys::BroadcastChannel>,
    }

    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.
        ///
        /// `channel` is the tab's ONE [`BroadcastChannel`](web_sys::BroadcastChannel)
        /// handle, shared with [`hydrate`]'s listener: posting and listening on the
        /// same object is what keeps a tab from hearing its own writes back (the
        /// channel never delivers a message to the object that sent it).
        async fn open(channel: Option<web_sys::BroadcastChannel>) -> 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, channel })
        }

        /// Tell the other tabs of this origin that `key` changed, so their mirrors
        /// can re-read it. Only the FILESYSTEM key space is announced: `@settings`,
        /// `@dock_layout`, `@recovery` and friends are per-tab working state, and
        /// syncing them live would have two windows fight over one layout.
        fn announce(channel: &Option<web_sys::BroadcastChannel>, key: &str) {
            if !key.starts_with(PREFIX) && !key.starts_with(DIR_PREFIX) && !key.starts_with(FILE_PREFIX) {
                return;
            }
            if let Some(channel) = channel {
                // A failed post costs this tab nothing it can act on — the write
                // itself landed — so it is dropped rather than toasted.
                let _ = channel.post_message(&JsValue::from_str(key));
            }
        }

        /// 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()
        }

        /// IndexedDB commits `readwrite` transactions in creation order, and
        /// `put` / `delete` create theirs synchronously — so the mirror issues
        /// every write at once, exactly as it did before the send queue existed.
        fn orders_writes_per_key(&self) -> bool {
            true
        }

        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)
            })
        }

        #[cfg(feature = "automation")]
        fn move_files(&self, entries: Vec<(String, String, String)>) -> BackendFuture<()> {
            let started = (|| -> Result<IdbFuture, String> {
                let (transaction, store) = self.transact(web_sys::IdbTransactionMode::Readwrite)?;
                for (old, new, value) in &entries {
                    let put = store.put_with_key(&JsValue::from_str(value), &JsValue::from_str(new));
                    let delete = put.and_then(|_| store.delete(&JsValue::from_str(old)));
                    if let Err(error) = delete {
                        let _ = transaction.abort();
                        return Err(js_error(&error));
                    }
                }
                Ok(on_transaction(transaction))
            })();
            let channel = self.channel.clone();
            Box::pin(async move {
                started?.await?;
                for (old, new, _) in entries {
                    Self::announce(&channel, &old);
                    Self::announce(&channel, &new);
                }
                Ok(())
            })
        }

        fn get(&self, key: &str) -> BackendFuture<Option<String>> {
            let started = (|| -> Result<IdbFuture, String> {
                let (_transaction, store) = self.transact(web_sys::IdbTransactionMode::Readonly)?;
                let request = store.get(&JsValue::from_str(key)).map_err(|e| js_error(&e))?;
                Ok(on_request(request))
            })();
            Box::pin(async move {
                // An absent key resolves to `undefined`, which is the `None` the
                // mirror turns into a removal.
                Ok(started?.await?.as_string())
            })
        }

        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))
            })();
            let channel = self.channel.clone();
            let key = key.to_string();
            Box::pin(async move {
                started?.await?;
                // AFTER the commit, never before: a tab told about the key reads
                // it back immediately, and must not be able to read the old bytes.
                Self::announce(&channel, &key);
                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))
            })();
            let channel = self.channel.clone();
            let key = key.to_string();
            Box::pin(async move {
                started?.await?;
                Self::announce(&channel, &key);
                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);
        if super::host::available() {
            let backend: Rc<dyn StoreBackend> = Rc::new(super::host::HostBackend);
            let core = match backend.load_index().await {
                Ok(entries) => MirrorStore::from_index(backend, entries, Some(wake)),
                Err(error) => unavailable(format!("OrcaSlicer storage: {error}"), Some(wake)),
            };
            install_verification_hooks(&core);
            BOOT_STORE.with(|c| *c.borrow_mut() = Some(IdbModelStore { core }));
            return;
        }
        let channel = web_sys::BroadcastChannel::new(CHANNEL_NAME).ok();
        let core = match IdbBackend::open(channel.clone()).await {
            Ok(backend) => {
                let mut backend: Rc<dyn StoreBackend> = Rc::new(backend);
                // A page the PLM serves (D6, `/cad/app/`) keeps its documents
                // and preferences there, with `@recovery` in IndexedDB first.
                // A refusal keeps the page on IndexedDB and says why; a page
                // served from anywhere else never asks.
                match crate::plm::backend::open_web_session(backend.clone()).await {
                    Ok(Some(plm)) => backend = plm,
                    Ok(None) => {}
                    Err(sentence) => set_boot_notice(format!("PLM: {sentence}")),
                }
                // `load_index`'s default IS `load_all` with every value
                // resident, so a browser origin still hydrates whole; the
                // index-only PLM keeps document bodies unloaded until an actual
                // read. Never prefetch the catalog: its bodies can exceed WASM memory.
                match backend.load_index().await {
                    Ok(entries) => {
                        let core = MirrorStore::from_index(backend, entries, Some(wake));
                        // Hydration is the LAST all-at-once read. From here the
                        // mirror keeps up with the other tabs one key at a time,
                        // so a part saved next door is insertable here without a
                        // reload.
                        listen_for_other_tabs(&core, channel);
                        core
                    }
                    // 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 }));
    }

    /// Subscribe this tab's mirror to the other tabs' commits: each message is a
    /// key one of them just wrote, and the mirror re-reads exactly that key.
    ///
    /// The handler is `forget()`-ed — one per tab, alive for the session, the same
    /// pattern the verification hooks use. It holds a `MirrorStore` clone, which is
    /// another handle on the SAME session state, not a copy of it.
    fn listen_for_other_tabs(core: &MirrorStore, channel: Option<web_sys::BroadcastChannel>) {
        let Some(channel) = channel else {
            return;
        };
        let core = core.clone();
        let on_message = Closure::wrap(Box::new(move |event: web_sys::MessageEvent| {
            if let Some(key) = event.data().as_string() {
                core.refresh_key(key);
            }
        }) as Box<dyn FnMut(web_sys::MessageEvent)>);
        channel.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
        on_message.forget();
        // The channel object itself must outlive this call — a dropped
        // `BroadcastChannel` stops delivering — and it does: `IdbBackend` holds the
        // same handle for the life of the session.
    }

    /// 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(if super::host::available() {
            format!("{reason} — this session will not be saved; check OrcaSlicer plugin permissions and reload")
        } else {
            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();

        // The DELETE sibling of `__brepStoreWrite`, so the two-tab check in
        // `web/verify_store.mjs` can prove the second half of live storage: a
        // document removed in one tab leaves the other tab's list as well.
        let store = core.clone();
        let remove = Closure::wrap(Box::new(move |name: String| -> JsValue {
            match store.remove(&name) {
                Ok(()) => JsValue::NULL,
                Err(message) => JsValue::from_str(&message),
            }
        }) as Box<dyn FnMut(String) -> JsValue>);
        publish("__brepStoreRemove", remove.as_ref());
        remove.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
    /// `.nbrep` model lane vs. a `.step` import lane).
    /// The file chooser's hidden input, created once: any file, its own name
    /// kept whole, its bytes into [`PICKED`].
    fn pick_input() -> Option<web_sys::HtmlInputElement> {
        if let Some(existing) = PICK_INPUT.with(|c| c.borrow().clone()) {
            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_hidden(true);
        let input_for_cb = input.clone();
        let onchange = Closure::wrap(Box::new(move |_e: web_sys::Event| {
            let Some(file) = input_for_cb.files().and_then(|files| 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();
                    PICKED.with(|c| *c.borrow_mut() = Some(ImportedFile { name: name.clone(), bytes }));
                    wake_frame_loop();
                }
            }) as Box<dyn FnMut(web_sys::Event)>);
            reader.set_onload(Some(onload.as_ref().unchecked_ref()));
            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();
        if let Some(body) = document.body() {
            let _ = body.append_child(&input);
        }
        PICK_INPUT.with(|c| *c.borrow_mut() = Some(input.clone()));
        Some(input)
    }

    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 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())?;
        click_download(file_name, &blob)
    }

    /// [`download`] for BINARY content: the bytes are handed to the Blob as a
    /// `Uint8Array`, so nothing on the way out reinterprets them as UTF-8.
    fn download_bytes(file_name: &str, mime: &str, contents: &[u8]) -> Result<(), String> {
        let array = js_sys::Uint8Array::new_with_length(contents.len() as u32);
        array.copy_from(contents);
        let parts = js_sys::Array::of1(&array);
        let options = web_sys::BlobPropertyBag::new();
        options.set_type(mime);
        let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &options)
            .map_err(|_| "blob create failed".to_string())?;
        click_download(file_name, &blob)
    }

    /// The half both downloads share: an object URL for `blob`, a synthetic
    /// anchor click carrying EXACTLY `file_name`, then the URL released.
    fn click_download(file_name: &str, blob: &web_sys::Blob) -> Result<(), String> {
        if super::host::available() {
            let name = file_name.to_owned();
            let blob = blob.clone();
            wasm_bindgen_futures::spawn_local(async move {
                let result = async {
                    let buffer = wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await
                        .map_err(|e| format!("export bytes: {e:?}"))?;
                    let bytes = js_sys::Uint8Array::new(&buffer).to_vec();
                    let binary: String = bytes.into_iter().map(char::from).collect();
                    let encoded = web_sys::window().ok_or("no window")?.btoa(&binary)
                        .map_err(|e| format!("export encoding: {e:?}"))?;
                    super::host::request(serde_json::json!({"op":"export", "name":name,
                        "base64":encoded})).await
                }.await;
                if let Err(error) = result {
                    BOOT_NOTICE.with(|n| *n.borrow_mut() = Some(format!("Local export failed: {error}")));
                    wake_frame_loop();
                }
            });
            return Ok(());
        }
        let document = web_sys::window()
            .and_then(|w| w.document())
            .ok_or("no document")?;
        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 {
        #[cfg(feature = "automation")]
        fn files(&self, request: &brep_mcp_core::files::Request) -> Result<brep_mcp_core::files::Reply, String> {
            self.core.files(request)
        }
        #[cfg(feature = "automation")]
        fn files_settled(&self, request: &brep_mcp_core::files::Request) -> Option<Result<(), String>> { self.core.files_settled(request) }

        // --- delegated to the mirror ------------------------------------------
        fn backend_label(&self) -> String {
            self.core.backend_label()
        }
        fn plm_client(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> {
            self.core.plm_client()
        }
        fn plm_revision(&self, key: &str) -> Option<crate::plm::client::IndexEntry> {
            self.core.plm_revision(key)
        }
        fn note_checked_out(&self, key: &str) {
            self.core.note_checked_out(key)
        }
        fn plm_written_by_us(&self, key: &str) -> bool {
            self.core.plm_written_by_us(key)
        }
        fn refresh_plm_index(&self, keys: &[String], stale: bool) {
            self.core.refresh_plm_index(keys, stale)
        }
        fn remember_saved_document(&self, name: &str, contents: &str) {
            self.core.remember_saved_document(name, contents)
        }
        fn list(&self) -> Vec<String> {
            self.core.list()
        }
        fn read(&self, name: &str) -> Option<String> {
            self.core.read(name)
        }
        fn residency(&self, name: &str) -> super::Residency {
            self.core.residency(name)
        }
        fn canonical_identity(&self, name: &str) -> String {
            self.core.canonical_identity(name)
        }
        fn canonicalizer(&self) -> super::Canonicalizer {
            self.core.canonicalizer()
        }
        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 mutation_generation(&self) -> u64 {
            self.core.mutation_generation()
        }
        fn take_persistence_errors(&self) -> Vec<String> {
            let mut errors: Vec<String> = BOOT_NOTICE.with(|n| n.borrow_mut().take()).into_iter().collect();
            errors.extend(self.core.take_persistence_errors());
            errors
        }
        fn take_failed_writes(&self) -> Vec<String> {
            self.core.take_failed_writes()
        }
        fn write_failed(&self, name: &str) -> bool {
            self.core.write_failed(name)
        }
        fn failed_write_base(&self, name: &str) -> Option<String> {
            self.core.failed_write_base(name)
        }
        fn write_if(&self, name: &str, contents: &str, expected: &str) -> Result<(), String> {
            self.core.write_if(name, contents, expected)
        }
        fn plm_session(&self) -> Option<crate::plm::connection::Session> {
            use crate::plm::connection::{parse_label, Keep, Session, Status};
            if let Some((url, username)) = parse_label(&self.core.backend_label()) {
                return Some(Session { status: Status::Connected { url, username }, keep: Keep::BrowserSession });
            }
            let location = web_sys::window()?.location();
            if !crate::plm::backend::served_by_plm(&location.pathname().ok()?) {
                return None;
            }
            let reason = BOOT_REASON.with(|r| r.borrow().clone());
            Some(Session { status: Status::NotConnected { url: location.origin().ok()?, reason }, keep: Keep::BrowserSession })
        }
        fn pending_writes(&self) -> usize {
            self.core.pending_writes()
        }
        fn pending_writes_except(&self, names: &[&str]) -> usize {
            self.core.pending_writes_except(names)
        }
        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
        }

        fn begin_pick_file(&self) -> Result<(), String> {
            let input = pick_input().ok_or("the browser's file chooser is unavailable")?;
            // Clear so choosing the same file again still fires `change`.
            input.set_value("");
            input.click();
            Ok(())
        }

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

        /// Offer the document as a `<name>.nbrep` 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);
            let file_name = super::model_file_name(&name);
            download(&file_name, super::media_type(&file_name), contents)?;
            Ok(Some(name))
        }

        fn begin_import(&self) -> Result<(), String> {
            let input =
                ensure_input(".nbrep,.fbrep,.tbrep").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
        // `.nbrep`), 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`]. The
        /// media type is the file's own ([`super::media_type`]), so a sheet
        /// leaves as `image/svg+xml` and not as anonymous bytes.
        fn export_file_named(&self, file_name: &str, contents: &str) -> Result<(), String> {
            download(file_name, super::media_type(file_name), contents)
        }

        /// The same, for bytes: `model/gltf-binary` for a GLB, `application/pdf`
        /// for a drawing sheet. It used to be glTF whatever the file was, which
        /// is why this lane could only ever carry one format.
        fn export_file_named_bytes(&self, file_name: &str, contents: &[u8]) -> Result<(), String> {
            download_bytes(file_name, super::media_type(file_name), contents)
        }
    }
}