Skip to main content

brep_render/
runner.rs

1//! The history-run seam — the async RUN machine behind a trait, mirroring the
2//! platform-seam shape of `brep-app/src/store.rs`'s `ModelStore` (a trait with
3//! impls behind it, async surfaced via a poll idiom).
4//!
5//! A history run is split SUBMIT → POLL/APPLY: [`HistoryRunner::submit_run`]
6//! kicks off a run tagged with a monotonic generation, and the completed
7//! [`RunReply`] is drained later via [`HistoryRunner::poll_run`]. The runner OWNS
8//! the [`SceneRunner`](crate::pipeline::SceneRunner) — so a future thread/worker
9//! impl owns the resident registry that `execute_history` populates — and holds
10//! the delta baseline across reruns.
11//!
12//! This slice ships the DEFAULT [`InlineRunner`]: it runs on `submit_run` and
13//! stashes the reply for an immediate `poll_run`, so the run stays synchronous
14//! and byte-identical to the pre-seam in-process run. A native-thread impl (M2b)
15//! and a wasm-worker impl (M3) slot in behind the SAME trait — `submit_run`
16//! defers the work and `poll_run` surfaces it a frame (or many) later, so the
17//! `EngineState::pump` caller never changes.
18
19/// A completed history run, tagged with the [`generation`](Self::generation) it
20/// was submitted under so the applier can drop stale replies (a newer run that
21/// finished first). The [`output`](Self::output) is the [`SceneRunner`] delta to
22/// apply to the display scene.
23///
24/// [`SceneRunner`]: crate::pipeline::SceneRunner
25#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
26pub struct RunReply {
27    /// The monotonic generation this run was submitted under.
28    pub generation: u64,
29    /// The delta snapshot + report the run produced.
30    pub output: crate::pipeline::RunOutput,
31}
32
33/// A feature about to EXECUTE inside an in-flight run (cached replays are
34/// instant and are not reported): which one, of how many, under which
35/// generation. Posted by the runner before the kernel starts the feature, so
36/// the UI can name what it is waiting on — and, after a cancel, what it was
37/// waiting on.
38#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
39pub struct RunProgress {
40    /// The generation of the run this belongs to (see [`RunReply::generation`]).
41    pub generation: u64,
42    /// Zero-based position of the feature in the request.
43    pub index: usize,
44    /// The request's feature count.
45    pub total: usize,
46    pub feature_id: String,
47    pub feature_type: String,
48}
49
50/// A STEP text to PROBE for product structure on the runner — the parse that
51/// `brep_kernel::read_step_assembly` performs, which builds every product's
52/// bodies and takes seconds on a real assembly (8.3 s natively for a 5 MB,
53/// 140-product file), so it must not run on the browser's main thread.
54#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
55pub struct StepProbeRequest {
56    pub id: u64,
57    pub text: String,
58}
59
60/// The probe's answer: the parsed assembly (`Some`), no structure (`None`),
61/// or a parse failure. The assembly crosses back to the main side whole — its
62/// JSON is large (74 MB for the file above) but the trip costs a third of a
63/// second against the seconds the parse took.
64#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
65pub struct StepProbeReply {
66    pub id: u64,
67    pub result: Result<Option<brep_kernel::StepAssembly>, String>,
68}
69
70/// Which exact measurement a [`MeasureQuery`] wants, mirroring the object-info
71/// kinds ([`crate::metadata`]): a whole solid, one named face, or one named edge.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
73pub enum MeasureKind {
74    Solid,
75    Face,
76    Edge,
77    /// A whole-solid CHECK for `model_inspect`: the kernel's topology
78    /// validation issues and the exact volume, read from the runner's warm
79    /// registry instead of a main-thread re-execution of the history.
80    Inspect,
81}
82
83/// A per-object MEASUREMENT request routed to the runner (which owns the warm
84/// registry). The runner resolves `owner` to its resident handle and measures by
85/// [`kind`](Self::kind); the reply is the object-info JSON fragment MINUS the
86/// main-injected `name`/`creatingFeature` fields. Tagged with a monotonic
87/// [`id`](Self::id) so the main side can pair the reply with its pending request.
88#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
89pub struct MeasureQuery {
90    /// Monotonic request id (main pairs the reply back by it).
91    pub id: u64,
92    /// The measurement to run.
93    pub kind: MeasureKind,
94    /// The OWNING solid name (a solid is its own owner; a face/edge names its solid).
95    pub owner: String,
96    /// The face/edge NAME to measure (ignored for a whole-solid query).
97    pub entity: String,
98    /// The density (mass per mm³) to scale a solid's weight (ignored for face/edge).
99    pub density: f64,
100}
101
102/// A completed [`MeasureQuery`]: the object-info measurement fields as a JSON
103/// fragment (WITHOUT `name`/`creatingFeature`, which the main thread injects from
104/// its eager provenance), tagged with the request [`id`](Self::id).
105#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
106pub struct MeasureReply {
107    /// The request id this answers.
108    pub id: u64,
109    /// The measurement JSON fragment (see `measure_json`).
110    pub result: String,
111}
112
113/// A request for the B-rep TOPOLOGY of resident solids, by the handle each
114/// display was tessellated from. The drawing sheet's exact hidden-line pass
115/// reads faces and edges, and the resident registry that holds them is
116/// thread-local to the runner, so the main side asks for exactly the solids a
117/// placement draws and does not already hold. Nothing else ever asks, so a
118/// document with no sheet never pays for the topology crossing.
119#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
120pub struct TopologyRequest {
121    /// Monotonic request id (main pairs the reply back by it).
122    pub id: u64,
123    /// `(solid name, resident handle)` per solid wanted.
124    pub solids: Vec<(String, u32)>,
125}
126
127/// A completed [`TopologyRequest`]: a clone of every requested solid the
128/// registry still holds, `(name, handle, solid)`. A handle the registry no
129/// longer holds (a later run freed it) is left out.
130#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
131pub struct TopologyReply {
132    /// The request id this answers.
133    pub id: u64,
134    pub solids: Vec<(String, u32, brep_kernel::BrepSolid)>,
135}
136
137/// Answer a topology request against the resident registry of the thread this
138/// runs on. Shared by every runner.
139fn topology_reply(request: TopologyRequest) -> TopologyReply {
140    let solids = request
141        .solids
142        .into_iter()
143        .filter_map(|(name, handle)| {
144            brep_kernel::registered_solid_clone(handle)
145                .ok()
146                .map(|solid| (name, handle, solid))
147        })
148        .collect();
149    TopologyReply { id: request.id, solids }
150}
151
152/// A drawing sheet's exact hidden-line pass for ONE placement, handed to the
153/// runner so the UI thread never runs it (see
154/// [`crate::sheets::project::LinesJob`]). The job names the runner's own
155/// resident solids by handle and content fingerprint, so nothing crosses the
156/// seam but the question and the lines.
157#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
158pub struct SheetLinesRequest {
159    /// Monotonic request id (main pairs the reply back by it).
160    pub id: u64,
161    pub job: crate::sheets::project::LinesJob,
162}
163
164/// A completed [`SheetLinesRequest`]: the placement's lines relative to its
165/// position, or why the runner could not draw them (a handle its registry no
166/// longer holds, or holds different geometry under).
167#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
168pub struct SheetLinesReply {
169    /// The request id this answers.
170    pub id: u64,
171    pub key: String,
172    pub lines: Result<crate::sheets::project::ExactLines, String>,
173}
174
175/// Answer a sheet-lines request against the resident registry of the thread
176/// this runs on. Shared by every runner.
177fn sheet_lines_reply(request: SheetLinesRequest) -> SheetLinesReply {
178    SheetLinesReply {
179        id: request.id,
180        lines: crate::sheets::project::run_lines_job(&request.job),
181        key: request.job.key,
182    }
183}
184
185/// ONE CAM operation's generation, off the UI thread (the CAM workbench's
186/// Generate). The job carries everything the generator reads as plain data:
187/// the operation, its setup and the document's tools (the shared model, by
188/// value), and the resident solids it machines by `(name, handle)`, which
189/// the runner clones out of its registry and tessellates through the CAM
190/// kernel adapter. The main side submits ONE operation per job and the next
191/// when its reply lands, so a cancel between operations is immediate on
192/// every platform; inside a job the native thread's cancel flag ends it at
193/// the generator's next work chunk, and the browser worker — which cannot
194/// read a message while it is inside a job — finishes the operation, whose
195/// reply the main side then drops as cancelled. A document `Reset` drops
196/// nothing here: the job holds no parked state across commands.
197#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
198pub struct CamJob {
199    /// Monotonic job id (main pairs the reply and the progress back by it).
200    pub id: u64,
201    pub operation: brep_cam::model::Operation,
202    pub setup: brep_cam::model::Setup,
203    pub tools: Vec<brep_cam::model::Tool>,
204    /// The bodies the setup machines or protects: `(solid name, resident handle)`.
205    pub solids: Vec<(String, u32)>,
206    /// The chordal tolerance the bodies are tessellated at, in model units.
207    pub chord_tolerance: f64,
208    /// Work units per progress / cancel check (the generator's chunk).
209    pub budget_chunk: u64,
210    /// The sketch curves the operation's chains name, `(sketch id, geometry
211    /// id, curve)` in model space, from the last history run (the runner's
212    /// registry holds solids, not sketches).
213    #[serde(default)]
214    pub chain_curves: Vec<(String, String, brep_kernel::NurbsCurve)>,
215    /// The sketch profiles the operation's chains name, `(sketch id, profile)`.
216    #[serde(default)]
217    pub chain_profiles: Vec<(String, brep_kernel::SketchProfile)>,
218    /// The setup's machine, resolved (its id is `setup.machine`): the
219    /// generator's kinematics context for rotary-capable strategies.
220    #[serde(default)]
221    pub machine: Option<brep_cam::model::Machine>,
222    /// Exact automatically programmed geometry and associative feature identity.
223    #[serde(default)]
224    pub autoprogram: Option<brep_cam::autoprogram::binding::Binding>,
225    /// The setup's operations BEFORE this one, in program order, each with
226    /// its current toolpath (`None`: not generated, failed or stale): the
227    /// runner replays them into the stock this operation starts from (lane C7).
228    #[serde(default)]
229    pub earlier: Vec<(brep_cam::model::Operation, Option<brep_cam::model::Toolpath>)>,
230    /// The setups this one continues from (`Stock::FromRest`), oldest first.
231    #[serde(default)]
232    pub previous_setups: Vec<brep_cam::SetupHistory>,
233    /// A multi-axis finish's designated three-axis source, generated and
234    /// current (lane C17): the generator tilts this path.
235    #[serde(default)]
236    pub source: Option<brep_cam::program::OperationInput>,
237    /// The designated source's definition when it has no current result: the
238    /// worker generates it on this job's bodies first.
239    #[serde(default)]
240    pub source_operation: Option<brep_cam::model::Operation>,
241}
242
243/// A completed [`CamJob`]: the toolpath, or why the operation could not be
244/// generated (the generator's own words), and how much work it took.
245#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
246pub struct CamReply {
247    /// Certified setup-Z meridian, carried with the generated result for axial replay.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub turning_profile: Option<brep_cam::turning::profile::TurningProfile>,
250    /// The stock the operation's setup starts from, as this job resolved it
251    /// (the simulation loads it; absent when the job built no pre-operation stock).
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub setup_start: Option<brep_cam::SetupStart>,
254    pub id: u64,
255    pub operation: String,
256    pub toolpath: Result<brep_cam::model::Toolpath, String>,
257    pub work_units: u64,
258    /// Whether the job ended on the cancel flag rather than on its own.
259    pub cancelled: bool,
260}
261
262/// A generation's progress, posted from inside the job at its stage and
263/// chunk boundaries.
264#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
265pub struct CamProgress {
266    pub id: u64,
267    pub operation: String,
268    pub phase: String,
269    pub message: String,
270    pub current: u64,
271    pub total: u64,
272}
273
274/// A CAM SIMULATION request (lane C17b). The runner keeps ONE simulation
275/// session resident (its stock and checkpoints live runner-side; a thread
276/// local, so the native thread and the wasm worker hold it the same way);
277/// the main side loads it once and then asks it to advance in bounded
278/// chunks, so a cancel between chunks is immediate on every platform and a
279/// chunk stops between two motions on the native thread.
280#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
281pub enum CamSimRequest {
282    /// Make `stock` the session's stock over `timeline`, each range cut by its cutter.
283    Load {
284        timeline: brep_cam::multiaxis::sim::Timeline,
285        stock: brep_cam::multiaxis::sim::StockModel,
286        ranges: Vec<brep_cam::multiaxis::sim::RangeCutter>,
287        options: brep_cam::multiaxis::sim::DriverOptions,
288        /// The machine whose chain applies rotary positioning (C7's
289        /// `*_on_machine`); none refuses any nonzero rotary word.
290        #[serde(default)]
291        machine: Option<brep_cam::model::Machine>,
292    },
293    /// Advance (or rewind and replay) toward `target` applied motions, at
294    /// most `budget` motions. `stock: true` returns the stock whenever its
295    /// version differs from `known_version` (the one the caller holds), so
296    /// a chunk whose reply the caller dropped is still made good.
297    Advance { target: usize, budget: usize, stock: bool, known_version: u64 },
298    /// Forget the session.
299    Drop,
300}
301
302/// One simulation command, paired back by `(session, seq)`.
303#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
304pub struct CamSimJob {
305    pub session: u64,
306    pub seq: u64,
307    pub request: CamSimRequest,
308}
309
310/// The session's state after a [`CamSimJob`].
311#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
312pub struct CamSimReply {
313    pub session: u64,
314    pub seq: u64,
315    pub applied: usize,
316    pub version: u64,
317    pub removed_volume: f64,
318    pub stock_volume: f64,
319    pub unsupported: Vec<usize>,
320    pub warnings: Vec<(usize, brep_cam::model::Diagnostic)>,
321    /// The stock, when asked and it changed since the job started.
322    pub stock: Option<brep_cam::multiaxis::sim::StockModel>,
323    /// The target was reached (`false`: the budget ran out or it stopped).
324    pub reached: bool,
325    /// The chunk stopped on the cancel flag (between two motions).
326    pub cancelled: bool,
327    pub error: Option<String>,
328}
329
330/// A simulation chunk's progress, posted between motions.
331#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
332pub struct CamSimProgress {
333    pub session: u64,
334    pub seq: u64,
335    pub applied: usize,
336    pub target: usize,
337}
338
339/// The runner-side simulation session.
340struct CamSimSession {
341    session: u64,
342    timeline: brep_cam::multiaxis::sim::Timeline,
343    ranges: Vec<brep_cam::multiaxis::sim::RangeCutter>,
344    driver: brep_cam::multiaxis::sim::SimDriver,
345}
346
347thread_local! {
348    static CAM_SIM: std::cell::RefCell<Option<CamSimSession>> = const { std::cell::RefCell::new(None) };
349}
350
351/// Forget the resident simulation (a document switch).
352fn cam_sim_clear() {
353    CAM_SIM.with(|c| *c.borrow_mut() = None);
354}
355
356thread_local! {
357    /// Pre-operation stock states of this document session (lane C7): a
358    /// regenerated operation replays only from the longest unchanged prefix.
359    static PRE_OP_STOCK: std::cell::RefCell<brep_cam::PreOpStockCache> = std::cell::RefCell::new(brep_cam::PreOpStockCache::new(16));
360}
361
362/// Forget the pre-operation stock states (a document switch).
363fn pre_op_stock_clear() {
364    PRE_OP_STOCK.with(|c| c.borrow_mut().clear());
365}
366
367fn cam_sim_reply(job: CamSimJob, post: &mut dyn FnMut(Reply) -> bool) -> CamSimReply {
368    let (session, seq) = (job.session, job.seq);
369    let empty = |error: Option<String>| CamSimReply {
370        session,
371        seq,
372        applied: 0,
373        version: 0,
374        removed_volume: 0.0,
375        stock_volume: 0.0,
376        unsupported: Vec::new(),
377        warnings: Vec::new(),
378        stock: None,
379        reached: false,
380        cancelled: false,
381        error,
382    };
383    match job.request {
384        CamSimRequest::Drop => {
385            cam_sim_clear();
386            empty(None)
387        }
388        CamSimRequest::Load { timeline, stock, ranges, options, machine } => match brep_cam::multiaxis::sim::SimDriver::new(stock, options) {
389            Ok(driver) => {
390                let driver = driver.with_chain(brep_cam::multiaxis::sim::sim_chain(machine.as_ref()));
391                let reply = CamSimReply {
392                    applied: driver.applied,
393                    version: driver.version,
394                    stock_volume: driver.stock.volume(),
395                    reached: true,
396                    ..empty(None)
397                };
398                CAM_SIM.with(|c| *c.borrow_mut() = Some(CamSimSession { session, timeline, ranges, driver }));
399                reply
400            }
401            Err(e) => empty(Some(e.to_string())),
402        },
403        CamSimRequest::Advance { target, budget, stock, known_version } => CAM_SIM.with(|c| {
404            let mut guard = c.borrow_mut();
405            let Some(sim) = guard.as_mut().filter(|s| s.session == session) else {
406                return empty(Some("no simulation session is loaded on the runner".into()));
407            };
408            let mut cancelled = false;
409            let tolerance = brep_cam::Tolerance::default();
410            let outcome = sim.driver.advance_ranges(&sim.timeline, &sim.ranges, target, budget, &tolerance, &mut |applied| {
411                let keep = post(Reply::CamSimProgress(CamSimProgress { session, seq, applied, target }));
412                if !keep {
413                    cancelled = true;
414                }
415                keep
416            });
417            let d = &sim.driver;
418            let (reached, error) = match outcome {
419                Ok(o) => (o == brep_cam::multiaxis::sim::AdvanceOutcome::Reached, None),
420                Err(e) => (false, Some(e.to_string())),
421            };
422            CamSimReply {
423                session,
424                seq,
425                applied: d.applied,
426                version: d.version,
427                removed_volume: d.removed_volume,
428                stock_volume: d.stock.volume(),
429                unsupported: d.unsupported.clone(),
430                warnings: d.warnings.clone(),
431                stock: (stock && d.version != known_version).then(|| d.stock.clone()),
432                reached,
433                cancelled,
434                error,
435            }
436        }),
437    }
438}
439
440/// A progress sink that posts through the driver's reply channel and turns
441/// a driver that says "stop" into the generator's cancel.
442struct CamSink<'a> {
443    id: u64,
444    operation: String,
445    token: brep_cam::CancelToken,
446    post: &'a mut dyn FnMut(Reply) -> bool,
447}
448
449impl brep_cam::ProgressSink for CamSink<'_> {
450    fn progress(&mut self, progress: &brep_cam::Progress) {
451        if std::env::var_os("BREP_CAM_DEBUG").is_some() {
452            eprintln!("cam job {} progress: {} {}/{}", self.operation, progress.phase, progress.current, progress.total);
453        }
454        let keep_going = (self.post)(Reply::CamProgress(CamProgress {
455            id: self.id,
456            operation: self.operation.clone(),
457            phase: progress.phase.clone(),
458            message: progress.message.clone(),
459            current: progress.current,
460            total: progress.total,
461        }));
462        if !keep_going {
463            if std::env::var_os("BREP_CAM_DEBUG").is_some() {
464                eprintln!("cam job {}: the driver said stop; cancelling", self.operation);
465            }
466            self.token.cancel();
467        }
468    }
469}
470
471/// The most triangles a CAM job's part mesh may have (the triangle index and
472/// the drop-cutter queries scale with it).
473pub const CAM_TRIANGLE_BUDGET: usize = 4_000_000;
474
475/// Run one CAM job against the resident registry of this thread.
476fn cam_generate_reply(job: CamJob, post: &mut dyn FnMut(Reply) -> bool) -> CamReply {
477    use brep_cam::kernel_adapter::{machine_snapshot, revolved_faces, BodyInput};
478    use brep_cam::{Runner, Tolerance, TreeIndex, TreeOptions, WorkBudget};
479    let operation = job.operation.id.as_str().to_string();
480    let token = brep_cam::CancelToken::new();
481    let mut sink = CamSink { id: job.id, operation: operation.clone(), token: token.clone(), post };
482    let mut certified_turning_profile = None;
483    let mut setup_start = None;
484    let mut outcome = || -> Result<(brep_cam::model::Toolpath, u64), String> {
485        // The resident bodies, cloned out of the registry by handle.
486        let mut bodies: Vec<(String, brep_kernel::BrepSolid)> = Vec::new();
487        for (name, handle) in &job.solids {
488            let solid = brep_kernel::registered_solid_clone(*handle)
489                .map_err(|e| format!("body `{name}` is not resident on the runner ({e}); run the history again"))?;
490            bodies.push((name.clone(), solid));
491        }
492        let diagonal = bodies
493            .iter()
494            .filter_map(|(_, s)| brep_cam::kernel_adapter::body_bounds(s, job.chord_tolerance).ok())
495            .fold(brep_cam::model::Bounds3::empty(), |acc, b| acc.union(&b))
496            .diagonal();
497        let tolerance = if diagonal.is_finite() && diagonal > 0.0 { Tolerance::scaled_for_diagonal(diagonal) } else { Tolerance::default() };
498        // The snapshot holds the SETUP's bodies and the operation's own: an
499        // operation's target or protected body outside the setup's list is
500        // still machined or avoided, so it joins the snapshot here.
501        let mut snapshot_setup = job.setup.clone();
502        for name in &job.operation.targets.target_solids {
503            if !snapshot_setup.targets.iter().any(|t| &t.solid == name) {
504                snapshot_setup.targets.push(brep_cam::model::TargetRef { solid: name.clone(), face: None });
505            }
506        }
507        for name in &job.operation.targets.protected_solids {
508            let listed = snapshot_setup.targets.iter().chain(snapshot_setup.protected.iter()).any(|t| &t.solid == name);
509            if !listed {
510                snapshot_setup.protected.push(brep_cam::model::TargetRef { solid: name.clone(), face: None });
511            }
512        }
513        let (mesh, unresolved) = machine_snapshot(&snapshot_setup, job.chord_tolerance, tolerance, |name| bodies.iter().find(|(n, _)| n == name).map(|(_, s)| s))
514            .map_err(|e| format!("{e}"))?;
515        if !unresolved.is_empty() {
516            return Err(format!("the setup names bodies the model does not have: {}", unresolved.join(", ")));
517        }
518        if std::env::var_os("BREP_CAM_DEBUG").is_some() {
519            eprintln!("cam job {}: {} bodies, snapshot {} faces / {} triangles, bounds {:?}", operation, bodies.len(), mesh.faces.len(), mesh.triangles.len(), mesh.bounds);
520        }
521        // The mesh is tessellated at the operation's own tolerance (a quarter
522        // of it); a part that needs more triangles than the generators can
523        // carry is refused by name, never coarsened behind the user's back.
524        if mesh.triangles.len() > CAM_TRIANGLE_BUDGET {
525            return Err(format!(
526                "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",
527                mesh.triangles.len(),
528                job.chord_tolerance
529            ));
530        }
531        let index = TreeIndex::build(&mesh, TreeOptions::default());
532        let mut runner = Runner::new(token.clone(), &mut sink, WorkBudget::new(job.budget_chunk.max(1))).with_operation(operation.clone());
533        // Drilling reads the recognised holes of the target bodies.
534        let holes = if matches!(job.operation.strategy, brep_cam::model::Strategy::Drill(_)) {
535            let mut carriers = Vec::new();
536            for (name, solid) in &bodies {
537                if job.setup.targets.iter().any(|t| t.solid == *name) || job.operation.targets.target_solids.contains(name) {
538                    let body = BodyInput { name, solid, protected_only: false };
539                    carriers.extend(revolved_faces(&body, &job.setup));
540                }
541            }
542            brep_cam::holes::recognize(&carriers, &mesh, tolerance, &mut runner).map_err(|e| e.to_string())?.holes
543        } else {
544            Vec::new()
545        };
546        // Frozen geometry is valid only for the exact bodies it was planned
547        // against. A body edit re-recognises by face identity and XY dimensions,
548        // preserving depth associativity without choosing a different feature.
549        let mut effective_operation = job.operation.clone();
550        let mut automatic_geometry = None;
551        let mut rebound = false;
552        if let Some(binding) = &job.autoprogram {
553            let tool = job.tools.iter().find(|t| t.id == job.operation.tool).ok_or("automatic programming tool is missing")?;
554            binding.validate_inputs(&job.operation, &job.setup, tool)?;
555            let fingerprints: std::collections::BTreeMap<_, _> = bodies.iter().map(|(name, solid)| (name.clone(), crate::scene::brep_fingerprint(solid))).collect();
556            if fingerprints == binding.body_fingerprints {
557                automatic_geometry = Some(binding.geometry.clone());
558            } else {
559                let recognized = brep_cam::autoprogram::binding::recognize_bodies(&bodies, &job.setup, &mesh, job.chord_tolerance, tolerance, &mut runner).map_err(|e| e.to_string())?;
560                let model_bounds = bodies.iter().filter(|(name, _)| job.setup.targets.iter().any(|t| &t.solid == name))
561                    .filter_map(|(_, s)| brep_cam::kernel_adapter::body_bounds(s, job.chord_tolerance).ok())
562                    .fold(brep_cam::model::Bounds3::empty(), |a, b| a.union(&b));
563                let stock_bounds = match &job.setup.stock {
564                    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()),
565                    _ => job.setup.stock.model_bounds(&model_bounds),
566                };
567                let stock_top = stock_bounds.map(|b| job.setup.model_to_machine.apply_bounds(&b).max.z);
568                let (op, geometry) = binding.rebind_with_mesh(&recognized, &mesh, &job.operation, &job.setup, &job.tools, job.machine.as_ref(), stock_top, tolerance)?;
569                effective_operation = op;
570                automatic_geometry = Some(geometry);
571                rebound = true;
572            }
573        }
574        let resolved_planar = match &automatic_geometry { Some(brep_cam::autoprogram::OperationGeometry::Planar(p)) => Some((&effective_operation.id, p)), _ => None };
575        let holes = match &automatic_geometry { Some(brep_cam::autoprogram::OperationGeometry::Holes(h)) => h.as_slice(), _ => holes.as_slice() };
576        // Lane C7: the stock as it stands before this operation (the setup's
577        // earlier operations replayed; a FromRest setup carried from the one it
578        // continues from). Unavailable: a named warning on the operation, and the
579        // linkers keep above the conservative material top. Never the raw stock.
580        let mut pre_op_warning = None;
581        // Automatic axial live contouring uses conservative planar links and
582        // does not consume the milling stock cache. Replaying a preceding
583        // turning operation into that cache is both unused and inappropriate.
584        let live_contour = matches!(job.operation.strategy, brep_cam::Strategy::Contour2D(_) | brep_cam::Strategy::Trace(_))
585            && job.operation.live_tool.unwrap_or(true)
586            && job.machine.as_ref().is_some_and(|m| matches!(m.kind, brep_cam::MachineKind::MillTurn { .. }));
587        let pre_op = if !live_contour && brep_cam::uses_pre_op_stock(&job.operation.strategy, job.machine.as_ref()) {
588            let fallback = job.operation.targets.target_solids.clone();
589            let request = brep_cam::JobStock {
590                setup: &job.setup,
591                machine: job.machine.as_ref(),
592                tools: &job.tools,
593                mesh: &mesh,
594                fallback_targets: &fallback,
595                earlier: &job.earlier,
596                previous: &job.previous_setups,
597                tolerance,
598            };
599            match PRE_OP_STOCK.with(|c| brep_cam::job_stock(&mut c.borrow_mut(), &request, &mut runner)) {
600                Ok(result) => Some(result),
601                Err(brep_cam::PreOpStockError::Cancelled) => return Err("cancelled".to_string()),
602                Err(error) => {
603                    pre_op_warning = Some(brep_cam::unavailable_warning(&error));
604                    None
605                }
606            }
607        } else {
608            None
609        };
610        let input = brep_cam::dispatch::GenerateInput {
611            operation: &effective_operation,
612            setup: &job.setup,
613            tools: &job.tools,
614            mesh: &mesh,
615            index: Some(&index),
616            tolerance,
617            holes,
618        };
619        // Picked chains resolve by identity against the bodies, sketch curves
620        // and profiles the job carries (C20's KernelChainGeometry).
621        let solid_refs: Vec<(&str, &brep_kernel::BrepSolid)> = bodies.iter().map(|(n, s)| (n.as_str(), s)).collect();
622        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();
623        let profile_refs: Vec<(&str, &brep_kernel::SketchProfile)> = job.chain_profiles.iter().map(|(s, p)| (s.as_str(), p)).collect();
624        let chain_geometry = brep_cam::dispatch::chains::KernelChainGeometry { solids: &solid_refs, curves: &curve_refs, profiles: &profile_refs };
625        let is_turning = matches!(job.operation.strategy, brep_cam::Strategy::TurnFace(_) | brep_cam::Strategy::TurnProfile(_));
626        let mut turning_carriers = Vec::new();
627        let turning_tool = if is_turning {
628            let tool = job.tools.iter().find(|t| t.id == job.operation.tool).ok_or("turning tool is missing")?;
629            if tool.turning_geometry.is_none() { return Err(format!("tool {} has no insert geometry", tool.id)); }
630            if job.setup.turning_stick_out.is_none() { return Err("setup has no stick-out".into()); }
631            let targets: std::collections::BTreeSet<_> = job.setup.targets.iter().map(|t| t.solid.as_str()).collect();
632            if targets.len() != 1 || job.operation.targets.target_solids.iter().any(|n| !targets.contains(n.as_str())) {
633                return Err("turning requires one exact setup solid and matching operation targets".into());
634            }
635            let name = *targets.iter().next().unwrap();
636            let solid = bodies.iter().find(|(n, _)| n == name).map(|(_, s)| s).ok_or("turning setup solid is missing")?;
637            if !job.machine.as_ref().is_some_and(|m| matches!(m.kind, brep_cam::MachineKind::Lathe | brep_cam::MachineKind::MillTurn { .. })) {
638                return Err("turning envelope requires a defined lathe spindle axis".into());
639            }
640            certified_turning_profile = Some(match brep_cam::kernel_adapter::turning_faces(&BodyInput { name, solid, protected_only: false }, &job.setup, tolerance) {
641                Ok(carriers) => {
642                    turning_carriers = carriers;
643                    brep_cam::turning::profile::extract(&turning_carriers, &mesh, job.operation.tolerance * 0.125, &mut runner)
644                }
645                Err(_) => brep_cam::turning::envelope::extract(&mesh, job.chord_tolerance, &mut runner),
646            }.map_err(|e| e.to_string())?);
647            Some(tool)
648        } else { None };
649        let turning = turning_tool.map(|tool| brep_cam::dispatch::TurningInput {
650            tool_id: &tool.id, tool_geometry: tool.turning_geometry.as_ref().unwrap(),
651            carriers: &turning_carriers, profile: certified_turning_profile.as_ref(), contour: None,
652            stick_out: job.setup.turning_stick_out.unwrap(), groove_center_z: None, thread_radius: None,
653        });
654        let context = brep_cam::dispatch::GenerateContext {
655            turning: turning.as_ref(),
656            chain_geometry: Some(&chain_geometry),
657            machine: job.machine.as_ref(),
658            resolved_planar,
659            rest_stock: pre_op.as_ref().map(|r| &r.stock.grid),
660            pre_op_stock: pre_op.as_ref().map(|r| &r.stock.envelope),
661            source: job.source.as_ref(),
662            source_operation: job.source_operation.as_ref(),
663            ..Default::default()
664        };
665        let mut path = brep_cam::dispatch::generate_with_context(&input, &context, &mut runner).map_err(|e| e.to_string())?;
666        if rebound { path.report.warn(brep_cam::model::Diagnostic::new("autoprogram-re-recognised", "re-recognised after model change")); }
667        if let Some(warning) = pre_op_warning {
668            // First, so a reader finds it at warnings[0] whenever it is there.
669            path.report.warn(warning);
670            path.report.warnings.rotate_right(1);
671        }
672        if let Some(result) = pre_op {
673            path.report.approximations.extend(result.limits);
674            setup_start = Some(result.start);
675        }
676        Ok((path, runner.budget().used()))
677    };
678    match outcome() {
679        Ok((toolpath, work_units)) => CamReply { turning_profile: certified_turning_profile, setup_start, id: job.id, operation, toolpath: Ok(toolpath), work_units, cancelled: false },
680        Err(message) => {
681            let cancelled = token.is_cancelled();
682            CamReply { turning_profile: None, setup_start: None, id: job.id, operation, toolpath: Err(if cancelled { "cancelled".to_string() } else { message }), work_units: 0, cancelled }
683        }
684    }
685}
686
687pub use brep_reconstruction::stl_conversion::{
688    ConversionBackend, ConversionPolicy, HybridDemotion, StlConversionOptions, StlConversionOutput,
689    StlConversionReport,
690};
691pub use brep_reconstruction::import_session::{
692    FitAttempt, FitKind, ImportRegion, ImportRegions, NurbsFaceChoice, NurbsFaceOutcome, NurbsFit, RegionFit,
693    RegionFitRequest, RegionKind, UNASSIGNED as UNASSIGNED_REGION,
694};
695
696/// Mesh encoding accepted by the off-thread reconstruction channel.
697#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
698pub enum MeshImportFormat {
699    Stl,
700    Obj,
701    /// 3MF (core specification): a package whose build instances are flattened
702    /// into one millimetre triangle soup before this common chain runs.
703    ThreeMf,
704}
705
706/// A mesh reconstruction request. The byte payload moves to the native thread
707/// or is serialized to the browser worker; no parsing or fitting happens on UI.
708#[derive(Debug, serde::Serialize, serde::Deserialize)]
709pub struct MeshImportRequest {
710    pub id: u64,
711    pub format: MeshImportFormat,
712    pub bytes: Vec<u8>,
713    pub options: StlConversionOptions,
714    /// Stream the interactive import's phases ([`Reply::MeshImportPhase`])
715    /// before the final reply: the parsed mesh, then its regions. The final
716    /// reply is the same with or without them.
717    #[serde(default)]
718    pub phases: bool,
719}
720
721/// One phase of an interactive mesh import, posted from inside the
722/// reconstruction before its [`MeshImportReply`].
723#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
724pub enum MeshImportPhase {
725    /// The parsed, welded triangle soup the reconstruction reads.
726    Mesh { positions: Vec<f64>, indices: Vec<u32> },
727    /// The regions the builder starts from, per source triangle.
728    Regions(brep_reconstruction::import_session::ImportRegions),
729    /// The regions could not be read (the reconstruction still runs).
730    RegionsFailed(String),
731}
732
733#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
734pub struct MeshImportPhaseReply {
735    pub id: u64,
736    pub phase: MeshImportPhase,
737}
738
739/// Refit one region of an interactive import. The caller sends the region's
740/// own triangles (a small mesh), so the runner keeps no import state.
741#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
742pub struct RegionFitJob {
743    pub id: u64,
744    pub positions: Vec<f64>,
745    pub indices: Vec<u32>,
746    pub request: brep_reconstruction::import_session::RegionFitRequest,
747}
748
749#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
750pub struct RegionFitReply {
751    pub id: u64,
752    pub fit: brep_reconstruction::import_session::RegionFit,
753}
754
755/// Run a region refit wherever the runner runs.
756pub fn region_fit_reply(job: RegionFitJob) -> RegionFitReply {
757    RegionFitReply {
758        id: job.id,
759        fit: brep_reconstruction::import_session::fit_region(&job.positions, &job.indices, &job.request),
760    }
761}
762
763/// Rebuild an interactive import's chosen regions as NURBS faces: the
764/// conversion's STEP, the welded mesh the regions index, and one choice per
765/// region (`brep_reconstruction::import_session::apply_region_choices`).
766#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
767pub struct ApplyRegionChoicesJob {
768    pub id: u64,
769    pub step_text: String,
770    pub positions: Vec<f64>,
771    pub indices: Vec<u32>,
772    pub choices: Vec<NurbsFaceChoice>,
773}
774
775#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
776pub struct ApplyRegionChoicesReply {
777    pub id: u64,
778    /// The new STEP (unchanged when no choice applied) and one outcome per
779    /// choice, in order.
780    pub result: Result<(String, Vec<NurbsFaceOutcome>), String>,
781}
782
783/// Apply region choices wherever the runner runs.
784pub fn apply_region_choices_reply(job: ApplyRegionChoicesJob) -> ApplyRegionChoicesReply {
785    ApplyRegionChoicesReply {
786        id: job.id,
787        result: brep_reconstruction::import_session::apply_region_choices(&job.step_text, &job.positions, &job.indices, &job.choices),
788    }
789}
790
791/// Completed off-thread reconstruction. Success carries validated STEP and
792/// diagnostics for a preview or an ordinary IMPORT3D history insertion.
793#[derive(Debug, serde::Serialize, serde::Deserialize)]
794pub struct MeshImportReply {
795    pub id: u64,
796    pub result: Result<StlConversionOutput, String>,
797}
798
799/// Validate explicitly installed packages away from the UI thread.
800#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
801pub struct PluginInstallRequest {
802    pub id: u64,
803    pub packages: serde_json::Value,
804}
805#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
806pub struct PluginInstallReply {
807    pub id: u64,
808    pub result: Result<brep_plugins::Registry, String>,
809}
810fn validate_plugins(request: PluginInstallRequest) -> PluginInstallReply {
811    let result = serde_json::from_value(request.packages)
812        .map_err(|e| format!("plugin packages: {e}"))
813        .and_then(brep_plugins::Runtime::new)
814        .map(|runtime| runtime.registry().clone());
815    PluginInstallReply { id: request.id, result }
816}
817
818/// A callback request against an immutable document/selection snapshot.
819#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
820pub struct PluginActionRequest {
821    pub id: u64,
822    pub pins: Vec<brep_plugins::PluginPin>,
823    pub action: String,
824    pub input: serde_json::Value,
825    #[serde(default, skip_serializing_if = "Option::is_none")]
826    pub script: Option<String>,
827}
828
829#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
830pub struct PluginActionReply {
831    pub id: u64,
832    pub result: Result<brep_plugins::ActionPlan, String>,
833}
834
835/// The history-run seam: SUBMIT a run, POLL for its completed reply, RESET the
836/// delta baseline, plus a QUERY channel for per-object measurements (routed to the
837/// runner so the warm registry answers them, never the cold main-side one). The
838/// Inline impl runs everything synchronously; a later thread/worker impl defers
839/// the work and surfaces the replies through the same poll idiom.
840/// Where the main thread gets the assembly session of the run it applied
841/// ([`HistoryRunner::session_for_main`]).
842pub enum SessionOnMain {
843    /// The run executed on the main thread and its session is still the
844    /// thread's: nothing to do.
845    Resident,
846    /// An owned copy from the runner's thread, to import.
847    Copied(brep_kernel::SessionTransfer),
848    /// Not available (busy, replaced, or a runner that cannot copy): replay.
849    Unavailable,
850}
851
852pub trait HistoryRunner {
853    /// The assembly session the run of `generation` left, for the main
854    /// thread's constraint actions. Blocking, but bounded. The default cannot
855    /// provide one, and the caller replays the history instead.
856    fn session_for_main(&mut self, _generation: u64) -> SessionOnMain {
857        SessionOnMain::Unavailable
858    }
859    /// Ask, WITHOUT waiting, for a copy of the session the run of `generation`
860    /// left; the answer comes back through [`Self::poll_session`] on a later
861    /// pump. `false`: this runner cannot export one.
862    fn request_session(&mut self, _generation: u64) -> bool {
863        false
864    }
865    /// The next answered [`Self::request_session`]: the generation asked for
866    /// and the copy (`None` when the runner no longer held that run's session).
867    fn poll_session(&mut self) -> Option<(u64, Option<brep_kernel::SessionTransfer>)> {
868        None
869    }
870    /// Whether the main side may REPLAY the history to get a session it cannot
871    /// import. True for a runner that runs on the caller's thread anyway (the
872    /// inline runner, test doubles); a background runner answers false, so a
873    /// missing session is fetched and waited for, never rebuilt on the UI
874    /// thread (a whole assembly, its stale parts included).
875    fn session_replay_on_main(&self) -> bool {
876        true
877    }
878    fn submit_plugin_install(&mut self, _request: PluginInstallRequest) -> bool { false }
879    fn poll_plugin_install(&mut self) -> Option<PluginInstallReply> { None }
880    /// Trusted installed content, separate from saved document dependency pins.
881    fn sync_plugins(&mut self, _revision: u64, _fetch: &mut dyn FnMut() -> serde_json::Value) {}
882    /// False explicitly reports a runner without action support.
883    fn submit_plugin_action(&mut self, _request: PluginActionRequest) -> bool { false }
884    fn poll_plugin_action(&mut self) -> Option<PluginActionReply> { None }
885
886    /// Submit a history run tagged with a monotonic generation. The runner executes
887    /// it (immediately for Inline; on a background thread later) and makes the reply
888    /// available via [`poll_run`](Self::poll_run).
889    fn submit_run(&mut self, request: brep_kernel::HistoryRequest, generation: u64);
890    /// Non-blocking: the next completed run reply, if any (drained each frame).
891    fn poll_run(&mut self) -> Option<RunReply>;
892    /// Submit a per-object measurement query (answered against the runner's warm
893    /// registry). Inline computes it immediately; a thread impl computes it on the
894    /// runner thread and surfaces it via [`poll_query`](Self::poll_query).
895    fn submit_query(&mut self, query: MeasureQuery);
896    /// Non-blocking: the next completed measurement reply, if any.
897    fn poll_query(&mut self) -> Option<MeasureReply>;
898    /// Submit RANSAC mesh reconstruction to the runner's thread/worker.
899    fn submit_mesh_import(&mut self, request: MeshImportRequest);
900    /// Non-blocking: the next completed mesh reconstruction, if any.
901    fn poll_mesh_import(&mut self) -> Option<MeshImportReply>;
902    /// Non-blocking: the next phase of an interactive mesh import
903    /// ([`MeshImportRequest::phases`]). The default posts none.
904    fn poll_mesh_import_phase(&mut self) -> Option<MeshImportPhaseReply> {
905        None
906    }
907    /// Submit a region refit; `false` when this runner cannot run one (the
908    /// caller then fits on its own thread — a region is small).
909    fn submit_region_fit(&mut self, _job: RegionFitJob) -> bool {
910        false
911    }
912    /// Non-blocking: the next completed region refit, if any.
913    fn poll_region_fit(&mut self) -> Option<RegionFitReply> {
914        None
915    }
916    /// Submit region choices to apply; `false` when this runner cannot (the
917    /// caller then applies them on its own thread).
918    fn submit_apply_region_choices(&mut self, _job: ApplyRegionChoicesJob) -> bool {
919        false
920    }
921    /// Non-blocking: the next applied region choices, if any.
922    fn poll_apply_region_choices(&mut self) -> Option<ApplyRegionChoicesReply> {
923        None
924    }
925    /// Submit a STEP product-structure probe (see [`StepProbeRequest`]).
926    fn submit_step_probe(&mut self, request: StepProbeRequest);
927    /// Non-blocking: the next completed STEP probe, if any.
928    fn poll_step_probe(&mut self) -> Option<StepProbeReply>;
929    /// Submit a topology request (see [`TopologyRequest`]). The default drops
930    /// it: a runner that never answers leaves a sheet on its mesh
931    /// approximation, which the drawing reports.
932    fn submit_topology(&mut self, _request: TopologyRequest) {}
933    /// Non-blocking: the next completed topology reply, if any.
934    fn poll_topology(&mut self) -> Option<TopologyReply> {
935        None
936    }
937    /// BLOCK up to `timeout` until a topology reply is ready to poll: `true`
938    /// when one is. An export that needs the exact solids waits this way on a
939    /// runner with a thread of its own; the default cannot wait (a worker
940    /// answers through the page's event loop, which a blocked page never
941    /// turns), so the export draws the mesh approximation and the file says
942    /// so.
943    fn wait_topology(&mut self, _timeout: std::time::Duration) -> bool {
944        false
945    }
946    /// Submit a sheet placement's exact pass (see [`SheetLinesRequest`]).
947    /// `false` when this runner cannot run one — the engine then runs it on
948    /// its own thread, as every projection did before the pass moved off it.
949    fn submit_sheet_lines(&mut self, _request: SheetLinesRequest) -> bool {
950        false
951    }
952    /// Non-blocking: the next completed sheet-lines reply, if any.
953    fn poll_sheet_lines(&mut self) -> Option<SheetLinesReply> {
954        None
955    }
956    /// Submit ONE CAM operation's generation (see [`CamJob`]); `false` when
957    /// this runner cannot run it.
958    fn submit_cam(&mut self, _job: CamJob) -> bool {
959        false
960    }
961    fn poll_cam(&mut self) -> Option<CamReply> {
962        None
963    }
964    fn poll_cam_progress(&mut self) -> Option<CamProgress> {
965        None
966    }
967    /// Cancel the CAM job in flight at its next work chunk, where the driver
968    /// can reach it (the native thread); a driver that cannot lets the job
969    /// finish and the main side drops its reply.
970    fn cancel_cam(&mut self) {}
971    /// TEST HOLD (automation only): while `hold`, finished CAM replies are
972    /// kept back from `poll_cam`, so a job stays in flight on the main side
973    /// however fast it ran — the one way a script can meet it with a cancel
974    /// every time. Releasing delivers what was kept, in order. A driver
975    /// without the hold ignores it.
976    fn hold_cam_replies(&mut self, _hold: bool) {}
977    /// Submit ONE CAM simulation command (see [`CamSimJob`]); `false` when
978    /// this runner cannot simulate (the caller then simulates inline).
979    fn submit_cam_sim(&mut self, _job: CamSimJob) -> bool {
980        false
981    }
982    fn poll_cam_sim(&mut self) -> Option<CamSimReply> {
983        None
984    }
985    fn poll_cam_sim_progress(&mut self) -> Option<CamSimProgress> {
986        None
987    }
988    /// Stop the simulation chunk in flight between two motions where the
989    /// driver can reach it (the native thread); elsewhere the chunk finishes
990    /// and the caller drops its reply.
991    fn cancel_cam_sim(&mut self) {}
992    /// Drop the delta baseline (document switch → full rebuild).
993    fn reset(&mut self);
994
995    /// Bring the runner's resident PARTS LIBRARY up to `revision`, calling
996    /// `fetch` ONLY when it is not already there. Called immediately before
997    /// every [`submit_run`](Self::submit_run).
998    ///
999    /// This is the whole point of the library channel: the library is sent
1000    /// when it CHANGES (insert, document load, refresh), not on every run.
1001    /// Cheap to call — the revision comparison is an integer, and `fetch`
1002    /// (which clones the store) never runs in the steady state. The default is
1003    /// a no-op for [`InlineRunner`], which shares the caller's kernel store.
1004    fn sync_parts_library(
1005        &mut self,
1006        _revision: u64,
1007        _fetch: &mut dyn FnMut() -> brep_kernel::PartsLibraryMap,
1008    ) {
1009    }
1010
1011    /// True when the runner REFUSED a run because its resident parts library
1012    /// could not serve it (see [`Reply::NeedPartsLibrary`]). It has already
1013    /// forgotten its copy, so the next `sync_parts_library` reinstalls; the
1014    /// caller must re-submit the run. Never true for a runner that shares the
1015    /// caller's store.
1016    fn poll_library_request(&mut self) -> bool {
1017        false
1018    }
1019
1020    /// Whether a run reply (or a refusal asking for the parts library) is
1021    /// waiting for [`poll_run`](Self::poll_run): a caller may skip what only a
1022    /// landing needs while this is false. `true` when the runner cannot tell.
1023    fn run_reply_waiting(&mut self) -> bool {
1024        true
1025    }
1026
1027    /// Non-blocking: the MOST RECENT progress report of the in-flight run, with
1028    /// any older ones discarded (only the latest feature matters). `None` for
1029    /// a synchronous runner — Inline has finished before anyone could ask.
1030    fn poll_progress(&mut self) -> Option<RunProgress> {
1031        None
1032    }
1033
1034    /// ABANDON the in-flight work and start over with an EMPTY resident
1035    /// registry. Returns `false` when there is nothing this runner can abandon
1036    /// (Inline: the run already completed on the caller's thread). A `true`
1037    /// means every handle the caller holds is now invalid, no reply is coming
1038    /// for anything submitted so far, and the parts library must be re-sent —
1039    /// the caller reconciles its generations and pending sets accordingly
1040    /// (`EngineState::cancel_run`). Nothing inside a feature is interruptible:
1041    /// the thread runner lets its old thread finish the feature it is on and
1042    /// stop at the next boundary; the browser worker is terminated outright.
1043    fn cancel(&mut self) -> bool {
1044        false
1045    }
1046
1047    /// The agent this runner works on DIED, with what it said (consumed): a
1048    /// browser worker whose wasm failed to start, or that trapped mid-command.
1049    /// Nothing submitted to it will answer. The caller replaces it with
1050    /// [`cancel`](Self::cancel) and reconciles as after one. `None` for a
1051    /// runner that cannot die apart from its caller.
1052    fn poll_failure(&mut self) -> Option<String> {
1053        None
1054    }
1055}
1056
1057/// Measure `query` against `runner`'s resident geometry and emit the object-info
1058/// JSON FRAGMENT — EXACTLY the fields [`crate::metadata::EngineState::object_info_json`]
1059/// emits for that kind EXCEPT `name` and `creatingFeature` (the main thread injects
1060/// those from its eager provenance, so the merged output is byte-identical to the
1061/// pre-seam in-process result). Shared verbatim by the Inline and thread runners so
1062/// both produce the identical fragment. A missing handle / kernel error yields
1063/// `{ "ok": false, "message": .. }` (main injects `name`).
1064fn measure_json(runner: &crate::pipeline::SceneRunner, query: &MeasureQuery) -> String {
1065    let Some(handle) = runner.handle_of(&query.owner) else {
1066        return serde_json::json!({
1067            "ok": false,
1068            "message": format!("solid '{}' has no resident geometry", query.owner),
1069        })
1070        .to_string();
1071    };
1072    match query.kind {
1073        MeasureKind::Inspect => {
1074            let issues: Vec<serde_json::Value> = match brep_kernel::validate_handle_native(handle) {
1075                Ok(issues) => issues.into_iter().map(|(severity, message)| serde_json::json!({ "severity": severity, "message": message })).collect(),
1076                Err(error) => vec![serde_json::json!({ "severity": "error", "message": format!("validation unavailable: {error}") })],
1077            };
1078            let (volume, volume_error) = match brep_kernel::mass_measures_handle_native(handle) {
1079                Ok(properties) => (Some(properties.volume), None),
1080                Err(error) => (None, Some(error)),
1081            };
1082            serde_json::json!({ "ok": true, "kind": "inspect", "issues": issues, "volume": volume, "volumeError": volume_error }).to_string()
1083        }
1084        MeasureKind::Solid => {
1085            match brep_kernel::mass_properties_handle_native(handle, query.density) {
1086                Ok(properties) => {
1087                    let edge_total =
1088                        brep_kernel::solid_edge_length_total_native(handle).unwrap_or(0.0);
1089                    serde_json::json!({
1090                        "ok": true,
1091                        "kind": "solid",
1092                        "volume": properties.volume,
1093                        "surfaceArea": properties.surface_area,
1094                        "edgeLengthTotal": edge_total,
1095                        "density": properties.density,
1096                        "weight": properties.mass,
1097                    })
1098                    .to_string()
1099                }
1100                Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
1101            }
1102        }
1103        MeasureKind::Face => match brep_kernel::face_measurements_native(handle, &query.entity) {
1104            Ok((area, edge_total, surface_type)) => {
1105                let dimensions =
1106                    brep_kernel::face_carrier_dimensions_native(handle, &query.entity)
1107                        .ok()
1108                        .flatten();
1109                // A partial revolution of a straight line is a "Surface of
1110                // revolution" to the kernel and a cylinder to the user.
1111                let surface_type = dimensions.as_ref().map_or(surface_type, |d| d.label);
1112                let mut fragment = serde_json::json!({
1113                    "ok": true,
1114                    "kind": "face",
1115                    "solid": query.owner,
1116                    "surfaceType": surface_type,
1117                    "area": area,
1118                    "edgeLengthTotal": edge_total,
1119                });
1120                insert_dimensions(&mut fragment, dimensions.as_ref());
1121                fragment.to_string()
1122            }
1123            Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
1124        },
1125        MeasureKind::Edge => match brep_kernel::edge_length_native(handle, &query.entity) {
1126            Ok(length) => {
1127                let dimensions =
1128                    brep_kernel::edge_carrier_dimensions_native(handle, &query.entity)
1129                        .ok()
1130                        .flatten();
1131                let mut fragment = serde_json::json!({
1132                    "ok": true,
1133                    "kind": "edge",
1134                    "solid": query.owner,
1135                    "length": length,
1136                });
1137                if let Some(dimensions) = &dimensions {
1138                    fragment["curveType"] = serde_json::Value::from(dimensions.label);
1139                }
1140                insert_dimensions(&mut fragment, dimensions.as_ref());
1141                fragment.to_string()
1142            }
1143            Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
1144        },
1145    }
1146}
1147
1148/// Add a carrier's named dimensions (`radius`, `diameter`, `halfAngleDeg`,
1149/// `majorRadius`, `minorRadius`, `sweepDeg`) to an object-info fragment.
1150fn insert_dimensions(
1151    fragment: &mut serde_json::Value,
1152    dimensions: Option<&brep_kernel::CarrierDimensions>,
1153) {
1154    let (Some(dimensions), Some(object)) = (dimensions, fragment.as_object_mut()) else {
1155        return;
1156    };
1157    for (key, value) in &dimensions.values {
1158        object.insert((*key).to_string(), serde_json::Value::from(*value));
1159    }
1160}
1161
1162/// The default, SYNCHRONOUS runner: runs on submit, stashes the reply for an
1163/// immediate poll. Behavior-identical to the pre-seam in-process run.
1164pub struct InlineRunner {
1165    /// The scene-free history runner it owns (delta baseline lives here).
1166    runner: crate::pipeline::SceneRunner,
1167    /// Completed replies awaiting a poll. For Inline this holds exactly one entry
1168    /// between a `submit_run` and the immediately-following `poll_run`.
1169    pending: std::collections::VecDeque<RunReply>,
1170    /// Completed measurement replies awaiting a poll (computed synchronously on
1171    /// `submit_query`, popped on `poll_query`) — the synchronous mirror of the
1172    /// thread runner's query buffer, so the object-info path resolves same-call.
1173    query_pending: std::collections::VecDeque<MeasureReply>,
1174    mesh_import_pending: std::collections::VecDeque<MeshImportReply>,
1175    mesh_phase_pending: std::collections::VecDeque<MeshImportPhaseReply>,
1176    region_fit_pending: std::collections::VecDeque<RegionFitReply>,
1177    apply_choices_pending: std::collections::VecDeque<ApplyRegionChoicesReply>,
1178    step_probe_pending: std::collections::VecDeque<StepProbeReply>,
1179    topology_pending: std::collections::VecDeque<TopologyReply>,
1180    sheet_lines_pending: std::collections::VecDeque<SheetLinesReply>,
1181    plugin_action_pending: std::collections::VecDeque<PluginActionReply>,
1182    plugin_install_pending: std::collections::VecDeque<PluginInstallReply>,
1183}
1184
1185impl InlineRunner {
1186    pub fn new() -> Self {
1187        Self {
1188            runner: crate::pipeline::SceneRunner::new(),
1189            pending: std::collections::VecDeque::new(),
1190            query_pending: std::collections::VecDeque::new(),
1191            mesh_import_pending: std::collections::VecDeque::new(),
1192            mesh_phase_pending: std::collections::VecDeque::new(),
1193            region_fit_pending: std::collections::VecDeque::new(),
1194            apply_choices_pending: std::collections::VecDeque::new(),
1195            step_probe_pending: std::collections::VecDeque::new(),
1196            topology_pending: std::collections::VecDeque::new(),
1197            sheet_lines_pending: std::collections::VecDeque::new(),
1198            plugin_action_pending: std::collections::VecDeque::new(),
1199            plugin_install_pending: std::collections::VecDeque::new(),
1200        }
1201    }
1202}
1203
1204impl HistoryRunner for InlineRunner {
1205    fn submit_plugin_install(&mut self, request: PluginInstallRequest) -> bool {
1206        self.plugin_install_pending.push_back(validate_plugins(request));
1207        true
1208    }
1209    fn poll_plugin_install(&mut self) -> Option<PluginInstallReply> {
1210        self.plugin_install_pending.pop_front()
1211    }
1212    fn sync_plugins(&mut self, revision: u64, fetch: &mut dyn FnMut() -> serde_json::Value) {
1213        if self.runner.plugin_revision != Some(revision) {
1214            self.runner.set_plugins(revision, fetch());
1215        }
1216    }
1217    fn submit_plugin_action(&mut self, request: PluginActionRequest) -> bool {
1218        self.plugin_action_pending.push_back(self.runner.plugin_action(request));
1219        true
1220    }
1221    fn poll_plugin_action(&mut self) -> Option<PluginActionReply> {
1222        self.plugin_action_pending.pop_front()
1223    }
1224
1225    fn submit_run(&mut self, request: brep_kernel::HistoryRequest, generation: u64) {
1226        let serial = brep_kernel::assembly_session_serial();
1227        let output = self.runner.run(&request);
1228        let after = brep_kernel::assembly_session_serial();
1229        self.runner.session_of = (after != serial).then_some((generation, after));
1230        self.pending.push_back(RunReply { generation, output });
1231    }
1232
1233    /// The run executed on this (the caller's) thread: its session is already
1234    /// here unless something has replaced it since.
1235    fn session_for_main(&mut self, generation: u64) -> SessionOnMain {
1236        match self.runner.session_of {
1237            Some((ran, serial)) if ran == generation && serial == brep_kernel::assembly_session_serial() => {
1238                SessionOnMain::Resident
1239            }
1240            _ => SessionOnMain::Unavailable,
1241        }
1242    }
1243
1244    /// Nothing to send: Inline runs on the CALLER's thread against the CALLER's
1245    /// kernel store, so the library the caller would hand over is already the
1246    /// one this run resolves against. (Which is also why Inline never needs the
1247    /// preflight — there is only one store, and the caller seeds it directly.)
1248    fn sync_parts_library(
1249        &mut self,
1250        _revision: u64,
1251        _fetch: &mut dyn FnMut() -> brep_kernel::PartsLibraryMap,
1252    ) {
1253    }
1254
1255    fn poll_run(&mut self) -> Option<RunReply> {
1256        self.pending.pop_front()
1257    }
1258
1259    fn submit_query(&mut self, query: MeasureQuery) {
1260        let result = measure_json(&self.runner, &query);
1261        self.query_pending.push_back(MeasureReply { id: query.id, result });
1262    }
1263
1264    fn poll_query(&mut self) -> Option<MeasureReply> {
1265        self.query_pending.pop_front()
1266    }
1267
1268    fn submit_mesh_import(&mut self, request: MeshImportRequest) {
1269        let phases = &mut self.mesh_phase_pending;
1270        let reply = reconstruct_mesh_phased(request, &mut |phase| {
1271            phases.push_back(phase);
1272            true
1273        });
1274        self.mesh_import_pending.push_back(reply);
1275    }
1276
1277    fn poll_mesh_import(&mut self) -> Option<MeshImportReply> {
1278        self.mesh_import_pending.pop_front()
1279    }
1280
1281    fn poll_mesh_import_phase(&mut self) -> Option<MeshImportPhaseReply> {
1282        self.mesh_phase_pending.pop_front()
1283    }
1284
1285    fn submit_region_fit(&mut self, job: RegionFitJob) -> bool {
1286        self.region_fit_pending.push_back(region_fit_reply(job));
1287        true
1288    }
1289
1290    fn poll_region_fit(&mut self) -> Option<RegionFitReply> {
1291        self.region_fit_pending.pop_front()
1292    }
1293
1294    fn submit_apply_region_choices(&mut self, job: ApplyRegionChoicesJob) -> bool {
1295        self.apply_choices_pending.push_back(apply_region_choices_reply(job));
1296        true
1297    }
1298
1299    fn poll_apply_region_choices(&mut self) -> Option<ApplyRegionChoicesReply> {
1300        self.apply_choices_pending.pop_front()
1301    }
1302
1303    fn submit_step_probe(&mut self, request: StepProbeRequest) {
1304        self.step_probe_pending.push_back(probe_step(request));
1305    }
1306
1307    fn poll_step_probe(&mut self) -> Option<StepProbeReply> {
1308        self.step_probe_pending.pop_front()
1309    }
1310
1311    fn submit_topology(&mut self, request: TopologyRequest) {
1312        self.topology_pending.push_back(topology_reply(request));
1313    }
1314
1315    fn poll_topology(&mut self) -> Option<TopologyReply> {
1316        self.topology_pending.pop_front()
1317    }
1318
1319    /// Runs the pass at once, on the caller's thread: an inline runner's
1320    /// registry IS the caller's, so the answer is ready for the next poll.
1321    fn submit_sheet_lines(&mut self, request: SheetLinesRequest) -> bool {
1322        self.sheet_lines_pending.push_back(sheet_lines_reply(request));
1323        true
1324    }
1325
1326    fn poll_sheet_lines(&mut self) -> Option<SheetLinesReply> {
1327        self.sheet_lines_pending.pop_front()
1328    }
1329
1330    fn reset(&mut self) {
1331        self.runner.reset();
1332    }
1333}
1334
1335impl Default for InlineRunner {
1336    fn default() -> Self {
1337        Self::new()
1338    }
1339}
1340
1341// ===========================================================================
1342// Shared run/query PROTOCOL (M3b): the `Command`/`Reply` message pair and the
1343// `process_command` step. Both async runners speak it — the native `ThreadRunner`
1344// ships the enums over `mpsc` (no serialization), and the wasm `WorkerRunner`
1345// serializes them to JSON for `postMessage`. Hence the serde derives (the enums
1346// carry serde types: `HistoryRequest`/`MeasureQuery`/`RunReply`/`MeasureReply`)
1347// and `process_command` being un-gated + shared so both drivers do the SAME work.
1348// ===========================================================================
1349
1350/// A command sent main → runner (thread channel OR worker `postMessage`) over one
1351/// ordered stream (so a `Reset` before a `Run` stays before it). `Run` carries the
1352/// whole request; the driver coalesces consecutive `Run`s to shed a slider drag's
1353/// backlog (the thread in `thread_main`, the worker's main side in `WorkerRunner`).
1354#[derive(serde::Serialize, serde::Deserialize)]
1355pub enum Command {
1356    ValidatePlugins(PluginInstallRequest),
1357    SetPlugins { revision: u64, packages: serde_json::Value },
1358    PluginAction(PluginActionRequest),
1359    Run {
1360        request: brep_kernel::HistoryRequest,
1361        generation: u64,
1362        /// The [`brep_kernel::parts_library_revision`] this run was built
1363        /// against. The runner refuses to execute a run stamped for a library
1364        /// it does not hold — see [`process_command`].
1365        #[serde(default)]
1366        parts_library_revision: u64,
1367    },
1368    /// Install the parts library on the runner's OWN kernel store. Sent only
1369    /// when the library actually changes (insert, document load, refresh),
1370    /// never per run: it carries the whole embedded-part payload, which for an
1371    /// imported STEP assembly is megabytes, and stringifying that on the
1372    /// browser's main thread once per edit is what froze the UI.
1373    ///
1374    /// Deliberately its OWN command rather than an optional field on `Run`:
1375    /// both drivers COALESCE consecutive runs (see `thread_main` and
1376    /// `WorkerRunner::submit_run`), so a library riding on a run could be
1377    /// dropped with it. A `SetPartsLibrary` is never coalesced away, and the
1378    /// stream is ordered, so it always lands before the run that needs it.
1379    SetPartsLibrary {
1380        library: brep_kernel::PartsLibraryMap,
1381        revision: u64,
1382    },
1383    Query(MeasureQuery),
1384    MeshImport(MeshImportRequest),
1385    RegionFit(RegionFitJob),
1386    ApplyRegionChoices(ApplyRegionChoicesJob),
1387    StepProbe(StepProbeRequest),
1388    Topology(TopologyRequest),
1389    SheetLines(SheetLinesRequest),
1390    /// Generate ONE CAM operation (never coalesced: every job answers).
1391    CamGenerate(CamJob),
1392    /// One CAM simulation command (never coalesced: every job answers).
1393    CamSimulate(CamSimJob),
1394    Reset,
1395    /// Copy the assembly session the run of `generation` left here. A worker
1396    /// sends the copy (kernel solids included) back as JSON.
1397    ExportSession { generation: u64 },
1398}
1399
1400/// A reply sent runner → main; the main side demuxes it into per-kind buffers.
1401#[derive(serde::Serialize, serde::Deserialize)]
1402pub enum Reply {
1403    ValidatedPlugins(PluginInstallReply),
1404    PluginAction(PluginActionReply),
1405    Run(RunReply),
1406    Query(MeasureReply),
1407    MeshImport(MeshImportReply),
1408    /// A phase of an interactive mesh import, posted before its `MeshImport`.
1409    MeshImportPhase(MeshImportPhaseReply),
1410    RegionFit(RegionFitReply),
1411    ApplyRegionChoices(ApplyRegionChoicesReply),
1412    StepProbe(StepProbeReply),
1413    Topology(TopologyReply),
1414    SheetLines(SheetLinesReply),
1415    CamGenerate(CamReply),
1416    /// A CAM job's progress, posted from inside the job.
1417    CamProgress(CamProgress),
1418    CamSimulate(CamSimReply),
1419    /// A simulation chunk's progress, posted between motions.
1420    CamSimProgress(CamSimProgress),
1421    /// The runner REFUSED a run because its resident parts library could not
1422    /// serve it (a part the request references is missing, or the run was
1423    /// stamped for a different library revision). No geometry was touched; the
1424    /// main side re-sends the library and re-submits. Refusing is the whole
1425    /// point — running with the wrong library would be silently wrong
1426    /// geometry, which is far worse than one extra round trip.
1427    NeedPartsLibrary,
1428    /// A feature of the in-flight run is about to execute (see
1429    /// [`RunProgress`]). Posted from INSIDE `process_command`, before its
1430    /// `Reply::Run`; the main side keeps only the latest.
1431    Progress(RunProgress),
1432    /// The answer to `Command::ExportSession`.
1433    SessionExport { generation: u64, transfer: Option<brep_kernel::SessionTransfer> },
1434}
1435
1436/// The probe itself — the one parse of a structured STEP import (see
1437/// `EngineState::submit_step_probe`), run wherever the runner runs.
1438fn probe_step(request: StepProbeRequest) -> StepProbeReply {
1439    StepProbeReply {
1440        id: request.id,
1441        // The same probe answers an IGES file, whose structure is subfigure
1442        // instances; the app's choice and import consume either alike.
1443        result: if crate::engine_state::is_iges_text(&request.text) {
1444            brep_kernel::read_iges_assembly(&request.text)
1445        } else {
1446            brep_kernel::read_step_assembly(&request.text)
1447        },
1448    }
1449}
1450
1451/// The import without its phase stream (every runner posts the phased one;
1452/// the runner's tests read the reply alone).
1453#[cfg_attr(not(test), allow(dead_code))]
1454fn reconstruct_mesh(request: MeshImportRequest) -> MeshImportReply {
1455    reconstruct_mesh_phased(request, &mut |_| true)
1456}
1457
1458/// [`reconstruct_mesh`], posting each phase of an interactive import to
1459/// `phase` as it completes when the request asks for them.
1460fn reconstruct_mesh_phased(
1461    request: MeshImportRequest,
1462    phase: &mut dyn FnMut(MeshImportPhaseReply) -> bool,
1463) -> MeshImportReply {
1464    let id = request.id;
1465    let phases = request.phases;
1466    let result = (|| {
1467        use brep_reconstruction::stl_conversion::{
1468            binary_stl_coordinate_precision_tolerance, convert_stl_mesh_to_step_with_colors,
1469        };
1470        use brep_reconstruction::{Mesh, Vec3};
1471
1472        // A 3MF build's placements, kept only to name each body afterwards.
1473        let mut instances = Vec::new();
1474        let mut reader_messages = Vec::new();
1475        // A 3MF's per-triangle colours (its base materials), parallel to the
1476        // soup's triangles; empty for STL and OBJ, which carry none.
1477        let mut triangle_colors: Vec<Option<[u8; 3]>> = Vec::new();
1478        let (mesh, positions, indices, coordinate_precision_tolerance) = match request.format {
1479            MeshImportFormat::Stl => {
1480                use brep_reconstruction::stl::{parse_stl_bytes, StlFormat, StlReadOptions};
1481                let read_options = StlReadOptions {
1482                    weld_tolerance: (request.options.weld_tolerance >= 0.0)
1483                        .then_some(request.options.weld_tolerance),
1484                };
1485                let imported = parse_stl_bytes(&request.bytes, &read_options)
1486                    .map_err(|error| format!("STL import failed: {error}"))?;
1487                let positions = imported
1488                    .mesh
1489                    .vertices
1490                    .iter()
1491                    .flat_map(|point| [point.x, point.y, point.z])
1492                    .collect::<Vec<_>>();
1493                let indices = imported
1494                    .mesh
1495                    .triangles
1496                    .iter()
1497                    .flatten()
1498                    .copied()
1499                    .collect::<Vec<_>>();
1500                let precision = if imported.format == StlFormat::Binary {
1501                    binary_stl_coordinate_precision_tolerance(&imported.mesh)
1502                } else {
1503                    0.0
1504                };
1505                if !imported.dropped_facets.is_empty() {
1506                    reader_messages.push(format!(
1507                        "the STL reader dropped {} of {} facet(s) with no area: {}",
1508                        imported.dropped_facets.len(),
1509                        imported.source_triangle_count,
1510                        imported.dropped_facets.iter().take(8).map(ToString::to_string).collect::<Vec<_>>().join("; ")
1511                    ));
1512                }
1513                (imported.mesh, positions, indices, precision)
1514            }
1515            MeshImportFormat::Obj => {
1516                let text = std::str::from_utf8(&request.bytes)
1517                    .map_err(|_| "OBJ import failed: file is not UTF-8 text".to_string())?;
1518                let obj = brep_kernel::read_obj(text)
1519                    .map_err(|error| format!("OBJ import failed: {error}"))?;
1520                let vertices = obj
1521                    .positions
1522                    .chunks_exact(3)
1523                    .map(|point| Vec3::new(point[0], point[1], point[2]))
1524                    .collect::<Vec<_>>();
1525                let triangles = obj
1526                    .indices
1527                    .chunks_exact(3)
1528                    .map(|triangle| [triangle[0], triangle[1], triangle[2]])
1529                    .collect::<Vec<_>>();
1530                (
1531                    Mesh::new(vertices, triangles),
1532                    obj.positions,
1533                    obj.indices,
1534                    0.0,
1535                )
1536            }
1537            // The 3MF reader has already applied the file's unit and every
1538            // build/component transform, so what arrives here is the same kind
1539            // of millimetre triangle soup an STL carries — including a build
1540            // that places SEVERAL instances, which is several bodies in that
1541            // one buffer. The chain splits a soup into its vertex-connected
1542            // components and reconstructs each as its own body, so the whole
1543            // build goes through in ONE call and the poses are already in the
1544            // coordinates.
1545            MeshImportFormat::ThreeMf => {
1546                let model = brep_kernel::read_3mf(&request.bytes)
1547                    .map_err(|error| format!("3MF import failed: {error}"))?;
1548                if let Some(instance) = model.instances.iter().find(|i| model.meshes[i.mesh].beam_lattice.is_some()) {
1549                    return Err(format!("3MF beam lattice in object {} ({}): retained as non-solid mesh exchange data; CAD reconstruction cannot build beam caps, junctions or clipping", instance.object_id, instance.name.as_deref().unwrap_or("unnamed")));
1550                }
1551                if !model.textures.is_empty() {
1552                    reader_messages.push("3MF texture images and UV coordinates cannot be displayed on reconstructed CAD faces or retained by CAD scene export.".to_owned());
1553                }
1554                instances = model.instances;
1555                triangle_colors = model.triangle_colors;
1556                let vertices = model
1557                    .positions
1558                    .chunks_exact(3)
1559                    .map(|point| Vec3::new(point[0], point[1], point[2]))
1560                    .collect::<Vec<_>>();
1561                let triangles = model
1562                    .indices
1563                    .chunks_exact(3)
1564                    .map(|triangle| [triangle[0], triangle[1], triangle[2]])
1565                    .collect::<Vec<_>>();
1566                (
1567                    Mesh::new(vertices, triangles),
1568                    model.positions,
1569                    model.indices,
1570                    0.0,
1571                )
1572            }
1573        };
1574        let mut options = request.options;
1575        options.coordinate_precision_tolerance = options.coordinate_precision_tolerance
1576            .max(coordinate_precision_tolerance);
1577        if phases {
1578            // `false` back from a post: nobody is listening any more (a
1579            // cancelled preview on the native thread) — stop here.
1580            let listening = phase(MeshImportPhaseReply {
1581                id,
1582                phase: MeshImportPhase::Mesh { positions: positions.clone(), indices: indices.clone() },
1583            });
1584            if !listening {
1585                return Err("cancelled".to_string());
1586            }
1587            let regions = brep_reconstruction::import_session::analyze_regions(&positions, &indices, &options);
1588            let listening = phase(MeshImportPhaseReply {
1589                id,
1590                phase: match regions {
1591                    Ok(regions) => MeshImportPhase::Regions(regions),
1592                    Err(error) => MeshImportPhase::RegionsFailed(error),
1593                },
1594            });
1595            if !listening {
1596                return Err("cancelled".to_string());
1597            }
1598        }
1599        convert_stl_mesh_to_step_with_colors(
1600            &mesh,
1601            &positions,
1602            Some(&indices),
1603            (!triangle_colors.is_empty()).then_some(triangle_colors.as_slice()),
1604            &options,
1605            "Imported mesh",
1606            "MM",
1607            "",
1608        )
1609        .map(|mut output| {
1610            name_bodies(&mut output.report, &instances);
1611            output.report.messages.splice(0..0, reader_messages);
1612            output
1613        })
1614        .map_err(|error| format!("RANSAC reconstruction failed: {error}"))
1615    })();
1616    MeshImportReply { id, result }
1617}
1618
1619/// Give each body the name of the 3MF object its first source triangle came
1620/// from, so a refusal can say WHICH object is missing. Bodies are found in the
1621/// flattened soup the reader laid out instance by instance.
1622fn name_bodies(
1623    report: &mut brep_reconstruction::stl_conversion::StlConversionReport,
1624    instances: &[brep_kernel::ThreeMfInstance],
1625) {
1626    for component in &mut report.components {
1627        component.source_name = instances
1628            .iter()
1629            .find(|instance| {
1630                (instance.first_triangle..instance.first_triangle + instance.triangle_count)
1631                    .contains(&component.first_triangle)
1632            })
1633            .and_then(|instance| instance.name.clone());
1634    }
1635}
1636
1637/// The notice for bodies a multi-body import left out, one clause per body,
1638/// named by the source's own name when it has one; `None` when every body was
1639/// built.
1640pub(crate) fn refused_bodies_notice(
1641    report: &brep_reconstruction::stl_conversion::StlConversionReport,
1642) -> Option<String> {
1643    let refused = report
1644        .components
1645        .iter()
1646        .filter_map(|component| {
1647            component.refusal.as_ref().map(|reason| {
1648                let body = match &component.source_name {
1649                    Some(name) => format!("body {} \"{name}\"", component.index + 1),
1650                    None => format!(
1651                        "body {} (from source triangle {})",
1652                        component.index + 1,
1653                        component.first_triangle
1654                    ),
1655                };
1656                format!("{body}: {reason}")
1657            })
1658        })
1659        .collect::<Vec<_>>();
1660    (!refused.is_empty()).then(|| {
1661        format!(
1662            "mesh import: {} of {} bodies could not be reconstructed and are NOT in the model — {}",
1663            refused.len(),
1664            report.components.len(),
1665            refused.join("; ")
1666        )
1667    })
1668}
1669
1670/// Execute ONE [`Command`] against `runner` and return the [`Reply`] it produces,
1671/// if any. The shared step both async drivers run: the native `thread_main`
1672/// calls it for each (post-coalescing) command on the runner thread; the wasm
1673/// `WorkerRunner`'s `worker_entry` calls it per `postMessage` on the worker.
1674/// `Run` → a [`Reply::Run`]; `Query` → a [`Reply::Query`]; `Reset` drops the delta
1675/// baseline AND the runner's OWN kernel history cache (the resident registry lives
1676/// with the runner — thread or worker — not on main) and yields no reply.
1677///
1678/// `progress` is called before every feature a `Run` actually executes, with
1679/// the report the driver should ship as [`Reply::Progress`]; returning `false`
1680/// stops the run at that boundary (the native thread's cooperative cancel —
1681/// the worker is terminated instead and always returns `true`).
1682pub fn process_command(
1683    runner: &mut crate::pipeline::SceneRunner,
1684    command: Command,
1685    progress: &mut dyn FnMut(Reply) -> bool,
1686) -> Option<Reply> {
1687    match command {
1688        Command::ValidatePlugins(request) => Some(Reply::ValidatedPlugins(validate_plugins(request))),
1689        Command::SetPlugins { revision, packages } => {
1690            runner.set_plugins(revision, packages);
1691            None
1692        }
1693        Command::PluginAction(request) => Some(Reply::PluginAction(runner.plugin_action(request))),
1694        Command::Run {
1695            request,
1696            generation,
1697            parts_library_revision,
1698        } => {
1699            // PREFLIGHT (see `Reply::NeedPartsLibrary`). Two independent
1700            // checks, because neither alone is enough:
1701            //
1702            // * the revision stamp catches CHANGED content the sender knows
1703            //   about but this store has not received;
1704            // * `missing_library_parts` catches content that is simply GONE
1705            //   here — the orphan GC at the end of every run drops entries no
1706            //   ACOMP in THAT run referenced, so an undo to zero components
1707            //   empties this store while the sender's (which never ran) keeps
1708            //   everything and its revision never moves. Only looking at the
1709            //   actual content sees that.
1710            let stale = match runner.parts_library_revision {
1711                Some(installed) => installed != parts_library_revision,
1712                // Nothing installed yet. Accept a run stamped 0 — that is
1713                // either an empty library or a caller driving `submit_run`
1714                // directly (the runner tests); the content preflight below is
1715                // what actually protects the run. A non-zero stamp with nothing
1716                // installed IS a gap: refuse it.
1717                None => parts_library_revision != 0,
1718            };
1719            // Only a part the sender DID send and this store has since lost is
1720            // worth asking for again. One it never sent is a dangling reference
1721            // in the document itself: run it, so the ACOMP feature reports it
1722            // the way it always has. (An install inserts every incoming name,
1723            // so right after one this set can only be empty — which is what
1724            // makes the ask-and-retry terminate.)
1725            let recoverable = brep_kernel::missing_library_parts(&request)
1726                .iter()
1727                .any(|name| runner.parts_library_names.contains(name));
1728            if stale || recoverable {
1729                runner.parts_library_revision = None;
1730                return Some(Reply::NeedPartsLibrary);
1731            }
1732            let serial = brep_kernel::assembly_session_serial();
1733            let output = runner.run_observed(&request, &mut |event| {
1734                progress(Reply::Progress(RunProgress {
1735                    generation,
1736                    index: event.index,
1737                    total: event.total,
1738                    feature_id: event.id.to_string(),
1739                    feature_type: event.feature_type.to_string(),
1740                }))
1741            });
1742            let after = brep_kernel::assembly_session_serial();
1743            runner.session_of = (after != serial).then_some((generation, after));
1744            Some(Reply::Run(RunReply { generation, output }))
1745        }
1746        Command::SetPartsLibrary { library, revision } => {
1747            runner.parts_library_names = library.keys().cloned().collect();
1748            brep_kernel::install_parts_library(&library);
1749            runner.parts_library_revision = Some(revision);
1750            None
1751        }
1752        Command::Query(query) => {
1753            let result = measure_json(runner, &query);
1754            Some(Reply::Query(MeasureReply { id: query.id, result }))
1755        }
1756        Command::MeshImport(request) => Some(Reply::MeshImport(reconstruct_mesh_phased(request, &mut |phase| {
1757            progress(Reply::MeshImportPhase(phase))
1758        }))),
1759        Command::RegionFit(job) => Some(Reply::RegionFit(region_fit_reply(job))),
1760        Command::ApplyRegionChoices(job) => Some(Reply::ApplyRegionChoices(apply_region_choices_reply(job))),
1761        Command::StepProbe(request) => Some(Reply::StepProbe(probe_step(request))),
1762        Command::Topology(request) => Some(Reply::Topology(topology_reply(request))),
1763        Command::SheetLines(request) => Some(Reply::SheetLines(sheet_lines_reply(request))),
1764        Command::CamGenerate(job) => Some(Reply::CamGenerate(cam_generate_reply(job, progress))),
1765        Command::CamSimulate(job) => Some(Reply::CamSimulate(cam_sim_reply(job, progress))),
1766        Command::Reset => {
1767            // A document switch: drop the delta baseline AND this runner's OWN kernel
1768            // history cache (the resident registry lives here, not on main), mirroring
1769            // `set_history_json`'s main-thread clear so a new model rebuilds fully and
1770            // the old model's handles are freed.
1771            runner.reset();
1772            brep_kernel::clear_history_cache();
1773            cam_sim_clear();
1774            pre_op_stock_clear();
1775            None
1776        }
1777        Command::ExportSession { generation } => {
1778            Some(Reply::SessionExport { generation, transfer: runner.export_session(generation) })
1779        }
1780    }
1781}
1782
1783// ===========================================================================
1784// ThreadRunner (M2b): a persistent std::thread that OWNS the SceneRunner, so a
1785// history run — and per-object measurement queries — execute OFF the main thread
1786// and the native UI stays responsive during a run AND during selection. Native
1787// only: `std::thread` + `std::sync::mpsc` do not exist on wasm32 (M3b lands a
1788// worker impl behind this same trait), so the whole thing is cfg-gated out there.
1789// ===========================================================================
1790
1791/// The persistent-thread runner. `submit_*`/`reset` push [`Command`]s down the
1792/// channel; `poll_*` first DRAIN every ready [`Reply`] into the two demux buffers,
1793/// then pop the matching one. The `SceneRunner` (and thus the kernel's resident
1794/// registry it warms) lives ENTIRELY on the thread — it is never shared — so the
1795/// only cross-thread traffic is the `Send` command/reply payloads.
1796/// Called after the runner thread posts a reply or a progress report, from
1797/// that thread: the app's event loop wakes and collects it at once instead of
1798/// at its next timed check (`set_reply_waker`). Process-wide, like the
1799/// thread's other plumbing; none installed is a no-op.
1800#[cfg(not(target_arch = "wasm32"))]
1801static REPLY_WAKER: std::sync::RwLock<Option<std::sync::Arc<dyn Fn() + Send + Sync>>> = std::sync::RwLock::new(None);
1802
1803/// Install (or with `None` remove) the hook a runner thread calls after each
1804/// reply it posts. The desktop event loop installs its own waker here.
1805#[cfg(not(target_arch = "wasm32"))]
1806pub fn set_reply_waker(waker: Option<std::sync::Arc<dyn Fn() + Send + Sync>>) {
1807    *REPLY_WAKER.write().unwrap_or_else(|p| p.into_inner()) = waker;
1808}
1809
1810#[cfg(not(target_arch = "wasm32"))]
1811fn wake_main() {
1812    let waker = REPLY_WAKER.read().unwrap_or_else(|p| p.into_inner()).clone();
1813    if let Some(waker) = waker {
1814        waker();
1815    }
1816}
1817
1818#[cfg(not(target_arch = "wasm32"))]
1819pub struct ThreadRunner {
1820    /// Main → thread. `Option` so [`Drop`] can take + drop it, ending the thread's
1821    /// blocking `recv` after already-submitted work finishes.
1822    tx: Option<std::sync::mpsc::Sender<Command>>,
1823    /// Thread → main.
1824    rx: std::sync::mpsc::Receiver<Reply>,
1825    /// Dropped without joining so closing a busy preview never stalls the UI.
1826    handle: Option<std::thread::JoinHandle<()>>,
1827    /// Demuxed completed run replies awaiting `poll_run`.
1828    run_buf: std::collections::VecDeque<RunReply>,
1829    /// Demuxed completed measurement replies awaiting `poll_query`.
1830    query_buf: std::collections::VecDeque<MeasureReply>,
1831    mesh_import_buf: std::collections::VecDeque<MeshImportReply>,
1832    mesh_phase_buf: std::collections::VecDeque<MeshImportPhaseReply>,
1833    region_fit_buf: std::collections::VecDeque<RegionFitReply>,
1834    apply_choices_buf: std::collections::VecDeque<ApplyRegionChoicesReply>,
1835    step_probe_buf: std::collections::VecDeque<StepProbeReply>,
1836    topology_buf: std::collections::VecDeque<TopologyReply>,
1837    sheet_lines_buf: std::collections::VecDeque<SheetLinesReply>,
1838    cam_buf: std::collections::VecDeque<CamReply>,
1839    /// [`HistoryRunner::hold_cam_replies`]: `poll_cam` answers `None` while set.
1840    cam_hold: bool,
1841    cam_progress_buf: std::collections::VecDeque<CamProgress>,
1842    /// Set by [`HistoryRunner::cancel_cam`]; the thread reads it on every CAM
1843    /// progress post and the running job cancels at its next chunk.
1844    cam_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
1845    cam_sim_buf: std::collections::VecDeque<CamSimReply>,
1846    cam_sim_progress_buf: std::collections::VecDeque<CamSimProgress>,
1847    /// Set by [`HistoryRunner::cancel_cam_sim`]; read between two motions.
1848    cam_sim_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
1849    plugin_action_buf: std::collections::VecDeque<PluginActionReply>,
1850    plugin_install_buf: std::collections::VecDeque<PluginInstallReply>,
1851    sent_plugin_revision: Option<u64>,
1852    /// Progress reports of the in-flight run, oldest first (`poll_progress`
1853    /// keeps the newest).
1854    progress_buf: std::collections::VecDeque<RunProgress>,
1855    /// Answered [`HistoryRunner::request_session`]s awaiting `poll_session`.
1856    session_buf: std::collections::VecDeque<(u64, Option<brep_kernel::SessionTransfer>)>,
1857    /// Behave as the wasm worker does: no blocking `session_for_main`, and
1858    /// every exported session crosses as JSON (see [`ThreadRunner::worker_like`]).
1859    worker_like: bool,
1860    /// The parts-library revision last SENT down the channel (`None` = never,
1861    /// or the thread dropped it). Lives here rather than on the caller so
1862    /// "reset forgets the library" is a local property of this object.
1863    sent_library_revision: Option<u64>,
1864    /// The thread refused a run for want of its library (drained by
1865    /// [`HistoryRunner::poll_library_request`]).
1866    library_requested: bool,
1867    /// The cooperative stop flag THIS thread checks between features. Each
1868    /// spawn gets its own, so a cancelled thread keeps its raised flag while
1869    /// the replacement starts clean.
1870    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1871}
1872
1873#[cfg(not(target_arch = "wasm32"))]
1874impl ThreadRunner {
1875    pub fn new() -> Self {
1876        let (tx, cmd_rx) = std::sync::mpsc::channel::<Command>();
1877        let (reply_tx, rx) = std::sync::mpsc::channel::<Reply>();
1878        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1879        let thread_stop = stop.clone();
1880        let cam_cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1881        let thread_cam_cancel = cam_cancel.clone();
1882        let cam_sim_cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1883        let thread_cam_sim_cancel = cam_sim_cancel.clone();
1884        let handle = std::thread::Builder::new()
1885            .name("brep-history-runner".to_string())
1886            .spawn(move || thread_main(cmd_rx, reply_tx, thread_stop, thread_cam_cancel, thread_cam_sim_cancel))
1887            .expect("spawn brep-history-runner thread");
1888        Self {
1889            tx: Some(tx),
1890            rx,
1891            handle: Some(handle),
1892            run_buf: std::collections::VecDeque::new(),
1893            query_buf: std::collections::VecDeque::new(),
1894            mesh_import_buf: std::collections::VecDeque::new(),
1895            mesh_phase_buf: std::collections::VecDeque::new(),
1896            region_fit_buf: std::collections::VecDeque::new(),
1897            apply_choices_buf: std::collections::VecDeque::new(),
1898            step_probe_buf: std::collections::VecDeque::new(),
1899            topology_buf: std::collections::VecDeque::new(),
1900            sheet_lines_buf: std::collections::VecDeque::new(),
1901            cam_buf: std::collections::VecDeque::new(),
1902            cam_hold: false,
1903            cam_progress_buf: std::collections::VecDeque::new(),
1904            cam_cancel,
1905            cam_sim_buf: std::collections::VecDeque::new(),
1906            cam_sim_progress_buf: std::collections::VecDeque::new(),
1907            cam_sim_cancel,
1908            plugin_action_buf: std::collections::VecDeque::new(),
1909            plugin_install_buf: std::collections::VecDeque::new(),
1910            sent_plugin_revision: None,
1911            progress_buf: std::collections::VecDeque::new(),
1912            session_buf: std::collections::VecDeque::new(),
1913            worker_like: false,
1914            sent_library_revision: None,
1915            library_requested: false,
1916            stop,
1917        }
1918    }
1919
1920    /// A thread runner that hands the main side its session the way the wasm
1921    /// worker must: never by a blocking wait, only by an asked-for copy that
1922    /// crosses as JSON. What a native test runs to exercise the worker path.
1923    pub fn worker_like() -> Self {
1924        let mut runner = Self::new();
1925        runner.worker_like = true;
1926        runner
1927    }
1928
1929    /// Pull every ready reply off the channel and demux it into the run/query
1930    /// buffers (so a `poll_run` never swallows a query reply and vice versa).
1931    fn drain(&mut self) {
1932        while let Ok(reply) = self.rx.try_recv() {
1933            if let Some(answer) = self.file(reply) {
1934                self.session_buf.push_back(answer);
1935            }
1936        }
1937    }
1938
1939    /// Demux one reply into its buffer. A session export is handed back to the
1940    /// caller: [`HistoryRunner::session_for_main`]'s wait, or `drain`, which
1941    /// keeps it for [`HistoryRunner::poll_session`].
1942    fn file(&mut self, reply: Reply) -> Option<(u64, Option<brep_kernel::SessionTransfer>)> {
1943        match reply {
1944            Reply::SessionExport { generation, transfer } => return Some((generation, transfer)),
1945            Reply::ValidatedPlugins(reply) => self.plugin_install_buf.push_back(reply),
1946            Reply::PluginAction(reply) => self.plugin_action_buf.push_back(reply),
1947            Reply::Run(run) => self.run_buf.push_back(run),
1948            Reply::Query(query) => self.query_buf.push_back(query),
1949            Reply::MeshImport(reply) => self.mesh_import_buf.push_back(reply),
1950            Reply::MeshImportPhase(reply) => self.mesh_phase_buf.push_back(reply),
1951            Reply::RegionFit(reply) => self.region_fit_buf.push_back(reply),
1952            Reply::ApplyRegionChoices(reply) => self.apply_choices_buf.push_back(reply),
1953            Reply::StepProbe(reply) => self.step_probe_buf.push_back(reply),
1954            Reply::Topology(reply) => self.topology_buf.push_back(reply),
1955            Reply::SheetLines(reply) => self.sheet_lines_buf.push_back(reply),
1956            Reply::CamGenerate(reply) => self.cam_buf.push_back(reply),
1957            Reply::CamProgress(progress) => self.cam_progress_buf.push_back(progress),
1958            Reply::CamSimulate(reply) => self.cam_sim_buf.push_back(reply),
1959            Reply::CamSimProgress(progress) => self.cam_sim_progress_buf.push_back(progress),
1960            Reply::Progress(progress) => self.progress_buf.push_back(progress),
1961            Reply::NeedPartsLibrary => {
1962                // The thread dropped (or never had) the library this run
1963                // needs. Forget what we believe it holds so the next
1964                // `sync_parts_library` re-installs, and flag the refused
1965                // run for the caller to re-submit.
1966                self.sent_library_revision = None;
1967                self.library_requested = true;
1968            }
1969        }
1970        None
1971    }
1972}
1973
1974/// How long the main thread waits for the runner's session copy before it
1975/// replays the history instead (the copy of l500 takes ~8 ms).
1976#[cfg(not(target_arch = "wasm32"))]
1977const SESSION_EXPORT_WAIT: std::time::Duration = std::time::Duration::from_millis(250);
1978
1979#[cfg(not(target_arch = "wasm32"))]
1980impl Default for ThreadRunner {
1981    fn default() -> Self {
1982        Self::new()
1983    }
1984}
1985
1986/// The runner thread's whole life: block on the next command, batch it with every
1987/// other command already queued, COALESCE consecutive `Run`s (a `Run` immediately
1988/// followed by another `Run` — with no `Query`/`Reset` between — is dropped; only
1989/// the last of each consecutive group runs), then process the batch IN ORDER so a
1990/// `Reset` or a `Query` interleaved between two runs keeps its place. Exits when
1991/// the command sender is dropped (`recv` errors) or the reply receiver is gone (a
1992/// `send` errors — the main side went away).
1993///
1994/// `stop` is the cooperative cancel: raised by [`ThreadRunner::cancel`] on a
1995/// thread that has already been abandoned, it is checked before every feature
1996/// a run executes, so the abandoned thread finishes the feature it is on and
1997/// exits at the next boundary instead of running the rest of the history for
1998/// a receiver that is gone.
1999#[cfg(not(target_arch = "wasm32"))]
2000fn thread_main(
2001    cmd_rx: std::sync::mpsc::Receiver<Command>,
2002    reply_tx: std::sync::mpsc::Sender<Reply>,
2003    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
2004    cam_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
2005    cam_sim_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
2006) {
2007    let mut runner = crate::pipeline::SceneRunner::new();
2008    while let Ok(first) = cmd_rx.recv() {
2009        if stop.load(std::sync::atomic::Ordering::Relaxed) {
2010            return;
2011        }
2012        // Gather this command plus everything else already waiting.
2013        let mut batch = vec![first];
2014        loop {
2015            match cmd_rx.try_recv() {
2016                Ok(command) => batch.push(command),
2017                Err(_) => break, // Empty or Disconnected — process what we have.
2018            }
2019        }
2020        // A Run immediately followed by another Run is coalesced away (its result
2021        // would be overwritten before anything observed it); a Run followed by a
2022        // Query/Reset/end still runs, so interleaved work sees the right geometry.
2023        let mut run_here: Vec<bool> = vec![true; batch.len()];
2024        for i in 0..batch.len() {
2025            if matches!(batch[i], Command::Run { .. })
2026                && matches!(batch.get(i + 1), Some(Command::Run { .. }))
2027            {
2028                run_here[i] = false;
2029            }
2030        }
2031        // Process the KEPT commands in order through the SHARED `process_command`
2032        // (byte-identical work to the wasm worker's per-message step), sending each
2033        // reply it produces; a coalesced-away Run is skipped without touching the
2034        // runner, so interleaved Query/Reset still see the right geometry.
2035        for (i, command) in batch.into_iter().enumerate() {
2036            if !run_here[i] {
2037                continue;
2038            }
2039            // A CAM job's progress post also reads the cancel flag: `false`
2040            // back to the job is its cancel (see `CamSink`).
2041            let is_cam = matches!(command, Command::CamGenerate(_));
2042            if is_cam {
2043                cam_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
2044            }
2045            let is_sim = matches!(command, Command::CamSimulate(_));
2046            let mut progress = |reply: Reply| {
2047                // A lost receiver means the main side abandoned this thread:
2048                // stop at this boundary rather than finishing for nobody.
2049                let sent = reply_tx.send(reply).is_ok();
2050                if sent {
2051                    wake_main();
2052                }
2053                sent
2054                    && !stop.load(std::sync::atomic::Ordering::Relaxed)
2055                    && !(is_cam && cam_cancel.load(std::sync::atomic::Ordering::SeqCst))
2056                    && !(is_sim && cam_sim_cancel.load(std::sync::atomic::Ordering::SeqCst))
2057            };
2058            if let Some(reply) = process_command(&mut runner, command, &mut progress) {
2059                if reply_tx.send(reply).is_err() {
2060                    return; // The reply receiver is gone — the main side went away.
2061                }
2062                wake_main();
2063            }
2064        }
2065    }
2066}
2067
2068#[cfg(not(target_arch = "wasm32"))]
2069impl HistoryRunner for ThreadRunner {
2070    fn session_for_main(&mut self, generation: u64) -> SessionOnMain {
2071        if self.worker_like {
2072            return SessionOnMain::Unavailable;
2073        }
2074        let Some(tx) = &self.tx else { return SessionOnMain::Unavailable };
2075        if tx.send(Command::ExportSession { generation }).is_err() {
2076            return SessionOnMain::Unavailable;
2077        }
2078        let deadline = std::time::Instant::now() + SESSION_EXPORT_WAIT;
2079        loop {
2080            let left = deadline.saturating_duration_since(std::time::Instant::now());
2081            let Ok(reply) = self.rx.recv_timeout(left) else { return SessionOnMain::Unavailable };
2082            if let Some((answered, transfer)) = self.file(reply) {
2083                if answered != generation {
2084                    continue; // a late answer to an earlier ask
2085                }
2086                return transfer.map_or(SessionOnMain::Unavailable, SessionOnMain::Copied);
2087            }
2088        }
2089    }
2090    fn request_session(&mut self, generation: u64) -> bool {
2091        let mut command = Command::ExportSession { generation };
2092        if self.worker_like {
2093            // The worker's wire: the command crosses as JSON.
2094            let json = serde_json::to_string(&command).expect("serialize worker command");
2095            command = serde_json::from_str(&json).expect("parse worker command");
2096        }
2097        self.tx.as_ref().is_some_and(|tx| tx.send(command).is_ok())
2098    }
2099    fn poll_session(&mut self) -> Option<(u64, Option<brep_kernel::SessionTransfer>)> {
2100        self.drain();
2101        let (generation, transfer) = self.session_buf.pop_front()?;
2102        if !self.worker_like {
2103            return Some((generation, transfer));
2104        }
2105        // The worker's wire: the reply, copy and all, is serialized there and
2106        // parsed here.
2107        let json = serde_json::to_string(&Reply::SessionExport { generation, transfer }).expect("serialize worker reply");
2108        match serde_json::from_str(&json).expect("parse worker reply") {
2109            Reply::SessionExport { generation, transfer } => Some((generation, transfer)),
2110            _ => unreachable!("a session export parses back as one"),
2111        }
2112    }
2113    fn session_replay_on_main(&self) -> bool {
2114        false
2115    }
2116    fn submit_plugin_install(&mut self, request: PluginInstallRequest) -> bool {
2117        self.tx.as_ref().is_some_and(|tx| tx.send(Command::ValidatePlugins(request)).is_ok())
2118    }
2119    fn poll_plugin_install(&mut self) -> Option<PluginInstallReply> {
2120        self.drain();
2121        self.plugin_install_buf.pop_front()
2122    }
2123    fn sync_plugins(&mut self, revision: u64, fetch: &mut dyn FnMut() -> serde_json::Value) {
2124        if self.sent_plugin_revision != Some(revision) {
2125            if let Some(tx) = &self.tx {
2126                if tx.send(Command::SetPlugins { revision, packages: fetch() }).is_ok() {
2127                    self.sent_plugin_revision = Some(revision);
2128                }
2129            }
2130        }
2131    }
2132    fn submit_plugin_action(&mut self, request: PluginActionRequest) -> bool {
2133        self.tx.as_ref().is_some_and(|tx| tx.send(Command::PluginAction(request)).is_ok())
2134    }
2135    fn poll_plugin_action(&mut self) -> Option<PluginActionReply> {
2136        self.drain();
2137        self.plugin_action_buf.pop_front()
2138    }
2139
2140    fn submit_run(&mut self, request: brep_kernel::HistoryRequest, generation: u64) {
2141        if let Some(tx) = &self.tx {
2142            let _ = tx.send(Command::Run {
2143                request,
2144                generation,
2145                parts_library_revision: self.sent_library_revision.unwrap_or(0),
2146            });
2147        }
2148    }
2149
2150    fn sync_parts_library(
2151        &mut self,
2152        revision: u64,
2153        fetch: &mut dyn FnMut() -> brep_kernel::PartsLibraryMap,
2154    ) {
2155        if self.sent_library_revision == Some(revision) {
2156            return;
2157        }
2158        if let Some(tx) = &self.tx {
2159            let _ = tx.send(Command::SetPartsLibrary {
2160                library: fetch(),
2161                revision,
2162            });
2163            self.sent_library_revision = Some(revision);
2164        }
2165    }
2166
2167    fn poll_library_request(&mut self) -> bool {
2168        self.drain();
2169        std::mem::take(&mut self.library_requested)
2170    }
2171
2172    fn poll_run(&mut self) -> Option<RunReply> {
2173        self.drain();
2174        self.run_buf.pop_front()
2175    }
2176
2177    fn run_reply_waiting(&mut self) -> bool {
2178        self.drain();
2179        !self.run_buf.is_empty() || self.library_requested
2180    }
2181
2182    fn submit_query(&mut self, query: MeasureQuery) {
2183        if let Some(tx) = &self.tx {
2184            let _ = tx.send(Command::Query(query));
2185        }
2186    }
2187
2188    fn poll_query(&mut self) -> Option<MeasureReply> {
2189        self.drain();
2190        self.query_buf.pop_front()
2191    }
2192
2193    fn submit_mesh_import(&mut self, request: MeshImportRequest) {
2194        if let Some(tx) = &self.tx {
2195            let _ = tx.send(Command::MeshImport(request));
2196        }
2197    }
2198
2199    fn poll_mesh_import(&mut self) -> Option<MeshImportReply> {
2200        self.drain();
2201        self.mesh_import_buf.pop_front()
2202    }
2203
2204    fn poll_mesh_import_phase(&mut self) -> Option<MeshImportPhaseReply> {
2205        self.drain();
2206        self.mesh_phase_buf.pop_front()
2207    }
2208
2209    fn submit_region_fit(&mut self, job: RegionFitJob) -> bool {
2210        match &self.tx {
2211            Some(tx) => tx.send(Command::RegionFit(job)).is_ok(),
2212            None => false,
2213        }
2214    }
2215
2216    fn poll_region_fit(&mut self) -> Option<RegionFitReply> {
2217        self.drain();
2218        self.region_fit_buf.pop_front()
2219    }
2220
2221    fn submit_apply_region_choices(&mut self, job: ApplyRegionChoicesJob) -> bool {
2222        match &self.tx {
2223            Some(tx) => tx.send(Command::ApplyRegionChoices(job)).is_ok(),
2224            None => false,
2225        }
2226    }
2227
2228    fn poll_apply_region_choices(&mut self) -> Option<ApplyRegionChoicesReply> {
2229        self.drain();
2230        self.apply_choices_buf.pop_front()
2231    }
2232
2233    fn submit_step_probe(&mut self, request: StepProbeRequest) {
2234        if let Some(tx) = &self.tx {
2235            let _ = tx.send(Command::StepProbe(request));
2236        }
2237    }
2238
2239    fn poll_step_probe(&mut self) -> Option<StepProbeReply> {
2240        self.drain();
2241        self.step_probe_buf.pop_front()
2242    }
2243
2244    fn submit_topology(&mut self, request: TopologyRequest) {
2245        if let Some(tx) = &self.tx {
2246            let _ = tx.send(Command::Topology(request));
2247        }
2248    }
2249
2250    fn poll_topology(&mut self) -> Option<TopologyReply> {
2251        self.drain();
2252        self.topology_buf.pop_front()
2253    }
2254
2255    fn wait_topology(&mut self, timeout: std::time::Duration) -> bool {
2256        self.drain();
2257        let deadline = std::time::Instant::now() + timeout;
2258        while self.topology_buf.is_empty() {
2259            let now = std::time::Instant::now();
2260            if now >= deadline {
2261                return false;
2262            }
2263            match self.rx.recv_timeout(deadline - now) {
2264                Ok(reply) => {
2265                    self.file(reply);
2266                }
2267                Err(_) => return false,
2268            }
2269        }
2270        true
2271    }
2272
2273    fn submit_sheet_lines(&mut self, request: SheetLinesRequest) -> bool {
2274        match &self.tx {
2275            Some(tx) => tx.send(Command::SheetLines(request)).is_ok(),
2276            None => false,
2277        }
2278    }
2279
2280    fn poll_sheet_lines(&mut self) -> Option<SheetLinesReply> {
2281        self.drain();
2282        self.sheet_lines_buf.pop_front()
2283    }
2284
2285    fn submit_cam(&mut self, job: CamJob) -> bool {
2286        self.cam_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
2287        match &self.tx {
2288            Some(tx) => tx.send(Command::CamGenerate(job)).is_ok(),
2289            None => false,
2290        }
2291    }
2292
2293    fn poll_cam(&mut self) -> Option<CamReply> {
2294        self.drain();
2295        if self.cam_hold {
2296            return None;
2297        }
2298        self.cam_buf.pop_front()
2299    }
2300
2301    fn hold_cam_replies(&mut self, hold: bool) {
2302        self.cam_hold = hold;
2303    }
2304
2305    fn poll_cam_progress(&mut self) -> Option<CamProgress> {
2306        self.drain();
2307        let latest = self.cam_progress_buf.pop_back();
2308        self.cam_progress_buf.clear();
2309        latest
2310    }
2311
2312    fn cancel_cam(&mut self) {
2313        self.cam_cancel.store(true, std::sync::atomic::Ordering::SeqCst);
2314    }
2315
2316    fn submit_cam_sim(&mut self, job: CamSimJob) -> bool {
2317        // A cancel raised for an earlier chunk must not stop this one.
2318        self.cam_sim_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
2319        match &self.tx {
2320            Some(tx) => tx.send(Command::CamSimulate(job)).is_ok(),
2321            None => false,
2322        }
2323    }
2324
2325    fn poll_cam_sim(&mut self) -> Option<CamSimReply> {
2326        self.drain();
2327        self.cam_sim_buf.pop_front()
2328    }
2329
2330    fn poll_cam_sim_progress(&mut self) -> Option<CamSimProgress> {
2331        self.drain();
2332        let latest = self.cam_sim_progress_buf.pop_back();
2333        self.cam_sim_progress_buf.clear();
2334        latest
2335    }
2336
2337    fn cancel_cam_sim(&mut self) {
2338        self.cam_sim_cancel.store(true, std::sync::atomic::Ordering::SeqCst);
2339    }
2340
2341    fn poll_progress(&mut self) -> Option<RunProgress> {
2342        self.drain();
2343        let latest = self.progress_buf.pop_back();
2344        self.progress_buf.clear();
2345        latest
2346    }
2347
2348    /// Abandon the thread: raise its stop flag, close its channels, and spawn a
2349    /// fresh thread with a fresh registry. The old thread cannot be interrupted
2350    /// inside a feature — it finishes the one it is on (burning CPU until
2351    /// then), sees the flag, and exits. Always `true`: there is always a
2352    /// thread to replace.
2353    fn cancel(&mut self) -> bool {
2354        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
2355        self.tx.take();
2356        self.handle.take();
2357        let worker_like = self.worker_like;
2358        *self = Self::new();
2359        self.worker_like = worker_like;
2360        true
2361    }
2362
2363    fn reset(&mut self) {
2364        self.sent_plugin_revision = None;
2365        self.plugin_action_buf.clear();
2366        if let Some(tx) = &self.tx {
2367            let _ = tx.send(Command::Reset);
2368        }
2369        // A reset is a wholesale document switch: any replies still buffered from
2370        // the old model are stale — drop them (a fresh run/query supersedes).
2371        self.run_buf.clear();
2372        self.query_buf.clear();
2373        self.mesh_import_buf.clear();
2374        self.mesh_phase_buf.clear();
2375        self.region_fit_buf.clear();
2376        self.apply_choices_buf.clear();
2377        self.step_probe_buf.clear();
2378        self.topology_buf.clear();
2379        self.sheet_lines_buf.clear();
2380        self.progress_buf.clear();
2381        self.session_buf.clear();
2382        // `Command::Reset` clears the thread's kernel store, library included,
2383        // so what we believe it holds is void.
2384        self.sent_library_revision = None;
2385        self.library_requested = false;
2386    }
2387}
2388
2389#[cfg(not(target_arch = "wasm32"))]
2390impl Drop for ThreadRunner {
2391    fn drop(&mut self) {
2392        // Closing a document or cancelling an import preview must not block
2393        // the UI on reconstruction. Closing the channel lets the worker exit
2394        // and release its registry once already-submitted work finishes.
2395        self.tx.take();
2396        self.handle.take();
2397    }
2398}
2399