BREP_render 0.11.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
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
//! The history-run seam — the async RUN machine behind a trait, mirroring the
//! platform-seam shape of `brep-app/src/store.rs`'s `ModelStore` (a trait with
//! impls behind it, async surfaced via a poll idiom).
//!
//! A history run is split SUBMIT → POLL/APPLY: [`HistoryRunner::submit_run`]
//! kicks off a run tagged with a monotonic generation, and the completed
//! [`RunReply`] is drained later via [`HistoryRunner::poll_run`]. The runner OWNS
//! the [`SceneRunner`](crate::pipeline::SceneRunner) — so a future thread/worker
//! impl owns the resident registry that `execute_history` populates — and holds
//! the delta baseline across reruns.
//!
//! This slice ships the DEFAULT [`InlineRunner`]: it runs on `submit_run` and
//! stashes the reply for an immediate `poll_run`, so the run stays synchronous
//! and byte-identical to the pre-seam in-process run. A native-thread impl (M2b)
//! and a wasm-worker impl (M3) slot in behind the SAME trait — `submit_run`
//! defers the work and `poll_run` surfaces it a frame (or many) later, so the
//! `EngineState::pump` caller never changes.

/// A completed history run, tagged with the [`generation`](Self::generation) it
/// was submitted under so the applier can drop stale replies (a newer run that
/// finished first). The [`output`](Self::output) is the [`SceneRunner`] delta to
/// apply to the display scene.
///
/// [`SceneRunner`]: crate::pipeline::SceneRunner
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RunReply {
    /// The monotonic generation this run was submitted under.
    pub generation: u64,
    /// The delta snapshot + report the run produced.
    pub output: crate::pipeline::RunOutput,
}

/// A feature about to EXECUTE inside an in-flight run (cached replays are
/// instant and are not reported): which one, of how many, under which
/// generation. Posted by the runner before the kernel starts the feature, so
/// the UI can name what it is waiting on — and, after a cancel, what it was
/// waiting on.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RunProgress {
    /// The generation of the run this belongs to (see [`RunReply::generation`]).
    pub generation: u64,
    /// Zero-based position of the feature in the request.
    pub index: usize,
    /// The request's feature count.
    pub total: usize,
    pub feature_id: String,
    pub feature_type: String,
}

/// A STEP text to PROBE for product structure on the runner — the parse that
/// `brep_kernel::read_step_assembly` performs, which builds every product's
/// bodies and takes seconds on a real assembly (8.3 s natively for a 5 MB,
/// 140-product file), so it must not run on the browser's main thread.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StepProbeRequest {
    pub id: u64,
    pub text: String,
}

/// The probe's answer: the parsed assembly (`Some`), no structure (`None`),
/// or a parse failure. The assembly crosses back to the main side whole — its
/// JSON is large (74 MB for the file above) but the trip costs a third of a
/// second against the seconds the parse took.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StepProbeReply {
    pub id: u64,
    pub result: Result<Option<brep_kernel::StepAssembly>, String>,
}

/// Which exact measurement a [`MeasureQuery`] wants, mirroring the object-info
/// kinds ([`crate::metadata`]): a whole solid, one named face, or one named edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MeasureKind {
    Solid,
    Face,
    Edge,
    /// A whole-solid CHECK for `model_inspect`: the kernel's topology
    /// validation issues and the exact volume, read from the runner's warm
    /// registry instead of a main-thread re-execution of the history.
    Inspect,
}

/// A per-object MEASUREMENT request routed to the runner (which owns the warm
/// registry). The runner resolves `owner` to its resident handle and measures by
/// [`kind`](Self::kind); the reply is the object-info JSON fragment MINUS the
/// main-injected `name`/`creatingFeature` fields. Tagged with a monotonic
/// [`id`](Self::id) so the main side can pair the reply with its pending request.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MeasureQuery {
    /// Monotonic request id (main pairs the reply back by it).
    pub id: u64,
    /// The measurement to run.
    pub kind: MeasureKind,
    /// The OWNING solid name (a solid is its own owner; a face/edge names its solid).
    pub owner: String,
    /// The face/edge NAME to measure (ignored for a whole-solid query).
    pub entity: String,
    /// The density (mass per mm³) to scale a solid's weight (ignored for face/edge).
    pub density: f64,
}

/// A completed [`MeasureQuery`]: the object-info measurement fields as a JSON
/// fragment (WITHOUT `name`/`creatingFeature`, which the main thread injects from
/// its eager provenance), tagged with the request [`id`](Self::id).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MeasureReply {
    /// The request id this answers.
    pub id: u64,
    /// The measurement JSON fragment (see `measure_json`).
    pub result: String,
}

/// A request for the B-rep TOPOLOGY of resident solids, by the handle each
/// display was tessellated from. The drawing sheet's exact hidden-line pass
/// reads faces and edges, and the resident registry that holds them is
/// thread-local to the runner, so the main side asks for exactly the solids a
/// placement draws and does not already hold. Nothing else ever asks, so a
/// document with no sheet never pays for the topology crossing.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TopologyRequest {
    /// Monotonic request id (main pairs the reply back by it).
    pub id: u64,
    /// `(solid name, resident handle)` per solid wanted.
    pub solids: Vec<(String, u32)>,
}

/// A completed [`TopologyRequest`]: a clone of every requested solid the
/// registry still holds, `(name, handle, solid)`. A handle the registry no
/// longer holds (a later run freed it) is left out.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TopologyReply {
    /// The request id this answers.
    pub id: u64,
    pub solids: Vec<(String, u32, brep_kernel::BrepSolid)>,
}

/// Answer a topology request against the resident registry of the thread this
/// runs on. Shared by every runner.
fn topology_reply(request: TopologyRequest) -> TopologyReply {
    let solids = request
        .solids
        .into_iter()
        .filter_map(|(name, handle)| {
            brep_kernel::registered_solid_clone(handle)
                .ok()
                .map(|solid| (name, handle, solid))
        })
        .collect();
    TopologyReply { id: request.id, solids }
}

/// A drawing sheet's exact hidden-line pass for ONE placement, handed to the
/// runner so the UI thread never runs it (see
/// [`crate::sheets::project::LinesJob`]). The job names the runner's own
/// resident solids by handle and content fingerprint, so nothing crosses the
/// seam but the question and the lines.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SheetLinesRequest {
    /// Monotonic request id (main pairs the reply back by it).
    pub id: u64,
    pub job: crate::sheets::project::LinesJob,
}

/// A completed [`SheetLinesRequest`]: the placement's lines relative to its
/// position, or why the runner could not draw them (a handle its registry no
/// longer holds, or holds different geometry under).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SheetLinesReply {
    /// The request id this answers.
    pub id: u64,
    pub key: String,
    pub lines: Result<crate::sheets::project::ExactLines, String>,
}

/// Answer a sheet-lines request against the resident registry of the thread
/// this runs on. Shared by every runner.
fn sheet_lines_reply(request: SheetLinesRequest) -> SheetLinesReply {
    SheetLinesReply {
        id: request.id,
        lines: crate::sheets::project::run_lines_job(&request.job),
        key: request.job.key,
    }
}

/// ONE CAM operation's generation, off the UI thread (the CAM workbench's
/// Generate). The job carries everything the generator reads as plain data:
/// the operation, its setup and the document's tools (the shared model, by
/// value), and the resident solids it machines by `(name, handle)`, which
/// the runner clones out of its registry and tessellates through the CAM
/// kernel adapter. The main side submits ONE operation per job and the next
/// when its reply lands, so a cancel between operations is immediate on
/// every platform; inside a job the native thread's cancel flag ends it at
/// the generator's next work chunk, and the browser worker — which cannot
/// read a message while it is inside a job — finishes the operation, whose
/// reply the main side then drops as cancelled. A document `Reset` drops
/// nothing here: the job holds no parked state across commands.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CamJob {
    /// Monotonic job id (main pairs the reply and the progress back by it).
    pub id: u64,
    pub operation: brep_cam::model::Operation,
    pub setup: brep_cam::model::Setup,
    pub tools: Vec<brep_cam::model::Tool>,
    /// The bodies the setup machines or protects: `(solid name, resident handle)`.
    pub solids: Vec<(String, u32)>,
    /// The chordal tolerance the bodies are tessellated at, in model units.
    pub chord_tolerance: f64,
    /// Work units per progress / cancel check (the generator's chunk).
    pub budget_chunk: u64,
    /// The sketch curves the operation's chains name, `(sketch id, geometry
    /// id, curve)` in model space, from the last history run (the runner's
    /// registry holds solids, not sketches).
    #[serde(default)]
    pub chain_curves: Vec<(String, String, brep_kernel::NurbsCurve)>,
    /// The sketch profiles the operation's chains name, `(sketch id, profile)`.
    #[serde(default)]
    pub chain_profiles: Vec<(String, brep_kernel::SketchProfile)>,
    /// The setup's machine, resolved (its id is `setup.machine`): the
    /// generator's kinematics context for rotary-capable strategies.
    #[serde(default)]
    pub machine: Option<brep_cam::model::Machine>,
    /// Exact automatically programmed geometry and associative feature identity.
    #[serde(default)]
    pub autoprogram: Option<brep_cam::autoprogram::binding::Binding>,
    /// The setup's operations BEFORE this one, in program order, each with
    /// its current toolpath (`None`: not generated, failed or stale): the
    /// runner replays them into the stock this operation starts from (lane C7).
    #[serde(default)]
    pub earlier: Vec<(brep_cam::model::Operation, Option<brep_cam::model::Toolpath>)>,
    /// The setups this one continues from (`Stock::FromRest`), oldest first.
    #[serde(default)]
    pub previous_setups: Vec<brep_cam::SetupHistory>,
    /// A multi-axis finish's designated three-axis source, generated and
    /// current (lane C17): the generator tilts this path.
    #[serde(default)]
    pub source: Option<brep_cam::program::OperationInput>,
    /// The designated source's definition when it has no current result: the
    /// worker generates it on this job's bodies first.
    #[serde(default)]
    pub source_operation: Option<brep_cam::model::Operation>,
}

/// A completed [`CamJob`]: the toolpath, or why the operation could not be
/// generated (the generator's own words), and how much work it took.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CamReply {
    /// Certified setup-Z meridian, carried with the generated result for axial replay.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turning_profile: Option<brep_cam::turning::profile::TurningProfile>,
    /// The stock the operation's setup starts from, as this job resolved it
    /// (the simulation loads it; absent when the job built no pre-operation stock).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub setup_start: Option<brep_cam::SetupStart>,
    pub id: u64,
    pub operation: String,
    pub toolpath: Result<brep_cam::model::Toolpath, String>,
    pub work_units: u64,
    /// Whether the job ended on the cancel flag rather than on its own.
    pub cancelled: bool,
}

/// A generation's progress, posted from inside the job at its stage and
/// chunk boundaries.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CamProgress {
    pub id: u64,
    pub operation: String,
    pub phase: String,
    pub message: String,
    pub current: u64,
    pub total: u64,
}

/// A CAM SIMULATION request (lane C17b). The runner keeps ONE simulation
/// session resident (its stock and checkpoints live runner-side; a thread
/// local, so the native thread and the wasm worker hold it the same way);
/// the main side loads it once and then asks it to advance in bounded
/// chunks, so a cancel between chunks is immediate on every platform and a
/// chunk stops between two motions on the native thread.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum CamSimRequest {
    /// Make `stock` the session's stock over `timeline`, each range cut by its cutter.
    Load {
        timeline: brep_cam::multiaxis::sim::Timeline,
        stock: brep_cam::multiaxis::sim::StockModel,
        ranges: Vec<brep_cam::multiaxis::sim::RangeCutter>,
        options: brep_cam::multiaxis::sim::DriverOptions,
        /// The machine whose chain applies rotary positioning (C7's
        /// `*_on_machine`); none refuses any nonzero rotary word.
        #[serde(default)]
        machine: Option<brep_cam::model::Machine>,
    },
    /// Advance (or rewind and replay) toward `target` applied motions, at
    /// most `budget` motions. `stock: true` returns the stock whenever its
    /// version differs from `known_version` (the one the caller holds), so
    /// a chunk whose reply the caller dropped is still made good.
    Advance { target: usize, budget: usize, stock: bool, known_version: u64 },
    /// Forget the session.
    Drop,
}

/// One simulation command, paired back by `(session, seq)`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CamSimJob {
    pub session: u64,
    pub seq: u64,
    pub request: CamSimRequest,
}

/// The session's state after a [`CamSimJob`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CamSimReply {
    pub session: u64,
    pub seq: u64,
    pub applied: usize,
    pub version: u64,
    pub removed_volume: f64,
    pub stock_volume: f64,
    pub unsupported: Vec<usize>,
    pub warnings: Vec<(usize, brep_cam::model::Diagnostic)>,
    /// The stock, when asked and it changed since the job started.
    pub stock: Option<brep_cam::multiaxis::sim::StockModel>,
    /// The target was reached (`false`: the budget ran out or it stopped).
    pub reached: bool,
    /// The chunk stopped on the cancel flag (between two motions).
    pub cancelled: bool,
    pub error: Option<String>,
}

/// A simulation chunk's progress, posted between motions.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CamSimProgress {
    pub session: u64,
    pub seq: u64,
    pub applied: usize,
    pub target: usize,
}

/// The runner-side simulation session.
struct CamSimSession {
    session: u64,
    timeline: brep_cam::multiaxis::sim::Timeline,
    ranges: Vec<brep_cam::multiaxis::sim::RangeCutter>,
    driver: brep_cam::multiaxis::sim::SimDriver,
}

thread_local! {
    static CAM_SIM: std::cell::RefCell<Option<CamSimSession>> = const { std::cell::RefCell::new(None) };
}

/// Forget the resident simulation (a document switch).
fn cam_sim_clear() {
    CAM_SIM.with(|c| *c.borrow_mut() = None);
}

thread_local! {
    /// Pre-operation stock states of this document session (lane C7): a
    /// regenerated operation replays only from the longest unchanged prefix.
    static PRE_OP_STOCK: std::cell::RefCell<brep_cam::PreOpStockCache> = std::cell::RefCell::new(brep_cam::PreOpStockCache::new(16));
}

/// Forget the pre-operation stock states (a document switch).
fn pre_op_stock_clear() {
    PRE_OP_STOCK.with(|c| c.borrow_mut().clear());
}

fn cam_sim_reply(job: CamSimJob, post: &mut dyn FnMut(Reply) -> bool) -> CamSimReply {
    let (session, seq) = (job.session, job.seq);
    let empty = |error: Option<String>| CamSimReply {
        session,
        seq,
        applied: 0,
        version: 0,
        removed_volume: 0.0,
        stock_volume: 0.0,
        unsupported: Vec::new(),
        warnings: Vec::new(),
        stock: None,
        reached: false,
        cancelled: false,
        error,
    };
    match job.request {
        CamSimRequest::Drop => {
            cam_sim_clear();
            empty(None)
        }
        CamSimRequest::Load { timeline, stock, ranges, options, machine } => match brep_cam::multiaxis::sim::SimDriver::new(stock, options) {
            Ok(driver) => {
                let driver = driver.with_chain(brep_cam::multiaxis::sim::sim_chain(machine.as_ref()));
                let reply = CamSimReply {
                    applied: driver.applied,
                    version: driver.version,
                    stock_volume: driver.stock.volume(),
                    reached: true,
                    ..empty(None)
                };
                CAM_SIM.with(|c| *c.borrow_mut() = Some(CamSimSession { session, timeline, ranges, driver }));
                reply
            }
            Err(e) => empty(Some(e.to_string())),
        },
        CamSimRequest::Advance { target, budget, stock, known_version } => CAM_SIM.with(|c| {
            let mut guard = c.borrow_mut();
            let Some(sim) = guard.as_mut().filter(|s| s.session == session) else {
                return empty(Some("no simulation session is loaded on the runner".into()));
            };
            let mut cancelled = false;
            let tolerance = brep_cam::Tolerance::default();
            let outcome = sim.driver.advance_ranges(&sim.timeline, &sim.ranges, target, budget, &tolerance, &mut |applied| {
                let keep = post(Reply::CamSimProgress(CamSimProgress { session, seq, applied, target }));
                if !keep {
                    cancelled = true;
                }
                keep
            });
            let d = &sim.driver;
            let (reached, error) = match outcome {
                Ok(o) => (o == brep_cam::multiaxis::sim::AdvanceOutcome::Reached, None),
                Err(e) => (false, Some(e.to_string())),
            };
            CamSimReply {
                session,
                seq,
                applied: d.applied,
                version: d.version,
                removed_volume: d.removed_volume,
                stock_volume: d.stock.volume(),
                unsupported: d.unsupported.clone(),
                warnings: d.warnings.clone(),
                stock: (stock && d.version != known_version).then(|| d.stock.clone()),
                reached,
                cancelled,
                error,
            }
        }),
    }
}

/// A progress sink that posts through the driver's reply channel and turns
/// a driver that says "stop" into the generator's cancel.
struct CamSink<'a> {
    id: u64,
    operation: String,
    token: brep_cam::CancelToken,
    post: &'a mut dyn FnMut(Reply) -> bool,
}

impl brep_cam::ProgressSink for CamSink<'_> {
    fn progress(&mut self, progress: &brep_cam::Progress) {
        if std::env::var_os("BREP_CAM_DEBUG").is_some() {
            eprintln!("cam job {} progress: {} {}/{}", self.operation, progress.phase, progress.current, progress.total);
        }
        let keep_going = (self.post)(Reply::CamProgress(CamProgress {
            id: self.id,
            operation: self.operation.clone(),
            phase: progress.phase.clone(),
            message: progress.message.clone(),
            current: progress.current,
            total: progress.total,
        }));
        if !keep_going {
            if std::env::var_os("BREP_CAM_DEBUG").is_some() {
                eprintln!("cam job {}: the driver said stop; cancelling", self.operation);
            }
            self.token.cancel();
        }
    }
}

/// The most triangles a CAM job's part mesh may have (the triangle index and
/// the drop-cutter queries scale with it).
pub const CAM_TRIANGLE_BUDGET: usize = 4_000_000;

/// Run one CAM job against the resident registry of this thread.
fn cam_generate_reply(job: CamJob, post: &mut dyn FnMut(Reply) -> bool) -> CamReply {
    use brep_cam::kernel_adapter::{machine_snapshot, revolved_faces, BodyInput};
    use brep_cam::{Runner, Tolerance, TreeIndex, TreeOptions, WorkBudget};
    let operation = job.operation.id.as_str().to_string();
    let token = brep_cam::CancelToken::new();
    let mut sink = CamSink { id: job.id, operation: operation.clone(), token: token.clone(), post };
    let mut certified_turning_profile = None;
    let mut setup_start = None;
    let mut outcome = || -> Result<(brep_cam::model::Toolpath, u64), String> {
        // The resident bodies, cloned out of the registry by handle.
        let mut bodies: Vec<(String, brep_kernel::BrepSolid)> = Vec::new();
        for (name, handle) in &job.solids {
            let solid = brep_kernel::registered_solid_clone(*handle)
                .map_err(|e| format!("body `{name}` is not resident on the runner ({e}); run the history again"))?;
            bodies.push((name.clone(), solid));
        }
        let diagonal = bodies
            .iter()
            .filter_map(|(_, s)| brep_cam::kernel_adapter::body_bounds(s, job.chord_tolerance).ok())
            .fold(brep_cam::model::Bounds3::empty(), |acc, b| acc.union(&b))
            .diagonal();
        let tolerance = if diagonal.is_finite() && diagonal > 0.0 { Tolerance::scaled_for_diagonal(diagonal) } else { Tolerance::default() };
        // The snapshot holds the SETUP's bodies and the operation's own: an
        // operation's target or protected body outside the setup's list is
        // still machined or avoided, so it joins the snapshot here.
        let mut snapshot_setup = job.setup.clone();
        for name in &job.operation.targets.target_solids {
            if !snapshot_setup.targets.iter().any(|t| &t.solid == name) {
                snapshot_setup.targets.push(brep_cam::model::TargetRef { solid: name.clone(), face: None });
            }
        }
        for name in &job.operation.targets.protected_solids {
            let listed = snapshot_setup.targets.iter().chain(snapshot_setup.protected.iter()).any(|t| &t.solid == name);
            if !listed {
                snapshot_setup.protected.push(brep_cam::model::TargetRef { solid: name.clone(), face: None });
            }
        }
        let (mesh, unresolved) = machine_snapshot(&snapshot_setup, job.chord_tolerance, tolerance, |name| bodies.iter().find(|(n, _)| n == name).map(|(_, s)| s))
            .map_err(|e| format!("{e}"))?;
        if !unresolved.is_empty() {
            return Err(format!("the setup names bodies the model does not have: {}", unresolved.join(", ")));
        }
        if std::env::var_os("BREP_CAM_DEBUG").is_some() {
            eprintln!("cam job {}: {} bodies, snapshot {} faces / {} triangles, bounds {:?}", operation, bodies.len(), mesh.faces.len(), mesh.triangles.len(), mesh.bounds);
        }
        // The mesh is tessellated at the operation's own tolerance (a quarter
        // of it); a part that needs more triangles than the generators can
        // carry is refused by name, never coarsened behind the user's back.
        if mesh.triangles.len() > CAM_TRIANGLE_BUDGET {
            return Err(format!(
                "the part mesh needs {} triangles at a chord of {}, over the budget of {CAM_TRIANGLE_BUDGET}; raise the operation's tolerance or machine fewer bodies at once",
                mesh.triangles.len(),
                job.chord_tolerance
            ));
        }
        let index = TreeIndex::build(&mesh, TreeOptions::default());
        let mut runner = Runner::new(token.clone(), &mut sink, WorkBudget::new(job.budget_chunk.max(1))).with_operation(operation.clone());
        // Drilling reads the recognised holes of the target bodies.
        let holes = if matches!(job.operation.strategy, brep_cam::model::Strategy::Drill(_)) {
            let mut carriers = Vec::new();
            for (name, solid) in &bodies {
                if job.setup.targets.iter().any(|t| t.solid == *name) || job.operation.targets.target_solids.contains(name) {
                    let body = BodyInput { name, solid, protected_only: false };
                    carriers.extend(revolved_faces(&body, &job.setup));
                }
            }
            brep_cam::holes::recognize(&carriers, &mesh, tolerance, &mut runner).map_err(|e| e.to_string())?.holes
        } else {
            Vec::new()
        };
        // Frozen geometry is valid only for the exact bodies it was planned
        // against. A body edit re-recognises by face identity and XY dimensions,
        // preserving depth associativity without choosing a different feature.
        let mut effective_operation = job.operation.clone();
        let mut automatic_geometry = None;
        let mut rebound = false;
        if let Some(binding) = &job.autoprogram {
            let tool = job.tools.iter().find(|t| t.id == job.operation.tool).ok_or("automatic programming tool is missing")?;
            binding.validate_inputs(&job.operation, &job.setup, tool)?;
            let fingerprints: std::collections::BTreeMap<_, _> = bodies.iter().map(|(name, solid)| (name.clone(), crate::scene::brep_fingerprint(solid))).collect();
            if fingerprints == binding.body_fingerprints {
                automatic_geometry = Some(binding.geometry.clone());
            } else {
                let recognized = brep_cam::autoprogram::binding::recognize_bodies(&bodies, &job.setup, &mesh, job.chord_tolerance, tolerance, &mut runner).map_err(|e| e.to_string())?;
                let model_bounds = bodies.iter().filter(|(name, _)| job.setup.targets.iter().any(|t| &t.solid == name))
                    .filter_map(|(_, s)| brep_cam::kernel_adapter::body_bounds(s, job.chord_tolerance).ok())
                    .fold(brep_cam::model::Bounds3::empty(), |a, b| a.union(&b));
                let stock_bounds = match &job.setup.stock {
                    brep_cam::model::Stock::FromSolid { solid } => bodies.iter().find(|(name, _)| name == solid).and_then(|(_, body)| brep_cam::kernel_adapter::body_bounds(body, job.chord_tolerance).ok()),
                    _ => job.setup.stock.model_bounds(&model_bounds),
                };
                let stock_top = stock_bounds.map(|b| job.setup.model_to_machine.apply_bounds(&b).max.z);
                let (op, geometry) = binding.rebind_with_mesh(&recognized, &mesh, &job.operation, &job.setup, &job.tools, job.machine.as_ref(), stock_top, tolerance)?;
                effective_operation = op;
                automatic_geometry = Some(geometry);
                rebound = true;
            }
        }
        let resolved_planar = match &automatic_geometry { Some(brep_cam::autoprogram::OperationGeometry::Planar(p)) => Some((&effective_operation.id, p)), _ => None };
        let holes = match &automatic_geometry { Some(brep_cam::autoprogram::OperationGeometry::Holes(h)) => h.as_slice(), _ => holes.as_slice() };
        // Lane C7: the stock as it stands before this operation (the setup's
        // earlier operations replayed; a FromRest setup carried from the one it
        // continues from). Unavailable: a named warning on the operation, and the
        // linkers keep above the conservative material top. Never the raw stock.
        let mut pre_op_warning = None;
        // Automatic axial live contouring uses conservative planar links and
        // does not consume the milling stock cache. Replaying a preceding
        // turning operation into that cache is both unused and inappropriate.
        let live_contour = matches!(job.operation.strategy, brep_cam::Strategy::Contour2D(_) | brep_cam::Strategy::Trace(_))
            && job.operation.live_tool.unwrap_or(true)
            && job.machine.as_ref().is_some_and(|m| matches!(m.kind, brep_cam::MachineKind::MillTurn { .. }));
        let pre_op = if !live_contour && brep_cam::uses_pre_op_stock(&job.operation.strategy, job.machine.as_ref()) {
            let fallback = job.operation.targets.target_solids.clone();
            let request = brep_cam::JobStock {
                setup: &job.setup,
                machine: job.machine.as_ref(),
                tools: &job.tools,
                mesh: &mesh,
                fallback_targets: &fallback,
                earlier: &job.earlier,
                previous: &job.previous_setups,
                tolerance,
            };
            match PRE_OP_STOCK.with(|c| brep_cam::job_stock(&mut c.borrow_mut(), &request, &mut runner)) {
                Ok(result) => Some(result),
                Err(brep_cam::PreOpStockError::Cancelled) => return Err("cancelled".to_string()),
                Err(error) => {
                    pre_op_warning = Some(brep_cam::unavailable_warning(&error));
                    None
                }
            }
        } else {
            None
        };
        let input = brep_cam::dispatch::GenerateInput {
            operation: &effective_operation,
            setup: &job.setup,
            tools: &job.tools,
            mesh: &mesh,
            index: Some(&index),
            tolerance,
            holes,
        };
        // Picked chains resolve by identity against the bodies, sketch curves
        // and profiles the job carries (C20's KernelChainGeometry).
        let solid_refs: Vec<(&str, &brep_kernel::BrepSolid)> = bodies.iter().map(|(n, s)| (n.as_str(), s)).collect();
        let curve_refs: Vec<(&str, &str, &brep_kernel::NurbsCurve)> = job.chain_curves.iter().map(|(s, g, c)| (s.as_str(), g.as_str(), c)).collect();
        let profile_refs: Vec<(&str, &brep_kernel::SketchProfile)> = job.chain_profiles.iter().map(|(s, p)| (s.as_str(), p)).collect();
        let chain_geometry = brep_cam::dispatch::chains::KernelChainGeometry { solids: &solid_refs, curves: &curve_refs, profiles: &profile_refs };
        let is_turning = matches!(job.operation.strategy, brep_cam::Strategy::TurnFace(_) | brep_cam::Strategy::TurnProfile(_));
        let mut turning_carriers = Vec::new();
        let turning_tool = if is_turning {
            let tool = job.tools.iter().find(|t| t.id == job.operation.tool).ok_or("turning tool is missing")?;
            if tool.turning_geometry.is_none() { return Err(format!("tool {} has no insert geometry", tool.id)); }
            if job.setup.turning_stick_out.is_none() { return Err("setup has no stick-out".into()); }
            let targets: std::collections::BTreeSet<_> = job.setup.targets.iter().map(|t| t.solid.as_str()).collect();
            if targets.len() != 1 || job.operation.targets.target_solids.iter().any(|n| !targets.contains(n.as_str())) {
                return Err("turning requires one exact setup solid and matching operation targets".into());
            }
            let name = *targets.iter().next().unwrap();
            let solid = bodies.iter().find(|(n, _)| n == name).map(|(_, s)| s).ok_or("turning setup solid is missing")?;
            if !job.machine.as_ref().is_some_and(|m| matches!(m.kind, brep_cam::MachineKind::Lathe | brep_cam::MachineKind::MillTurn { .. })) {
                return Err("turning envelope requires a defined lathe spindle axis".into());
            }
            certified_turning_profile = Some(match brep_cam::kernel_adapter::turning_faces(&BodyInput { name, solid, protected_only: false }, &job.setup, tolerance) {
                Ok(carriers) => {
                    turning_carriers = carriers;
                    brep_cam::turning::profile::extract(&turning_carriers, &mesh, job.operation.tolerance * 0.125, &mut runner)
                }
                Err(_) => brep_cam::turning::envelope::extract(&mesh, job.chord_tolerance, &mut runner),
            }.map_err(|e| e.to_string())?);
            Some(tool)
        } else { None };
        let turning = turning_tool.map(|tool| brep_cam::dispatch::TurningInput {
            tool_id: &tool.id, tool_geometry: tool.turning_geometry.as_ref().unwrap(),
            carriers: &turning_carriers, profile: certified_turning_profile.as_ref(), contour: None,
            stick_out: job.setup.turning_stick_out.unwrap(), groove_center_z: None, thread_radius: None,
        });
        let context = brep_cam::dispatch::GenerateContext {
            turning: turning.as_ref(),
            chain_geometry: Some(&chain_geometry),
            machine: job.machine.as_ref(),
            resolved_planar,
            rest_stock: pre_op.as_ref().map(|r| &r.stock.grid),
            pre_op_stock: pre_op.as_ref().map(|r| &r.stock.envelope),
            source: job.source.as_ref(),
            source_operation: job.source_operation.as_ref(),
            ..Default::default()
        };
        let mut path = brep_cam::dispatch::generate_with_context(&input, &context, &mut runner).map_err(|e| e.to_string())?;
        if rebound { path.report.warn(brep_cam::model::Diagnostic::new("autoprogram-re-recognised", "re-recognised after model change")); }
        if let Some(warning) = pre_op_warning {
            // First, so a reader finds it at warnings[0] whenever it is there.
            path.report.warn(warning);
            path.report.warnings.rotate_right(1);
        }
        if let Some(result) = pre_op {
            path.report.approximations.extend(result.limits);
            setup_start = Some(result.start);
        }
        Ok((path, runner.budget().used()))
    };
    match outcome() {
        Ok((toolpath, work_units)) => CamReply { turning_profile: certified_turning_profile, setup_start, id: job.id, operation, toolpath: Ok(toolpath), work_units, cancelled: false },
        Err(message) => {
            let cancelled = token.is_cancelled();
            CamReply { turning_profile: None, setup_start: None, id: job.id, operation, toolpath: Err(if cancelled { "cancelled".to_string() } else { message }), work_units: 0, cancelled }
        }
    }
}

pub use brep_reconstruction::stl_conversion::{
    ConversionPolicy, StlConversionOptions, StlConversionOutput,
};

/// Mesh encoding accepted by the off-thread reconstruction channel.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub enum MeshImportFormat {
    Stl,
    Obj,
    /// 3MF (core specification): a package whose build instances are flattened
    /// into one millimetre triangle soup before this common chain runs.
    ThreeMf,
}

/// A mesh reconstruction request. The byte payload moves to the native thread
/// or is serialized to the browser worker; no parsing or fitting happens on UI.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct MeshImportRequest {
    pub id: u64,
    pub format: MeshImportFormat,
    pub bytes: Vec<u8>,
    pub options: StlConversionOptions,
}

/// Completed off-thread reconstruction. Success carries validated STEP and
/// diagnostics for a preview or an ordinary IMPORT3D history insertion.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct MeshImportReply {
    pub id: u64,
    pub result: Result<StlConversionOutput, String>,
}

/// Validate explicitly installed packages away from the UI thread.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PluginInstallRequest {
    pub id: u64,
    pub packages: serde_json::Value,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PluginInstallReply {
    pub id: u64,
    pub result: Result<brep_plugins::Registry, String>,
}
fn validate_plugins(request: PluginInstallRequest) -> PluginInstallReply {
    let result = serde_json::from_value(request.packages)
        .map_err(|e| format!("plugin packages: {e}"))
        .and_then(brep_plugins::Runtime::new)
        .map(|runtime| runtime.registry().clone());
    PluginInstallReply { id: request.id, result }
}

/// A callback request against an immutable document/selection snapshot.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PluginActionRequest {
    pub id: u64,
    pub pins: Vec<brep_plugins::PluginPin>,
    pub action: String,
    pub input: serde_json::Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script: Option<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PluginActionReply {
    pub id: u64,
    pub result: Result<brep_plugins::ActionPlan, String>,
}

/// The history-run seam: SUBMIT a run, POLL for its completed reply, RESET the
/// delta baseline, plus a QUERY channel for per-object measurements (routed to the
/// runner so the warm registry answers them, never the cold main-side one). The
/// Inline impl runs everything synchronously; a later thread/worker impl defers
/// the work and surfaces the replies through the same poll idiom.
/// Where the main thread gets the assembly session of the run it applied
/// ([`HistoryRunner::session_for_main`]).
pub enum SessionOnMain {
    /// The run executed on the main thread and its session is still the
    /// thread's: nothing to do.
    Resident,
    /// An owned copy from the runner's thread, to import.
    Copied(brep_kernel::SessionTransfer),
    /// Not available (busy, replaced, or a runner that cannot copy): replay.
    Unavailable,
}

pub trait HistoryRunner {
    /// The assembly session the run of `generation` left, for the main
    /// thread's constraint actions. Blocking, but bounded. The default cannot
    /// provide one, and the caller replays the history instead.
    fn session_for_main(&mut self, _generation: u64) -> SessionOnMain {
        SessionOnMain::Unavailable
    }
    fn submit_plugin_install(&mut self, _request: PluginInstallRequest) -> bool { false }
    fn poll_plugin_install(&mut self) -> Option<PluginInstallReply> { None }
    /// Trusted installed content, separate from saved document dependency pins.
    fn sync_plugins(&mut self, _revision: u64, _fetch: &mut dyn FnMut() -> serde_json::Value) {}
    /// False explicitly reports a runner without action support.
    fn submit_plugin_action(&mut self, _request: PluginActionRequest) -> bool { false }
    fn poll_plugin_action(&mut self) -> Option<PluginActionReply> { None }

    /// Submit a history run tagged with a monotonic generation. The runner executes
    /// it (immediately for Inline; on a background thread later) and makes the reply
    /// available via [`poll_run`](Self::poll_run).
    fn submit_run(&mut self, request: brep_kernel::HistoryRequest, generation: u64);
    /// Non-blocking: the next completed run reply, if any (drained each frame).
    fn poll_run(&mut self) -> Option<RunReply>;
    /// Submit a per-object measurement query (answered against the runner's warm
    /// registry). Inline computes it immediately; a thread impl computes it on the
    /// runner thread and surfaces it via [`poll_query`](Self::poll_query).
    fn submit_query(&mut self, query: MeasureQuery);
    /// Non-blocking: the next completed measurement reply, if any.
    fn poll_query(&mut self) -> Option<MeasureReply>;
    /// Submit RANSAC mesh reconstruction to the runner's thread/worker.
    fn submit_mesh_import(&mut self, request: MeshImportRequest);
    /// Non-blocking: the next completed mesh reconstruction, if any.
    fn poll_mesh_import(&mut self) -> Option<MeshImportReply>;
    /// Submit a STEP product-structure probe (see [`StepProbeRequest`]).
    fn submit_step_probe(&mut self, request: StepProbeRequest);
    /// Non-blocking: the next completed STEP probe, if any.
    fn poll_step_probe(&mut self) -> Option<StepProbeReply>;
    /// Submit a topology request (see [`TopologyRequest`]). The default drops
    /// it: a runner that never answers leaves a sheet on its mesh
    /// approximation, which the drawing reports.
    fn submit_topology(&mut self, _request: TopologyRequest) {}
    /// Non-blocking: the next completed topology reply, if any.
    fn poll_topology(&mut self) -> Option<TopologyReply> {
        None
    }
    /// BLOCK up to `timeout` until a topology reply is ready to poll: `true`
    /// when one is. An export that needs the exact solids waits this way on a
    /// runner with a thread of its own; the default cannot wait (a worker
    /// answers through the page's event loop, which a blocked page never
    /// turns), so the export draws the mesh approximation and the file says
    /// so.
    fn wait_topology(&mut self, _timeout: std::time::Duration) -> bool {
        false
    }
    /// Submit a sheet placement's exact pass (see [`SheetLinesRequest`]).
    /// `false` when this runner cannot run one — the engine then runs it on
    /// its own thread, as every projection did before the pass moved off it.
    fn submit_sheet_lines(&mut self, _request: SheetLinesRequest) -> bool {
        false
    }
    /// Non-blocking: the next completed sheet-lines reply, if any.
    fn poll_sheet_lines(&mut self) -> Option<SheetLinesReply> {
        None
    }
    /// Submit ONE CAM operation's generation (see [`CamJob`]); `false` when
    /// this runner cannot run it.
    fn submit_cam(&mut self, _job: CamJob) -> bool {
        false
    }
    fn poll_cam(&mut self) -> Option<CamReply> {
        None
    }
    fn poll_cam_progress(&mut self) -> Option<CamProgress> {
        None
    }
    /// Cancel the CAM job in flight at its next work chunk, where the driver
    /// can reach it (the native thread); a driver that cannot lets the job
    /// finish and the main side drops its reply.
    fn cancel_cam(&mut self) {}
    /// TEST HOLD (automation only): while `hold`, finished CAM replies are
    /// kept back from `poll_cam`, so a job stays in flight on the main side
    /// however fast it ran — the one way a script can meet it with a cancel
    /// every time. Releasing delivers what was kept, in order. A driver
    /// without the hold ignores it.
    fn hold_cam_replies(&mut self, _hold: bool) {}
    /// Submit ONE CAM simulation command (see [`CamSimJob`]); `false` when
    /// this runner cannot simulate (the caller then simulates inline).
    fn submit_cam_sim(&mut self, _job: CamSimJob) -> bool {
        false
    }
    fn poll_cam_sim(&mut self) -> Option<CamSimReply> {
        None
    }
    fn poll_cam_sim_progress(&mut self) -> Option<CamSimProgress> {
        None
    }
    /// Stop the simulation chunk in flight between two motions where the
    /// driver can reach it (the native thread); elsewhere the chunk finishes
    /// and the caller drops its reply.
    fn cancel_cam_sim(&mut self) {}
    /// Drop the delta baseline (document switch → full rebuild).
    fn reset(&mut self);

    /// Bring the runner's resident PARTS LIBRARY up to `revision`, calling
    /// `fetch` ONLY when it is not already there. Called immediately before
    /// every [`submit_run`](Self::submit_run).
    ///
    /// This is the whole point of the library channel: the library is sent
    /// when it CHANGES (insert, document load, refresh), not on every run.
    /// Cheap to call — the revision comparison is an integer, and `fetch`
    /// (which clones the store) never runs in the steady state. The default is
    /// a no-op for [`InlineRunner`], which shares the caller's kernel store.
    fn sync_parts_library(
        &mut self,
        _revision: u64,
        _fetch: &mut dyn FnMut() -> brep_kernel::PartsLibraryMap,
    ) {
    }

    /// True when the runner REFUSED a run because its resident parts library
    /// could not serve it (see [`Reply::NeedPartsLibrary`]). It has already
    /// forgotten its copy, so the next `sync_parts_library` reinstalls; the
    /// caller must re-submit the run. Never true for a runner that shares the
    /// caller's store.
    fn poll_library_request(&mut self) -> bool {
        false
    }

    /// Whether a run reply (or a refusal asking for the parts library) is
    /// waiting for [`poll_run`](Self::poll_run): a caller may skip what only a
    /// landing needs while this is false. `true` when the runner cannot tell.
    fn run_reply_waiting(&mut self) -> bool {
        true
    }

    /// Non-blocking: the MOST RECENT progress report of the in-flight run, with
    /// any older ones discarded (only the latest feature matters). `None` for
    /// a synchronous runner — Inline has finished before anyone could ask.
    fn poll_progress(&mut self) -> Option<RunProgress> {
        None
    }

    /// ABANDON the in-flight work and start over with an EMPTY resident
    /// registry. Returns `false` when there is nothing this runner can abandon
    /// (Inline: the run already completed on the caller's thread). A `true`
    /// means every handle the caller holds is now invalid, no reply is coming
    /// for anything submitted so far, and the parts library must be re-sent —
    /// the caller reconciles its generations and pending sets accordingly
    /// (`EngineState::cancel_run`). Nothing inside a feature is interruptible:
    /// the thread runner lets its old thread finish the feature it is on and
    /// stop at the next boundary; the browser worker is terminated outright.
    fn cancel(&mut self) -> bool {
        false
    }
}

/// Measure `query` against `runner`'s resident geometry and emit the object-info
/// JSON FRAGMENT — EXACTLY the fields [`crate::metadata::EngineState::object_info_json`]
/// emits for that kind EXCEPT `name` and `creatingFeature` (the main thread injects
/// those from its eager provenance, so the merged output is byte-identical to the
/// pre-seam in-process result). Shared verbatim by the Inline and thread runners so
/// both produce the identical fragment. A missing handle / kernel error yields
/// `{ "ok": false, "message": .. }` (main injects `name`).
fn measure_json(runner: &crate::pipeline::SceneRunner, query: &MeasureQuery) -> String {
    let Some(handle) = runner.handle_of(&query.owner) else {
        return serde_json::json!({
            "ok": false,
            "message": format!("solid '{}' has no resident geometry", query.owner),
        })
        .to_string();
    };
    match query.kind {
        MeasureKind::Inspect => {
            let issues: Vec<serde_json::Value> = match brep_kernel::validate_handle_native(handle) {
                Ok(issues) => issues.into_iter().map(|(severity, message)| serde_json::json!({ "severity": severity, "message": message })).collect(),
                Err(error) => vec![serde_json::json!({ "severity": "error", "message": format!("validation unavailable: {error}") })],
            };
            let (volume, volume_error) = match brep_kernel::mass_measures_handle_native(handle) {
                Ok(properties) => (Some(properties.volume), None),
                Err(error) => (None, Some(error)),
            };
            serde_json::json!({ "ok": true, "kind": "inspect", "issues": issues, "volume": volume, "volumeError": volume_error }).to_string()
        }
        MeasureKind::Solid => {
            match brep_kernel::mass_properties_handle_native(handle, query.density) {
                Ok(properties) => {
                    let edge_total =
                        brep_kernel::solid_edge_length_total_native(handle).unwrap_or(0.0);
                    serde_json::json!({
                        "ok": true,
                        "kind": "solid",
                        "volume": properties.volume,
                        "surfaceArea": properties.surface_area,
                        "edgeLengthTotal": edge_total,
                        "density": properties.density,
                        "weight": properties.mass,
                    })
                    .to_string()
                }
                Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
            }
        }
        MeasureKind::Face => match brep_kernel::face_measurements_native(handle, &query.entity) {
            Ok((area, edge_total, surface_type)) => {
                let dimensions =
                    brep_kernel::face_carrier_dimensions_native(handle, &query.entity)
                        .ok()
                        .flatten();
                // A partial revolution of a straight line is a "Surface of
                // revolution" to the kernel and a cylinder to the user.
                let surface_type = dimensions.as_ref().map_or(surface_type, |d| d.label);
                let mut fragment = serde_json::json!({
                    "ok": true,
                    "kind": "face",
                    "solid": query.owner,
                    "surfaceType": surface_type,
                    "area": area,
                    "edgeLengthTotal": edge_total,
                });
                insert_dimensions(&mut fragment, dimensions.as_ref());
                fragment.to_string()
            }
            Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
        },
        MeasureKind::Edge => match brep_kernel::edge_length_native(handle, &query.entity) {
            Ok(length) => {
                let dimensions =
                    brep_kernel::edge_carrier_dimensions_native(handle, &query.entity)
                        .ok()
                        .flatten();
                let mut fragment = serde_json::json!({
                    "ok": true,
                    "kind": "edge",
                    "solid": query.owner,
                    "length": length,
                });
                if let Some(dimensions) = &dimensions {
                    fragment["curveType"] = serde_json::Value::from(dimensions.label);
                }
                insert_dimensions(&mut fragment, dimensions.as_ref());
                fragment.to_string()
            }
            Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
        },
    }
}

/// Add a carrier's named dimensions (`radius`, `diameter`, `halfAngleDeg`,
/// `majorRadius`, `minorRadius`, `sweepDeg`) to an object-info fragment.
fn insert_dimensions(
    fragment: &mut serde_json::Value,
    dimensions: Option<&brep_kernel::CarrierDimensions>,
) {
    let (Some(dimensions), Some(object)) = (dimensions, fragment.as_object_mut()) else {
        return;
    };
    for (key, value) in &dimensions.values {
        object.insert((*key).to_string(), serde_json::Value::from(*value));
    }
}

/// The default, SYNCHRONOUS runner: runs on submit, stashes the reply for an
/// immediate poll. Behavior-identical to the pre-seam in-process run.
pub struct InlineRunner {
    /// The scene-free history runner it owns (delta baseline lives here).
    runner: crate::pipeline::SceneRunner,
    /// Completed replies awaiting a poll. For Inline this holds exactly one entry
    /// between a `submit_run` and the immediately-following `poll_run`.
    pending: std::collections::VecDeque<RunReply>,
    /// Completed measurement replies awaiting a poll (computed synchronously on
    /// `submit_query`, popped on `poll_query`) — the synchronous mirror of the
    /// thread runner's query buffer, so the object-info path resolves same-call.
    query_pending: std::collections::VecDeque<MeasureReply>,
    mesh_import_pending: std::collections::VecDeque<MeshImportReply>,
    step_probe_pending: std::collections::VecDeque<StepProbeReply>,
    topology_pending: std::collections::VecDeque<TopologyReply>,
    sheet_lines_pending: std::collections::VecDeque<SheetLinesReply>,
    plugin_action_pending: std::collections::VecDeque<PluginActionReply>,
    plugin_install_pending: std::collections::VecDeque<PluginInstallReply>,
}

impl InlineRunner {
    pub fn new() -> Self {
        Self {
            runner: crate::pipeline::SceneRunner::new(),
            pending: std::collections::VecDeque::new(),
            query_pending: std::collections::VecDeque::new(),
            mesh_import_pending: std::collections::VecDeque::new(),
            step_probe_pending: std::collections::VecDeque::new(),
            topology_pending: std::collections::VecDeque::new(),
            sheet_lines_pending: std::collections::VecDeque::new(),
            plugin_action_pending: std::collections::VecDeque::new(),
            plugin_install_pending: std::collections::VecDeque::new(),
        }
    }
}

impl HistoryRunner for InlineRunner {
    fn submit_plugin_install(&mut self, request: PluginInstallRequest) -> bool {
        self.plugin_install_pending.push_back(validate_plugins(request));
        true
    }
    fn poll_plugin_install(&mut self) -> Option<PluginInstallReply> {
        self.plugin_install_pending.pop_front()
    }
    fn sync_plugins(&mut self, revision: u64, fetch: &mut dyn FnMut() -> serde_json::Value) {
        if self.runner.plugin_revision != Some(revision) {
            self.runner.set_plugins(revision, fetch());
        }
    }
    fn submit_plugin_action(&mut self, request: PluginActionRequest) -> bool {
        self.plugin_action_pending.push_back(self.runner.plugin_action(request));
        true
    }
    fn poll_plugin_action(&mut self) -> Option<PluginActionReply> {
        self.plugin_action_pending.pop_front()
    }

    fn submit_run(&mut self, request: brep_kernel::HistoryRequest, generation: u64) {
        let serial = brep_kernel::assembly_session_serial();
        let output = self.runner.run(&request);
        let after = brep_kernel::assembly_session_serial();
        self.runner.session_of = (after != serial).then_some((generation, after));
        self.pending.push_back(RunReply { generation, output });
    }

    /// The run executed on this (the caller's) thread: its session is already
    /// here unless something has replaced it since.
    fn session_for_main(&mut self, generation: u64) -> SessionOnMain {
        match self.runner.session_of {
            Some((ran, serial)) if ran == generation && serial == brep_kernel::assembly_session_serial() => {
                SessionOnMain::Resident
            }
            _ => SessionOnMain::Unavailable,
        }
    }

    /// Nothing to send: Inline runs on the CALLER's thread against the CALLER's
    /// kernel store, so the library the caller would hand over is already the
    /// one this run resolves against. (Which is also why Inline never needs the
    /// preflight — there is only one store, and the caller seeds it directly.)
    fn sync_parts_library(
        &mut self,
        _revision: u64,
        _fetch: &mut dyn FnMut() -> brep_kernel::PartsLibraryMap,
    ) {
    }

    fn poll_run(&mut self) -> Option<RunReply> {
        self.pending.pop_front()
    }

    fn submit_query(&mut self, query: MeasureQuery) {
        let result = measure_json(&self.runner, &query);
        self.query_pending.push_back(MeasureReply { id: query.id, result });
    }

    fn poll_query(&mut self) -> Option<MeasureReply> {
        self.query_pending.pop_front()
    }

    fn submit_mesh_import(&mut self, request: MeshImportRequest) {
        self.mesh_import_pending
            .push_back(reconstruct_mesh(request));
    }

    fn poll_mesh_import(&mut self) -> Option<MeshImportReply> {
        self.mesh_import_pending.pop_front()
    }

    fn submit_step_probe(&mut self, request: StepProbeRequest) {
        self.step_probe_pending.push_back(probe_step(request));
    }

    fn poll_step_probe(&mut self) -> Option<StepProbeReply> {
        self.step_probe_pending.pop_front()
    }

    fn submit_topology(&mut self, request: TopologyRequest) {
        self.topology_pending.push_back(topology_reply(request));
    }

    fn poll_topology(&mut self) -> Option<TopologyReply> {
        self.topology_pending.pop_front()
    }

    /// Runs the pass at once, on the caller's thread: an inline runner's
    /// registry IS the caller's, so the answer is ready for the next poll.
    fn submit_sheet_lines(&mut self, request: SheetLinesRequest) -> bool {
        self.sheet_lines_pending.push_back(sheet_lines_reply(request));
        true
    }

    fn poll_sheet_lines(&mut self) -> Option<SheetLinesReply> {
        self.sheet_lines_pending.pop_front()
    }

    fn reset(&mut self) {
        self.runner.reset();
    }
}

impl Default for InlineRunner {
    fn default() -> Self {
        Self::new()
    }
}

// ===========================================================================
// Shared run/query PROTOCOL (M3b): the `Command`/`Reply` message pair and the
// `process_command` step. Both async runners speak it — the native `ThreadRunner`
// ships the enums over `mpsc` (no serialization), and the wasm `WorkerRunner`
// serializes them to JSON for `postMessage`. Hence the serde derives (the enums
// carry serde types: `HistoryRequest`/`MeasureQuery`/`RunReply`/`MeasureReply`)
// and `process_command` being un-gated + shared so both drivers do the SAME work.
// ===========================================================================

/// A command sent main → runner (thread channel OR worker `postMessage`) over one
/// ordered stream (so a `Reset` before a `Run` stays before it). `Run` carries the
/// whole request; the driver coalesces consecutive `Run`s to shed a slider drag's
/// backlog (the thread in `thread_main`, the worker's main side in `WorkerRunner`).
#[derive(serde::Serialize, serde::Deserialize)]
pub enum Command {
    ValidatePlugins(PluginInstallRequest),
    SetPlugins { revision: u64, packages: serde_json::Value },
    PluginAction(PluginActionRequest),
    Run {
        request: brep_kernel::HistoryRequest,
        generation: u64,
        /// The [`brep_kernel::parts_library_revision`] this run was built
        /// against. The runner refuses to execute a run stamped for a library
        /// it does not hold — see [`process_command`].
        #[serde(default)]
        parts_library_revision: u64,
    },
    /// Install the parts library on the runner's OWN kernel store. Sent only
    /// when the library actually changes (insert, document load, refresh),
    /// never per run: it carries the whole embedded-part payload, which for an
    /// imported STEP assembly is megabytes, and stringifying that on the
    /// browser's main thread once per edit is what froze the UI.
    ///
    /// Deliberately its OWN command rather than an optional field on `Run`:
    /// both drivers COALESCE consecutive runs (see `thread_main` and
    /// `WorkerRunner::submit_run`), so a library riding on a run could be
    /// dropped with it. A `SetPartsLibrary` is never coalesced away, and the
    /// stream is ordered, so it always lands before the run that needs it.
    SetPartsLibrary {
        library: brep_kernel::PartsLibraryMap,
        revision: u64,
    },
    Query(MeasureQuery),
    MeshImport(MeshImportRequest),
    StepProbe(StepProbeRequest),
    Topology(TopologyRequest),
    SheetLines(SheetLinesRequest),
    /// Generate ONE CAM operation (never coalesced: every job answers).
    CamGenerate(CamJob),
    /// One CAM simulation command (never coalesced: every job answers).
    CamSimulate(CamSimJob),
    Reset,
    /// Copy the assembly session the run of `generation` left here (native
    /// thread only: the copy holds kernel solids and never crosses a worker).
    #[serde(skip)]
    ExportSession { generation: u64 },
}

/// A reply sent runner → main; the main side demuxes it into per-kind buffers.
#[derive(serde::Serialize, serde::Deserialize)]
pub enum Reply {
    ValidatedPlugins(PluginInstallReply),
    PluginAction(PluginActionReply),
    Run(RunReply),
    Query(MeasureReply),
    MeshImport(MeshImportReply),
    StepProbe(StepProbeReply),
    Topology(TopologyReply),
    SheetLines(SheetLinesReply),
    CamGenerate(CamReply),
    /// A CAM job's progress, posted from inside the job.
    CamProgress(CamProgress),
    CamSimulate(CamSimReply),
    /// A simulation chunk's progress, posted between motions.
    CamSimProgress(CamSimProgress),
    /// The runner REFUSED a run because its resident parts library could not
    /// serve it (a part the request references is missing, or the run was
    /// stamped for a different library revision). No geometry was touched; the
    /// main side re-sends the library and re-submits. Refusing is the whole
    /// point — running with the wrong library would be silently wrong
    /// geometry, which is far worse than one extra round trip.
    NeedPartsLibrary,
    /// A feature of the in-flight run is about to execute (see
    /// [`RunProgress`]). Posted from INSIDE `process_command`, before its
    /// `Reply::Run`; the main side keeps only the latest.
    Progress(RunProgress),
    /// The answer to `Command::ExportSession` (native thread only).
    #[serde(skip)]
    SessionExport { generation: u64, transfer: Option<brep_kernel::SessionTransfer> },
}

/// The probe itself — the one parse of a structured STEP import (see
/// `EngineState::submit_step_probe`), run wherever the runner runs.
fn probe_step(request: StepProbeRequest) -> StepProbeReply {
    StepProbeReply {
        id: request.id,
        result: brep_kernel::read_step_assembly(&request.text),
    }
}

fn reconstruct_mesh(request: MeshImportRequest) -> MeshImportReply {
    let result = (|| {
        use brep_reconstruction::stl_conversion::{
            binary_stl_coordinate_precision_tolerance, convert_stl_mesh_to_step_with_colors,
        };
        use brep_reconstruction::{Mesh, Vec3};

        // A 3MF build's placements, kept only to name each body afterwards.
        let mut instances = Vec::new();
        let mut reader_messages = Vec::new();
        // A 3MF's per-triangle colours (its base materials), parallel to the
        // soup's triangles; empty for STL and OBJ, which carry none.
        let mut triangle_colors: Vec<Option<[u8; 3]>> = Vec::new();
        let (mesh, positions, indices, coordinate_precision_tolerance) = match request.format {
            MeshImportFormat::Stl => {
                use brep_reconstruction::stl::{parse_stl_bytes, StlFormat, StlReadOptions};
                let read_options = StlReadOptions {
                    weld_tolerance: (request.options.weld_tolerance >= 0.0)
                        .then_some(request.options.weld_tolerance),
                };
                let imported = parse_stl_bytes(&request.bytes, &read_options)
                    .map_err(|error| format!("STL import failed: {error}"))?;
                let positions = imported
                    .mesh
                    .vertices
                    .iter()
                    .flat_map(|point| [point.x, point.y, point.z])
                    .collect::<Vec<_>>();
                let indices = imported
                    .mesh
                    .triangles
                    .iter()
                    .flatten()
                    .copied()
                    .collect::<Vec<_>>();
                let precision = if imported.format == StlFormat::Binary {
                    binary_stl_coordinate_precision_tolerance(&imported.mesh)
                } else {
                    0.0
                };
                if !imported.dropped_facets.is_empty() {
                    reader_messages.push(format!(
                        "the STL reader dropped {} of {} facet(s) with no area: {}",
                        imported.dropped_facets.len(),
                        imported.source_triangle_count,
                        imported.dropped_facets.iter().take(8).map(ToString::to_string).collect::<Vec<_>>().join("; ")
                    ));
                }
                (imported.mesh, positions, indices, precision)
            }
            MeshImportFormat::Obj => {
                let text = std::str::from_utf8(&request.bytes)
                    .map_err(|_| "OBJ import failed: file is not UTF-8 text".to_string())?;
                let obj = brep_kernel::read_obj(text)
                    .map_err(|error| format!("OBJ import failed: {error}"))?;
                let vertices = obj
                    .positions
                    .chunks_exact(3)
                    .map(|point| Vec3::new(point[0], point[1], point[2]))
                    .collect::<Vec<_>>();
                let triangles = obj
                    .indices
                    .chunks_exact(3)
                    .map(|triangle| [triangle[0], triangle[1], triangle[2]])
                    .collect::<Vec<_>>();
                (
                    Mesh::new(vertices, triangles),
                    obj.positions,
                    obj.indices,
                    0.0,
                )
            }
            // The 3MF reader has already applied the file's unit and every
            // build/component transform, so what arrives here is the same kind
            // of millimetre triangle soup an STL carries — including a build
            // that places SEVERAL instances, which is several bodies in that
            // one buffer. The chain splits a soup into its vertex-connected
            // components and reconstructs each as its own body, so the whole
            // build goes through in ONE call and the poses are already in the
            // coordinates.
            MeshImportFormat::ThreeMf => {
                let model = brep_kernel::read_3mf(&request.bytes)
                    .map_err(|error| format!("3MF import failed: {error}"))?;
                instances = model.instances;
                triangle_colors = model.triangle_colors;
                let vertices = model
                    .positions
                    .chunks_exact(3)
                    .map(|point| Vec3::new(point[0], point[1], point[2]))
                    .collect::<Vec<_>>();
                let triangles = model
                    .indices
                    .chunks_exact(3)
                    .map(|triangle| [triangle[0], triangle[1], triangle[2]])
                    .collect::<Vec<_>>();
                (
                    Mesh::new(vertices, triangles),
                    model.positions,
                    model.indices,
                    0.0,
                )
            }
        };
        let mut options = request.options;
        options.coordinate_precision_tolerance = options.coordinate_precision_tolerance
            .max(coordinate_precision_tolerance);
        convert_stl_mesh_to_step_with_colors(
            &mesh,
            &positions,
            Some(&indices),
            (!triangle_colors.is_empty()).then_some(triangle_colors.as_slice()),
            &options,
            "Imported mesh",
            "MM",
            "",
        )
        .map(|mut output| {
            name_bodies(&mut output.report, &instances);
            output.report.messages.splice(0..0, reader_messages);
            output
        })
        .map_err(|error| format!("RANSAC reconstruction failed: {error}"))
    })();
    MeshImportReply {
        id: request.id,
        result,
    }
}

/// Give each body the name of the 3MF object its first source triangle came
/// from, so a refusal can say WHICH object is missing. Bodies are found in the
/// flattened soup the reader laid out instance by instance.
fn name_bodies(
    report: &mut brep_reconstruction::stl_conversion::StlConversionReport,
    instances: &[brep_kernel::ThreeMfInstance],
) {
    for component in &mut report.components {
        component.source_name = instances
            .iter()
            .find(|instance| {
                (instance.first_triangle..instance.first_triangle + instance.triangle_count)
                    .contains(&component.first_triangle)
            })
            .and_then(|instance| instance.name.clone());
    }
}

/// The notice for bodies a multi-body import left out, one clause per body,
/// named by the source's own name when it has one; `None` when every body was
/// built.
pub(crate) fn refused_bodies_notice(
    report: &brep_reconstruction::stl_conversion::StlConversionReport,
) -> Option<String> {
    let refused = report
        .components
        .iter()
        .filter_map(|component| {
            component.refusal.as_ref().map(|reason| {
                let body = match &component.source_name {
                    Some(name) => format!("body {} \"{name}\"", component.index + 1),
                    None => format!(
                        "body {} (from source triangle {})",
                        component.index + 1,
                        component.first_triangle
                    ),
                };
                format!("{body}: {reason}")
            })
        })
        .collect::<Vec<_>>();
    (!refused.is_empty()).then(|| {
        format!(
            "mesh import: {} of {} bodies could not be reconstructed and are NOT in the model — {}",
            refused.len(),
            report.components.len(),
            refused.join("; ")
        )
    })
}

/// Execute ONE [`Command`] against `runner` and return the [`Reply`] it produces,
/// if any. The shared step both async drivers run: the native `thread_main`
/// calls it for each (post-coalescing) command on the runner thread; the wasm
/// `WorkerRunner`'s `worker_entry` calls it per `postMessage` on the worker.
/// `Run` → a [`Reply::Run`]; `Query` → a [`Reply::Query`]; `Reset` drops the delta
/// baseline AND the runner's OWN kernel history cache (the resident registry lives
/// with the runner — thread or worker — not on main) and yields no reply.
///
/// `progress` is called before every feature a `Run` actually executes, with
/// the report the driver should ship as [`Reply::Progress`]; returning `false`
/// stops the run at that boundary (the native thread's cooperative cancel —
/// the worker is terminated instead and always returns `true`).
pub fn process_command(
    runner: &mut crate::pipeline::SceneRunner,
    command: Command,
    progress: &mut dyn FnMut(Reply) -> bool,
) -> Option<Reply> {
    match command {
        Command::ValidatePlugins(request) => Some(Reply::ValidatedPlugins(validate_plugins(request))),
        Command::SetPlugins { revision, packages } => {
            runner.set_plugins(revision, packages);
            None
        }
        Command::PluginAction(request) => Some(Reply::PluginAction(runner.plugin_action(request))),
        Command::Run {
            request,
            generation,
            parts_library_revision,
        } => {
            // PREFLIGHT (see `Reply::NeedPartsLibrary`). Two independent
            // checks, because neither alone is enough:
            //
            // * the revision stamp catches CHANGED content the sender knows
            //   about but this store has not received;
            // * `missing_library_parts` catches content that is simply GONE
            //   here — the orphan GC at the end of every run drops entries no
            //   ACOMP in THAT run referenced, so an undo to zero components
            //   empties this store while the sender's (which never ran) keeps
            //   everything and its revision never moves. Only looking at the
            //   actual content sees that.
            let stale = match runner.parts_library_revision {
                Some(installed) => installed != parts_library_revision,
                // Nothing installed yet. Accept a run stamped 0 — that is
                // either an empty library or a caller driving `submit_run`
                // directly (the runner tests); the content preflight below is
                // what actually protects the run. A non-zero stamp with nothing
                // installed IS a gap: refuse it.
                None => parts_library_revision != 0,
            };
            // Only a part the sender DID send and this store has since lost is
            // worth asking for again. One it never sent is a dangling reference
            // in the document itself: run it, so the ACOMP feature reports it
            // the way it always has. (An install inserts every incoming name,
            // so right after one this set can only be empty — which is what
            // makes the ask-and-retry terminate.)
            let recoverable = brep_kernel::missing_library_parts(&request)
                .iter()
                .any(|name| runner.parts_library_names.contains(name));
            if stale || recoverable {
                runner.parts_library_revision = None;
                return Some(Reply::NeedPartsLibrary);
            }
            let serial = brep_kernel::assembly_session_serial();
            let output = runner.run_observed(&request, &mut |event| {
                progress(Reply::Progress(RunProgress {
                    generation,
                    index: event.index,
                    total: event.total,
                    feature_id: event.id.to_string(),
                    feature_type: event.feature_type.to_string(),
                }))
            });
            let after = brep_kernel::assembly_session_serial();
            runner.session_of = (after != serial).then_some((generation, after));
            Some(Reply::Run(RunReply { generation, output }))
        }
        Command::SetPartsLibrary { library, revision } => {
            runner.parts_library_names = library.keys().cloned().collect();
            brep_kernel::install_parts_library(&library);
            runner.parts_library_revision = Some(revision);
            None
        }
        Command::Query(query) => {
            let result = measure_json(runner, &query);
            Some(Reply::Query(MeasureReply { id: query.id, result }))
        }
        Command::MeshImport(request) => Some(Reply::MeshImport(reconstruct_mesh(request))),
        Command::StepProbe(request) => Some(Reply::StepProbe(probe_step(request))),
        Command::Topology(request) => Some(Reply::Topology(topology_reply(request))),
        Command::SheetLines(request) => Some(Reply::SheetLines(sheet_lines_reply(request))),
        Command::CamGenerate(job) => Some(Reply::CamGenerate(cam_generate_reply(job, progress))),
        Command::CamSimulate(job) => Some(Reply::CamSimulate(cam_sim_reply(job, progress))),
        Command::Reset => {
            // A document switch: drop the delta baseline AND this runner's OWN kernel
            // history cache (the resident registry lives here, not on main), mirroring
            // `set_history_json`'s main-thread clear so a new model rebuilds fully and
            // the old model's handles are freed.
            runner.reset();
            brep_kernel::clear_history_cache();
            cam_sim_clear();
            pre_op_stock_clear();
            None
        }
        Command::ExportSession { generation } => {
            Some(Reply::SessionExport { generation, transfer: runner.export_session(generation) })
        }
    }
}

// ===========================================================================
// ThreadRunner (M2b): a persistent std::thread that OWNS the SceneRunner, so a
// history run — and per-object measurement queries — execute OFF the main thread
// and the native UI stays responsive during a run AND during selection. Native
// only: `std::thread` + `std::sync::mpsc` do not exist on wasm32 (M3b lands a
// worker impl behind this same trait), so the whole thing is cfg-gated out there.
// ===========================================================================

/// The persistent-thread runner. `submit_*`/`reset` push [`Command`]s down the
/// channel; `poll_*` first DRAIN every ready [`Reply`] into the two demux buffers,
/// then pop the matching one. The `SceneRunner` (and thus the kernel's resident
/// registry it warms) lives ENTIRELY on the thread — it is never shared — so the
/// only cross-thread traffic is the `Send` command/reply payloads.
#[cfg(not(target_arch = "wasm32"))]
pub struct ThreadRunner {
    /// Main → thread. `Option` so [`Drop`] can take + drop it, ending the thread's
    /// blocking `recv` after already-submitted work finishes.
    tx: Option<std::sync::mpsc::Sender<Command>>,
    /// Thread → main.
    rx: std::sync::mpsc::Receiver<Reply>,
    /// Dropped without joining so closing a busy preview never stalls the UI.
    handle: Option<std::thread::JoinHandle<()>>,
    /// Demuxed completed run replies awaiting `poll_run`.
    run_buf: std::collections::VecDeque<RunReply>,
    /// Demuxed completed measurement replies awaiting `poll_query`.
    query_buf: std::collections::VecDeque<MeasureReply>,
    mesh_import_buf: std::collections::VecDeque<MeshImportReply>,
    step_probe_buf: std::collections::VecDeque<StepProbeReply>,
    topology_buf: std::collections::VecDeque<TopologyReply>,
    sheet_lines_buf: std::collections::VecDeque<SheetLinesReply>,
    cam_buf: std::collections::VecDeque<CamReply>,
    /// [`HistoryRunner::hold_cam_replies`]: `poll_cam` answers `None` while set.
    cam_hold: bool,
    cam_progress_buf: std::collections::VecDeque<CamProgress>,
    /// Set by [`HistoryRunner::cancel_cam`]; the thread reads it on every CAM
    /// progress post and the running job cancels at its next chunk.
    cam_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
    cam_sim_buf: std::collections::VecDeque<CamSimReply>,
    cam_sim_progress_buf: std::collections::VecDeque<CamSimProgress>,
    /// Set by [`HistoryRunner::cancel_cam_sim`]; read between two motions.
    cam_sim_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
    plugin_action_buf: std::collections::VecDeque<PluginActionReply>,
    plugin_install_buf: std::collections::VecDeque<PluginInstallReply>,
    sent_plugin_revision: Option<u64>,
    /// Progress reports of the in-flight run, oldest first (`poll_progress`
    /// keeps the newest).
    progress_buf: std::collections::VecDeque<RunProgress>,
    /// The parts-library revision last SENT down the channel (`None` = never,
    /// or the thread dropped it). Lives here rather than on the caller so
    /// "reset forgets the library" is a local property of this object.
    sent_library_revision: Option<u64>,
    /// The thread refused a run for want of its library (drained by
    /// [`HistoryRunner::poll_library_request`]).
    library_requested: bool,
    /// The cooperative stop flag THIS thread checks between features. Each
    /// spawn gets its own, so a cancelled thread keeps its raised flag while
    /// the replacement starts clean.
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

#[cfg(not(target_arch = "wasm32"))]
impl ThreadRunner {
    pub fn new() -> Self {
        let (tx, cmd_rx) = std::sync::mpsc::channel::<Command>();
        let (reply_tx, rx) = std::sync::mpsc::channel::<Reply>();
        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let thread_stop = stop.clone();
        let cam_cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let thread_cam_cancel = cam_cancel.clone();
        let cam_sim_cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let thread_cam_sim_cancel = cam_sim_cancel.clone();
        let handle = std::thread::Builder::new()
            .name("brep-history-runner".to_string())
            .spawn(move || thread_main(cmd_rx, reply_tx, thread_stop, thread_cam_cancel, thread_cam_sim_cancel))
            .expect("spawn brep-history-runner thread");
        Self {
            tx: Some(tx),
            rx,
            handle: Some(handle),
            run_buf: std::collections::VecDeque::new(),
            query_buf: std::collections::VecDeque::new(),
            mesh_import_buf: std::collections::VecDeque::new(),
            step_probe_buf: std::collections::VecDeque::new(),
            topology_buf: std::collections::VecDeque::new(),
            sheet_lines_buf: std::collections::VecDeque::new(),
            cam_buf: std::collections::VecDeque::new(),
            cam_hold: false,
            cam_progress_buf: std::collections::VecDeque::new(),
            cam_cancel,
            cam_sim_buf: std::collections::VecDeque::new(),
            cam_sim_progress_buf: std::collections::VecDeque::new(),
            cam_sim_cancel,
            plugin_action_buf: std::collections::VecDeque::new(),
            plugin_install_buf: std::collections::VecDeque::new(),
            sent_plugin_revision: None,
            progress_buf: std::collections::VecDeque::new(),
            sent_library_revision: None,
            library_requested: false,
            stop,
        }
    }

    /// Pull every ready reply off the channel and demux it into the run/query
    /// buffers (so a `poll_run` never swallows a query reply and vice versa).
    fn drain(&mut self) {
        while let Ok(reply) = self.rx.try_recv() {
            self.file(reply);
        }
    }

    /// Demux one reply into its buffer. A session export is handed back (only
    /// [`HistoryRunner::session_for_main`] waits for one; a late one is dropped).
    fn file(&mut self, reply: Reply) -> Option<(u64, Option<brep_kernel::SessionTransfer>)> {
        match reply {
            Reply::SessionExport { generation, transfer } => return Some((generation, transfer)),
            Reply::ValidatedPlugins(reply) => self.plugin_install_buf.push_back(reply),
            Reply::PluginAction(reply) => self.plugin_action_buf.push_back(reply),
            Reply::Run(run) => self.run_buf.push_back(run),
            Reply::Query(query) => self.query_buf.push_back(query),
            Reply::MeshImport(reply) => self.mesh_import_buf.push_back(reply),
            Reply::StepProbe(reply) => self.step_probe_buf.push_back(reply),
            Reply::Topology(reply) => self.topology_buf.push_back(reply),
            Reply::SheetLines(reply) => self.sheet_lines_buf.push_back(reply),
            Reply::CamGenerate(reply) => self.cam_buf.push_back(reply),
            Reply::CamProgress(progress) => self.cam_progress_buf.push_back(progress),
            Reply::CamSimulate(reply) => self.cam_sim_buf.push_back(reply),
            Reply::CamSimProgress(progress) => self.cam_sim_progress_buf.push_back(progress),
            Reply::Progress(progress) => self.progress_buf.push_back(progress),
            Reply::NeedPartsLibrary => {
                // The thread dropped (or never had) the library this run
                // needs. Forget what we believe it holds so the next
                // `sync_parts_library` re-installs, and flag the refused
                // run for the caller to re-submit.
                self.sent_library_revision = None;
                self.library_requested = true;
            }
        }
        None
    }
}

/// How long the main thread waits for the runner's session copy before it
/// replays the history instead (the copy of l500 takes ~8 ms).
#[cfg(not(target_arch = "wasm32"))]
const SESSION_EXPORT_WAIT: std::time::Duration = std::time::Duration::from_millis(250);

#[cfg(not(target_arch = "wasm32"))]
impl Default for ThreadRunner {
    fn default() -> Self {
        Self::new()
    }
}

/// The runner thread's whole life: block on the next command, batch it with every
/// other command already queued, COALESCE consecutive `Run`s (a `Run` immediately
/// followed by another `Run` — with no `Query`/`Reset` between — is dropped; only
/// the last of each consecutive group runs), then process the batch IN ORDER so a
/// `Reset` or a `Query` interleaved between two runs keeps its place. Exits when
/// the command sender is dropped (`recv` errors) or the reply receiver is gone (a
/// `send` errors — the main side went away).
///
/// `stop` is the cooperative cancel: raised by [`ThreadRunner::cancel`] on a
/// thread that has already been abandoned, it is checked before every feature
/// a run executes, so the abandoned thread finishes the feature it is on and
/// exits at the next boundary instead of running the rest of the history for
/// a receiver that is gone.
#[cfg(not(target_arch = "wasm32"))]
fn thread_main(
    cmd_rx: std::sync::mpsc::Receiver<Command>,
    reply_tx: std::sync::mpsc::Sender<Reply>,
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
    cam_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
    cam_sim_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
) {
    let mut runner = crate::pipeline::SceneRunner::new();
    while let Ok(first) = cmd_rx.recv() {
        if stop.load(std::sync::atomic::Ordering::Relaxed) {
            return;
        }
        // Gather this command plus everything else already waiting.
        let mut batch = vec![first];
        loop {
            match cmd_rx.try_recv() {
                Ok(command) => batch.push(command),
                Err(_) => break, // Empty or Disconnected — process what we have.
            }
        }
        // A Run immediately followed by another Run is coalesced away (its result
        // would be overwritten before anything observed it); a Run followed by a
        // Query/Reset/end still runs, so interleaved work sees the right geometry.
        let mut run_here: Vec<bool> = vec![true; batch.len()];
        for i in 0..batch.len() {
            if matches!(batch[i], Command::Run { .. })
                && matches!(batch.get(i + 1), Some(Command::Run { .. }))
            {
                run_here[i] = false;
            }
        }
        // Process the KEPT commands in order through the SHARED `process_command`
        // (byte-identical work to the wasm worker's per-message step), sending each
        // reply it produces; a coalesced-away Run is skipped without touching the
        // runner, so interleaved Query/Reset still see the right geometry.
        for (i, command) in batch.into_iter().enumerate() {
            if !run_here[i] {
                continue;
            }
            // A CAM job's progress post also reads the cancel flag: `false`
            // back to the job is its cancel (see `CamSink`).
            let is_cam = matches!(command, Command::CamGenerate(_));
            if is_cam {
                cam_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
            }
            let is_sim = matches!(command, Command::CamSimulate(_));
            let mut progress = |reply: Reply| {
                // A lost receiver means the main side abandoned this thread:
                // stop at this boundary rather than finishing for nobody.
                reply_tx.send(reply).is_ok()
                    && !stop.load(std::sync::atomic::Ordering::Relaxed)
                    && !(is_cam && cam_cancel.load(std::sync::atomic::Ordering::SeqCst))
                    && !(is_sim && cam_sim_cancel.load(std::sync::atomic::Ordering::SeqCst))
            };
            if let Some(reply) = process_command(&mut runner, command, &mut progress) {
                if reply_tx.send(reply).is_err() {
                    return; // The reply receiver is gone — the main side went away.
                }
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl HistoryRunner for ThreadRunner {
    fn session_for_main(&mut self, generation: u64) -> SessionOnMain {
        let Some(tx) = &self.tx else { return SessionOnMain::Unavailable };
        if tx.send(Command::ExportSession { generation }).is_err() {
            return SessionOnMain::Unavailable;
        }
        let deadline = std::time::Instant::now() + SESSION_EXPORT_WAIT;
        loop {
            let left = deadline.saturating_duration_since(std::time::Instant::now());
            let Ok(reply) = self.rx.recv_timeout(left) else { return SessionOnMain::Unavailable };
            if let Some((answered, transfer)) = self.file(reply) {
                if answered != generation {
                    continue; // a late answer to an earlier ask
                }
                return transfer.map_or(SessionOnMain::Unavailable, SessionOnMain::Copied);
            }
        }
    }
    fn submit_plugin_install(&mut self, request: PluginInstallRequest) -> bool {
        self.tx.as_ref().is_some_and(|tx| tx.send(Command::ValidatePlugins(request)).is_ok())
    }
    fn poll_plugin_install(&mut self) -> Option<PluginInstallReply> {
        self.drain();
        self.plugin_install_buf.pop_front()
    }
    fn sync_plugins(&mut self, revision: u64, fetch: &mut dyn FnMut() -> serde_json::Value) {
        if self.sent_plugin_revision != Some(revision) {
            if let Some(tx) = &self.tx {
                if tx.send(Command::SetPlugins { revision, packages: fetch() }).is_ok() {
                    self.sent_plugin_revision = Some(revision);
                }
            }
        }
    }
    fn submit_plugin_action(&mut self, request: PluginActionRequest) -> bool {
        self.tx.as_ref().is_some_and(|tx| tx.send(Command::PluginAction(request)).is_ok())
    }
    fn poll_plugin_action(&mut self) -> Option<PluginActionReply> {
        self.drain();
        self.plugin_action_buf.pop_front()
    }

    fn submit_run(&mut self, request: brep_kernel::HistoryRequest, generation: u64) {
        if let Some(tx) = &self.tx {
            let _ = tx.send(Command::Run {
                request,
                generation,
                parts_library_revision: self.sent_library_revision.unwrap_or(0),
            });
        }
    }

    fn sync_parts_library(
        &mut self,
        revision: u64,
        fetch: &mut dyn FnMut() -> brep_kernel::PartsLibraryMap,
    ) {
        if self.sent_library_revision == Some(revision) {
            return;
        }
        if let Some(tx) = &self.tx {
            let _ = tx.send(Command::SetPartsLibrary {
                library: fetch(),
                revision,
            });
            self.sent_library_revision = Some(revision);
        }
    }

    fn poll_library_request(&mut self) -> bool {
        self.drain();
        std::mem::take(&mut self.library_requested)
    }

    fn poll_run(&mut self) -> Option<RunReply> {
        self.drain();
        self.run_buf.pop_front()
    }

    fn run_reply_waiting(&mut self) -> bool {
        self.drain();
        !self.run_buf.is_empty() || self.library_requested
    }

    fn submit_query(&mut self, query: MeasureQuery) {
        if let Some(tx) = &self.tx {
            let _ = tx.send(Command::Query(query));
        }
    }

    fn poll_query(&mut self) -> Option<MeasureReply> {
        self.drain();
        self.query_buf.pop_front()
    }

    fn submit_mesh_import(&mut self, request: MeshImportRequest) {
        if let Some(tx) = &self.tx {
            let _ = tx.send(Command::MeshImport(request));
        }
    }

    fn poll_mesh_import(&mut self) -> Option<MeshImportReply> {
        self.drain();
        self.mesh_import_buf.pop_front()
    }

    fn submit_step_probe(&mut self, request: StepProbeRequest) {
        if let Some(tx) = &self.tx {
            let _ = tx.send(Command::StepProbe(request));
        }
    }

    fn poll_step_probe(&mut self) -> Option<StepProbeReply> {
        self.drain();
        self.step_probe_buf.pop_front()
    }

    fn submit_topology(&mut self, request: TopologyRequest) {
        if let Some(tx) = &self.tx {
            let _ = tx.send(Command::Topology(request));
        }
    }

    fn poll_topology(&mut self) -> Option<TopologyReply> {
        self.drain();
        self.topology_buf.pop_front()
    }

    fn wait_topology(&mut self, timeout: std::time::Duration) -> bool {
        self.drain();
        let deadline = std::time::Instant::now() + timeout;
        while self.topology_buf.is_empty() {
            let now = std::time::Instant::now();
            if now >= deadline {
                return false;
            }
            match self.rx.recv_timeout(deadline - now) {
                Ok(reply) => {
                    self.file(reply);
                }
                Err(_) => return false,
            }
        }
        true
    }

    fn submit_sheet_lines(&mut self, request: SheetLinesRequest) -> bool {
        match &self.tx {
            Some(tx) => tx.send(Command::SheetLines(request)).is_ok(),
            None => false,
        }
    }

    fn poll_sheet_lines(&mut self) -> Option<SheetLinesReply> {
        self.drain();
        self.sheet_lines_buf.pop_front()
    }

    fn submit_cam(&mut self, job: CamJob) -> bool {
        self.cam_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
        match &self.tx {
            Some(tx) => tx.send(Command::CamGenerate(job)).is_ok(),
            None => false,
        }
    }

    fn poll_cam(&mut self) -> Option<CamReply> {
        self.drain();
        if self.cam_hold {
            return None;
        }
        self.cam_buf.pop_front()
    }

    fn hold_cam_replies(&mut self, hold: bool) {
        self.cam_hold = hold;
    }

    fn poll_cam_progress(&mut self) -> Option<CamProgress> {
        self.drain();
        let latest = self.cam_progress_buf.pop_back();
        self.cam_progress_buf.clear();
        latest
    }

    fn cancel_cam(&mut self) {
        self.cam_cancel.store(true, std::sync::atomic::Ordering::SeqCst);
    }

    fn submit_cam_sim(&mut self, job: CamSimJob) -> bool {
        // A cancel raised for an earlier chunk must not stop this one.
        self.cam_sim_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
        match &self.tx {
            Some(tx) => tx.send(Command::CamSimulate(job)).is_ok(),
            None => false,
        }
    }

    fn poll_cam_sim(&mut self) -> Option<CamSimReply> {
        self.drain();
        self.cam_sim_buf.pop_front()
    }

    fn poll_cam_sim_progress(&mut self) -> Option<CamSimProgress> {
        self.drain();
        let latest = self.cam_sim_progress_buf.pop_back();
        self.cam_sim_progress_buf.clear();
        latest
    }

    fn cancel_cam_sim(&mut self) {
        self.cam_sim_cancel.store(true, std::sync::atomic::Ordering::SeqCst);
    }

    fn poll_progress(&mut self) -> Option<RunProgress> {
        self.drain();
        let latest = self.progress_buf.pop_back();
        self.progress_buf.clear();
        latest
    }

    /// Abandon the thread: raise its stop flag, close its channels, and spawn a
    /// fresh thread with a fresh registry. The old thread cannot be interrupted
    /// inside a feature — it finishes the one it is on (burning CPU until
    /// then), sees the flag, and exits. Always `true`: there is always a
    /// thread to replace.
    fn cancel(&mut self) -> bool {
        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
        self.tx.take();
        self.handle.take();
        *self = Self::new();
        true
    }

    fn reset(&mut self) {
        self.sent_plugin_revision = None;
        self.plugin_action_buf.clear();
        if let Some(tx) = &self.tx {
            let _ = tx.send(Command::Reset);
        }
        // A reset is a wholesale document switch: any replies still buffered from
        // the old model are stale — drop them (a fresh run/query supersedes).
        self.run_buf.clear();
        self.query_buf.clear();
        self.mesh_import_buf.clear();
        self.step_probe_buf.clear();
        self.topology_buf.clear();
        self.sheet_lines_buf.clear();
        self.progress_buf.clear();
        // `Command::Reset` clears the thread's kernel store, library included,
        // so what we believe it holds is void.
        self.sent_library_revision = None;
        self.library_requested = false;
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for ThreadRunner {
    fn drop(&mut self) {
        // Closing a document or cancelling an import preview must not block
        // the UI on reconstruction. Closing the channel lets the worker exit
        // and release its registry once already-submitted work finishes.
        self.tx.take();
        self.handle.take();
    }
}