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