BREP_app 0.3.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
//! File dialog — a **reusable modal** for model-document management: **New /
//! Open / Save / Save As** of the MODEL, driven from the toolbar. Mirrors the
//! shape of [`crate::palette::Palette`]: the caller owns ONE [`FileDialog`],
//! calls [`FileDialog::dispatch`] when a toolbar file button is clicked (which
//! either acts immediately or opens the modal in a mode), and calls
//! [`FileDialog::show`] every frame to draw the (possibly open) modal.
//!
//! The model document IS the engine-owned history: `EngineState` serializes it
//! with `history_request_json()` (the `.BREP.json` recipe) and loads it with
//! `set_history_json` / `load_model_and_fit`. This dialog keeps NO model state
//! and no document IDENTITY — the name and the clean baseline live on
//! [`Document`], and the open set on [`Documents`]. It holds only transient UI
//! buffers (the name field, a status line, the open modal) and drives the
//! documents + the [`ModelStore`] seam.
//!
//! # New and Open never discard anything now
//!
//! Both ADD A TAB: New pushes an empty document, Open pushes the opened one (or
//! focuses the tab already holding it). Nothing is replaced, so neither needs
//! the "discard unsaved changes?" prompt they used to raise — the only place
//! unsaved work can still be lost is CLOSING a tab, which is where that
//! confirmation now lives ([`Mode::ConfirmClose`]).
//!
//! Persistence crosses the unified [`ModelStore`] seam — the ONE platform
//! exception. The same embeddable explorer renders on web and desktop. The web
//! backend lists localStorage models and can Upload; desktop lists the app's
//! models directory. No OS-native file dialog is used.

use crate::document::{Document, Documents, EMPTY_DOCUMENT};
use crate::panels::parts_library::document_signature;
use crate::panels::file_explorer::{FileExplorer, FileExplorerOptions};
use crate::store::{model_display_name, ModelStore};
use brep_render::engine_state::{
    ComponentInsert, EngineState, PartSink, StepAssemblyImport, StepAssemblyProbe,
    StepAssemblyReport, StepProbeOutcome,
};
use eframe::egui;
#[cfg(target_arch = "wasm32")]
use serde_json::Value;
#[cfg(target_arch = "wasm32")]
use std::collections::HashMap;

/// The file operation a toolbar button requests. The shell maps a clicked
/// toolbar button to one of these and hands it to [`FileDialog::dispatch`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileAction {
    New,
    Open,
    Save,
    SaveAs,
    /// Import a CAD or mesh file FROM the user's filesystem, appending it to the
    /// model rather than replacing it. STL/OBJ use RANSAC reconstruction.
    Import,
    /// Export the model TO the user's filesystem in a chosen format (STEP / STL).
    Export,
    /// Export the sheet-metal FLAT PATTERN (unfold) as a 2D vector file
    /// (DXF / SVG). Opens the flat-pattern export modal.
    ExportFlatPattern,
    /// Insert an ASSEMBLY COMPONENT: opens the component selector — existing
    /// parts-library entries first, then the model store's Open list (+ Upload)
    /// — and routes the chosen document through the engine's insert flow
    /// (`add_part_to_library` → an ACOMP instance referencing the returned
    /// effective part name). Dispatched when the palette picks `ACOMP`.
    InsertComponent,
}

/// Which modal (if any) the dialog is currently showing.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    /// Open a saved model through the common explorer.
    Open,
    /// Prompt for a name and save under it.
    SaveAs,
    /// Confirm discarding unsaved changes before CLOSING a document tab —
    /// the ONE place unsaved work can still be lost now that New and Open
    /// both add a tab. `pending_close` holds the tab index.
    ConfirmClose,
    /// Choose an export format (STEP / STL) for the current model.
    Export,
    /// Choose a STEP / IGES / STL / OBJ file through the common explorer.
    Import,
    /// Choose a 2D vector format (DXF / SVG) for the sheet-metal flat pattern.
    FlatPattern,
    /// Pick a part to insert as an assembly component (library entries + the
    /// stored-model list + Upload).
    InsertComponent,
    /// A `.step` upload whose product structure the probe found: choose whether
    /// to keep that structure (parts + component instances) or flatten it to
    /// bodies. Backed by [`FileDialog::pending_step_import`].
    StepAssembly,
}

/// A probed `.step` upload waiting on the user's choice — the state that makes
/// the §3.9 modal work across frames (egui draws every frame; the click can
/// land many frames after the upload).
///
/// The PARSED assembly itself is NOT here: it lives in the engine's stash
/// (`EngineState::probe_step_assembly` put it there), and the import consumes
/// that stash. This holds only what the prompt says and the `text` the flat
/// lane needs — the two lanes that re-import from source rather than from the
/// parse ("Import as bodies", and the structured lane's own failure fallback).
struct PendingStepImport {
    /// The uploaded file's name — the prompt's subject and the status line's.
    name: String,
    /// The file text. The engine's stash holds the PARSE, not the source, so
    /// the flat lane's input has to be kept here.
    text: String,
    /// The counts the prompt shows, from the same walk the import runs.
    probe: StepAssemblyProbe,
    /// The §3.9 checkbox: flatten the sub-assembly tree to leaf occurrences
    /// instead of building nested rigid sub-assembly documents. Only shown (and
    /// only meaningful) when `probe.nested_depth > 1`; a depth-1 file imports
    /// identically either way.
    flatten: bool,
}

/// A `.step` upload whose structure probe is RUNNING on the document's
/// background runner (native thread / browser worker — the parse builds every
/// product's bodies and takes seconds on a real assembly, so it left the UI
/// thread). Resolved by [`FileDialog::poll_step_probe`] into either the §3.9
/// choice ([`PendingStepImport`]) or the flat lane.
struct PendingStepProbe {
    /// The engine's probe id, so a stale answer (a superseded upload) is ignored.
    id: u64,
    name: String,
    /// The file text, kept for the flat lane the outcome may route to.
    text: String,
}

/// What the user clicked in the §3.9 assembly-choice modal.
#[derive(Clone, Copy, PartialEq, Eq)]
enum StepChoice {
    /// Keep the structure: parts-library entries + one component per occurrence.
    Assembly,
    /// Today's flat lane, unchanged: one IMPORT3D feature carrying the text.
    Bodies,
    /// Import nothing, and drop the parse (Esc / click-outside land here too).
    Cancel,
}

/// `"s"` unless there is exactly one — the difference between "1 parts" and a
/// sentence a user believes.
fn plural(count: usize) -> &'static str {
    if count == 1 {
        ""
    } else {
        "s"
    }
}

/// The document name an imported assembly's unnamed products are stemmed from:
/// the file's base name without its STEP extension, so a nameless product reads
/// `bracket-assy-part-7`, not `bracket-assy.step-part-7`.
fn step_document_name(file_name: &str) -> String {
    let base = file_name.rsplit(['/', '\\']).next().unwrap_or(file_name);
    let cut = base
        .rfind('.')
        .filter(|dot| is_step_name(&base[*dot..]))
        .unwrap_or(base.len());
    let stem = &base[..cut];
    if stem.is_empty() {
        base.to_string()
    } else {
        stem.to_string()
    }
}

/// The §3.9 outcome line: `imported bracket-assy.step — 7 parts, 23 components
/// (2 mirrored instances baked)`, plus the tail an imperfect import owes the
/// user. Every qualifier is reported ONLY when it happened, so a clean import
/// reads clean — but a partial one never reads as a whole one:
///
/// * `baked_nonrigid` — occurrences whose mirror/scale was baked into a part of
///   their own (§3.4), which is why the part count can exceed the file's;
/// * `failed_products` — products that did not encode, skipped and counted;
/// * `flat_fallback` — the user asked for an assembly and got bodies. Said
///   plainly, never silently (the dialog lane reports this through the Err
///   branch instead, which is the only way it can reach the user from here);
/// * `first_error` — the one thing that explains the rest.
/// The STEP-assembly import's [`PartSink`]: writes each unique part document to
/// the model store and hands back the identity it was stored under, so an
/// imported part carries a REAL `sourceKey` and there is no second kind of part.
///
/// # The destination
///
/// `browser_write` at the explorer's CURRENT location, under
/// `{assembly}-{part}` — the convention `panels::step_parts` already uses for a
/// single STEP part (that panel lets the user pick the folder first; the
/// assembly modal inherits wherever the explorer is pointing).
///
/// The kernel plan's alternative — a `{assembly}/{part}.BREP.json` SUB-FOLDER —
/// is not reachable through this door: every `browser_write` implementation
/// flattens the name to a single file (native takes `file_name()`, web takes
/// `model_display_name`), so a sub-path would silently collapse. Writing the
/// assembly name into the FILE name keeps a 50-part import grouped in one
/// listing without a folder convention this seam cannot express. Creating and
/// navigating into a folder as a side effect of an import is the prompt this
/// lane would have to grow, and it is not bolted on here.
///
/// A failed write is per part: that part stays embedded-only (`None`) and the
/// import continues. Losing one part's FILE is recoverable; losing the import
/// is not.
///
/// # Known limit of a flat name
///
/// `taken` is per IMPORT, so re-importing the same file reuses the same names —
/// which is what makes cross-import dedup work (same key, same signature, the
/// resident entry is reused). But two DIFFERENT assemblies whose document names
/// sanitize to the same stem (`as1-ug` and `as1_ug`) write to each other's file
/// names. The second import wins the file; the first assembly's entry then
/// disagrees with it, so it badges outdated and the write-through guard refuses
/// to clobber it — visible and recoverable (the embedded document is intact),
/// but two assemblies sharing one name. The fix is the per-assembly sub-folder
/// `browser_write` cannot express; see the kernel plan's §3.5.
struct StorePartSink<'a> {
    store: &'a dyn ModelStore,
    /// Prefixes every file name, so one import's parts sort together.
    prefix: String,
    /// File names already claimed this import — two STEP products can sanitize
    /// to the same name, and the second must not overwrite the first's file
    /// (that would leave two entries pointing at one document).
    taken: std::collections::HashSet<String>,
    written: usize,
    failures: Vec<String>,
}

impl<'a> StorePartSink<'a> {
    fn new(store: &'a dyn ModelStore, prefix: &str) -> Self {
        Self {
            store,
            prefix: sanitize_file_stem(prefix),
            taken: std::collections::HashSet::new(),
            written: 0,
            failures: Vec::new(),
        }
    }
}

impl PartSink for StorePartSink<'_> {
    fn store_part(&mut self, part_name: &str, document_json: &str) -> Option<String> {
        let base = format!("{}-{}", self.prefix, sanitize_file_stem(part_name));
        let mut name = base.clone();
        let mut suffix = 2;
        while !self.taken.insert(name.clone()) {
            name = format!("{base}-{suffix}");
            suffix += 1;
        }
        match self.store.browser_write(&name, document_json) {
            Ok(identity) => {
                self.written += 1;
                Some(identity)
            }
            Err(error) => {
                self.failures.push(format!("{name}: {error}"));
                None
            }
        }
    }
}

/// A STEP product name reduced to something every store backend can hold as a
/// file name: ASCII word characters, `.`, `-` kept; everything else (spaces,
/// slashes, the `(mirrored)` parentheses this crate appends) becomes `_`. Runs
/// of `_` collapse and the ends are trimmed, so a name is readable rather than
/// a row of underscores. Empty input yields `part`.
fn sanitize_file_stem(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    for ch in name.chars() {
        if ch.is_ascii_alphanumeric() || ch == '.' || ch == '-' {
            out.push(ch);
        } else if !out.ends_with('_') {
            out.push('_');
        }
    }
    let trimmed = out.trim_matches('_');
    if trimmed.is_empty() {
        "part".to_string()
    } else {
        trimmed.to_string()
    }
}

fn assembly_import_message(name: &str, report: &StepAssemblyReport) -> String {
    let mut message = format!(
        "imported {name} \u{2014} {} part{}, {} component{}",
        report.parts,
        plural(report.parts),
        report.instances,
        plural(report.instances)
    );
    if report.baked_nonrigid > 0 {
        message.push_str(&format!(
            " ({} mirrored instance{} baked)",
            report.baked_nonrigid,
            plural(report.baked_nonrigid)
        ));
    }
    if report.failed_products > 0 {
        message.push_str(&format!(
            "; {} product{} could not be built",
            report.failed_products,
            plural(report.failed_products)
        ));
    }
    if report.flat_fallback {
        message.push_str("; the structure was NOT used \u{2014} the bodies came in flat");
    }
    if let Some(error) = &report.first_error {
        message.push_str(&format!(" [{error}]"));
    }
    message
}

/// Whether an imported file name is a STEP file (`.step` / `.stp`, any case) —
/// the routing key in [`FileDialog::show`]. Model documents arrive
/// extension-stripped (web) or as a stored model name, so this
/// never mis-routes a `.BREP.json` file.
fn is_step_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower.ends_with(".step") || lower.ends_with(".stp")
}

/// Whether an imported file name is an IGES file (`.iges` / `.igs`, any case) —
/// the sibling routing key of [`is_step_name`].
fn is_iges_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower.ends_with(".iges") || lower.ends_with(".igs")
}

fn is_stl_name(name: &str) -> bool {
    name.to_ascii_lowercase().ends_with(".stl")
}

fn is_obj_name(name: &str) -> bool {
    name.to_ascii_lowercase().ends_with(".obj")
}

/// The reusable file dialog — transient UI buffers + the current document
/// identity; the model itself lives in `EngineState`'s history.
pub struct FileDialog {
    /// Reusable browser body shared by Open, Save As, and ACOMP selection.
    explorer: FileExplorer,
    /// The name field buffer, used by the Save As modal.
    name_buf: String,
    /// Last-action status line, surfaced inside the modal.
    status: String,
    /// Whether a modal is currently open.
    open: bool,
    /// The open modal's mode (only meaningful while `open`).
    mode: Mode,
    /// Set on open so the Save As text input grabs focus on the next frame.
    want_focus: bool,
    /// A pending real-file pick belongs to the INSERT-COMPONENT flow (the
    /// modal's Upload fired there): the next completed `take_import` routes to
    /// the component insert instead of Open's load-document.
    pending_component_import: bool,
    /// The tab index a pending [`Mode::ConfirmClose`] will close on "Discard".
    pending_close: Option<usize>,
    /// A probed STEP assembly waiting on the §3.9 choice modal. `Some` means the
    /// ENGINE is holding a parsed assembly for us (with every product's solids
    /// resident), so every exit from that modal must end its life: import it,
    /// discard it, or be superseded by the next upload.
    pending_step_import: Option<PendingStepImport>,
    /// A `.step` upload whose probe has not answered yet (see
    /// [`PendingStepProbe`]); the status line says "reading…" meanwhile.
    pending_step_probe: Option<PendingStepProbe>,
    pending_stl_import: Option<(String, Vec<u8>)>,
    /// Bumped on every SUCCESSFUL store save (plain Save / Save As / native
    /// Save-As) — one half of the update-components staleness key (saving a
    /// part's source must re-check the outdated badges without a reload).
    save_generation: u64,
    /// Per-frame widget hit-rects for the headed verifier (wasm only).
    #[cfg(target_arch = "wasm32")]
    hits: HashMap<String, egui::Rect>,
}

impl FileDialog {
    /// A closed dialog with empty buffers. Document identity (name + clean
    /// baseline) lives on [`Document`], so there is nothing to seed here.
    pub fn new() -> Self {
        Self {
            explorer: FileExplorer::new(),
            name_buf: String::new(),
            status: String::new(),
            open: false,
            mode: Mode::Open,
            want_focus: false,
            pending_component_import: false,
            pending_close: None,
            pending_step_import: None,
            pending_step_probe: None,
            pending_stl_import: None,
            save_generation: 0,
            #[cfg(target_arch = "wasm32")]
            hits: HashMap::new(),
        }
    }

    /// The monotonic successful-save counter — the shell feeds it to the
    /// update-components checker as half its staleness key.
    pub fn save_generation(&self) -> u64 {
        self.save_generation
    }

    // --- dispatch: a toolbar button was clicked -------------------------------

    /// Act on a toolbar file button. New acts immediately (it adds a tab, so
    /// there is nothing to discard); all browsing flows use the same in-app
    /// modal on both platforms.
    pub fn dispatch(&mut self, action: FileAction, docs: &mut Documents, store: &dyn ModelStore) {
        match action {
            FileAction::New => self.new_document(docs),
            FileAction::Open => self.open_modal(Mode::Open),
            FileAction::Save => match docs.active().name().map(str::to_string) {
                // A named document saves straight to its name.
                Some(name) => {
                    let _ = self.save_to(docs, store, name);
                }
                // An unnamed document falls through to Save As.
                None => self.dispatch(FileAction::SaveAs, docs, store),
            },
            FileAction::SaveAs => {
                self.name_buf = self.effective_name(docs);
                self.open_modal(Mode::SaveAs);
            }
            FileAction::Import => {
                self.open_modal(Mode::Import);
            }
            FileAction::Export => {
                self.name_buf = self.effective_name(docs);
                self.open_modal(Mode::Export);
            }
            FileAction::ExportFlatPattern => {
                self.name_buf = self.effective_name(docs);
                self.open_modal(Mode::FlatPattern);
            }
            // ALWAYS the in-app modal (never the native picker directly): the
            // "existing library entries first" list is an in-app concept; the
            // modal's own Upload button drives the platform picker when the
            // store supports interchange.
            FileAction::InsertComponent => self.open_modal(Mode::InsertComponent),
        }
    }

    /// Open the modal in `mode` (and focus its input next frame).
    fn open_modal(&mut self, mode: Mode) {
        self.mode = mode;
        self.open = true;
        self.want_focus = true;
    }

    // --- per-frame draw -------------------------------------------------------

    /// Draw the modal (if open) and pick up any completed async import. Called
    /// every frame by the shell with a ctx-level handle (the modal is ctx-level,
    /// like the command palette).
    pub fn show(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
        #[cfg(target_arch = "wasm32")]
        self.hits.clear();

        // A STEP probe the runner has answered since last frame resolves into
        // the assembly choice or the flat import now, before drawing.
        self.poll_step_probe(docs.engine_mut());

        // A completed async browser upload is picked up
        // here, before drawing, so the model is live for this frame. Routed by
        // extension: a STEP file (`.step`/`.stp`) is APPENDED to the model as an
        // IMPORT3D feature; anything else is a `.BREP.json` model document loaded
        // (replacing the model). The model lanes deliver an extension-less name
        // (web, stripped by `model_display_name`) or a stored model name, so only
        // real STEP files route here.
        if let Some(imported) = store.take_import() {
            // A new delivery SUPERSEDES an armed assembly choice. The modal
            // describes a parse this routing is about to replace (a STEP probe
            // drops the previous stash by contract, and a document load drops it
            // outright), so leaving the choice armed would offer the user a
            // button whose stash is already gone.
            self.cancel_pending_step_import(docs.engine_mut());
            let name = imported.name;
            let bytes = imported.bytes;
            // CAD/mesh imports target the active document. STL waits for
            // preview acceptance; model documents open in a separate tab.
            if is_step_name(&name) {
                self.import_text(docs.engine_mut(), &name, &bytes, Self::import_step);
            } else if is_iges_name(&name) {
                self.import_text(docs.engine_mut(), &name, &bytes, Self::import_iges);
            } else if is_stl_name(&name) {
                self.stage_stl_preview(name, bytes);
            } else if is_obj_name(&name) {
                self.import_obj(docs.engine_mut(), &name, &bytes);
            } else if std::mem::take(&mut self.pending_component_import) {
                // The insert-component modal's Upload fired this pick: the
                // chosen document becomes a parts-library entry + an instance,
                // NOT a new tab.
                match String::from_utf8(bytes) {
                    Ok(contents) => {
                        self.insert_component_document(docs.engine_mut(), &name, &contents)
                    }
                    Err(_) => self.status = format!("open failed: {name} is not UTF-8 text"),
                }
            } else {
                match String::from_utf8(bytes) {
                    Ok(contents) => self.load_document(docs, &name, &contents),
                    Err(_) => self.status = format!("open failed: {name} is not UTF-8 text"),
                }
            }
            self.close_after_import();
        }

        if !self.open {
            return;
        }

        match self.mode {
            Mode::ConfirmClose => self.show_confirm_close(ctx, docs),
            Mode::SaveAs => self.show_save_as(ctx, docs, store),
            Mode::Open => self.show_open(ctx, docs, store),
            Mode::Import => self.show_import(ctx, docs.engine_mut(), store),
            Mode::Export => self.show_export(ctx, docs, store),
            Mode::FlatPattern => self.show_flat_pattern(ctx, docs, store),
            Mode::InsertComponent => self.show_insert_component(ctx, docs.engine_mut(), store),
            Mode::StepAssembly => self.show_step_assembly(ctx, docs.engine_mut(), store),
        }
    }

    /// Close the modal after a completed import — unless the import ARMED the
    /// §3.9 assembly choice, in which case the modal stays open and switches to
    /// it. Both import routing sites (the async-upload poll and the Import
    /// modal's own pick) end here, so neither can close a dialog the probe just
    /// raised.
    fn close_after_import(&mut self) {
        if self.pending_step_import.is_some() {
            self.open_modal(Mode::StepAssembly);
        } else {
            self.open = false;
        }
    }

    /// Abandon an armed assembly choice and the engine stash behind it. The ONE
    /// place the app-side pending state and the engine-side parse are dropped
    /// together — they are two halves of one thing, and a half-drop is either a
    /// dialog with no stash or solids nobody will ever consume.
    fn cancel_pending_step_import(&mut self, state: &mut EngineState) {
        if self.pending_step_import.take().is_some() {
            state.discard_probed_step_assembly();
        }
    }

    /// Common CAD/mesh browser. Desktop enumerates files in the application's
    /// models directory; web shows the same explorer shell with an Upload action.
    fn show_import(
        &mut self,
        ctx: &egui::Context,
        state: &mut EngineState,
        store: &dyn ModelStore,
    ) {
        const EXTENSIONS: &[&str] = &["step", "stp", "iges", "igs", "stl", "obj"];
        let modal = egui::Modal::new(egui::Id::new("brep-file-import")).show(ctx, |ui| {
            ui.set_width(600.0);
            ui.heading("Import CAD file");
            ui.add_space(4.0);
            let options = FileExplorerOptions {
                hit_prefix: "import",
                empty_label: "(no STEP, IGES, STL, or OBJ files)",
                row_icon: "\u{1F5CE}",
                current: None,
                allow_delete: false,
                allow_import: store.supports_file_interchange(),
                import_label: "Upload\u{2026}",
                import_hit: "import:upload",
                show_cancel: true,
                confirm_label: Some("Import"),
                extensions: EXTENSIONS,
            };
            let output = self.explorer.show_store(ui, store, options);
            self.record_explorer_hits(&output.hits);
            if !self.status.is_empty() {
                ui.add_space(4.0);
                ui.weak(&self.status);
            }
            output
        });
        let should_close = modal.should_close();
        let output = modal.inner;
        if let Some(name) = output.activated {
            match store.read_external_file(&name) {
                Some(bytes) if is_step_name(&name) => {
                    self.import_text(state, &name, &bytes, Self::import_step)
                }
                Some(bytes) if is_iges_name(&name) => {
                    self.import_text(state, &name, &bytes, Self::import_iges)
                }
                Some(bytes) if is_stl_name(&name) => self.stage_stl_preview(name, bytes),
                Some(bytes) if is_obj_name(&name) => self.import_obj(state, &name, &bytes),
                Some(_) => self.status = format!("unsupported import file: {name}"),
                None => self.status = format!("import failed: '{name}' not found"),
            }
            self.close_after_import();
        } else if output.import {
            match store.begin_import_filtered(("CAD / mesh", EXTENSIONS)) {
                Ok(()) => {
                    self.status = "choose a STEP, IGES, STL, or OBJ file\u{2026}".into();
                    self.open = false;
                }
                Err(e) => self.status = format!("import failed: {e}"),
            }
        } else if output.cancel || should_close {
            self.open = false;
        }
    }

    /// CLOSE tab `index` with the unsaved-changes contract: a DIRTY document
    /// prompts to discard first (the confirm modal); a clean one closes
    /// immediately. The tab strip's `\u{2715}` routes here — it is the only
    /// door through which unsaved work can be dropped, so it is the only one
    /// that asks.
    pub fn request_close(&mut self, docs: &mut Documents, index: usize) {
        let dirty = docs.get(index).is_some_and(Document::is_dirty);
        if dirty {
            self.pending_close = Some(index);
            self.open_modal(Mode::ConfirmClose);
        } else {
            docs.close(index);
        }
    }

    /// The **Discard unsaved changes?** confirmation shown before closing a
    /// dirty document tab. Keeps the verifier's `confirm:discard` /
    /// `confirm:cancel` hit keys — the same two buttons, one door further on.
    fn show_confirm_close(&mut self, ctx: &egui::Context, docs: &mut Documents) {
        // A tab closed / reordered under an open prompt (there is no such path
        // today, but the index is only meaningful while it resolves).
        let Some(title) = self
            .pending_close
            .and_then(|index| docs.get(index))
            .map(Document::title)
        else {
            self.pending_close = None;
            self.open = false;
            return;
        };
        let mut discard = false;
        let mut cancel = false;
        let modal = egui::Modal::new(egui::Id::new("brep-file-confirm-close")).show(ctx, |ui| {
            ui.set_width(340.0);
            ui.heading("Discard unsaved changes?");
            ui.add_space(4.0);
            ui.label(format!("\"{title}\" has unsaved changes. Close it?"));
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                let d = ui.button("Discard and close");
                self.hit("confirm:discard", &d);
                if d.clicked() {
                    discard = true;
                }
                let c = ui.button("Cancel");
                self.hit("confirm:cancel", &c);
                if c.clicked() {
                    cancel = true;
                }
            });
        });
        if discard {
            if let Some(index) = self.pending_close.take() {
                docs.close(index);
            }
            self.open = false;
        } else if cancel || modal.should_close() {
            self.pending_close = None;
            self.open = false;
        }
    }

    /// The §3.9 **assembly choice**, raised when a `.step` upload's probe found a
    /// product structure:
    ///
    /// > **"bracket-assy.step" contains an assembly** — 7 parts, 23 instances.
    /// > [ Import as assembly ] [ Import as bodies ] [ Cancel ]
    ///
    /// Default (and first) is **Import as assembly**. "Import as bodies" is
    /// today's flat lane, unchanged. Cancel — and Esc / click-outside, which
    /// egui folds into `should_close` — import nothing and DROP the parse: the
    /// engine is holding every product's solids until one of these three lands.
    ///
    /// **Flatten sub-assemblies** (§3.9) is offered only when the file actually
    /// HAS sub-assemblies (`nested_depth > 1`) — on a single-level file both
    /// lanes produce the identical document, so a box there would teach the user
    /// a distinction that does not exist. Unchecked (the default) keeps the
    /// tree; checked flattens to leaf occurrences, which is the right answer for
    /// a deep or pathological file and stores a part reused across two levels
    /// once rather than once per level (build-spec §2.2).
    fn show_step_assembly(
        &mut self,
        ctx: &egui::Context,
        state: &mut EngineState,
        store: &dyn ModelStore,
    ) {
        // Nothing armed means nothing to choose about (a supersession raced the
        // draw): close rather than render an empty prompt.
        let Some(pending) = self.pending_step_import.as_ref() else {
            self.open = false;
            return;
        };
        let name = pending.name.clone();
        let probe = pending.probe;
        let mut flatten = pending.flatten;
        let mut choice: Option<StepChoice> = None;
        let modal = egui::Modal::new(egui::Id::new("brep-file-step-assembly")).show(ctx, |ui| {
            ui.set_width(360.0);
            ui.heading(format!("\"{name}\" contains an assembly"));
            ui.add_space(4.0);
            ui.label(format!(
                "{} part{}, {} instance{}{}.",
                probe.parts,
                plural(probe.parts),
                probe.instances,
                plural(probe.instances),
                match probe.nested_depth {
                    0 | 1 => String::new(),
                    depth => format!(", {depth} levels deep"),
                }
            ));
            if probe.nested_depth > 1 {
                ui.add_space(4.0);
                let check = ui.checkbox(&mut flatten, "Flatten sub-assemblies");
                self.hit("stepassembly:flatten", &check);
                check.on_hover_text(
                    "Off: each sub-assembly becomes one rigid component you can \
                     expand in the structure tree.\nOn: every part is placed \
                     directly in this document at its world position.",
                );
            }
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                let a = ui.button("Import as assembly");
                self.hit("stepassembly:assembly", &a);
                if a.clicked() {
                    choice = Some(StepChoice::Assembly);
                }
                let b = ui.button("Import as bodies");
                self.hit("stepassembly:bodies", &b);
                if b.clicked() {
                    choice = Some(StepChoice::Bodies);
                }
                let c = ui.button("Cancel");
                self.hit("stepassembly:cancel", &c);
                if c.clicked() {
                    choice = Some(StepChoice::Cancel);
                }
            });
        });
        // The box must survive the frames between the tick and the click.
        if let Some(pending) = self.pending_step_import.as_mut() {
            pending.flatten = flatten;
        }
        // Esc / click-outside is a Cancel, not a no-op: the stash must not
        // outlive the prompt that was going to consume it.
        let choice = choice.or_else(|| modal.should_close().then_some(StepChoice::Cancel));
        let Some(choice) = choice else { return };
        match choice {
            StepChoice::Assembly => self.step_assembly_import(state, store),
            StepChoice::Bodies => self.step_assembly_bodies(state),
            StepChoice::Cancel => self.step_assembly_cancel(state),
        }
        self.open = false;
    }

    /// The **Save As** name prompt.
    fn show_save_as(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
        let current = docs.active().name().map(str::to_string);
        let mut do_save = false;
        let mut cancel = false;
        let modal = egui::Modal::new(egui::Id::new("brep-file-saveas")).show(ctx, |ui| {
            ui.set_width(600.0);
            ui.heading("Save model as");
            ui.add_space(4.0);
            let options = FileExplorerOptions {
                hit_prefix: "saveas:file",
                empty_label: "(no saved models)",
                row_icon: "\u{1F5CE}",
                current: current.as_deref(),
                allow_delete: false,
                allow_import: false,
                import_label: "",
                import_hit: "saveas:upload",
                show_cancel: false,
                confirm_label: None,
                extensions: &["BREP.json", "json"],
            };
            let output = self.explorer.show_store(ui, store, options);
            self.record_explorer_hits(&output.hits);
            // Selecting (or double-clicking) a stored model fills the name field
            // so it can be overwritten; `picked`/`activated` are one-shot so it
            // never clobbers a name the user then types.
            if let Some(name) = output.picked.or(output.activated) {
                self.name_buf = model_display_name(&name);
            }
            ui.label("File name");
            let field = ui.add(
                egui::TextEdit::singleline(&mut self.name_buf)
                    .hint_text("model name")
                    .desired_width(f32::INFINITY),
            );
            self.hit("field:name", &field);
            if self.want_focus {
                field.request_focus();
                self.want_focus = false;
            }
            let enter = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                let save = ui.button("Save");
                self.hit("save", &save);
                if save.clicked() || enter {
                    do_save = true;
                }
                let c = ui.button("Cancel");
                self.hit("cancel", &c);
                if c.clicked() {
                    cancel = true;
                }
            });
            if !self.status.is_empty() {
                ui.add_space(4.0);
                ui.weak(&self.status);
            }
        });
        if do_save {
            let name = self.name_buf.clone();
            if self.save_to_browser(docs, store, name) {
                self.open = false;
            }
        } else if cancel || modal.should_close() {
            self.open = false;
        }
    }

    /// The **Export** chooser: pick a format (STEP / IGES / STL) and write the
    /// current model to the user's filesystem under `<name>.<ext>` through the
    /// store's format-typed interchange. STEP and IGES serialize the exact NURBS
    /// topology; STL is the ASCII display mesh. No solids → a clear status line,
    /// nothing written. A second row offers the assembly BOM (CSV / JSON),
    /// enabled only while the document HAS components.
    fn show_export(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
        // BOM gating (assemblies build-spec §9): `component_ids` scans the
        // history (cheap, no kernel session). A rolled-back/failed ACOMP can
        // still enable the buttons — the export's own loud "no components"
        // error covers that gap.
        let has_components = !docs.engine().component_ids().is_empty();
        let mut chosen: Option<&'static str> = None;
        let mut bom_chosen: Option<&'static str> = None;
        let mut cancel = false;
        let modal = egui::Modal::new(egui::Id::new("brep-file-export")).show(ctx, |ui| {
            ui.set_width(320.0);
            ui.heading("Export model");
            ui.add_space(4.0);
            let field = ui.add(
                egui::TextEdit::singleline(&mut self.name_buf)
                    .hint_text("file name")
                    .desired_width(f32::INFINITY),
            );
            self.hit("field:name", &field);
            if self.want_focus {
                field.request_focus();
                self.want_focus = false;
            }
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                let step = ui.button("STEP (.step)");
                self.hit("export:step", &step);
                if step.clicked() {
                    chosen = Some("step");
                }
                let iges = ui.button("IGES (.igs)");
                self.hit("export:iges", &iges);
                if iges.clicked() {
                    chosen = Some("iges");
                }
                let stl = ui.button("STL (.stl)");
                self.hit("export:stl", &stl);
                if stl.clicked() {
                    chosen = Some("stl");
                }
                // The full model RECIPE (`.BREP.json`) — for saving a document to
                // disk / sharing a failing model for a bug report. Re-openable via
                // Open / Import.
                let json = ui.button("JSON (.BREP.json)");
                self.hit("export:json", &json);
                if json.clicked() {
                    chosen = Some("json");
                }
                let c = ui.button("Cancel");
                self.hit("cancel", &c);
                if c.clicked() {
                    cancel = true;
                }
            });
            ui.add_space(4.0);
            ui.horizontal(|ui| {
                // The assembly BOM (parts list): one row per parts-library
                // entry with the live instance count. Disabled while the
                // document has no components (spec §9).
                let csv = ui.add_enabled(has_components, egui::Button::new("BOM (CSV)"));
                self.hit("export:bomcsv", &csv);
                if csv.clicked() {
                    bom_chosen = Some("csv");
                }
                let json = ui.add_enabled(has_components, egui::Button::new("BOM (JSON)"));
                self.hit("export:bomjson", &json);
                if json.clicked() {
                    bom_chosen = Some("json");
                }
            });
            if !self.status.is_empty() {
                ui.add_space(4.0);
                ui.weak(&self.status);
            }
        });
        if let Some(format) = chosen {
            if self.export_as(docs, store, format) {
                self.open = false;
            }
        } else if let Some(format) = bom_chosen {
            if self.export_bom_as(docs, store, format) {
                self.open = false;
            }
        } else if cancel || modal.should_close() {
            self.open = false;
        }
    }

    /// The **Flat pattern** chooser: pick a 2D vector format (DXF R12 / SVG) and
    /// write the sheet-metal body's unfolded flat pattern to the user's filesystem
    /// under `<name>.<ext>`. The unfold runs TRANSIENTLY in the engine (no feature,
    /// no history change). A part with no sheet-metal body reports it in the status
    /// line AND queues a toast (see [`Self::export_flat_pattern_as`]).
    fn show_flat_pattern(
        &mut self,
        ctx: &egui::Context,
        docs: &mut Documents,
        store: &dyn ModelStore,
    ) {
        let mut chosen: Option<&'static str> = None;
        let mut cancel = false;
        let modal = egui::Modal::new(egui::Id::new("brep-file-flatpattern")).show(ctx, |ui| {
            ui.set_width(340.0);
            ui.heading("Export flat pattern");
            ui.add_space(2.0);
            ui.weak("Unfolds the sheet-metal body to a 2D vector file.");
            ui.add_space(4.0);
            let field = ui.add(
                egui::TextEdit::singleline(&mut self.name_buf)
                    .hint_text("file name")
                    .desired_width(f32::INFINITY),
            );
            self.hit("field:name", &field);
            if self.want_focus {
                field.request_focus();
                self.want_focus = false;
            }
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                let dxf = ui.button("DXF (.dxf)");
                self.hit("flat:dxf", &dxf);
                if dxf.clicked() {
                    chosen = Some("dxf");
                }
                let svg = ui.button("SVG (.svg)");
                self.hit("flat:svg", &svg);
                if svg.clicked() {
                    chosen = Some("svg");
                }
                let c = ui.button("Cancel");
                self.hit("cancel", &c);
                if c.clicked() {
                    cancel = true;
                }
            });
            if !self.status.is_empty() {
                ui.add_space(4.0);
                ui.weak(&self.status);
            }
        });
        if let Some(format) = chosen {
            if self.export_flat_pattern_as(docs, store, format) {
                self.open = false;
            }
        } else if cancel || modal.should_close() {
            self.open = false;
        }
    }

    /// The **Open** browser: the saved-model list (+ Upload where the platform
    /// supports real-file interchange).
    fn show_open(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
        let current = docs.active().name().map(str::to_string);
        let modal = egui::Modal::new(egui::Id::new("brep-file-open")).show(ctx, |ui| {
            ui.set_width(600.0);
            ui.heading("Open model");
            ui.add_space(4.0);
            let mut options = FileExplorerOptions::open(current.as_deref());
            options.allow_import = store.supports_file_interchange();
            let output = self.explorer.show_store(ui, store, options);
            self.record_explorer_hits(&output.hits);
            if !self.status.is_empty() {
                ui.add_space(4.0);
                ui.weak(&self.status);
            }
            output
        });
        let should_close = modal.should_close();
        let output = modal.inner;
        if let Some(name) = output.activated {
            self.open_document(docs, store, &name);
            self.open = false;
        } else if let Some(name) = output.remove {
            let _ = store.remove(&name);
            self.status = format!("removed {name}");
            // A tab holding the removed document keeps its content but loses its
            // file: it becomes an untitled document, so a later Save asks where
            // to put it rather than silently recreating what was deleted.
            if let Some(index) = docs.index_of(&name) {
                if let Some(doc) = docs.get_mut(index) {
                    doc.set_name(None);
                }
            }
        } else if output.import {
            // Fire the platform picker; the file arrives via take_import() and is
            // loaded on a later frame (the modal closes now).
            match store.begin_import() {
                Ok(()) => {
                    self.status = "choose a file…".into();
                    self.open = false;
                }
                Err(e) => self.status = format!("import failed: {e}"),
            }
        } else if output.cancel || should_close {
            self.open = false;
        }
    }

    /// The **Insert component** selector (assemblies build-spec §2.2): the
    /// EXISTING parts-library entries first (instant re-insert — no store read),
    /// then the model store's document list, + Upload where the platform
    /// supports real-file interchange. REUSES the Open modal's machinery (the
    /// same list + `take_import` poll), routed to the engine's insert flow.
    fn show_insert_component(
        &mut self,
        ctx: &egui::Context,
        state: &mut EngineState,
        store: &dyn ModelStore,
    ) {
        let library = state.parts_library_names();
        let modal = egui::Modal::new(egui::Id::new("brep-file-insert-component")).show(ctx, |ui| {
            ui.set_width(600.0);
            ui.heading("Insert component");
            ui.add_space(4.0);
            let mut chosen_library = None;
            if !library.is_empty() {
                ui.weak("In this document (parts library)");
                for name in &library {
                    let row = ui.add_sized(
                        egui::vec2(ui.available_width(), 18.0),
                        crate::icon_text::icon_button(ui, &format!("\u{25A3} {name}")).frame(false),
                    );
                    self.hit(&format!("insert:lib:{name}"), &row);
                    if row.clicked() {
                        chosen_library = Some(name.clone());
                    }
                }
                ui.add_space(4.0);
            }
            let options = FileExplorerOptions {
                hit_prefix: "insert:model",
                empty_label: "(no saved models)",
                row_icon: "\u{1F5CE}",
                current: None,
                allow_delete: false,
                allow_import: store.supports_file_interchange(),
                import_label: "Upload\u{2026}",
                import_hit: "insert:upload",
                show_cancel: true,
                confirm_label: Some("Insert"),
                extensions: &["BREP.json", "json"],
            };
            let output = self.explorer.show_store(ui, store, options);
            self.record_explorer_hits(&output.hits);
            if !self.status.is_empty() {
                ui.add_space(4.0);
                ui.weak(&self.status);
            }
            (chosen_library, output)
        });
        let should_close = modal.should_close();
        let (chosen_library, output) = modal.inner;
        if let Some(part_name) = chosen_library {
            // An already-inserted library part: skip the store read entirely.
            match state.insert_component(ComponentInsert::Existing { part_name: &part_name }) {
                Ok(id) => {
                    self.status = format!("inserted {part_name} ({id})");
                    self.open = false;
                }
                Err(e) => self.status = format!("insert failed: {e}"),
            }
        } else if let Some(name) = output.activated {
            match store.read(&name) {
                Some(contents) => {
                    self.insert_component_document(state, &name, &contents);
                    self.open = false;
                }
                None => self.status = format!("insert failed: '{name}' not found"),
            }
        } else if output.import {
            match store.begin_import() {
                Ok(()) => {
                    // The picked file routes to the component insert (not Open).
                    self.pending_component_import = true;
                    self.status = "choose a part file…".into();
                    self.open = false;
                }
                Err(e) => self.status = format!("insert failed: {e}"),
            }
        } else if output.cancel || should_close {
            self.open = false;
        }
    }

    /// Insert a part DOCUMENT as an assembly component: library-add (dedup by
    /// sourceKey + content signature; the RETURNED effective name is what the
    /// instance references) + an ACOMP feature, through the engine's one insert
    /// flow. The first instance of an empty assembly is written `isFixed:true`.
    /// `sourceSignature` is written with [`document_signature`] — the ONE
    /// signature fn — so the update-components comparison reads a freshly
    /// inserted, unchanged part as up-to-date.
    fn insert_component_document(&mut self, state: &mut EngineState, name: &str, contents: &str) {
        let display = model_display_name(name);
        match state.insert_component(ComponentInsert::New {
            name: &display,
            source_key: name,
            source_signature: &document_signature(contents),
            document_json: contents,
        }) {
            Ok(id) => self.status = format!("inserted {display} ({id})"),
            Err(e) => self.status = format!("insert failed: {e}"),
        }
    }

    // --- model operations -----------------------------------------------------

    /// The name to save under: the field if non-empty, else the active
    /// document's name, else `"untitled"`.
    fn effective_name(&self, docs: &Documents) -> String {
        let field = self.name_buf.trim();
        if !field.is_empty() {
            field.to_string()
        } else {
            docs.active()
                .name()
                .map(str::to_string)
                .unwrap_or_else(|| "untitled".into())
        }
    }

    /// **New** — an empty model in a NEW TAB. Nothing is replaced, so there is
    /// nothing to confirm.
    fn new_document(&mut self, docs: &mut Documents) {
        let mut engine = docs.spawn_engine();
        let _ = engine.set_history_json(EMPTY_DOCUMENT);
        docs.open_document(Document::new(engine));
        self.name_buf.clear();
        self.status = "new (empty) model".into();
    }

    /// Refuse a save that would give TWO open tabs the same store identity —
    /// "focus the tab holding this document" has no answer then, and the second
    /// save would silently overwrite the first tab's file. `true` = go ahead.
    ///
    /// Compared by DISPLAY name, not raw identity: on desktop an open document
    /// carries the full path it was loaded from while the Save As field holds a
    /// bare name, so an identity compare would never match and the clobber would
    /// happen before anything noticed. Two same-stemmed files in different
    /// folders are refused too — stricter than strictly necessary, and the side
    /// to err on when the alternative is overwriting another tab's file.
    fn name_is_free(&mut self, docs: &Documents, name: &str) -> bool {
        let display = model_display_name(name);
        let taken = docs.iter().enumerate().any(|(index, doc)| {
            index != docs.active_index()
                && doc
                    .name()
                    .is_some_and(|open| model_display_name(open) == display)
        });
        if taken {
            self.status = format!("'{display}' is already open in another tab");
        }
        !taken
    }

    /// Write the active document's request JSON through the store under `name`.
    /// Returns `true` on success (so the caller can close the modal).
    fn save_to(&mut self, docs: &mut Documents, store: &dyn ModelStore, name: String) -> bool {
        let name = name.trim().to_string();
        if name.is_empty() {
            self.status = "enter a name to save".into();
            return false;
        }
        if !self.name_is_free(docs, &name) {
            return false;
        }
        match store.write(&name, &docs.engine().history_request_json()) {
            Ok(()) => {
                // The document keeps the raw identity (a full path when a
                // native dialog chose it); the name field shows the bare name.
                self.name_buf = model_display_name(&name);
                let doc = docs.active_mut();
                doc.set_name(Some(name.clone()));
                doc.mark_clean();
                self.save_generation += 1;
                self.status = format!("saved {name}");
                true
            }
            Err(e) => {
                self.status = format!("save failed: {e}");
                false
            }
        }
    }

    /// Save As through the explorer's current directory, then retain the
    /// backend's returned identity (an absolute path on desktop or a virtual
    /// `/models/...` path in the browser) for subsequent plain Save commands.
    fn save_to_browser(
        &mut self,
        docs: &mut Documents,
        store: &dyn ModelStore,
        name: String,
    ) -> bool {
        let name = name.trim().to_string();
        if name.is_empty() {
            self.status = "enter a name to save".into();
            return false;
        }
        if !self.name_is_free(docs, &name) {
            return false;
        }
        match store.browser_write(&name, &docs.engine().history_request_json()) {
            Ok(identity) => {
                self.name_buf = model_display_name(&identity);
                let doc = docs.active_mut();
                doc.set_name(Some(identity.clone()));
                doc.mark_clean();
                self.save_generation += 1;
                self.status = format!("saved {identity}");
                true
            }
            Err(e) => {
                self.status = format!("save failed: {e}");
                false
            }
        }
    }

    /// **Open** — read a stored document into its own tab (or focus the tab
    /// already holding it). The one door every open lane uses: File>Open, the
    /// Edit-Part flow, and the session restore's siblings.
    pub fn open_document(&mut self, docs: &mut Documents, store: &dyn ModelStore, name: &str) {
        if docs.focus_named(name) {
            self.status = format!("{name} is already open");
            return;
        }
        match store.read(name) {
            Some(contents) => self.load_document(docs, name, &contents),
            None => self.status = format!("open failed: '{name}' not found"),
        }
    }

    /// Serialize the current model in `format` (`"step"` | `"stl"` | `"json"`) and
    /// write it through the store's format-typed interchange under `<name>.<ext>`.
    /// `"json"` is the full model RECIPE (`.BREP.json`, `history_request_json`) —
    /// the exact document Open/Import consume, for sharing a failing model. Returns
    /// `true` on success (so the caller can close the modal); a guard message and
    /// `false` when there is nothing to export or the engine/store errs.
    fn export_as(&mut self, docs: &Documents, store: &dyn ModelStore, format: &str) -> bool {
        let name = self.effective_name(docs);
        let state = docs.engine();
        let (text, ext) = match format {
            "stl" => (state.export_stl_text(), "stl"),
            "iges" => (state.export_iges_text(), "igs"),
            "json" => (Ok(state.history_request_json()), "BREP.json"),
            _ => (state.export_step_text(), "step"),
        };
        match text {
            Ok(contents) => match store.export_file_named(&format!("{name}.{ext}"), &contents) {
                Ok(()) => {
                    self.status = format!("exported {name}.{ext}");
                    true
                }
                Err(e) => {
                    self.status = format!("export failed: {e}");
                    false
                }
            },
            Err(e) => {
                self.status = format!("export failed: {e}");
                false
            }
        }
    }

    /// Serialize the sheet-metal flat pattern in `format` (`"dxf"` | `"svg"`) and
    /// write it through the store under `<name>.<ext>`. Returns `true` on success
    /// (so the caller can close the modal). On failure the message goes to the
    /// status line AND is queued as a toast (the existing engine notice path), so
    /// a "no sheet-metal body in the part" error is surfaced prominently.
    fn export_flat_pattern_as(
        &mut self,
        docs: &mut Documents,
        store: &dyn ModelStore,
        format: &str,
    ) -> bool {
        let name = self.effective_name(docs);
        let state = docs.engine_mut();
        let (text, ext) = match format {
            "svg" => (state.export_flat_pattern_svg(), "svg"),
            _ => (state.export_flat_pattern_dxf(), "dxf"),
        };
        match text {
            Ok(contents) => match store.export_file_named(&format!("{name}.{ext}"), &contents) {
                Ok(()) => {
                    self.status = format!("exported {name}.{ext}");
                    true
                }
                Err(e) => {
                    self.status = format!("flat-pattern export failed: {e}");
                    false
                }
            },
            Err(e) => {
                self.status = format!("flat-pattern export failed: {e}");
                state.push_notice(format!("Flat pattern: {e}"));
                false
            }
        }
    }

    /// Serialize the assembly BOM in `format` (`"csv"` | `"json"`) and write it
    /// through the store under `<name>.bom.<ext>` (a compound extension naming
    /// the content, like the `.BREP.json` recipe). On failure the message goes
    /// to the status line AND is queued as a toast — the flat-pattern error
    /// pattern — so a componentless document reports loudly.
    fn export_bom_as(
        &mut self,
        docs: &mut Documents,
        store: &dyn ModelStore,
        format: &str,
    ) -> bool {
        let name = self.effective_name(docs);
        let state = docs.engine_mut();
        let (text, ext) = match format {
            "json" => (state.export_bom_json(), "bom.json"),
            _ => (state.export_bom_csv(), "bom.csv"),
        };
        match text {
            Ok(contents) => match store.export_file_named(&format!("{name}.{ext}"), &contents) {
                Ok(()) => {
                    self.status = format!("exported {name}.{ext}");
                    true
                }
                Err(e) => {
                    self.status = format!("BOM export failed: {e}");
                    false
                }
            },
            Err(e) => {
                self.status = format!("BOM export failed: {e}");
                state.push_notice(format!("BOM export: {e}"));
                false
            }
        }
    }

    /// Route an imported STEP file: **probe first** (kernel-plan §3.9). The probe
    /// IS the parse — it stashes the structure in the engine for the import to
    /// consume — so a structured file arms the choice modal and is imported on
    /// the click, never parsed a second time.
    ///
    /// Everything else goes straight to today's flat lane, unchanged:
    ///
    /// * `Ok(None)` — no product structure. A part file must NEVER see the
    ///   dialog, and its behaviour stays byte-for-byte what it was.
    /// * `Err` — text the Part 21 parser refuses. Handing it to the flat lane
    ///   keeps the failure wording exactly today's (the two share the same
    ///   `ISO-10303-21` guard), rather than inventing a second one.
    fn import_step(&mut self, state: &mut EngineState, name: &str, contents: &str) {
        // A previous file's armed choice cannot survive this one: the probe
        // below REPLACES the engine's stash on every outcome (including the
        // structureless one), so an app-side pending left standing would offer
        // a button whose parse is already gone. A probe still running for an
        // earlier upload is superseded the same way (its answer is ignored).
        self.pending_step_import = None;
        let id = state.submit_step_probe(contents);
        self.pending_step_probe = Some(PendingStepProbe {
            id,
            name: name.to_string(),
            text: contents.to_string(),
        });
        self.status = format!("reading \"{name}\"\u{2026}");
        // The synchronous Inline runner (tests, headless) has answered inside
        // the submit; a background runner answers on a later frame's poll.
        self.poll_step_probe(state);
    }

    /// Resolve an answered STEP probe: structure arms the §3.9 choice, no
    /// structure (or a parse the flat lane will refuse with its own wording)
    /// takes the flat lane. A probe the engine no longer holds — a document
    /// switch or a cancelled run dropped it — is reported and forgotten.
    fn poll_step_probe(&mut self, state: &mut EngineState) {
        while let Some((id, outcome)) = state.take_step_probe() {
            let Some(pending) = self.pending_step_probe.as_ref() else {
                continue;
            };
            if pending.id != id {
                continue; // an earlier upload's answer; a newer probe replaced it
            }
            let PendingStepProbe { name, text, .. } = self.pending_step_probe.take().unwrap();
            match outcome {
                StepProbeOutcome::Structure(probe) => {
                    self.status = format!(
                        "\"{name}\" contains an assembly — {} part{}, {} instance{}",
                        probe.parts,
                        plural(probe.parts),
                        probe.instances,
                        plural(probe.instances)
                    );
                    self.pending_step_import = Some(PendingStepImport {
                        name,
                        text,
                        probe,
                        // Default = keep the tree (§3.9). Flattening is the escape
                        // hatch for a deep or pathological file, not the norm.
                        flatten: false,
                    });
                    // The routing site's `close_after_import` ran frames ago,
                    // while the probe was still out, and closed the modal: the
                    // choice is raised HERE, when the answer lands. (Under the
                    // synchronous Inline runner both run in the same call, and
                    // the second open is idempotent.)
                    self.open_modal(Mode::StepAssembly);
                }
                StepProbeOutcome::Flat | StepProbeOutcome::Failed(_) => {
                    self.import_step_flat(state, &name, &text);
                }
            }
        }
        if self.pending_step_probe.is_some() && !state.step_probes_pending() {
            // Nothing is running and no answer came: the engine dropped the
            // probe (document switch / cancel). Say so rather than reading
            // "reading…" forever.
            let pending = self.pending_step_probe.take().unwrap();
            self.status = format!("import of \"{}\" was cancelled", pending.name);
        }
    }

    /// Append an imported STEP file to the model (an IMPORT3D feature), then treat
    /// the enlarged model as dirty (an import is an edit, not an Open — the model
    /// keeps its current name / save baseline). THE flat lane, reached from a
    /// structureless file, an unparseable one, and the dialog's "Import as
    /// bodies".
    fn import_step_flat(&mut self, state: &mut EngineState, name: &str, contents: &str) {
        match state.import_step_feature(contents) {
            // Framing is deferred to the engine (`pending_fit`): under the native
            // thread / wasm worker runner the body is not resident yet, so framing
            // here would frame the empty scene. See [`EngineState::pending_fit`].
            Ok(_) => self.status = format!("imported {name}"),
            Err(e) => self.status = format!("import failed: {e}"),
        }
    }

    /// **Import as assembly** — consume the probe's stash into parts-library
    /// entries + one component per occurrence, in the engine's single batch.
    ///
    /// An `Err` here means the structured lane produced nothing, and the engine
    /// returns BEFORE it touches history when that happens — so the honest
    /// answer is the one A6's contract prescribes: re-run the flat import with
    /// the text this dialog is still holding, and say plainly that the assembly
    /// the user asked for came in as bodies. Silence there would leave them
    /// believing they have a structure tree that does not exist.
    fn step_assembly_import(&mut self, state: &mut EngineState, store: &dyn ModelStore) {
        let Some(pending) = self.pending_step_import.take() else {
            return;
        };
        // Read BEFORE the import: afterwards its own ACOMP features make the
        // answer unconditionally "yes" and the workbench switch never fires.
        let was_assembly = state.history_has_assembly();
        let doc_name = step_document_name(&pending.name);
        // The §3.9 checkbox. A depth-1 file imports identically either way, so
        // an un-shown box costs nothing.
        let opts = StepAssemblyImport {
            nested: !pending.flatten,
        };
        // Every unique part is written to the store as its own document, at the
        // browser's current location and under `{assembly}-{part}` — the same
        // `browser_write` door + "wherever the explorer is pointing" convention
        // the STEP parts-library import uses (`panels::step_parts`). So an
        // imported part is a part like any other: Open Part opens it, Update
        // Components tracks it, a part edit writes through to it.
        let mut sink = StorePartSink::new(store, &doc_name);
        let message = match state.import_probed_step_assembly(&doc_name, opts, &mut sink) {
            Ok(report) => {
                if !was_assembly {
                    self.enter_assembly_workbench(state);
                }
                // The store side effect is REPORTED, never silent: a 50-part
                // import writes 50 files the user did not individually ask for.
                for failure in &sink.failures {
                    state.push_notice(format!("part not saved — {failure}"));
                }
                let saved = sink.written;
                let base = assembly_import_message(&pending.name, &report);
                match (saved, sink.failures.len()) {
                    (0, _) => base,
                    (saved, 0) => format!("{base}; saved {saved} part file(s)"),
                    (saved, failed) => {
                        format!("{base}; saved {saved} part file(s), {failed} could not be saved")
                    }
                }
            }
            Err(error) => match state.import_step_feature(&pending.text) {
                Ok(_) => format!(
                    "imported {} as bodies — the assembly structure could not be built ({error})",
                    pending.name
                ),
                Err(flat) => format!("import failed: {flat}"),
            },
        };
        // The status line only renders inside an OPEN modal and this one closes
        // on the click, so the toast is the half the user actually sees.
        self.status = message.clone();
        state.push_notice(message);
    }

    /// **Import as bodies** — today's flat lane, unchanged. Drops the probe's
    /// stash first: the user chose the text, so the parsed assembly (and every
    /// product's solids it is holding resident) has no consumer left.
    fn step_assembly_bodies(&mut self, state: &mut EngineState) {
        let Some(pending) = self.pending_step_import.take() else {
            return;
        };
        state.discard_probed_step_assembly();
        self.import_step_flat(state, &pending.name, &pending.text);
    }

    /// **Cancel** — import nothing and drop the parse (§3.9).
    fn step_assembly_cancel(&mut self, state: &mut EngineState) {
        let Some(pending) = self.pending_step_import.take() else {
            return;
        };
        state.discard_probed_step_assembly();
        self.status = format!("import cancelled: {}", pending.name);
    }

    /// Switch to the **Assembly** workbench so a freshly imported structure is
    /// actually reachable: the Assembly Structure tree and the Constraints panel
    /// are CLAIMED by that workbench, so an assembly imported under Modeling
    /// would land with its structure invisible.
    ///
    /// No-op when the active workbench already shows those panels — Assembly
    /// itself, and "All", whose users must not be yanked out of it. Applied
    /// through the same settings seam the toolbar dropdown and the saved-
    /// workbench restore use, and like the restore NOT persisted to the settings
    /// blob: that blob stays the user's boot preference, and a document's
    /// workbench is session-scoped.
    fn enter_assembly_workbench(&mut self, state: &mut EngineState) {
        if crate::workbench::panel_visible(
            &state.settings.workbench,
            crate::workbench::assembly::BOM_PANEL_ID,
        ) {
            return;
        }
        let _ = state.apply_settings_json(
            &serde_json::json!({ "workbench": crate::workbench::assembly::ASSEMBLY.id })
                .to_string(),
        );
    }

    /// Append an imported IGES file to the model (an IMPORT3D feature) — the
    /// IGES sibling of [`Self::import_step`].
    fn import_iges(&mut self, state: &mut EngineState, name: &str, contents: &str) {
        match state.import_iges_feature(contents) {
            // Framing deferred to the engine (`pending_fit`) — see `import_step`.
            Ok(_) => self.status = format!("imported {name}"),
            Err(e) => self.status = format!("import failed: {e}"),
        }
    }

    fn stage_stl_preview(&mut self, name: String, contents: Vec<u8>) {
        self.pending_stl_import = Some((name, contents));
        self.status.clear();
    }

    /// Selecting an STL starts a preview session; only its Accept action edits
    /// the destination document.
    pub fn take_stl_import(&mut self) -> Option<(String, Vec<u8>)> {
        self.pending_stl_import.take()
    }

    fn import_obj(&mut self, state: &mut EngineState, name: &str, contents: &[u8]) {
        match state.import_obj_bytes_feature(contents) {
            Ok(_) => self.status = format!("reconstructing {name} in background…"),
            Err(e) => self.status = format!("import failed: {e}"),
        }
    }

    fn import_text(
        &mut self,
        state: &mut EngineState,
        name: &str,
        bytes: &[u8],
        importer: fn(&mut Self, &mut EngineState, &str, &str),
    ) {
        match std::str::from_utf8(bytes) {
            Ok(contents) => importer(self, state, name, contents),
            Err(_) => self.status = format!("import failed: {name} is not UTF-8 text"),
        }
    }

    /// Load a model document's contents into a NEW TAB (roll to the last
    /// feature + zoom-to-fit), clean from the start. A document that fails to
    /// load leaves no tab behind — the engine it was loading into is dropped
    /// with its runner.
    fn load_document(&mut self, docs: &mut Documents, name: &str, contents: &str) {
        let mut engine = docs.spawn_engine();
        match engine.load_model_and_fit(contents) {
            Ok(_) => {
                // The document keeps the raw identity — the full path when a
                // native dialog picked the file, so plain Save writes back to
                // it; the name field shows only the bare display name.
                let mut doc = Document::new(engine);
                doc.set_name(Some(name.to_string()));
                docs.open_document(doc);
                self.name_buf = model_display_name(name);
                self.status = format!("opened {name}");
            }
            Err(e) => self.status = format!("open failed: {e}"),
        }
    }

    // --- verifier hooks (wasm only) -------------------------------------------

    /// The published state for the headed verifier: current name, dirty flag,
    /// backend label, the stored-document list, and the modal's open/mode.
    #[cfg(target_arch = "wasm32")]
    pub fn file_state_json(&self, docs: &Documents, store: &dyn ModelStore) -> String {
        serde_json::json!({
            "name": docs.active().name(),
            "nameBuf": self.name_buf,
            "selected": self.explorer.selected(),
            "location": store.browser_location(),
            "dirty": docs.active().is_dirty(),
            "backend": store.backend_label(),
            "interchange": store.supports_file_interchange(),
            "list": store.list(),
            "status": self.status,
            "open": self.open,
            "mode": match self.mode {
                Mode::Open => "open",
                Mode::SaveAs => "saveas",
                Mode::ConfirmClose => "confirmclose",
                Mode::Export => "export",
                Mode::Import => "import",
                Mode::FlatPattern => "flatpattern",
                Mode::InsertComponent => "insertcomponent",
                Mode::StepAssembly => "stepassembly",
            },
            // The armed §3.9 assembly choice: the file it belongs to and the
            // counts the prompt is showing, so the headed verifier can confirm
            // the dialog appeared with the numbers the import will deliver.
            // A `.step` upload whose structure probe is still running on the
            // background runner (the "reading…" state).
            "probing": self.pending_step_probe.as_ref().map(|pending| pending.name.clone()),
            "stepAssembly": self.pending_step_import.as_ref().map(|pending| {
                serde_json::json!({
                    "name": pending.name,
                    "parts": pending.probe.parts,
                    "instances": pending.probe.instances,
                    "nestedDepth": pending.probe.nested_depth,
                    // The §3.9 checkbox: shown only when there is a tree to
                    // flatten, and OFF by default (import keeps the tree).
                    "flatten": pending.flatten,
                })
            }),
        })
        .to_string()
    }

    /// The published widget hit-rects (egui points) for the headed verifier.
    #[cfg(target_arch = "wasm32")]
    pub fn hits_json(&self) -> String {
        let map: serde_json::Map<String, Value> = self
            .hits
            .iter()
            .map(|(k, r)| {
                (
                    k.clone(),
                    serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]),
                )
            })
            .collect();
        Value::Object(map).to_string()
    }

    /// Record a widget's screen rect for the headed verifier (wasm only; a no-op
    /// elsewhere so the dialog code reads the same on both targets).
    #[cfg(target_arch = "wasm32")]
    fn hit(&mut self, key: &str, resp: &egui::Response) {
        self.hits.insert(key.to_string(), resp.rect);
    }
    #[cfg(not(target_arch = "wasm32"))]
    #[inline]
    fn hit(&mut self, _key: &str, _resp: &egui::Response) {}

    #[cfg(target_arch = "wasm32")]
    fn record_explorer_hits(&mut self, hits: &[(String, egui::Rect)]) {
        self.hits.extend(hits.iter().cloned());
    }
    #[cfg(not(target_arch = "wasm32"))]
    #[inline]
    fn record_explorer_hits(&mut self, _hits: &[(String, egui::Rect)]) {}
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;
    use crate::store::native_test_store;

    /// A ONE-DOCUMENT session over the SYNCHRONOUS inline runner, seeded with
    /// `history` and clean — the shape every dialog flow needs now that the
    /// dialog acts on documents rather than a bare engine. (The real shell's
    /// factory installs a background runner; a test needs the load's solids
    /// resident by the time the call returns.)
    fn documents(history: &str) -> Documents {
        let mut docs = Documents::new(Box::new(EngineState::new));
        docs.engine_mut().set_history_json(history).unwrap();
        docs.active_mut().mark_clean();
        docs
    }

    /// The engine's `history_request_json()` is a stable model document: writing
    /// it through the store and loading it back reproduces the same request —
    /// the native save/open round-trip the brief asks for.
    #[test]
    fn model_document_round_trips_through_store_and_engine() {
        // A temp-dir store (never touches the real config dir).
        let dir = std::env::temp_dir().join(format!("brep-app-file-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        // Build a model in the engine, serialize it, save it through the store.
        let mut engine = EngineState::new();
        let seed = r#"{"expressions":"","configurator":{},"features":[
            {"type":"P.CU","inputParams":{"id":"Box","sizeX":8.0,"sizeY":8.0,"sizeZ":8.0,
             "transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},
             "boolean":{"targets":[],"operation":"NONE"}},"persistentData":{}}
        ]}"#;
        engine.set_history_json(seed).unwrap();
        let before = engine.history_request_json();
        store.write("roundtrip", &before).unwrap();

        // A fresh engine loads the stored document + frames it, reproducing it.
        let mut reopened = EngineState::new();
        let contents = store.read("roundtrip").unwrap();
        reopened.load_model_and_fit(&contents).unwrap();
        let after = reopened.history_request_json();

        assert_eq!(before, after, "request JSON round-trips through the store");
        assert_eq!(reopened.history_len(), 1);
        assert_eq!(reopened.scene.solids().len(), 1);

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

    /// A saved part REMEMBERS the active workbench and Open RESTORES it — the
    /// full app-side lane over the engine's document round-trip: Save writes the
    /// top-level `workbench` field through the store; opening a stored document
    /// that carries the field switches the app's workbench through the shared
    /// settings seam (the toolbar dropdown's apply path); a LEGACY document
    /// without the field changes nothing; a BOGUS stored id opens cleanly and
    /// resolves to the default workbench via the registry's `resolve()`
    /// tolerance (never a panic or an error status).
    #[test]
    fn saved_documents_remember_and_restore_the_workbench() {
        use serde_json::Value;
        let dir = std::env::temp_dir().join(format!("brep-app-wb-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        // SAVE from the Sheet Metal workbench → the stored bytes carry the id.
        let mut docs = documents(BOX_SEED);
        docs.engine_mut()
            .apply_settings_json(r#"{"workbench":"sheetMetal"}"#)
            .unwrap();
        let mut dialog = FileDialog::new();
        assert!(dialog.save_to(&mut docs, &*store, "part".into()));
        let stored: Value = serde_json::from_str(&store.read("part").unwrap()).unwrap();
        assert_eq!(
            stored.get("workbench").and_then(Value::as_str),
            Some("sheetMetal"),
            "Save embeds the active workbench id in the document"
        );

        // OPEN in a fresh (default-Modeling) session → the NEW TAB comes up in
        // Sheet Metal, and is CLEAN (the baseline includes the field).
        let mut reopened = documents(EMPTY_DOCUMENT);
        assert_eq!(
            reopened.engine().settings.workbench, "modeling",
            "fresh session default"
        );
        let mut viewer = FileDialog::new();
        viewer.open_document(&mut reopened, &*store, "part");
        assert_eq!(reopened.len(), 2, "Open adds a tab");
        assert_eq!(
            reopened.engine().settings.workbench, "sheetMetal",
            "Open restores the saved workbench"
        );
        assert!(
            !reopened.active().is_dirty(),
            "a just-opened document is clean"
        );

        // LEGACY: a document WITHOUT the field leaves the active workbench alone.
        store.write("legacy", BOX_SEED).unwrap();
        viewer.open_document(&mut reopened, &*store, "legacy");
        assert!(viewer.status.starts_with("opened"), "legacy open succeeds");
        assert_eq!(
            reopened.engine().settings.workbench, "sheetMetal",
            "a legacy document inherits the session's workbench, unchanged"
        );

        // BOGUS: an unknown stored id opens fine — stored raw, resolved to the
        // default workbench at every consumption site by the registry.
        let mut bogus: Value = serde_json::from_str(BOX_SEED).unwrap();
        bogus["workbench"] = Value::String("conveyorBelts".into());
        store.write("bogus", &bogus.to_string()).unwrap();
        viewer.open_document(&mut reopened, &*store, "bogus");
        assert!(
            viewer.status.starts_with("opened"),
            "a bogus workbench id must not fail the open: {}",
            viewer.status
        );
        assert_eq!(
            reopened.engine().settings.workbench, "conveyorBelts",
            "raw id stored"
        );
        assert_eq!(
            crate::workbench::resolve(&reopened.engine().settings.workbench).id,
            "modeling",
            "…and it resolves to the default workbench wherever it is consumed"
        );

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

    /// An edit marks the DOCUMENT dirty; saving clears the flag again and
    /// records the name on that document.
    #[test]
    fn dirty_flag_flips_on_edit_and_clears_on_save() {
        let dir = std::env::temp_dir().join(format!("brep-app-dirty-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        let mut docs = documents(r#"{"features":[{"type":"P.CU","inputParams":{"id":"Box","sizeX":4.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}}]}"#);
        let mut dialog = FileDialog::new();
        assert!(!docs.active().is_dirty(), "seeded model is clean");
        assert_eq!(dialog.save_generation(), 0, "no saves yet");

        // Edit a parameter → dirty.
        docs.engine_mut()
            .update_feature_params(
                "Box",
                r#"{"id":"Box","sizeX":9.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}"#,
            )
            .unwrap();
        assert!(docs.active().is_dirty(), "edit marks dirty");

        // Save under a name (the Save As path) → clean, name recorded.
        assert!(
            dialog.save_to(&mut docs, &*store, "m".into()),
            "save succeeds"
        );
        assert!(!docs.active().is_dirty(), "save clears dirty");
        assert_eq!(docs.active().name(), Some("m"));
        assert_eq!(
            dialog.save_generation(),
            1,
            "a successful save bumps the update-components staleness key"
        );

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

    /// New ADDS A TAB and never prompts — nothing is replaced, so a dirty
    /// document has nothing to lose. CLOSING is where the unsaved-changes
    /// contract lives now: a clean tab closes on the spot, a dirty one raises
    /// the confirm modal and stays open until the user decides.
    #[test]
    fn new_adds_a_tab_and_only_closing_confirms() {
        let dir = std::env::temp_dir().join(format!("brep-app-newcfm-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        let mut docs = documents(r#"{"features":[{"type":"P.CU","inputParams":{"id":"Box","sizeX":4.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}}]}"#);
        let mut dialog = FileDialog::new();

        // New on a DIRTY document: still no modal, and the dirty model is still
        // there — in its own tab, behind the new empty one.
        docs.engine_mut()
            .update_feature_params(
                "Box",
                r#"{"id":"Box","sizeX":9.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}"#,
            )
            .unwrap();
        assert!(docs.active().is_dirty());
        dialog.dispatch(FileAction::New, &mut docs, &*store);
        assert!(!dialog.open, "New never opens a modal");
        assert_eq!(docs.len(), 2, "New adds a tab");
        assert_eq!(docs.active_index(), 1, "…and focuses it");
        assert_eq!(docs.engine().history_len(), 0, "the new tab is empty");
        assert_eq!(
            docs.get(0).unwrap().engine.history_len(),
            1,
            "the dirty document is untouched in its own tab"
        );

        // Closing the CLEAN new tab is immediate.
        dialog.request_close(&mut docs, 1);
        assert!(!dialog.open, "a clean close needs no confirmation");
        assert_eq!(docs.len(), 1);

        // Closing the DIRTY one raises the prompt and closes nothing yet.
        dialog.request_close(&mut docs, 0);
        assert!(dialog.open && dialog.mode == Mode::ConfirmClose);
        assert_eq!(dialog.pending_close, Some(0));
        assert_eq!(docs.len(), 1, "nothing closed until the user discards");

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

    /// A plain Save on a never-named document routes through Save As: with no
    /// name it opens the modal (nothing written); after a name is set + saved it
    /// records the name and clears dirty.
    #[test]
    fn save_on_unnamed_falls_through_to_save_as_modal() {
        let dir = std::env::temp_dir().join(format!("brep-app-unnamed-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        let mut docs = documents(r#"{"features":[{"type":"P.CU","inputParams":{"id":"Box","sizeX":4.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}}]}"#);
        let mut dialog = FileDialog::new();

        // Unnamed Save → Save As modal opens (feature-off native build).
        dialog.dispatch(FileAction::Save, &mut docs, &*store);
        assert!(dialog.open, "unnamed Save opens the Save As modal");
        assert!(store.list().is_empty(), "nothing written yet");

        // Provide a name + save.
        assert!(dialog.save_to(&mut docs, &*store, "part".into()));
        assert_eq!(docs.active().name(), Some("part"));
        assert_eq!(store.list(), vec!["part".to_string()]);

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

    /// A single-box model document, for the import/export lane tests.
    const BOX_SEED: &str = r#"{"expressions":"","configurator":{},"features":[
        {"type":"P.CU","inputParams":{"id":"Box","sizeX":8.0,"sizeY":8.0,"sizeZ":8.0,
         "transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},
         "boolean":{"targets":[],"operation":"NONE"}},"persistentData":{}}
    ]}"#;

    /// STEP file names route to the import lane; extension-less model names (and
    /// `.json` documents) do not — so the take_import poll never mis-routes.
    #[test]
    fn step_names_route_to_the_import_lane() {
        assert!(is_step_name("part.step"));
        assert!(is_step_name("PART.STP"));
        assert!(is_stl_name("scan.STL"));
        assert!(is_obj_name("scan.obj"));
        assert!(!is_step_name("model"), "model docs arrive extension-less");
        assert!(!is_step_name("model.json"));
        assert!(!is_stl_name("model.json"));
        assert!(!is_obj_name("model.json"));
    }

    /// Export dispatch opens the format chooser; choosing STEP / STL on a box
    /// model serializes into the native store directory. An empty model reports a
    /// clear guard rather than exporting.
    #[test]
    fn export_dispatch_and_chooser_serialize_the_model() {
        let dir = std::env::temp_dir().join(format!("brep-app-export-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        let mut docs = documents(BOX_SEED);
        let mut dialog = FileDialog::new();

        dialog.dispatch(FileAction::Export, &mut docs, &*store);
        assert!(dialog.open && dialog.mode == Mode::Export, "Export opens the chooser");
        assert!(dialog.export_as(&docs, &*store, "step"), "STEP export ok");
        assert!(dialog.status.contains("exported"), "status: {}", dialog.status);
        assert!(dialog.export_as(&docs, &*store, "stl"), "STL export ok");
        assert!(dialog.export_as(&docs, &*store, "json"), "JSON recipe export ok");
        assert!(dialog.status.contains(".BREP.json"), "json status: {}", dialog.status);
        assert!(dir.join("untitled.step").is_file());
        assert!(dir.join("untitled.stl").is_file());
        assert!(dir.join("untitled.BREP.json").is_file());

        let empty = documents(EMPTY_DOCUMENT);
        assert!(!dialog.export_as(&empty, &*store, "step"), "empty model does not export");
        assert!(dialog.status.contains("nothing to export"), "status: {}", dialog.status);

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

    #[test]
    fn import_dispatch_opens_the_common_explorer() {
        let dir = std::env::temp_dir().join(format!("brep-app-import-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());
        let mut docs = documents(EMPTY_DOCUMENT);
        let mut dialog = FileDialog::new();

        dialog.dispatch(FileAction::Import, &mut docs, &*store);
        assert!(dialog.open && dialog.mode == Mode::Import);

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

    /// The flat-pattern action opens the DXF/SVG chooser (its own modal mode). On
    /// a model with NO sheet-metal body the export reports the exact target error
    /// in the status line AND queues it as a toast (the engine notice path).
    #[test]
    fn flat_pattern_dispatch_errors_and_toasts_without_sheet_metal() {
        let dir = std::env::temp_dir().join(format!("brep-app-flat-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        // A plain box — no sheet-metal body.
        let mut docs = documents(BOX_SEED);
        let mut dialog = FileDialog::new();

        dialog.dispatch(FileAction::ExportFlatPattern, &mut docs, &*store);
        assert!(
            dialog.open && dialog.mode == Mode::FlatPattern,
            "flat-pattern action opens the DXF/SVG chooser"
        );

        // Choosing DXF fails loudly (no SM body): status set, notice queued, modal
        // stays open (the false return keeps it up).
        assert!(!dialog.export_flat_pattern_as(&mut docs, &*store, "dxf"));
        assert!(
            dialog.status.contains("no sheet-metal body"),
            "status names the missing body: {}",
            dialog.status
        );
        let notices = docs.engine_mut().take_notices();
        assert!(
            notices.iter().any(|n| n.contains("no sheet-metal body")),
            "the error is queued as a toast: {notices:?}"
        );

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

    /// The BOM lane (assemblies §9): on a componentless document the Export
    /// chooser's BOM buttons gate DISABLED (the `component_ids` predicate) and
    /// a direct export refuses loudly (status + toast, modal stays open) — the
    /// flat-pattern outcome pattern. With components resident the gate flips
    /// and both formats export under the `<name>.bom.<ext>` compound extension.
    #[test]
    fn bom_export_gates_on_components_and_exports_both_formats() {
        brep_render::brep_kernel::clear_history_cache();
        let dir = std::env::temp_dir().join(format!("brep-app-bom-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        // A plain box — no components.
        let mut docs = documents(BOX_SEED);
        let mut dialog = FileDialog::new();
        assert!(
            docs.engine().component_ids().is_empty(),
            "componentless doc → the chooser draws the BOM buttons disabled"
        );
        assert!(!dialog.export_bom_as(&mut docs, &*store, "csv"));
        assert!(
            dialog.status.contains("no components"),
            "status names the guard: {}",
            dialog.status
        );
        let notices = docs.engine_mut().take_notices();
        assert!(
            notices.iter().any(|n| n.contains("no components")),
            "the error is queued as a toast: {notices:?}"
        );

        // Insert the SAME part twice (one library entry, two instances): the
        // gate flips and both formats export.
        dialog.insert_component_document(docs.engine_mut(), "widget", BOX_SEED);
        dialog.insert_component_document(docs.engine_mut(), "widget", BOX_SEED);
        assert!(
            !docs.engine().component_ids().is_empty(),
            "components resident → the BOM buttons enable"
        );
        assert!(dialog.export_bom_as(&mut docs, &*store, "csv"), "CSV export ok");
        assert!(dialog.status.contains(".bom.csv"), "status: {}", dialog.status);
        assert!(dialog.export_bom_as(&mut docs, &*store, "json"), "JSON export ok");
        assert!(dialog.status.contains(".bom.json"), "status: {}", dialog.status);

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

    /// The INSERT-COMPONENT lane: a stored part document inserts as a
    /// parts-library entry + an ACOMP instance (the returned effective name in
    /// `partName`, first instance explicitly fixed), and `sourceSignature` is
    /// written with the ONE signature fn (`document_signature`) — the
    /// update-components comparison's up-to-date invariant.
    #[test]
    fn insert_component_document_adds_a_library_backed_instance() {
        brep_render::brep_kernel::clear_history_cache();
        let mut engine = EngineState::new();
        let mut dialog = FileDialog::new();

        // Insert the box part document as a component.
        dialog.insert_component_document(&mut engine, "box-part", BOX_SEED);
        assert!(
            dialog.status.contains("inserted box-part (ACOMP1)"),
            "status: {}",
            dialog.status
        );
        let params = engine
            .history
            .feature_params(engine.history.index_of("ACOMP1").unwrap())
            .unwrap();
        assert_eq!(params["partName"], "box-part", "effective library name");
        assert_eq!(params["isFixed"], true, "first instance explicitly fixed");
        assert_eq!(engine.parts_library_names(), vec!["box-part".to_string()]);
        // The instance is live geometry under the namespaced member name.
        assert!(engine.scene.solid("ACOMP1:Box").is_some());
        // The entry's signature is document_signature(contents): a fresh insert
        // with UNCHANGED source must compare up-to-date (outdated count 0).
        let doc: serde_json::Value =
            serde_json::from_str(&engine.history_request_json()).unwrap();
        assert_eq!(
            doc["partsLibrary"]["box-part"]["sourceSignature"],
            document_signature(BOX_SEED),
            "insert writes the ONE signature fn's value"
        );

        // Re-inserting the SAME document dedups to the same library entry and
        // the second instance is NOT fixed.
        dialog.insert_component_document(&mut engine, "box-part", BOX_SEED);
        let params2 = engine
            .history
            .feature_params(engine.history.index_of("ACOMP2").unwrap())
            .unwrap();
        assert_eq!(params2["partName"], "box-part");
        assert_eq!(params2["isFixed"], false);
        assert_eq!(engine.parts_library_names(), vec!["box-part".to_string()]);
    }

    /// The Edit-Part lane (and File>Open, which is the same door):
    /// `open_document` ADDS A TAB for a document that is not open, and FOCUSES
    /// the existing tab for one that is — never a second copy of one file, and
    /// never a prompt, because nothing is replaced.
    #[test]
    fn open_document_adds_a_tab_or_focuses_the_open_one() {
        let dir = std::env::temp_dir().join(format!("brep-app-openpart-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());
        store.write("part", BOX_SEED).unwrap();
        store.write("other", BOX_SEED).unwrap();

        // A DIRTY current document — the case that used to prompt.
        let mut docs = documents(BOX_SEED);
        docs.engine_mut()
            .update_feature_params(
                "Box",
                r#"{"id":"Box","sizeX":9.0,"sizeY":8.0,"sizeZ":8.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}"#,
            )
            .unwrap();
        assert!(docs.active().is_dirty());
        let mut dialog = FileDialog::new();

        dialog.open_document(&mut docs, &*store, "part");
        assert!(!dialog.open, "opening never raises a modal");
        assert_eq!(docs.len(), 2, "a tab was added");
        assert_eq!(docs.active().name(), Some("part"));
        assert!(!docs.active().is_dirty(), "freshly opened is clean");
        assert!(
            docs.get(0).unwrap().is_dirty(),
            "the dirty document is still open and still dirty"
        );

        // A second document opens beside them…
        dialog.open_document(&mut docs, &*store, "other");
        assert_eq!(docs.len(), 3);
        assert_eq!(docs.active_index(), 2);

        // …and re-opening the first FOCUSES its tab rather than adding another.
        dialog.open_document(&mut docs, &*store, "part");
        assert_eq!(docs.len(), 3, "no second tab for one file");
        assert_eq!(docs.active_index(), 1);
        assert!(dialog.status.contains("already open"), "status: {}", dialog.status);

        // A name with no document says so and opens nothing.
        dialog.open_document(&mut docs, &*store, "missing");
        assert_eq!(docs.len(), 3);
        assert!(dialog.status.contains("not found"), "status: {}", dialog.status);

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

    /// A save that would give TWO tabs one store identity is refused: "focus the
    /// tab holding this document" has no answer then, and the second save would
    /// silently overwrite the first tab's file.
    #[test]
    fn saving_onto_a_name_open_in_another_tab_is_refused() {
        let dir = std::env::temp_dir().join(format!("brep-app-dupname-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());
        store.write("part", BOX_SEED).unwrap();

        let mut docs = documents(BOX_SEED);
        let mut dialog = FileDialog::new();
        dialog.open_document(&mut docs, &*store, "part");
        assert_eq!(docs.active_index(), 1);

        // The untitled scratch tab tries to save over the open document — by the
        // BARE name, which on desktop is not the open document's raw identity
        // (that is a full path), so the guard has to compare display names.
        docs.activate(0);
        assert!(!dialog.save_to(&mut docs, &*store, "part".into()));
        assert!(
            !dialog.save_to_browser(&mut docs, &*store, "part".into()),
            "the Save As lane refuses BEFORE it writes, never after"
        );
        assert!(
            dialog.status.contains("already open in another tab"),
            "status: {}",
            dialog.status
        );
        assert_eq!(docs.active().name(), None, "nothing claimed the name");

        // Saving over ITS OWN name is of course fine.
        docs.activate(1);
        assert!(dialog.save_to(&mut docs, &*store, "part".into()));

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

    /// A STEP file routed to import is APPENDED to the model (an edit → dirty),
    /// unlike Open which replaces + cleans. Uses the engine's own STEP export to
    /// produce a valid document without a direct kernel dependency.
    #[test]
    fn import_step_appends_and_marks_dirty() {
        let dir = std::env::temp_dir().join(format!("brep-app-imp-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let store = native_test_store(dir.clone());

        // A box model → STEP text via the engine.
        let mut source = EngineState::new();
        source.set_history_json(BOX_SEED).unwrap();
        let step = source.export_step_text().unwrap();

        // A fresh (empty, clean) document imports it: one body appended, dirty.
        let mut docs = documents(EMPTY_DOCUMENT);
        let mut dialog = FileDialog::new();
        assert!(!docs.active().is_dirty(), "empty seed is clean");
        dialog.import_step(docs.engine_mut(), "part.step", &step);
        assert_eq!(docs.engine().history_len(), 1, "IMPORT3D feature appended");
        assert_eq!(
            docs.engine().scene.solids().len(),
            1,
            "the imported body is in the scene"
        );
        assert!(docs.active().is_dirty(), "an import is an edit");
        assert!(dialog.status.contains("imported"), "status: {}", dialog.status);
        let _ = store; // store unused beyond construction (test stores never drive dialogs)

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

    // -----------------------------------------------------------------------
    // Structured STEP assembly import (kernel-plan `step-assembly-import.md`
    // §3.9) — the trigger: probe first, then the choice modal.
    // -----------------------------------------------------------------------

    /// A STEP fixture from the KERNEL's corpus, read at RUNTIME: that corpus is
    /// test-only ROOT data which deliberately stays outside every crate package
    /// archive, so it must not be `include_str!`d into this crate. (The engine's
    /// own assembly tests read it exactly this way.)
    fn step_fixture(name: &str) -> String {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../BREP_kernel/tests/fixtures/step-import")
            .join(name);
        std::fs::read_to_string(&path)
            .unwrap_or_else(|error| panic!("read fixture {}: {error}", path.display()))
    }

    /// The classic AP214 assembly: 5 geometry-bearing parts in 18 placements.
    const AS1: &str = "as1-ug-214.stp";

    /// A dialog with the AS1 choice ARMED — the state every dialog-exit test
    /// starts from. Asserts the arming itself, so each caller can go straight to
    /// the click it is about.
    fn armed(engine: &mut EngineState) -> FileDialog {
        let mut dialog = FileDialog::new();
        dialog.import_step(engine, AS1, &step_fixture(AS1));
        let pending = dialog
            .pending_step_import
            .as_ref()
            .expect("as1-ug-214 carries a product structure, so the choice arms");
        assert_eq!(
            (pending.probe.parts, pending.probe.instances),
            (5, 18),
            "the prompt shows the counts the import will deliver"
        );
        assert_eq!(engine.history_len(), 0, "nothing is imported before the click");
        dialog
    }

    /// Whether the engine is still holding a probed parse — observed through the
    /// consume, which is the only public window onto the stash: `Err` is
    /// "nothing probed", and it is also the double-import guard.
    fn stash_is_empty(engine: &mut EngineState) -> bool {
        engine
            .import_probed_step_assembly(
                "probe",
                StepAssemblyImport::default(),
                &mut brep_render::engine_state::EmbeddedOnly,
            )
            .is_err()
    }

    /// The store-write lane's naming: a STEP product name is reduced to
    /// something every backend can hold as a file name, and two products that
    /// reduce to the SAME name get distinct files — otherwise the second
    /// overwrites the first and two library entries point at one document.
    #[test]
    fn imported_part_file_names_are_sanitized_and_never_collide() {
        assert_eq!(sanitize_file_stem("L Bracket"), "L_Bracket");
        assert_eq!(sanitize_file_stem("rod/assem"), "rod_assem", "no path escape");
        assert_eq!(
            sanitize_file_stem("bolt (mirrored)"),
            "bolt_mirrored",
            "the crate's own factor suffix survives readably"
        );
        assert_eq!(sanitize_file_stem("a///b"), "a_b", "runs collapse");
        assert_eq!(sanitize_file_stem("  "), "part", "never an empty name");
        assert_eq!(sanitize_file_stem("plate-1.2"), "plate-1.2", "kept as-is");

        let store = crate::store::MemModelStore::new();
        let mut sink = StorePartSink::new(&store, "as1 ug");
        // Two DIFFERENT products that sanitize to the same stem.
        let first = sink.store_part("L Bracket", "{\"a\":1}").expect("written");
        let second = sink.store_part("L/Bracket", "{\"a\":2}").expect("written");
        assert_eq!(first, "as1_ug-L_Bracket");
        assert_eq!(second, "as1_ug-L_Bracket-2", "disambiguated, not overwritten");
        assert_eq!(store.read(&first).as_deref(), Some("{\"a\":1}"));
        assert_eq!(store.read(&second).as_deref(), Some("{\"a\":2}"));
        assert_eq!(sink.written, 2);
        assert!(sink.failures.is_empty());
    }

    /// A file with NO product structure must never see the dialog: the probe
    /// reports nothing, the flat lane runs immediately, and the modal closes as
    /// it always did. This is the "unchanged for part files" half of §3.9, and
    /// the engine is left holding nothing.
    #[test]
    fn a_structureless_step_never_sees_the_dialog() {
        let mut source = EngineState::new();
        source.set_history_json(BOX_SEED).unwrap();
        let step = source.export_step_text().unwrap();

        let mut engine = EngineState::new();
        let mut dialog = FileDialog::new();
        dialog.import_step(&mut engine, "part.step", &step);

        assert!(
            dialog.pending_step_import.is_none(),
            "a part file must not arm the assembly choice"
        );
        dialog.close_after_import();
        assert!(!dialog.open, "nothing armed, so the modal closes");
        assert_eq!(engine.history_len(), 1, "one IMPORT3D feature, as before");
        assert!(
            engine.history_request_json().contains("stepText"),
            "the flat lane stores the STEP text, byte-for-byte as before"
        );
        assert!(!engine.history_has_assembly(), "no components");
        assert!(engine.parts_library_names().is_empty(), "no library entries");
        assert_eq!(dialog.status, "imported part.step");
        assert!(stash_is_empty(&mut engine), "a structureless probe stashes nothing");
    }

    /// The whole §3.9 flow on the classic fixture: the probe arms the choice
    /// with the file's real counts, the modal opens in its own mode, and "Import
    /// as assembly" consumes THAT parse — keeping the TREE, which is the default
    /// now that A8 has made the box mean something. `as1-ug-214` is
    /// `as1-ug → { plate, lb_assem ×2, rod_assem }`, so the document gets 3
    /// entries and 4 components and the depth lives inside them. The §3.9 line
    /// goes to both the status line and the toast lane, and the import switches
    /// to the Assembly workbench (whose panels the structure needs).
    #[test]
    fn importing_as_an_assembly_reports_the_counts_and_enters_the_workbench() {
        let mut engine = EngineState::new();
        assert_eq!(engine.settings.workbench, "modeling", "fresh session default");
        let mut dialog = armed(&mut engine);

        dialog.close_after_import();
        assert!(dialog.open && dialog.mode == Mode::StepAssembly, "the modal opens");
        assert!(
            !dialog.pending_step_import.as_ref().unwrap().flatten,
            "the §3.9 box defaults OFF — an import keeps the tree"
        );

        let store = crate::store::MemModelStore::new();
        dialog.step_assembly_import(&mut engine, &store);

        // CHANGED: the import now WRITES its unique parts to the store as their
        // own documents (the owner's "no distinction between part kinds"), so
        // the outcome line reports that side effect rather than hiding it — a
        // 50-part import writes 50 files nobody individually asked for.
        assert_eq!(
            dialog.status,
            "imported as1-ug-214.stp \u{2014} 3 parts, 4 components; saved 8 part file(s)",
            "the §3.9 outcome line, with the report's real numbers + the writes"
        );
        // 8 = the 3 root-level entries plus the 5 distinct parts inside the two
        // sub-assembly documents. Every one is a part in its own right now.
        let saved = store.list();
        assert_eq!(saved.len(), 8, "one file per distinct part: {saved:?}");
        assert!(
            saved.iter().all(|name| name.starts_with("as1-ug-")),
            "each file carries the assembly name, so one import groups in a \
             listing without a folder convention `browser_write` cannot express: \
             {saved:?}"
        );
        // ...and every entry points at one of them, with a signature over the
        // bytes actually written — the write-through guard depends on that.
        for name in engine.parts_library_names() {
            let (key, signature) = engine.part_source(&name).expect("a library entry");
            assert!(!key.is_empty(), "'{name}' carries a real sourceKey");
            let stored = store.read(&key).unwrap_or_else(|| panic!("'{key}' written"));
            assert_eq!(
                signature,
                document_signature(&stored),
                "'{name}': entry signature and stored file describe one thing"
            );
        }
        let notices = engine.take_notices();
        assert!(
            notices.iter().any(|notice| notice == &dialog.status),
            "the outcome is toasted too — the status line is invisible once the \
             modal closes: {notices:?}"
        );
        assert_eq!(
            engine.parts_library_names().len(),
            3,
            "one library entry per unique ROOT-level product: plate, lb_assem, \
             rod_assem — the deeper parts live in THEIR documents' libraries"
        );
        assert_eq!(
            component_part_names(&engine).len(),
            4,
            "one ACOMP per root occurrence — a sub-assembly is ONE component"
        );
        assert!(engine.history_has_assembly(), "the document is an assembly now");
        assert_eq!(
            engine.settings.workbench, "assembly",
            "an imported assembly switches to the workbench its panels are gated on"
        );
        assert!(dialog.pending_step_import.is_none(), "the choice is spent");
        assert!(
            stash_is_empty(&mut engine),
            "the consume TAKES the parse — a second one is never a double insert"
        );
    }

    /// **Flatten sub-assemblies** — the §3.9 checkbox, which A8 makes real. The
    /// same click, the same parse, but every leaf occurrence lands directly in
    /// this document at its world pose: 5 entries, 18 components, and no nested
    /// library anywhere. Still a proper assembly (dedup, BOM, per-component
    /// selection) — just without the tree.
    #[test]
    fn flattening_sub_assemblies_places_every_leaf_in_this_document() {
        let mut engine = EngineState::new();
        let mut dialog = armed(&mut engine);
        dialog.pending_step_import.as_mut().unwrap().flatten = true;

        let store = crate::store::MemModelStore::new();
        dialog.step_assembly_import(&mut engine, &store);

        assert_eq!(
            dialog.status,
            "imported as1-ug-214.stp \u{2014} 5 parts, 18 components; saved 5 part file(s)",
            "flattened: the leaf counts the prompt showed, plus the writes"
        );
        // FIVE files for EIGHTEEN components: the store write is per DISTINCT
        // part, so the six-bolt classic is one bolt file, not six.
        assert_eq!(store.list().len(), 5, "one file per distinct part");
        assert_eq!(engine.parts_library_names().len(), 5);
        assert_eq!(component_part_names(&engine).len(), 18);
        let document: serde_json::Value =
            serde_json::from_str(&engine.history_request_json()).expect("document JSON");
        for (name, entry) in document["partsLibrary"].as_object().expect("library") {
            assert!(
                entry["document"]["partsLibrary"].is_null(),
                "'{name}' must be a leaf part — flattening leaves no nested library"
            );
        }
    }

    /// "Import as bodies" is today's lane, unchanged — one IMPORT3D carrying the
    /// text, no library entries, no components — and it DROPS the parse: the
    /// user chose the text, so nothing may keep every product's solids resident.
    /// The workbench is left alone (no assembly was created).
    #[test]
    fn importing_as_bodies_uses_the_flat_lane_and_drops_the_parse() {
        let mut engine = EngineState::new();
        let mut dialog = armed(&mut engine);

        dialog.step_assembly_bodies(&mut engine);

        assert_eq!(engine.history_len(), 1, "one IMPORT3D feature");
        assert!(
            engine.history_request_json().contains("stepText"),
            "the flat lane stores the STEP text"
        );
        assert!(engine.parts_library_names().is_empty(), "no library entries");
        assert!(!engine.history_has_assembly(), "no components");
        assert_eq!(engine.settings.workbench, "modeling", "no assembly, no switch");
        assert_eq!(dialog.status, "imported as1-ug-214.stp");
        assert!(dialog.pending_step_import.is_none(), "the choice is spent");
        assert!(stash_is_empty(&mut engine), "the parse is dropped, not left resident");
    }

    /// Cancel imports NOTHING and drops the parse — the stash and its resident
    /// solids must not outlive the prompt that was going to consume them. Esc /
    /// click-outside route here too (`show_step_assembly` folds `should_close`
    /// into this same call).
    #[test]
    fn cancel_imports_nothing_and_discards_the_parse() {
        let mut engine = EngineState::new();
        let mut dialog = armed(&mut engine);

        dialog.step_assembly_cancel(&mut engine);

        assert_eq!(engine.history_len(), 0, "cancel imports nothing");
        assert!(engine.parts_library_names().is_empty(), "no library entries");
        assert_eq!(engine.settings.workbench, "modeling", "no switch");
        assert!(dialog.status.contains("cancelled"), "status: {}", dialog.status);
        assert!(dialog.pending_step_import.is_none());
        assert!(stash_is_empty(&mut engine), "Cancel drops the parse");
    }

    /// The armed choice never outlives the file it describes. A second STEP
    /// upload replaces it (the probe replaces the engine stash on EVERY outcome,
    /// so a structureless second file must not leave the first one's prompt
    /// standing), and any other delivery supersedes it outright.
    #[test]
    fn a_new_upload_supersedes_an_armed_choice() {
        let mut source = EngineState::new();
        source.set_history_json(BOX_SEED).unwrap();
        let part = source.export_step_text().unwrap();

        // A structureless STEP after an armed assembly: the prompt goes with it.
        let mut engine = EngineState::new();
        let mut dialog = armed(&mut engine);
        dialog.import_step(&mut engine, "part.step", &part);
        assert!(
            dialog.pending_step_import.is_none(),
            "the prompt cannot outlive the parse the new probe dropped"
        );
        assert_eq!(engine.history_len(), 1, "the part file imported flat");

        // Any other delivery (IGES / STL / a model document) supersedes it too.
        let mut other = EngineState::new();
        let mut dialog = armed(&mut other);
        dialog.cancel_pending_step_import(&mut other);
        assert!(dialog.pending_step_import.is_none());
        assert!(stash_is_empty(&mut other), "the superseded parse is discarded");
        dialog.close_after_import();
        assert!(!dialog.open, "nothing armed, so the import routing closes the modal");
    }

    /// The workbench switch is a no-op where the assembly panels ALREADY show:
    /// "All" claims nothing away, so an "All" user must not be yanked into
    /// Assembly by an import.
    #[test]
    fn importing_an_assembly_leaves_the_all_workbench_alone() {
        let mut engine = EngineState::new();
        engine.apply_settings_json(r#"{"workbench":"all"}"#).unwrap();
        let mut dialog = armed(&mut engine);

        dialog.step_assembly_import(&mut engine, &crate::store::MemModelStore::new());

        assert_eq!(
            engine.settings.workbench, "all",
            "'All' already shows the assembly panels — never switch away from it"
        );
        assert_eq!(component_part_names(&engine).len(), 4, "the import still ran");
    }

    /// Every ACOMP feature's `partName`, in history order — the components an
    /// import actually appended.
    fn component_part_names(state: &EngineState) -> Vec<String> {
        serde_json::from_str::<serde_json::Value>(&state.history_request_json())
            .expect("history JSON")["features"]
            .as_array()
            .expect("features array")
            .iter()
            .filter(|feature| feature["type"] == "ACOMP")
            .map(|feature| feature["inputParams"]["partName"].as_str().unwrap().to_string())
            .collect()
    }

    /// The outcome line reports every qualifier the report carries, and ONLY the
    /// ones that happened: a clean import reads clean, a baked mirror says so,
    /// skipped products are counted, and a flat fallback is never silent.
    #[test]
    fn the_outcome_line_reports_exactly_what_happened() {
        let clean = StepAssemblyReport {
            parts: 5,
            instances: 18,
            ..StepAssemblyReport::default()
        };
        assert_eq!(
            assembly_import_message("as1.stp", &clean),
            "imported as1.stp \u{2014} 5 parts, 18 components"
        );
        assert_eq!(
            assembly_import_message(
                "one.stp",
                &StepAssemblyReport { parts: 1, instances: 1, ..clean.clone() }
            ),
            "imported one.stp \u{2014} 1 part, 1 component",
            "singulars, so the sentence is one a user believes"
        );

        let messy = StepAssemblyReport {
            baked_nonrigid: 2,
            failed_products: 1,
            first_error: Some("body 7: unsupported surface".into()),
            ..clean.clone()
        };
        let line = assembly_import_message("mixed.stp", &messy);
        assert!(line.contains("(2 mirrored instances baked)"), "{line}");
        assert!(line.contains("1 product could not be built"), "{line}");
        assert!(line.contains("unsupported surface"), "{line}");

        let fell_back = StepAssemblyReport { flat_fallback: true, ..clean };
        assert!(
            assembly_import_message("flat.stp", &fell_back).contains("the bodies came in flat"),
            "a user who asked for an assembly and got bodies must be told"
        );
    }

    /// Unnamed products are stemmed from the file's BASE name without its STEP
    /// extension (`bracket-assy-part-7`, never `bracket-assy.step-part-7`).
    #[test]
    fn the_document_name_drops_the_step_extension() {
        assert_eq!(step_document_name("bracket-assy.step"), "bracket-assy");
        assert_eq!(step_document_name("BRACKET.STP"), "BRACKET");
        assert_eq!(step_document_name("/tmp/a/b/as1-ug-214.stp"), "as1-ug-214");
        assert_eq!(step_document_name("no-extension"), "no-extension");
        assert_eq!(step_document_name(".step"), ".step", "a bare extension is the name");
    }
}