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
1048/// Measure `query` against `runner`'s resident geometry and emit the object-info
1049/// JSON FRAGMENT — EXACTLY the fields [`crate::metadata::EngineState::object_info_json`]
1050/// emits for that kind EXCEPT `name` and `creatingFeature` (the main thread injects
1051/// those from its eager provenance, so the merged output is byte-identical to the
1052/// pre-seam in-process result). Shared verbatim by the Inline and thread runners so
1053/// both produce the identical fragment. A missing handle / kernel error yields
1054/// `{ "ok": false, "message": .. }` (main injects `name`).
1055fn measure_json(runner: &crate::pipeline::SceneRunner, query: &MeasureQuery) -> String {
1056    let Some(handle) = runner.handle_of(&query.owner) else {
1057        return serde_json::json!({
1058            "ok": false,
1059            "message": format!("solid '{}' has no resident geometry", query.owner),
1060        })
1061        .to_string();
1062    };
1063    match query.kind {
1064        MeasureKind::Inspect => {
1065            let issues: Vec<serde_json::Value> = match brep_kernel::validate_handle_native(handle) {
1066                Ok(issues) => issues.into_iter().map(|(severity, message)| serde_json::json!({ "severity": severity, "message": message })).collect(),
1067                Err(error) => vec![serde_json::json!({ "severity": "error", "message": format!("validation unavailable: {error}") })],
1068            };
1069            let (volume, volume_error) = match brep_kernel::mass_measures_handle_native(handle) {
1070                Ok(properties) => (Some(properties.volume), None),
1071                Err(error) => (None, Some(error)),
1072            };
1073            serde_json::json!({ "ok": true, "kind": "inspect", "issues": issues, "volume": volume, "volumeError": volume_error }).to_string()
1074        }
1075        MeasureKind::Solid => {
1076            match brep_kernel::mass_properties_handle_native(handle, query.density) {
1077                Ok(properties) => {
1078                    let edge_total =
1079                        brep_kernel::solid_edge_length_total_native(handle).unwrap_or(0.0);
1080                    serde_json::json!({
1081                        "ok": true,
1082                        "kind": "solid",
1083                        "volume": properties.volume,
1084                        "surfaceArea": properties.surface_area,
1085                        "edgeLengthTotal": edge_total,
1086                        "density": properties.density,
1087                        "weight": properties.mass,
1088                    })
1089                    .to_string()
1090                }
1091                Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
1092            }
1093        }
1094        MeasureKind::Face => match brep_kernel::face_measurements_native(handle, &query.entity) {
1095            Ok((area, edge_total, surface_type)) => {
1096                let dimensions =
1097                    brep_kernel::face_carrier_dimensions_native(handle, &query.entity)
1098                        .ok()
1099                        .flatten();
1100                // A partial revolution of a straight line is a "Surface of
1101                // revolution" to the kernel and a cylinder to the user.
1102                let surface_type = dimensions.as_ref().map_or(surface_type, |d| d.label);
1103                let mut fragment = serde_json::json!({
1104                    "ok": true,
1105                    "kind": "face",
1106                    "solid": query.owner,
1107                    "surfaceType": surface_type,
1108                    "area": area,
1109                    "edgeLengthTotal": edge_total,
1110                });
1111                insert_dimensions(&mut fragment, dimensions.as_ref());
1112                fragment.to_string()
1113            }
1114            Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
1115        },
1116        MeasureKind::Edge => match brep_kernel::edge_length_native(handle, &query.entity) {
1117            Ok(length) => {
1118                let dimensions =
1119                    brep_kernel::edge_carrier_dimensions_native(handle, &query.entity)
1120                        .ok()
1121                        .flatten();
1122                let mut fragment = serde_json::json!({
1123                    "ok": true,
1124                    "kind": "edge",
1125                    "solid": query.owner,
1126                    "length": length,
1127                });
1128                if let Some(dimensions) = &dimensions {
1129                    fragment["curveType"] = serde_json::Value::from(dimensions.label);
1130                }
1131                insert_dimensions(&mut fragment, dimensions.as_ref());
1132                fragment.to_string()
1133            }
1134            Err(error) => serde_json::json!({ "ok": false, "message": error }).to_string(),
1135        },
1136    }
1137}
1138
1139/// Add a carrier's named dimensions (`radius`, `diameter`, `halfAngleDeg`,
1140/// `majorRadius`, `minorRadius`, `sweepDeg`) to an object-info fragment.
1141fn insert_dimensions(
1142    fragment: &mut serde_json::Value,
1143    dimensions: Option<&brep_kernel::CarrierDimensions>,
1144) {
1145    let (Some(dimensions), Some(object)) = (dimensions, fragment.as_object_mut()) else {
1146        return;
1147    };
1148    for (key, value) in &dimensions.values {
1149        object.insert((*key).to_string(), serde_json::Value::from(*value));
1150    }
1151}
1152
1153/// The default, SYNCHRONOUS runner: runs on submit, stashes the reply for an
1154/// immediate poll. Behavior-identical to the pre-seam in-process run.
1155pub struct InlineRunner {
1156    /// The scene-free history runner it owns (delta baseline lives here).
1157    runner: crate::pipeline::SceneRunner,
1158    /// Completed replies awaiting a poll. For Inline this holds exactly one entry
1159    /// between a `submit_run` and the immediately-following `poll_run`.
1160    pending: std::collections::VecDeque<RunReply>,
1161    /// Completed measurement replies awaiting a poll (computed synchronously on
1162    /// `submit_query`, popped on `poll_query`) — the synchronous mirror of the
1163    /// thread runner's query buffer, so the object-info path resolves same-call.
1164    query_pending: std::collections::VecDeque<MeasureReply>,
1165    mesh_import_pending: std::collections::VecDeque<MeshImportReply>,
1166    mesh_phase_pending: std::collections::VecDeque<MeshImportPhaseReply>,
1167    region_fit_pending: std::collections::VecDeque<RegionFitReply>,
1168    apply_choices_pending: std::collections::VecDeque<ApplyRegionChoicesReply>,
1169    step_probe_pending: std::collections::VecDeque<StepProbeReply>,
1170    topology_pending: std::collections::VecDeque<TopologyReply>,
1171    sheet_lines_pending: std::collections::VecDeque<SheetLinesReply>,
1172    plugin_action_pending: std::collections::VecDeque<PluginActionReply>,
1173    plugin_install_pending: std::collections::VecDeque<PluginInstallReply>,
1174}
1175
1176impl InlineRunner {
1177    pub fn new() -> Self {
1178        Self {
1179            runner: crate::pipeline::SceneRunner::new(),
1180            pending: std::collections::VecDeque::new(),
1181            query_pending: std::collections::VecDeque::new(),
1182            mesh_import_pending: std::collections::VecDeque::new(),
1183            mesh_phase_pending: std::collections::VecDeque::new(),
1184            region_fit_pending: std::collections::VecDeque::new(),
1185            apply_choices_pending: std::collections::VecDeque::new(),
1186            step_probe_pending: std::collections::VecDeque::new(),
1187            topology_pending: std::collections::VecDeque::new(),
1188            sheet_lines_pending: std::collections::VecDeque::new(),
1189            plugin_action_pending: std::collections::VecDeque::new(),
1190            plugin_install_pending: std::collections::VecDeque::new(),
1191        }
1192    }
1193}
1194
1195impl HistoryRunner for InlineRunner {
1196    fn submit_plugin_install(&mut self, request: PluginInstallRequest) -> bool {
1197        self.plugin_install_pending.push_back(validate_plugins(request));
1198        true
1199    }
1200    fn poll_plugin_install(&mut self) -> Option<PluginInstallReply> {
1201        self.plugin_install_pending.pop_front()
1202    }
1203    fn sync_plugins(&mut self, revision: u64, fetch: &mut dyn FnMut() -> serde_json::Value) {
1204        if self.runner.plugin_revision != Some(revision) {
1205            self.runner.set_plugins(revision, fetch());
1206        }
1207    }
1208    fn submit_plugin_action(&mut self, request: PluginActionRequest) -> bool {
1209        self.plugin_action_pending.push_back(self.runner.plugin_action(request));
1210        true
1211    }
1212    fn poll_plugin_action(&mut self) -> Option<PluginActionReply> {
1213        self.plugin_action_pending.pop_front()
1214    }
1215
1216    fn submit_run(&mut self, request: brep_kernel::HistoryRequest, generation: u64) {
1217        let serial = brep_kernel::assembly_session_serial();
1218        let output = self.runner.run(&request);
1219        let after = brep_kernel::assembly_session_serial();
1220        self.runner.session_of = (after != serial).then_some((generation, after));
1221        self.pending.push_back(RunReply { generation, output });
1222    }
1223
1224    /// The run executed on this (the caller's) thread: its session is already
1225    /// here unless something has replaced it since.
1226    fn session_for_main(&mut self, generation: u64) -> SessionOnMain {
1227        match self.runner.session_of {
1228            Some((ran, serial)) if ran == generation && serial == brep_kernel::assembly_session_serial() => {
1229                SessionOnMain::Resident
1230            }
1231            _ => SessionOnMain::Unavailable,
1232        }
1233    }
1234
1235    /// Nothing to send: Inline runs on the CALLER's thread against the CALLER's
1236    /// kernel store, so the library the caller would hand over is already the
1237    /// one this run resolves against. (Which is also why Inline never needs the
1238    /// preflight — there is only one store, and the caller seeds it directly.)
1239    fn sync_parts_library(
1240        &mut self,
1241        _revision: u64,
1242        _fetch: &mut dyn FnMut() -> brep_kernel::PartsLibraryMap,
1243    ) {
1244    }
1245
1246    fn poll_run(&mut self) -> Option<RunReply> {
1247        self.pending.pop_front()
1248    }
1249
1250    fn submit_query(&mut self, query: MeasureQuery) {
1251        let result = measure_json(&self.runner, &query);
1252        self.query_pending.push_back(MeasureReply { id: query.id, result });
1253    }
1254
1255    fn poll_query(&mut self) -> Option<MeasureReply> {
1256        self.query_pending.pop_front()
1257    }
1258
1259    fn submit_mesh_import(&mut self, request: MeshImportRequest) {
1260        let phases = &mut self.mesh_phase_pending;
1261        let reply = reconstruct_mesh_phased(request, &mut |phase| {
1262            phases.push_back(phase);
1263            true
1264        });
1265        self.mesh_import_pending.push_back(reply);
1266    }
1267
1268    fn poll_mesh_import(&mut self) -> Option<MeshImportReply> {
1269        self.mesh_import_pending.pop_front()
1270    }
1271
1272    fn poll_mesh_import_phase(&mut self) -> Option<MeshImportPhaseReply> {
1273        self.mesh_phase_pending.pop_front()
1274    }
1275
1276    fn submit_region_fit(&mut self, job: RegionFitJob) -> bool {
1277        self.region_fit_pending.push_back(region_fit_reply(job));
1278        true
1279    }
1280
1281    fn poll_region_fit(&mut self) -> Option<RegionFitReply> {
1282        self.region_fit_pending.pop_front()
1283    }
1284
1285    fn submit_apply_region_choices(&mut self, job: ApplyRegionChoicesJob) -> bool {
1286        self.apply_choices_pending.push_back(apply_region_choices_reply(job));
1287        true
1288    }
1289
1290    fn poll_apply_region_choices(&mut self) -> Option<ApplyRegionChoicesReply> {
1291        self.apply_choices_pending.pop_front()
1292    }
1293
1294    fn submit_step_probe(&mut self, request: StepProbeRequest) {
1295        self.step_probe_pending.push_back(probe_step(request));
1296    }
1297
1298    fn poll_step_probe(&mut self) -> Option<StepProbeReply> {
1299        self.step_probe_pending.pop_front()
1300    }
1301
1302    fn submit_topology(&mut self, request: TopologyRequest) {
1303        self.topology_pending.push_back(topology_reply(request));
1304    }
1305
1306    fn poll_topology(&mut self) -> Option<TopologyReply> {
1307        self.topology_pending.pop_front()
1308    }
1309
1310    /// Runs the pass at once, on the caller's thread: an inline runner's
1311    /// registry IS the caller's, so the answer is ready for the next poll.
1312    fn submit_sheet_lines(&mut self, request: SheetLinesRequest) -> bool {
1313        self.sheet_lines_pending.push_back(sheet_lines_reply(request));
1314        true
1315    }
1316
1317    fn poll_sheet_lines(&mut self) -> Option<SheetLinesReply> {
1318        self.sheet_lines_pending.pop_front()
1319    }
1320
1321    fn reset(&mut self) {
1322        self.runner.reset();
1323    }
1324}
1325
1326impl Default for InlineRunner {
1327    fn default() -> Self {
1328        Self::new()
1329    }
1330}
1331
1332// ===========================================================================
1333// Shared run/query PROTOCOL (M3b): the `Command`/`Reply` message pair and the
1334// `process_command` step. Both async runners speak it — the native `ThreadRunner`
1335// ships the enums over `mpsc` (no serialization), and the wasm `WorkerRunner`
1336// serializes them to JSON for `postMessage`. Hence the serde derives (the enums
1337// carry serde types: `HistoryRequest`/`MeasureQuery`/`RunReply`/`MeasureReply`)
1338// and `process_command` being un-gated + shared so both drivers do the SAME work.
1339// ===========================================================================
1340
1341/// A command sent main → runner (thread channel OR worker `postMessage`) over one
1342/// ordered stream (so a `Reset` before a `Run` stays before it). `Run` carries the
1343/// whole request; the driver coalesces consecutive `Run`s to shed a slider drag's
1344/// backlog (the thread in `thread_main`, the worker's main side in `WorkerRunner`).
1345#[derive(serde::Serialize, serde::Deserialize)]
1346pub enum Command {
1347    ValidatePlugins(PluginInstallRequest),
1348    SetPlugins { revision: u64, packages: serde_json::Value },
1349    PluginAction(PluginActionRequest),
1350    Run {
1351        request: brep_kernel::HistoryRequest,
1352        generation: u64,
1353        /// The [`brep_kernel::parts_library_revision`] this run was built
1354        /// against. The runner refuses to execute a run stamped for a library
1355        /// it does not hold — see [`process_command`].
1356        #[serde(default)]
1357        parts_library_revision: u64,
1358    },
1359    /// Install the parts library on the runner's OWN kernel store. Sent only
1360    /// when the library actually changes (insert, document load, refresh),
1361    /// never per run: it carries the whole embedded-part payload, which for an
1362    /// imported STEP assembly is megabytes, and stringifying that on the
1363    /// browser's main thread once per edit is what froze the UI.
1364    ///
1365    /// Deliberately its OWN command rather than an optional field on `Run`:
1366    /// both drivers COALESCE consecutive runs (see `thread_main` and
1367    /// `WorkerRunner::submit_run`), so a library riding on a run could be
1368    /// dropped with it. A `SetPartsLibrary` is never coalesced away, and the
1369    /// stream is ordered, so it always lands before the run that needs it.
1370    SetPartsLibrary {
1371        library: brep_kernel::PartsLibraryMap,
1372        revision: u64,
1373    },
1374    Query(MeasureQuery),
1375    MeshImport(MeshImportRequest),
1376    RegionFit(RegionFitJob),
1377    ApplyRegionChoices(ApplyRegionChoicesJob),
1378    StepProbe(StepProbeRequest),
1379    Topology(TopologyRequest),
1380    SheetLines(SheetLinesRequest),
1381    /// Generate ONE CAM operation (never coalesced: every job answers).
1382    CamGenerate(CamJob),
1383    /// One CAM simulation command (never coalesced: every job answers).
1384    CamSimulate(CamSimJob),
1385    Reset,
1386    /// Copy the assembly session the run of `generation` left here. A worker
1387    /// sends the copy (kernel solids included) back as JSON.
1388    ExportSession { generation: u64 },
1389}
1390
1391/// A reply sent runner → main; the main side demuxes it into per-kind buffers.
1392#[derive(serde::Serialize, serde::Deserialize)]
1393pub enum Reply {
1394    ValidatedPlugins(PluginInstallReply),
1395    PluginAction(PluginActionReply),
1396    Run(RunReply),
1397    Query(MeasureReply),
1398    MeshImport(MeshImportReply),
1399    /// A phase of an interactive mesh import, posted before its `MeshImport`.
1400    MeshImportPhase(MeshImportPhaseReply),
1401    RegionFit(RegionFitReply),
1402    ApplyRegionChoices(ApplyRegionChoicesReply),
1403    StepProbe(StepProbeReply),
1404    Topology(TopologyReply),
1405    SheetLines(SheetLinesReply),
1406    CamGenerate(CamReply),
1407    /// A CAM job's progress, posted from inside the job.
1408    CamProgress(CamProgress),
1409    CamSimulate(CamSimReply),
1410    /// A simulation chunk's progress, posted between motions.
1411    CamSimProgress(CamSimProgress),
1412    /// The runner REFUSED a run because its resident parts library could not
1413    /// serve it (a part the request references is missing, or the run was
1414    /// stamped for a different library revision). No geometry was touched; the
1415    /// main side re-sends the library and re-submits. Refusing is the whole
1416    /// point — running with the wrong library would be silently wrong
1417    /// geometry, which is far worse than one extra round trip.
1418    NeedPartsLibrary,
1419    /// A feature of the in-flight run is about to execute (see
1420    /// [`RunProgress`]). Posted from INSIDE `process_command`, before its
1421    /// `Reply::Run`; the main side keeps only the latest.
1422    Progress(RunProgress),
1423    /// The answer to `Command::ExportSession`.
1424    SessionExport { generation: u64, transfer: Option<brep_kernel::SessionTransfer> },
1425}
1426
1427/// The probe itself — the one parse of a structured STEP import (see
1428/// `EngineState::submit_step_probe`), run wherever the runner runs.
1429fn probe_step(request: StepProbeRequest) -> StepProbeReply {
1430    StepProbeReply {
1431        id: request.id,
1432        // The same probe answers an IGES file, whose structure is subfigure
1433        // instances; the app's choice and import consume either alike.
1434        result: if crate::engine_state::is_iges_text(&request.text) {
1435            brep_kernel::read_iges_assembly(&request.text)
1436        } else {
1437            brep_kernel::read_step_assembly(&request.text)
1438        },
1439    }
1440}
1441
1442/// The import without its phase stream (every runner posts the phased one;
1443/// the runner's tests read the reply alone).
1444#[cfg_attr(not(test), allow(dead_code))]
1445fn reconstruct_mesh(request: MeshImportRequest) -> MeshImportReply {
1446    reconstruct_mesh_phased(request, &mut |_| true)
1447}
1448
1449/// [`reconstruct_mesh`], posting each phase of an interactive import to
1450/// `phase` as it completes when the request asks for them.
1451fn reconstruct_mesh_phased(
1452    request: MeshImportRequest,
1453    phase: &mut dyn FnMut(MeshImportPhaseReply) -> bool,
1454) -> MeshImportReply {
1455    let id = request.id;
1456    let phases = request.phases;
1457    let result = (|| {
1458        use brep_reconstruction::stl_conversion::{
1459            binary_stl_coordinate_precision_tolerance, convert_stl_mesh_to_step_with_colors,
1460        };
1461        use brep_reconstruction::{Mesh, Vec3};
1462
1463        // A 3MF build's placements, kept only to name each body afterwards.
1464        let mut instances = Vec::new();
1465        let mut reader_messages = Vec::new();
1466        // A 3MF's per-triangle colours (its base materials), parallel to the
1467        // soup's triangles; empty for STL and OBJ, which carry none.
1468        let mut triangle_colors: Vec<Option<[u8; 3]>> = Vec::new();
1469        let (mesh, positions, indices, coordinate_precision_tolerance) = match request.format {
1470            MeshImportFormat::Stl => {
1471                use brep_reconstruction::stl::{parse_stl_bytes, StlFormat, StlReadOptions};
1472                let read_options = StlReadOptions {
1473                    weld_tolerance: (request.options.weld_tolerance >= 0.0)
1474                        .then_some(request.options.weld_tolerance),
1475                };
1476                let imported = parse_stl_bytes(&request.bytes, &read_options)
1477                    .map_err(|error| format!("STL import failed: {error}"))?;
1478                let positions = imported
1479                    .mesh
1480                    .vertices
1481                    .iter()
1482                    .flat_map(|point| [point.x, point.y, point.z])
1483                    .collect::<Vec<_>>();
1484                let indices = imported
1485                    .mesh
1486                    .triangles
1487                    .iter()
1488                    .flatten()
1489                    .copied()
1490                    .collect::<Vec<_>>();
1491                let precision = if imported.format == StlFormat::Binary {
1492                    binary_stl_coordinate_precision_tolerance(&imported.mesh)
1493                } else {
1494                    0.0
1495                };
1496                if !imported.dropped_facets.is_empty() {
1497                    reader_messages.push(format!(
1498                        "the STL reader dropped {} of {} facet(s) with no area: {}",
1499                        imported.dropped_facets.len(),
1500                        imported.source_triangle_count,
1501                        imported.dropped_facets.iter().take(8).map(ToString::to_string).collect::<Vec<_>>().join("; ")
1502                    ));
1503                }
1504                (imported.mesh, positions, indices, precision)
1505            }
1506            MeshImportFormat::Obj => {
1507                let text = std::str::from_utf8(&request.bytes)
1508                    .map_err(|_| "OBJ import failed: file is not UTF-8 text".to_string())?;
1509                let obj = brep_kernel::read_obj(text)
1510                    .map_err(|error| format!("OBJ import failed: {error}"))?;
1511                let vertices = obj
1512                    .positions
1513                    .chunks_exact(3)
1514                    .map(|point| Vec3::new(point[0], point[1], point[2]))
1515                    .collect::<Vec<_>>();
1516                let triangles = obj
1517                    .indices
1518                    .chunks_exact(3)
1519                    .map(|triangle| [triangle[0], triangle[1], triangle[2]])
1520                    .collect::<Vec<_>>();
1521                (
1522                    Mesh::new(vertices, triangles),
1523                    obj.positions,
1524                    obj.indices,
1525                    0.0,
1526                )
1527            }
1528            // The 3MF reader has already applied the file's unit and every
1529            // build/component transform, so what arrives here is the same kind
1530            // of millimetre triangle soup an STL carries — including a build
1531            // that places SEVERAL instances, which is several bodies in that
1532            // one buffer. The chain splits a soup into its vertex-connected
1533            // components and reconstructs each as its own body, so the whole
1534            // build goes through in ONE call and the poses are already in the
1535            // coordinates.
1536            MeshImportFormat::ThreeMf => {
1537                let model = brep_kernel::read_3mf(&request.bytes)
1538                    .map_err(|error| format!("3MF import failed: {error}"))?;
1539                if let Some(instance) = model.instances.iter().find(|i| model.meshes[i.mesh].beam_lattice.is_some()) {
1540                    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")));
1541                }
1542                if !model.textures.is_empty() {
1543                    reader_messages.push("3MF texture images and UV coordinates cannot be displayed on reconstructed CAD faces or retained by CAD scene export.".to_owned());
1544                }
1545                instances = model.instances;
1546                triangle_colors = model.triangle_colors;
1547                let vertices = model
1548                    .positions
1549                    .chunks_exact(3)
1550                    .map(|point| Vec3::new(point[0], point[1], point[2]))
1551                    .collect::<Vec<_>>();
1552                let triangles = model
1553                    .indices
1554                    .chunks_exact(3)
1555                    .map(|triangle| [triangle[0], triangle[1], triangle[2]])
1556                    .collect::<Vec<_>>();
1557                (
1558                    Mesh::new(vertices, triangles),
1559                    model.positions,
1560                    model.indices,
1561                    0.0,
1562                )
1563            }
1564        };
1565        let mut options = request.options;
1566        options.coordinate_precision_tolerance = options.coordinate_precision_tolerance
1567            .max(coordinate_precision_tolerance);
1568        if phases {
1569            // `false` back from a post: nobody is listening any more (a
1570            // cancelled preview on the native thread) — stop here.
1571            let listening = phase(MeshImportPhaseReply {
1572                id,
1573                phase: MeshImportPhase::Mesh { positions: positions.clone(), indices: indices.clone() },
1574            });
1575            if !listening {
1576                return Err("cancelled".to_string());
1577            }
1578            let regions = brep_reconstruction::import_session::analyze_regions(&positions, &indices, &options);
1579            let listening = phase(MeshImportPhaseReply {
1580                id,
1581                phase: match regions {
1582                    Ok(regions) => MeshImportPhase::Regions(regions),
1583                    Err(error) => MeshImportPhase::RegionsFailed(error),
1584                },
1585            });
1586            if !listening {
1587                return Err("cancelled".to_string());
1588            }
1589        }
1590        convert_stl_mesh_to_step_with_colors(
1591            &mesh,
1592            &positions,
1593            Some(&indices),
1594            (!triangle_colors.is_empty()).then_some(triangle_colors.as_slice()),
1595            &options,
1596            "Imported mesh",
1597            "MM",
1598            "",
1599        )
1600        .map(|mut output| {
1601            name_bodies(&mut output.report, &instances);
1602            output.report.messages.splice(0..0, reader_messages);
1603            output
1604        })
1605        .map_err(|error| format!("RANSAC reconstruction failed: {error}"))
1606    })();
1607    MeshImportReply { id, result }
1608}
1609
1610/// Give each body the name of the 3MF object its first source triangle came
1611/// from, so a refusal can say WHICH object is missing. Bodies are found in the
1612/// flattened soup the reader laid out instance by instance.
1613fn name_bodies(
1614    report: &mut brep_reconstruction::stl_conversion::StlConversionReport,
1615    instances: &[brep_kernel::ThreeMfInstance],
1616) {
1617    for component in &mut report.components {
1618        component.source_name = instances
1619            .iter()
1620            .find(|instance| {
1621                (instance.first_triangle..instance.first_triangle + instance.triangle_count)
1622                    .contains(&component.first_triangle)
1623            })
1624            .and_then(|instance| instance.name.clone());
1625    }
1626}
1627
1628/// The notice for bodies a multi-body import left out, one clause per body,
1629/// named by the source's own name when it has one; `None` when every body was
1630/// built.
1631pub(crate) fn refused_bodies_notice(
1632    report: &brep_reconstruction::stl_conversion::StlConversionReport,
1633) -> Option<String> {
1634    let refused = report
1635        .components
1636        .iter()
1637        .filter_map(|component| {
1638            component.refusal.as_ref().map(|reason| {
1639                let body = match &component.source_name {
1640                    Some(name) => format!("body {} \"{name}\"", component.index + 1),
1641                    None => format!(
1642                        "body {} (from source triangle {})",
1643                        component.index + 1,
1644                        component.first_triangle
1645                    ),
1646                };
1647                format!("{body}: {reason}")
1648            })
1649        })
1650        .collect::<Vec<_>>();
1651    (!refused.is_empty()).then(|| {
1652        format!(
1653            "mesh import: {} of {} bodies could not be reconstructed and are NOT in the model — {}",
1654            refused.len(),
1655            report.components.len(),
1656            refused.join("; ")
1657        )
1658    })
1659}
1660
1661/// Execute ONE [`Command`] against `runner` and return the [`Reply`] it produces,
1662/// if any. The shared step both async drivers run: the native `thread_main`
1663/// calls it for each (post-coalescing) command on the runner thread; the wasm
1664/// `WorkerRunner`'s `worker_entry` calls it per `postMessage` on the worker.
1665/// `Run` → a [`Reply::Run`]; `Query` → a [`Reply::Query`]; `Reset` drops the delta
1666/// baseline AND the runner's OWN kernel history cache (the resident registry lives
1667/// with the runner — thread or worker — not on main) and yields no reply.
1668///
1669/// `progress` is called before every feature a `Run` actually executes, with
1670/// the report the driver should ship as [`Reply::Progress`]; returning `false`
1671/// stops the run at that boundary (the native thread's cooperative cancel —
1672/// the worker is terminated instead and always returns `true`).
1673pub fn process_command(
1674    runner: &mut crate::pipeline::SceneRunner,
1675    command: Command,
1676    progress: &mut dyn FnMut(Reply) -> bool,
1677) -> Option<Reply> {
1678    match command {
1679        Command::ValidatePlugins(request) => Some(Reply::ValidatedPlugins(validate_plugins(request))),
1680        Command::SetPlugins { revision, packages } => {
1681            runner.set_plugins(revision, packages);
1682            None
1683        }
1684        Command::PluginAction(request) => Some(Reply::PluginAction(runner.plugin_action(request))),
1685        Command::Run {
1686            request,
1687            generation,
1688            parts_library_revision,
1689        } => {
1690            // PREFLIGHT (see `Reply::NeedPartsLibrary`). Two independent
1691            // checks, because neither alone is enough:
1692            //
1693            // * the revision stamp catches CHANGED content the sender knows
1694            //   about but this store has not received;
1695            // * `missing_library_parts` catches content that is simply GONE
1696            //   here — the orphan GC at the end of every run drops entries no
1697            //   ACOMP in THAT run referenced, so an undo to zero components
1698            //   empties this store while the sender's (which never ran) keeps
1699            //   everything and its revision never moves. Only looking at the
1700            //   actual content sees that.
1701            let stale = match runner.parts_library_revision {
1702                Some(installed) => installed != parts_library_revision,
1703                // Nothing installed yet. Accept a run stamped 0 — that is
1704                // either an empty library or a caller driving `submit_run`
1705                // directly (the runner tests); the content preflight below is
1706                // what actually protects the run. A non-zero stamp with nothing
1707                // installed IS a gap: refuse it.
1708                None => parts_library_revision != 0,
1709            };
1710            // Only a part the sender DID send and this store has since lost is
1711            // worth asking for again. One it never sent is a dangling reference
1712            // in the document itself: run it, so the ACOMP feature reports it
1713            // the way it always has. (An install inserts every incoming name,
1714            // so right after one this set can only be empty — which is what
1715            // makes the ask-and-retry terminate.)
1716            let recoverable = brep_kernel::missing_library_parts(&request)
1717                .iter()
1718                .any(|name| runner.parts_library_names.contains(name));
1719            if stale || recoverable {
1720                runner.parts_library_revision = None;
1721                return Some(Reply::NeedPartsLibrary);
1722            }
1723            let serial = brep_kernel::assembly_session_serial();
1724            let output = runner.run_observed(&request, &mut |event| {
1725                progress(Reply::Progress(RunProgress {
1726                    generation,
1727                    index: event.index,
1728                    total: event.total,
1729                    feature_id: event.id.to_string(),
1730                    feature_type: event.feature_type.to_string(),
1731                }))
1732            });
1733            let after = brep_kernel::assembly_session_serial();
1734            runner.session_of = (after != serial).then_some((generation, after));
1735            Some(Reply::Run(RunReply { generation, output }))
1736        }
1737        Command::SetPartsLibrary { library, revision } => {
1738            runner.parts_library_names = library.keys().cloned().collect();
1739            brep_kernel::install_parts_library(&library);
1740            runner.parts_library_revision = Some(revision);
1741            None
1742        }
1743        Command::Query(query) => {
1744            let result = measure_json(runner, &query);
1745            Some(Reply::Query(MeasureReply { id: query.id, result }))
1746        }
1747        Command::MeshImport(request) => Some(Reply::MeshImport(reconstruct_mesh_phased(request, &mut |phase| {
1748            progress(Reply::MeshImportPhase(phase))
1749        }))),
1750        Command::RegionFit(job) => Some(Reply::RegionFit(region_fit_reply(job))),
1751        Command::ApplyRegionChoices(job) => Some(Reply::ApplyRegionChoices(apply_region_choices_reply(job))),
1752        Command::StepProbe(request) => Some(Reply::StepProbe(probe_step(request))),
1753        Command::Topology(request) => Some(Reply::Topology(topology_reply(request))),
1754        Command::SheetLines(request) => Some(Reply::SheetLines(sheet_lines_reply(request))),
1755        Command::CamGenerate(job) => Some(Reply::CamGenerate(cam_generate_reply(job, progress))),
1756        Command::CamSimulate(job) => Some(Reply::CamSimulate(cam_sim_reply(job, progress))),
1757        Command::Reset => {
1758            // A document switch: drop the delta baseline AND this runner's OWN kernel
1759            // history cache (the resident registry lives here, not on main), mirroring
1760            // `set_history_json`'s main-thread clear so a new model rebuilds fully and
1761            // the old model's handles are freed.
1762            runner.reset();
1763            brep_kernel::clear_history_cache();
1764            cam_sim_clear();
1765            pre_op_stock_clear();
1766            None
1767        }
1768        Command::ExportSession { generation } => {
1769            Some(Reply::SessionExport { generation, transfer: runner.export_session(generation) })
1770        }
1771    }
1772}
1773
1774// ===========================================================================
1775// ThreadRunner (M2b): a persistent std::thread that OWNS the SceneRunner, so a
1776// history run — and per-object measurement queries — execute OFF the main thread
1777// and the native UI stays responsive during a run AND during selection. Native
1778// only: `std::thread` + `std::sync::mpsc` do not exist on wasm32 (M3b lands a
1779// worker impl behind this same trait), so the whole thing is cfg-gated out there.
1780// ===========================================================================
1781
1782/// The persistent-thread runner. `submit_*`/`reset` push [`Command`]s down the
1783/// channel; `poll_*` first DRAIN every ready [`Reply`] into the two demux buffers,
1784/// then pop the matching one. The `SceneRunner` (and thus the kernel's resident
1785/// registry it warms) lives ENTIRELY on the thread — it is never shared — so the
1786/// only cross-thread traffic is the `Send` command/reply payloads.
1787/// Called after the runner thread posts a reply or a progress report, from
1788/// that thread: the app's event loop wakes and collects it at once instead of
1789/// at its next timed check (`set_reply_waker`). Process-wide, like the
1790/// thread's other plumbing; none installed is a no-op.
1791#[cfg(not(target_arch = "wasm32"))]
1792static REPLY_WAKER: std::sync::RwLock<Option<std::sync::Arc<dyn Fn() + Send + Sync>>> = std::sync::RwLock::new(None);
1793
1794/// Install (or with `None` remove) the hook a runner thread calls after each
1795/// reply it posts. The desktop event loop installs its own waker here.
1796#[cfg(not(target_arch = "wasm32"))]
1797pub fn set_reply_waker(waker: Option<std::sync::Arc<dyn Fn() + Send + Sync>>) {
1798    *REPLY_WAKER.write().unwrap_or_else(|p| p.into_inner()) = waker;
1799}
1800
1801#[cfg(not(target_arch = "wasm32"))]
1802fn wake_main() {
1803    let waker = REPLY_WAKER.read().unwrap_or_else(|p| p.into_inner()).clone();
1804    if let Some(waker) = waker {
1805        waker();
1806    }
1807}
1808
1809#[cfg(not(target_arch = "wasm32"))]
1810pub struct ThreadRunner {
1811    /// Main → thread. `Option` so [`Drop`] can take + drop it, ending the thread's
1812    /// blocking `recv` after already-submitted work finishes.
1813    tx: Option<std::sync::mpsc::Sender<Command>>,
1814    /// Thread → main.
1815    rx: std::sync::mpsc::Receiver<Reply>,
1816    /// Dropped without joining so closing a busy preview never stalls the UI.
1817    handle: Option<std::thread::JoinHandle<()>>,
1818    /// Demuxed completed run replies awaiting `poll_run`.
1819    run_buf: std::collections::VecDeque<RunReply>,
1820    /// Demuxed completed measurement replies awaiting `poll_query`.
1821    query_buf: std::collections::VecDeque<MeasureReply>,
1822    mesh_import_buf: std::collections::VecDeque<MeshImportReply>,
1823    mesh_phase_buf: std::collections::VecDeque<MeshImportPhaseReply>,
1824    region_fit_buf: std::collections::VecDeque<RegionFitReply>,
1825    apply_choices_buf: std::collections::VecDeque<ApplyRegionChoicesReply>,
1826    step_probe_buf: std::collections::VecDeque<StepProbeReply>,
1827    topology_buf: std::collections::VecDeque<TopologyReply>,
1828    sheet_lines_buf: std::collections::VecDeque<SheetLinesReply>,
1829    cam_buf: std::collections::VecDeque<CamReply>,
1830    /// [`HistoryRunner::hold_cam_replies`]: `poll_cam` answers `None` while set.
1831    cam_hold: bool,
1832    cam_progress_buf: std::collections::VecDeque<CamProgress>,
1833    /// Set by [`HistoryRunner::cancel_cam`]; the thread reads it on every CAM
1834    /// progress post and the running job cancels at its next chunk.
1835    cam_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
1836    cam_sim_buf: std::collections::VecDeque<CamSimReply>,
1837    cam_sim_progress_buf: std::collections::VecDeque<CamSimProgress>,
1838    /// Set by [`HistoryRunner::cancel_cam_sim`]; read between two motions.
1839    cam_sim_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
1840    plugin_action_buf: std::collections::VecDeque<PluginActionReply>,
1841    plugin_install_buf: std::collections::VecDeque<PluginInstallReply>,
1842    sent_plugin_revision: Option<u64>,
1843    /// Progress reports of the in-flight run, oldest first (`poll_progress`
1844    /// keeps the newest).
1845    progress_buf: std::collections::VecDeque<RunProgress>,
1846    /// Answered [`HistoryRunner::request_session`]s awaiting `poll_session`.
1847    session_buf: std::collections::VecDeque<(u64, Option<brep_kernel::SessionTransfer>)>,
1848    /// Behave as the wasm worker does: no blocking `session_for_main`, and
1849    /// every exported session crosses as JSON (see [`ThreadRunner::worker_like`]).
1850    worker_like: bool,
1851    /// The parts-library revision last SENT down the channel (`None` = never,
1852    /// or the thread dropped it). Lives here rather than on the caller so
1853    /// "reset forgets the library" is a local property of this object.
1854    sent_library_revision: Option<u64>,
1855    /// The thread refused a run for want of its library (drained by
1856    /// [`HistoryRunner::poll_library_request`]).
1857    library_requested: bool,
1858    /// The cooperative stop flag THIS thread checks between features. Each
1859    /// spawn gets its own, so a cancelled thread keeps its raised flag while
1860    /// the replacement starts clean.
1861    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1862}
1863
1864#[cfg(not(target_arch = "wasm32"))]
1865impl ThreadRunner {
1866    pub fn new() -> Self {
1867        let (tx, cmd_rx) = std::sync::mpsc::channel::<Command>();
1868        let (reply_tx, rx) = std::sync::mpsc::channel::<Reply>();
1869        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1870        let thread_stop = stop.clone();
1871        let cam_cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1872        let thread_cam_cancel = cam_cancel.clone();
1873        let cam_sim_cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1874        let thread_cam_sim_cancel = cam_sim_cancel.clone();
1875        let handle = std::thread::Builder::new()
1876            .name("brep-history-runner".to_string())
1877            .spawn(move || thread_main(cmd_rx, reply_tx, thread_stop, thread_cam_cancel, thread_cam_sim_cancel))
1878            .expect("spawn brep-history-runner thread");
1879        Self {
1880            tx: Some(tx),
1881            rx,
1882            handle: Some(handle),
1883            run_buf: std::collections::VecDeque::new(),
1884            query_buf: std::collections::VecDeque::new(),
1885            mesh_import_buf: std::collections::VecDeque::new(),
1886            mesh_phase_buf: std::collections::VecDeque::new(),
1887            region_fit_buf: std::collections::VecDeque::new(),
1888            apply_choices_buf: std::collections::VecDeque::new(),
1889            step_probe_buf: std::collections::VecDeque::new(),
1890            topology_buf: std::collections::VecDeque::new(),
1891            sheet_lines_buf: std::collections::VecDeque::new(),
1892            cam_buf: std::collections::VecDeque::new(),
1893            cam_hold: false,
1894            cam_progress_buf: std::collections::VecDeque::new(),
1895            cam_cancel,
1896            cam_sim_buf: std::collections::VecDeque::new(),
1897            cam_sim_progress_buf: std::collections::VecDeque::new(),
1898            cam_sim_cancel,
1899            plugin_action_buf: std::collections::VecDeque::new(),
1900            plugin_install_buf: std::collections::VecDeque::new(),
1901            sent_plugin_revision: None,
1902            progress_buf: std::collections::VecDeque::new(),
1903            session_buf: std::collections::VecDeque::new(),
1904            worker_like: false,
1905            sent_library_revision: None,
1906            library_requested: false,
1907            stop,
1908        }
1909    }
1910
1911    /// A thread runner that hands the main side its session the way the wasm
1912    /// worker must: never by a blocking wait, only by an asked-for copy that
1913    /// crosses as JSON. What a native test runs to exercise the worker path.
1914    pub fn worker_like() -> Self {
1915        let mut runner = Self::new();
1916        runner.worker_like = true;
1917        runner
1918    }
1919
1920    /// Pull every ready reply off the channel and demux it into the run/query
1921    /// buffers (so a `poll_run` never swallows a query reply and vice versa).
1922    fn drain(&mut self) {
1923        while let Ok(reply) = self.rx.try_recv() {
1924            if let Some(answer) = self.file(reply) {
1925                self.session_buf.push_back(answer);
1926            }
1927        }
1928    }
1929
1930    /// Demux one reply into its buffer. A session export is handed back to the
1931    /// caller: [`HistoryRunner::session_for_main`]'s wait, or `drain`, which
1932    /// keeps it for [`HistoryRunner::poll_session`].
1933    fn file(&mut self, reply: Reply) -> Option<(u64, Option<brep_kernel::SessionTransfer>)> {
1934        match reply {
1935            Reply::SessionExport { generation, transfer } => return Some((generation, transfer)),
1936            Reply::ValidatedPlugins(reply) => self.plugin_install_buf.push_back(reply),
1937            Reply::PluginAction(reply) => self.plugin_action_buf.push_back(reply),
1938            Reply::Run(run) => self.run_buf.push_back(run),
1939            Reply::Query(query) => self.query_buf.push_back(query),
1940            Reply::MeshImport(reply) => self.mesh_import_buf.push_back(reply),
1941            Reply::MeshImportPhase(reply) => self.mesh_phase_buf.push_back(reply),
1942            Reply::RegionFit(reply) => self.region_fit_buf.push_back(reply),
1943            Reply::ApplyRegionChoices(reply) => self.apply_choices_buf.push_back(reply),
1944            Reply::StepProbe(reply) => self.step_probe_buf.push_back(reply),
1945            Reply::Topology(reply) => self.topology_buf.push_back(reply),
1946            Reply::SheetLines(reply) => self.sheet_lines_buf.push_back(reply),
1947            Reply::CamGenerate(reply) => self.cam_buf.push_back(reply),
1948            Reply::CamProgress(progress) => self.cam_progress_buf.push_back(progress),
1949            Reply::CamSimulate(reply) => self.cam_sim_buf.push_back(reply),
1950            Reply::CamSimProgress(progress) => self.cam_sim_progress_buf.push_back(progress),
1951            Reply::Progress(progress) => self.progress_buf.push_back(progress),
1952            Reply::NeedPartsLibrary => {
1953                // The thread dropped (or never had) the library this run
1954                // needs. Forget what we believe it holds so the next
1955                // `sync_parts_library` re-installs, and flag the refused
1956                // run for the caller to re-submit.
1957                self.sent_library_revision = None;
1958                self.library_requested = true;
1959            }
1960        }
1961        None
1962    }
1963}
1964
1965/// How long the main thread waits for the runner's session copy before it
1966/// replays the history instead (the copy of l500 takes ~8 ms).
1967#[cfg(not(target_arch = "wasm32"))]
1968const SESSION_EXPORT_WAIT: std::time::Duration = std::time::Duration::from_millis(250);
1969
1970#[cfg(not(target_arch = "wasm32"))]
1971impl Default for ThreadRunner {
1972    fn default() -> Self {
1973        Self::new()
1974    }
1975}
1976
1977/// The runner thread's whole life: block on the next command, batch it with every
1978/// other command already queued, COALESCE consecutive `Run`s (a `Run` immediately
1979/// followed by another `Run` — with no `Query`/`Reset` between — is dropped; only
1980/// the last of each consecutive group runs), then process the batch IN ORDER so a
1981/// `Reset` or a `Query` interleaved between two runs keeps its place. Exits when
1982/// the command sender is dropped (`recv` errors) or the reply receiver is gone (a
1983/// `send` errors — the main side went away).
1984///
1985/// `stop` is the cooperative cancel: raised by [`ThreadRunner::cancel`] on a
1986/// thread that has already been abandoned, it is checked before every feature
1987/// a run executes, so the abandoned thread finishes the feature it is on and
1988/// exits at the next boundary instead of running the rest of the history for
1989/// a receiver that is gone.
1990#[cfg(not(target_arch = "wasm32"))]
1991fn thread_main(
1992    cmd_rx: std::sync::mpsc::Receiver<Command>,
1993    reply_tx: std::sync::mpsc::Sender<Reply>,
1994    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1995    cam_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
1996    cam_sim_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
1997) {
1998    let mut runner = crate::pipeline::SceneRunner::new();
1999    while let Ok(first) = cmd_rx.recv() {
2000        if stop.load(std::sync::atomic::Ordering::Relaxed) {
2001            return;
2002        }
2003        // Gather this command plus everything else already waiting.
2004        let mut batch = vec![first];
2005        loop {
2006            match cmd_rx.try_recv() {
2007                Ok(command) => batch.push(command),
2008                Err(_) => break, // Empty or Disconnected — process what we have.
2009            }
2010        }
2011        // A Run immediately followed by another Run is coalesced away (its result
2012        // would be overwritten before anything observed it); a Run followed by a
2013        // Query/Reset/end still runs, so interleaved work sees the right geometry.
2014        let mut run_here: Vec<bool> = vec![true; batch.len()];
2015        for i in 0..batch.len() {
2016            if matches!(batch[i], Command::Run { .. })
2017                && matches!(batch.get(i + 1), Some(Command::Run { .. }))
2018            {
2019                run_here[i] = false;
2020            }
2021        }
2022        // Process the KEPT commands in order through the SHARED `process_command`
2023        // (byte-identical work to the wasm worker's per-message step), sending each
2024        // reply it produces; a coalesced-away Run is skipped without touching the
2025        // runner, so interleaved Query/Reset still see the right geometry.
2026        for (i, command) in batch.into_iter().enumerate() {
2027            if !run_here[i] {
2028                continue;
2029            }
2030            // A CAM job's progress post also reads the cancel flag: `false`
2031            // back to the job is its cancel (see `CamSink`).
2032            let is_cam = matches!(command, Command::CamGenerate(_));
2033            if is_cam {
2034                cam_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
2035            }
2036            let is_sim = matches!(command, Command::CamSimulate(_));
2037            let mut progress = |reply: Reply| {
2038                // A lost receiver means the main side abandoned this thread:
2039                // stop at this boundary rather than finishing for nobody.
2040                let sent = reply_tx.send(reply).is_ok();
2041                if sent {
2042                    wake_main();
2043                }
2044                sent
2045                    && !stop.load(std::sync::atomic::Ordering::Relaxed)
2046                    && !(is_cam && cam_cancel.load(std::sync::atomic::Ordering::SeqCst))
2047                    && !(is_sim && cam_sim_cancel.load(std::sync::atomic::Ordering::SeqCst))
2048            };
2049            if let Some(reply) = process_command(&mut runner, command, &mut progress) {
2050                if reply_tx.send(reply).is_err() {
2051                    return; // The reply receiver is gone — the main side went away.
2052                }
2053                wake_main();
2054            }
2055        }
2056    }
2057}
2058
2059#[cfg(not(target_arch = "wasm32"))]
2060impl HistoryRunner for ThreadRunner {
2061    fn session_for_main(&mut self, generation: u64) -> SessionOnMain {
2062        if self.worker_like {
2063            return SessionOnMain::Unavailable;
2064        }
2065        let Some(tx) = &self.tx else { return SessionOnMain::Unavailable };
2066        if tx.send(Command::ExportSession { generation }).is_err() {
2067            return SessionOnMain::Unavailable;
2068        }
2069        let deadline = std::time::Instant::now() + SESSION_EXPORT_WAIT;
2070        loop {
2071            let left = deadline.saturating_duration_since(std::time::Instant::now());
2072            let Ok(reply) = self.rx.recv_timeout(left) else { return SessionOnMain::Unavailable };
2073            if let Some((answered, transfer)) = self.file(reply) {
2074                if answered != generation {
2075                    continue; // a late answer to an earlier ask
2076                }
2077                return transfer.map_or(SessionOnMain::Unavailable, SessionOnMain::Copied);
2078            }
2079        }
2080    }
2081    fn request_session(&mut self, generation: u64) -> bool {
2082        let mut command = Command::ExportSession { generation };
2083        if self.worker_like {
2084            // The worker's wire: the command crosses as JSON.
2085            let json = serde_json::to_string(&command).expect("serialize worker command");
2086            command = serde_json::from_str(&json).expect("parse worker command");
2087        }
2088        self.tx.as_ref().is_some_and(|tx| tx.send(command).is_ok())
2089    }
2090    fn poll_session(&mut self) -> Option<(u64, Option<brep_kernel::SessionTransfer>)> {
2091        self.drain();
2092        let (generation, transfer) = self.session_buf.pop_front()?;
2093        if !self.worker_like {
2094            return Some((generation, transfer));
2095        }
2096        // The worker's wire: the reply, copy and all, is serialized there and
2097        // parsed here.
2098        let json = serde_json::to_string(&Reply::SessionExport { generation, transfer }).expect("serialize worker reply");
2099        match serde_json::from_str(&json).expect("parse worker reply") {
2100            Reply::SessionExport { generation, transfer } => Some((generation, transfer)),
2101            _ => unreachable!("a session export parses back as one"),
2102        }
2103    }
2104    fn session_replay_on_main(&self) -> bool {
2105        false
2106    }
2107    fn submit_plugin_install(&mut self, request: PluginInstallRequest) -> bool {
2108        self.tx.as_ref().is_some_and(|tx| tx.send(Command::ValidatePlugins(request)).is_ok())
2109    }
2110    fn poll_plugin_install(&mut self) -> Option<PluginInstallReply> {
2111        self.drain();
2112        self.plugin_install_buf.pop_front()
2113    }
2114    fn sync_plugins(&mut self, revision: u64, fetch: &mut dyn FnMut() -> serde_json::Value) {
2115        if self.sent_plugin_revision != Some(revision) {
2116            if let Some(tx) = &self.tx {
2117                if tx.send(Command::SetPlugins { revision, packages: fetch() }).is_ok() {
2118                    self.sent_plugin_revision = Some(revision);
2119                }
2120            }
2121        }
2122    }
2123    fn submit_plugin_action(&mut self, request: PluginActionRequest) -> bool {
2124        self.tx.as_ref().is_some_and(|tx| tx.send(Command::PluginAction(request)).is_ok())
2125    }
2126    fn poll_plugin_action(&mut self) -> Option<PluginActionReply> {
2127        self.drain();
2128        self.plugin_action_buf.pop_front()
2129    }
2130
2131    fn submit_run(&mut self, request: brep_kernel::HistoryRequest, generation: u64) {
2132        if let Some(tx) = &self.tx {
2133            let _ = tx.send(Command::Run {
2134                request,
2135                generation,
2136                parts_library_revision: self.sent_library_revision.unwrap_or(0),
2137            });
2138        }
2139    }
2140
2141    fn sync_parts_library(
2142        &mut self,
2143        revision: u64,
2144        fetch: &mut dyn FnMut() -> brep_kernel::PartsLibraryMap,
2145    ) {
2146        if self.sent_library_revision == Some(revision) {
2147            return;
2148        }
2149        if let Some(tx) = &self.tx {
2150            let _ = tx.send(Command::SetPartsLibrary {
2151                library: fetch(),
2152                revision,
2153            });
2154            self.sent_library_revision = Some(revision);
2155        }
2156    }
2157
2158    fn poll_library_request(&mut self) -> bool {
2159        self.drain();
2160        std::mem::take(&mut self.library_requested)
2161    }
2162
2163    fn poll_run(&mut self) -> Option<RunReply> {
2164        self.drain();
2165        self.run_buf.pop_front()
2166    }
2167
2168    fn run_reply_waiting(&mut self) -> bool {
2169        self.drain();
2170        !self.run_buf.is_empty() || self.library_requested
2171    }
2172
2173    fn submit_query(&mut self, query: MeasureQuery) {
2174        if let Some(tx) = &self.tx {
2175            let _ = tx.send(Command::Query(query));
2176        }
2177    }
2178
2179    fn poll_query(&mut self) -> Option<MeasureReply> {
2180        self.drain();
2181        self.query_buf.pop_front()
2182    }
2183
2184    fn submit_mesh_import(&mut self, request: MeshImportRequest) {
2185        if let Some(tx) = &self.tx {
2186            let _ = tx.send(Command::MeshImport(request));
2187        }
2188    }
2189
2190    fn poll_mesh_import(&mut self) -> Option<MeshImportReply> {
2191        self.drain();
2192        self.mesh_import_buf.pop_front()
2193    }
2194
2195    fn poll_mesh_import_phase(&mut self) -> Option<MeshImportPhaseReply> {
2196        self.drain();
2197        self.mesh_phase_buf.pop_front()
2198    }
2199
2200    fn submit_region_fit(&mut self, job: RegionFitJob) -> bool {
2201        match &self.tx {
2202            Some(tx) => tx.send(Command::RegionFit(job)).is_ok(),
2203            None => false,
2204        }
2205    }
2206
2207    fn poll_region_fit(&mut self) -> Option<RegionFitReply> {
2208        self.drain();
2209        self.region_fit_buf.pop_front()
2210    }
2211
2212    fn submit_apply_region_choices(&mut self, job: ApplyRegionChoicesJob) -> bool {
2213        match &self.tx {
2214            Some(tx) => tx.send(Command::ApplyRegionChoices(job)).is_ok(),
2215            None => false,
2216        }
2217    }
2218
2219    fn poll_apply_region_choices(&mut self) -> Option<ApplyRegionChoicesReply> {
2220        self.drain();
2221        self.apply_choices_buf.pop_front()
2222    }
2223
2224    fn submit_step_probe(&mut self, request: StepProbeRequest) {
2225        if let Some(tx) = &self.tx {
2226            let _ = tx.send(Command::StepProbe(request));
2227        }
2228    }
2229
2230    fn poll_step_probe(&mut self) -> Option<StepProbeReply> {
2231        self.drain();
2232        self.step_probe_buf.pop_front()
2233    }
2234
2235    fn submit_topology(&mut self, request: TopologyRequest) {
2236        if let Some(tx) = &self.tx {
2237            let _ = tx.send(Command::Topology(request));
2238        }
2239    }
2240
2241    fn poll_topology(&mut self) -> Option<TopologyReply> {
2242        self.drain();
2243        self.topology_buf.pop_front()
2244    }
2245
2246    fn wait_topology(&mut self, timeout: std::time::Duration) -> bool {
2247        self.drain();
2248        let deadline = std::time::Instant::now() + timeout;
2249        while self.topology_buf.is_empty() {
2250            let now = std::time::Instant::now();
2251            if now >= deadline {
2252                return false;
2253            }
2254            match self.rx.recv_timeout(deadline - now) {
2255                Ok(reply) => {
2256                    self.file(reply);
2257                }
2258                Err(_) => return false,
2259            }
2260        }
2261        true
2262    }
2263
2264    fn submit_sheet_lines(&mut self, request: SheetLinesRequest) -> bool {
2265        match &self.tx {
2266            Some(tx) => tx.send(Command::SheetLines(request)).is_ok(),
2267            None => false,
2268        }
2269    }
2270
2271    fn poll_sheet_lines(&mut self) -> Option<SheetLinesReply> {
2272        self.drain();
2273        self.sheet_lines_buf.pop_front()
2274    }
2275
2276    fn submit_cam(&mut self, job: CamJob) -> bool {
2277        self.cam_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
2278        match &self.tx {
2279            Some(tx) => tx.send(Command::CamGenerate(job)).is_ok(),
2280            None => false,
2281        }
2282    }
2283
2284    fn poll_cam(&mut self) -> Option<CamReply> {
2285        self.drain();
2286        if self.cam_hold {
2287            return None;
2288        }
2289        self.cam_buf.pop_front()
2290    }
2291
2292    fn hold_cam_replies(&mut self, hold: bool) {
2293        self.cam_hold = hold;
2294    }
2295
2296    fn poll_cam_progress(&mut self) -> Option<CamProgress> {
2297        self.drain();
2298        let latest = self.cam_progress_buf.pop_back();
2299        self.cam_progress_buf.clear();
2300        latest
2301    }
2302
2303    fn cancel_cam(&mut self) {
2304        self.cam_cancel.store(true, std::sync::atomic::Ordering::SeqCst);
2305    }
2306
2307    fn submit_cam_sim(&mut self, job: CamSimJob) -> bool {
2308        // A cancel raised for an earlier chunk must not stop this one.
2309        self.cam_sim_cancel.store(false, std::sync::atomic::Ordering::SeqCst);
2310        match &self.tx {
2311            Some(tx) => tx.send(Command::CamSimulate(job)).is_ok(),
2312            None => false,
2313        }
2314    }
2315
2316    fn poll_cam_sim(&mut self) -> Option<CamSimReply> {
2317        self.drain();
2318        self.cam_sim_buf.pop_front()
2319    }
2320
2321    fn poll_cam_sim_progress(&mut self) -> Option<CamSimProgress> {
2322        self.drain();
2323        let latest = self.cam_sim_progress_buf.pop_back();
2324        self.cam_sim_progress_buf.clear();
2325        latest
2326    }
2327
2328    fn cancel_cam_sim(&mut self) {
2329        self.cam_sim_cancel.store(true, std::sync::atomic::Ordering::SeqCst);
2330    }
2331
2332    fn poll_progress(&mut self) -> Option<RunProgress> {
2333        self.drain();
2334        let latest = self.progress_buf.pop_back();
2335        self.progress_buf.clear();
2336        latest
2337    }
2338
2339    /// Abandon the thread: raise its stop flag, close its channels, and spawn a
2340    /// fresh thread with a fresh registry. The old thread cannot be interrupted
2341    /// inside a feature — it finishes the one it is on (burning CPU until
2342    /// then), sees the flag, and exits. Always `true`: there is always a
2343    /// thread to replace.
2344    fn cancel(&mut self) -> bool {
2345        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
2346        self.tx.take();
2347        self.handle.take();
2348        let worker_like = self.worker_like;
2349        *self = Self::new();
2350        self.worker_like = worker_like;
2351        true
2352    }
2353
2354    fn reset(&mut self) {
2355        self.sent_plugin_revision = None;
2356        self.plugin_action_buf.clear();
2357        if let Some(tx) = &self.tx {
2358            let _ = tx.send(Command::Reset);
2359        }
2360        // A reset is a wholesale document switch: any replies still buffered from
2361        // the old model are stale — drop them (a fresh run/query supersedes).
2362        self.run_buf.clear();
2363        self.query_buf.clear();
2364        self.mesh_import_buf.clear();
2365        self.mesh_phase_buf.clear();
2366        self.region_fit_buf.clear();
2367        self.apply_choices_buf.clear();
2368        self.step_probe_buf.clear();
2369        self.topology_buf.clear();
2370        self.sheet_lines_buf.clear();
2371        self.progress_buf.clear();
2372        self.session_buf.clear();
2373        // `Command::Reset` clears the thread's kernel store, library included,
2374        // so what we believe it holds is void.
2375        self.sent_library_revision = None;
2376        self.library_requested = false;
2377    }
2378}
2379
2380#[cfg(not(target_arch = "wasm32"))]
2381impl Drop for ThreadRunner {
2382    fn drop(&mut self) {
2383        // Closing a document or cancelling an import preview must not block
2384        // the UI on reconstruction. Closing the channel lets the worker exit
2385        // and release its registry once already-submitted work finishes.
2386        self.tx.take();
2387        self.handle.take();
2388    }
2389}
2390