Skip to main content

brep_render/engine_state/
history_ops.rs

1use super::*;
2
3// --- Scene feed (R10) -------------------------------------------------
4
5impl EngineState {
6    /// Run a whole history and reconcile the display scene (R10 incremental):
7    /// reused solids keep their buffers, the rest re-tessellate. Returns the build
8    /// report JSON (`{featureErrors, unresolved, displayErrors}`). Marks dirty.
9    ///
10    /// A SCENE-ONLY one-shot: it does not touch the engine-owned history document
11    /// and does not run the [`Self::finish_apply`] tail, so it also does not paint
12    /// model colours. Callers that need those use [`Self::set_history_json`].
13    pub fn run_history_json(&mut self, request_json: &str) -> Result<String, String> {
14        let request: HistoryRequest = serde_json::from_str(request_json)
15            .map_err(|error| format!("history request parse: {error}"))?;
16        let report = self.run_plugin_scene(&request)?;
17        self.dirty = true;
18        Ok(with_approximations(
19            with_refusals(
20                serde_json::json!({
21                    "featureErrors": report.feature_errors,
22                    "featureNotes": report.feature_notes,
23                    "featureFulfilment": fulfilment_map(&report),
24                    "unresolved": report.unresolved,
25                    "displayErrors": report.display_errors,
26                }),
27                &report,
28            ),
29            &report,
30        )
31        .to_string())
32    }
33
34    /// (Re)run the current rolled-to prefix of the engine's history through the
35    /// SAME kernel pipeline and reconcile the display scene. Stores + returns the
36    /// build report JSON.
37    pub(super) fn rerun_history(&mut self) -> String {
38        self.rerun_history_forcing(None)
39    }
40
41    pub(super) fn rerun_history_forcing(&mut self, feature_id: Option<&str>) -> String {
42        if self.defer_plugin_run() { return self.history_report.clone(); }
43        // This run publishes whatever a symbol edit did to the PORT features,
44        // so `pump` need not run again for it.
45        self.history.take_ports_followed();
46        // Keep the incremental cache when rolling or editing: producer entries
47        // own their handles, so rolling before a consuming boolean can reuse its
48        // inputs. Document switches clear the cache in `set_history_json`.
49        // Tag each submission with a generation; `pump` applies completed deltas
50        // immediately for the inline runner or on a later frame for workers.
51        // A transient preview replaces what the run evaluates, in the request
52        // only: the history keeps its own source.
53        self.drop_stale_expression_preview();
54        let request_value = self.run_request_value();
55        match serde_json::from_value::<HistoryRequest>(request_value) {
56            Ok(mut request) => {
57                if let Some(id) = feature_id {
58                    request.force_rebuild.push(id.to_string());
59                }
60                // Carry the live display LOD to the runner (the request is the run
61                // boundary the thread/worker receives). The runner re-tessellates
62                // every resident mesh when this differs from its last run's lod.
63                request.display_lod = self.settings.lod_factor;
64                self.run_generation += 1;
65                // A new run supersedes a cancelled one's notice.
66                self.cancelled_run = None;
67                // The PARTS-LIBRARY CHANNEL. A background runner (native
68                // thread / browser worker) owns its own kernel store, so it
69                // needs the library — but sending it WITH every run meant
70                // stringifying every embedded part payload on the UI thread
71                // for every edit, which froze the browser on an imported STEP
72                // assembly. It is sent only when it CHANGES; `fetch` does not
73                // run in the steady state. Inline shares this thread's store
74                // and no-ops.
75                self.runner.sync_parts_library(
76                    brep_kernel::parts_library_revision(),
77                    &mut brep_kernel::parts_library_map,
78                );
79                self.sync_plugin_runner();
80                self.runner.submit_run(request, self.run_generation);
81            }
82            // A parse failure runs nothing: clear the surfaced frames/profiles (so
83            // stale construction geometry does not linger — the scene keeps its
84            // previous solids) and set an error report, then run the shared
85            // post-apply tail synchronously (no kernel work), so this branch shares
86            // the dirty/gizmo/overlay continuation verbatim with a real apply.
87            Err(error) => {
88                self.construction_frames.clear();
89                self.sketch_profiles.clear();
90                self.sketch_paths.clear();
91                self.sketch_points.clear();
92                self.sketch_axes.clear();
93                self.wire_harness_report = None;
94                self.ports_report = None;
95                self.finish_apply(
96                    serde_json::json!({ "error": format!("history request: {error}") }).to_string(),
97                );
98            }
99        }
100        // Inline applies the submitted run NOW; a thread impl would defer it to a
101        // later frame's `pump`. Either way `history_report` is fresh once the reply
102        // is applied — for Inline that is before this call returns.
103        self.pump();
104        self.history_report.clone()
105    }
106
107    /// Drain every completed run reply and APPLY it — the POLL/APPLY half of the
108    /// M2a seam. Called from [`rerun_history`](Self::rerun_history) for the Inline
109    /// runner's immediate apply, and once per frame from the app so a future async
110    /// runner's completed runs land on the main thread. A reply older than
111    /// [`applied_generation`](Self::applied_generation) (a newer run that finished
112    /// first) is dropped.
113    pub fn pump(&mut self) {
114        self.pump_plugin_installations();
115        // The runner REFUSED a run because its resident parts library could not
116        // serve it (see `Reply::NeedPartsLibrary`). It has already forgotten
117        // its copy, so re-running re-installs the library and re-submits. This
118        // is a real path, not just a tripwire: the kernel's orphan GC drops
119        // entries at the end of every run, so an undo to zero components empties
120        // the RUNNER's store while this side's (which never ran) keeps
121        // everything — no revision bookkeeping can see that, only the runner's
122        // content preflight can. `library_resync` breaks the rerun→pump→rerun
123        // recursion (the reinstall makes the second attempt succeed, but a
124        // guard beats relying on that). The guard is tested FIRST because
125        // `poll_library_request` CONSUMES the flag — polling it while a resync
126        // is already in flight would swallow a second refusal.
127        if !self.library_resync && self.runner.poll_library_request() {
128            self.library_resync = true;
129            self.rerun_history();
130            self.library_resync = false;
131        }
132        // A symbol edit relabelled, added or removed a PORT feature. The eCAD
133        // editors write their blocks straight into the history, which does not
134        // run it, so the run happens here, on the next frame, for every host.
135        if self.history.take_ports_followed() {
136            self.rerun_history();
137        }
138        while let Some(reply) = self.runner.poll_mesh_import() {
139            // A document switch clears this set. Ignore any older reconstruction
140            // reply that was already running when its Reset crossed the queue.
141            let Some(destination) = self.pending_mesh_imports.remove(&reply.id) else {
142                continue;
143            };
144            if destination == MeshImportDestination::Preview {
145                self.mesh_preview_results.push_back(reply);
146                continue;
147            }
148            match reply.result {
149                Ok(output) => match self.import_step_feature(&output.step_text) {
150                    Ok(_) => {
151                        self.push_notice(
152                            "RANSAC reconstruction complete; building imported CAD body",
153                        );
154                        // A body the chain refused is left out of the model;
155                        // say so, by name, rather than let it vanish.
156                        if let Some(notice) = crate::runner::refused_bodies_notice(&output.report)
157                        {
158                            self.push_notice(notice);
159                        }
160                    }
161                    Err(error) => self.push_notice(format!("mesh import failed: {error}")),
162                },
163                Err(error) => self.push_notice(format!("mesh import failed: {error}")),
164            }
165        }
166        // STEP probes: the parse ran on the runner; stash the structure it
167        // found (the import consumes it) and queue the outcome for the panel.
168        while let Some(reply) = self.runner.poll_step_probe() {
169            if !self.pending_step_probes.remove(&reply.id) {
170                continue; // cancelled, or a document switch — nobody is waiting
171            }
172            let outcome = match reply.result {
173                Ok(Some(assembly)) => {
174                    let probe = super::model_io::probe_counts(&assembly);
175                    // The kernel already refuses a structure that reaches no
176                    // geometry, so this is belt-and-braces: an assembly with
177                    // zero instances would import as zero components, which
178                    // is the silent failure the structured lane forbids.
179                    if probe.instances == 0 {
180                        super::StepProbeOutcome::Flat
181                    } else {
182                        self.pending_step_assembly = Some(assembly);
183                        super::StepProbeOutcome::Structure(probe)
184                    }
185                }
186                Ok(None) => super::StepProbeOutcome::Flat,
187                Err(error) => super::StepProbeOutcome::Failed(error),
188            };
189            self.step_probe_results.push_back((reply.id, outcome));
190        }
191        // The in-flight run's latest progress report (a background runner
192        // posts one before each feature it executes). Kept only for a run
193        // newer than the applied one: a report from a superseded run — or one
194        // still arriving after a cancel bumped the generations — is stale.
195        if let Some(progress) = self.runner.poll_progress() {
196            if progress.generation > self.applied_generation {
197                self.run_progress = Some(progress);
198            }
199        }
200        self.pump_plugin_callbacks();
201        while let Some(reply) = self.runner.poll_run() {
202            self.runs_replied += 1;
203            if reply.generation >= self.run_generation && self.accept_plugin_run(&reply) {
204                self.applied_generation = reply.generation;
205                self.apply_run_output(reply.output);
206            } else {
207                // Superseded — but the runner's baseline has moved past every
208                // display in it, so a later keep can name one of them. Hold
209                // them for that keep (see `superseded_displays`).
210                for (name, _handle, maybe) in reply.output.snapshot {
211                    if let Some(display) = maybe {
212                        self.superseded_displays.insert(name, display);
213                    }
214                }
215            }
216        }
217        // The run just applied released sketch links the kernel could not
218        // resolve, editing the history after the fact: run it again so the
219        // report matches the document. Once, since the second run finds no
220        // listed edge left to release (the inline runner applies it before
221        // this returns; a background runner lands it on a later frame).
222        if std::mem::take(&mut self.sketch_links_released) {
223            self.rerun_history();
224        }
225        if !self.run_pending() {
226            self.run_progress = None;
227        }
228        // Deferred one-shot framing (Import / Open): frame the scene the moment the
229        // run they submitted has fully landed. Consumed unconditionally once the run
230        // is no longer pending — even when it produced no solids (bbox empty →
231        // `zoom_to_fit` no-ops) — so a later unrelated run never inherits a stale fit.
232        if self.pending_fit && !self.run_pending() {
233            self.pending_fit = false;
234            self.zoom_to_fit();
235        }
236        // Drain any completed measurement replies too (a background runner surfaces
237        // them a frame after selection); for Inline this is a no-op each frame since
238        // `object_info_json` already pumped its own query same-call.
239        self.pump_queries();
240        self.pump_topology();
241        self.pump_sheet_lines();
242    }
243
244    /// Ask the runner for the B-rep topology of the displayed solids `names`
245    /// that the scene does not hold for their current handle and that have not
246    /// been asked for since the last applied run, then drain whatever has
247    /// already answered (all of it, for the synchronous Inline runner). The
248    /// drawing sheet's door, and the balloon bubble drag's (which re-projects
249    /// the arrow head on the exact solid, `pmi_reproject_balloon_head`):
250    /// nothing else needs topology on this side, so a document with neither a
251    /// sheet nor a dragged balloon never asks.
252    pub fn request_exact_solids<'a>(&mut self, names: impl IntoIterator<Item = &'a str>) {
253        let mut wanted: Vec<(String, u32)> = Vec::new();
254        for name in names {
255            let Some(display) = self.scene.solid(name) else { continue };
256            let handle = display.source_handle;
257            if handle == 0 || display.is_sketch || self.scene.exact_solid(name).is_some() {
258                continue;
259            }
260            if self.topology_asked.insert(handle) {
261                wanted.push((name.to_string(), handle));
262            }
263        }
264        if !wanted.is_empty() {
265            self.next_topology_id += 1;
266            let id = self.next_topology_id;
267            self.pending_topology.insert(id);
268            self.runner.submit_topology(crate::runner::TopologyRequest { id, solids: wanted });
269        }
270        self.pump_topology();
271    }
272
273    /// Fold every answered topology request into the scene. A reply for a
274    /// display that has moved on to another handle is dropped; the next
275    /// projection asks for the new one.
276    pub fn pump_topology(&mut self) {
277        let mut landed = false;
278        while let Some(reply) = self.runner.poll_topology() {
279            if !self.pending_topology.remove(&reply.id) {
280                continue; // cancelled, or a document switch
281            }
282            for (name, handle, solid) in reply.solids {
283                self.scene.set_exact_solid(&name, handle, solid);
284            }
285            landed = true;
286        }
287        if landed {
288            self.pmi_refresh_stale_balloon();
289        }
290    }
291
292    /// Whether a topology request is still in flight — the frame loop and the
293    /// idle contract wait on it like a measurement query.
294    pub fn topology_pending(&self) -> bool {
295        !self.pending_topology.is_empty()
296    }
297
298    /// Whether a measurement query is still in flight (its reply not yet drained) —
299    /// the query analogue of [`run_pending`](Self::run_pending), so the app keeps the
300    /// frame loop alive until a background runner's measurement lands and displays.
301    /// Always `false` for the synchronous Inline runner.
302    pub fn queries_pending(&self) -> bool {
303        !self.pending_query.is_empty()
304    }
305
306    /// Whether RANSAC reconstruction is still executing on the native runner
307    /// thread or browser worker.
308    pub fn mesh_imports_pending(&self) -> bool {
309        !self.pending_mesh_imports.is_empty()
310    }
311
312    /// Whether a submitted run has not yet been applied (`run_generation !=
313    /// applied_generation`). Always `false` for the synchronous Inline runner
314    /// (submit → immediate `pump` keeps the two in lockstep); a background runner
315    /// uses it to keep the frame loop alive until its reply lands.
316    pub fn run_pending(&self) -> bool {
317        self.run_generation != self.applied_generation || self.plugin_work_pending()
318    }
319
320    /// The generation of the last APPLIED run — bumps once per applied history
321    /// run (document loads, edits, constraint mutations, solves). A cheap
322    /// staleness key for app-side caches derived from the applied document
323    /// (the update-components outdated badge keys on it).
324    pub fn applied_generation(&self) -> u64 {
325        self.applied_generation
326    }
327
328    /// What the in-flight run is executing right now, as far as the runner
329    /// has reported (see [`crate::runner::RunProgress`]); `None` when nothing
330    /// is running or the run has not reached its first executed feature.
331    pub fn run_progress(&self) -> Option<&crate::runner::RunProgress> {
332        self.run_progress.as_ref()
333    }
334
335    /// The feature id the last cancelled run was executing (empty when it was
336    /// cancelled before any progress arrived), until the next submit.
337    pub fn cancelled_run(&self) -> Option<&str> {
338        self.cancelled_run.as_deref()
339    }
340
341    /// CANCEL the in-flight run. The runner abandons its work and comes back
342    /// with an EMPTY resident registry (a fresh thread / a fresh worker — see
343    /// [`crate::runner::HistoryRunner::cancel`]), so this side forgets
344    /// everything that was waiting on it: the run itself (generations are
345    /// bumped past it, so a straggling reply from the old runner is dropped
346    /// as stale), pending measurement queries, document-bound mesh imports
347    /// and a deferred fit. The DISPLAY SCENE is left as the last applied run
348    /// built it — the document is ahead of it now, which the notice says; the
349    /// next edit re-runs the whole history through the new runner (a cold
350    /// run: the warm cache went with the old one). Nothing inside a feature
351    /// is interruptible, so the native thread keeps burning CPU until the
352    /// feature it is on finishes; the browser worker is terminated outright.
353    ///
354    /// `false` when nothing was running, or the runner cannot abandon (the
355    /// synchronous Inline runner, whose runs are over before anyone can ask).
356    pub fn cancel_run(&mut self) -> bool {
357        self.cancel_run_with_notice(true)
358    }
359
360    pub(super) fn cancel_run_with_notice(&mut self, notify: bool) -> bool {
361        if self.plugin_installation_pending() { return false; }
362        if self.cancel_plugin_action() { return true; }
363        if !self.run_pending() || !self.runner.cancel() {
364            return false;
365        }
366        let stalled_on = self.run_progress.take().map(|progress| progress.feature_id);
367        // Past every generation submitted so far: a reply the old runner
368        // already posted (sitting in the main event loop on wasm) carries an
369        // older number than this and is dropped by `pump`'s gate.
370        self.run_generation += 1;
371        self.applied_generation = self.run_generation;
372        self.pending_query.clear();
373        // The new runner's registry counts handles from one again, so every
374        // topology keyed by an old handle could alias a new display.
375        self.pending_topology.clear();
376        self.topology_asked.clear();
377        self.scene.clear_exact_solids();
378        self.sheet_lines.forget();
379        // The old runner's held displays name ITS handles; the new one's
380        // first run emits every display afresh.
381        self.superseded_displays.clear();
382        let dropped_imports = self.pending_mesh_imports.len();
383        self.pending_mesh_imports.clear();
384        let dropped_probes = self.pending_step_probes.len();
385        self.pending_step_probes.clear();
386        self.pending_fit = false;
387        self.library_resync = false;
388        self.sketch_links_released = false;
389        self.cancelled_run = Some(stalled_on.clone().unwrap_or_default());
390        if notify {
391            self.push_notice(match stalled_on {
392                Some(id) if !id.is_empty() => format!(
393                    "Run cancelled while executing {id}. The model shows the last completed \
394                     result; edit or delete the feature to rebuild."
395                ),
396                _ => "Run cancelled. The model shows the last completed result; the next edit \
397                      rebuilds it."
398                    .to_string(),
399            });
400        }
401        if dropped_imports > 0 {
402            self.push_notice(format!(
403                "cancelled {dropped_imports} pending mesh import{}",
404                if dropped_imports == 1 { "" } else { "s" }
405            ));
406        }
407        if dropped_probes > 0 {
408            self.push_notice("cancelled the STEP file being read — upload it again to import it");
409        }
410        true
411    }
412
413    /// How many run replies the runner has sent back (see `runs_replied`).
414    pub fn runs_replied(&self) -> u64 {
415        self.runs_replied
416    }
417
418    /// Whether the display scene currently holds at least one solid. Used by the
419    /// app's async-safe first-frame framing: under a background runner (thread /
420    /// worker) the seed run lands a frame (or many) after boot, so the shell waits
421    /// for `has_solids() && !run_pending()` before its one-shot `zoom_to_fit`.
422    pub fn has_solids(&self) -> bool {
423        !self.scene.solids().is_empty()
424    }
425
426    /// Swap in a different history runner (the platform injects its own — the native
427    /// app installs a [`ThreadRunner`](crate::runner::ThreadRunner); wasm keeps the
428    /// default Inline until M3's worker). Resets the new runner's delta baseline so
429    /// the next run rebuilds fully. Call BEFORE seeding a document so the seed builds
430    /// through the installed runner.
431    pub fn set_runner(&mut self, runner: Box<dyn crate::runner::HistoryRunner>) {
432        self.runner = runner;
433        self.plugin_runner_replaced();
434        self.runner.reset();
435        self.superseded_displays.clear();
436        self.pending_mesh_imports.clear();
437        self.mesh_preview_results.clear();
438        self.pending_topology.clear();
439        self.topology_asked.clear();
440        self.scene.clear_exact_solids();
441        self.sheet_lines.forget();
442    }
443
444    /// Apply a [`SceneRunner`](crate::pipeline::SceneRunner) delta to the display
445    /// scene and build the history report JSON — the APPLY half of the M2a seam.
446    ///
447    /// Reconcile preserving ORDER + reuse: MOVE every current display out of the
448    /// scene ([`RenderScene::drain`](crate::scene::RenderScene::drain)) into a
449    /// name-keyed `kept` map, then reinsert in snapshot order — a fresh entry
450    /// (`Some`) replaces, an UNCHANGED entry (`None`) reuses its moved-out display
451    /// (stable `revision` ⇒ GPU-buffer reuse, Task-1; its `source_handle` equals
452    /// the run's handle by the monotonic-handle reuse invariant). Leftovers in
453    /// `kept` — departed kernel solids AND the previous run's sketch sheets — are
454    /// dropped; `refresh_committed_sketches` (run in the shared continuation after)
455    /// re-adds the sheets, so dropping them here is correct.
456    ///
457    /// Then the report continuation (identical to the pre-seam run): keep the run's
458    /// resolved frames + solved sketch profiles and fold the per-feature timings /
459    /// output-names into the id-keyed report JSON, then hand it to
460    /// [`finish_apply`](Self::finish_apply) — the shared dirty/gizmo/overlay tail
461    /// that the parse-error branch in [`rerun_history`](Self::rerun_history) also
462    /// calls, so both paths share the continuation verbatim.
463    pub(super) fn apply_run_output(&mut self, output: crate::pipeline::RunOutput) {
464        let crate::pipeline::RunOutput {
465            snapshot,
466            mut report,
467            provenance,
468            entity_origin,
469            assembly_poses,
470            assembly_fixed,
471            moved_solids,
472            imported_colors,
473            consumed,
474            assembly,
475        } = output;
476        for (id, data) in &report.plugin_persistent_data {
477            self.history.fold_plugin_persistent_data(id, data.clone());
478        }
479        // The runner already forced fresh displays for the solver-moved solids
480        // (their snapshot entries arrive `Some`); nothing extra to do main-side.
481        let _ = moved_solids;
482        // Un-pose the active PMI view's exploded displays BEFORE the reconcile
483        // keeps them, so the re-pose after apply starts from the modeling
484        // pose and never compounds.
485        self.pmi_restore_explode();
486
487        // The names this run consumed, for the committed-sketch refresh in the
488        // tail below — the runner folded them, so the UI thread does not execute
489        // the history a second time to fold them again.
490        self.consumed_names = consumed.into_iter().collect();
491        // Adopt the run's assembly tail. The PARTS LIBRARY comes out of it here
492        // rather than in `adopt_assembly_sync`, so the (potentially megabyte)
493        // store is installed and mirrored into the document exactly once, on the
494        // run that moved it, and never kept in the snapshot afterwards.
495        self.assembly_sync = assembly.map(|mut sync| {
496            if let Some(library) = sync.parts_library.take() {
497                // CLEAR, then install. `install_parts_library` keeps a resident
498                // entry whose identity (source key + signature + document hash)
499                // matches the incoming one VERBATIM — the right rule for the
500                // main → runner direction it was written for, because the
501                // runner may hold a heal the sender never saw. This is the
502                // other direction: the run that just healed an entry (a heal
503                // rewrites the snapshot and deliberately does NOT change the
504                // identity) is the one holding the newer copy, so keeping the
505                // resident one would silently drop it and the document would
506                // re-heal on every open. Emptying first makes every incoming
507                // entry a fresh insert, i.e. "the store IS what the run left".
508                brep_kernel::install_parts_library(&Default::default());
509                brep_kernel::install_parts_library(&library);
510                if let Ok(block) = serde_json::to_value(&library) {
511                    self.history.set_parts_library(block);
512                }
513            }
514            sync
515        });
516
517        // --- assembly pose-authority fold -------- Adopt the solver's pose /
518        // isFixed write-backs into the owning ACOMP features by
519        // `inputParams.id` BEFORE anything persists or re-runs this document.
520        // Deliberately NOT `update_feature_params`: the fold must not mint an
521        // undo entry nor trigger a rerun (rerun → solve → fold → rerun would
522        // loop); `fold_param_no_undo` writes the param silently, and the next
523        // run's request simply carries the solved pose (a no-motion solve emits
524        // no updates, so fingerprints never churn).
525        for (id, pose) in assembly_poses {
526            let expression_driven = self.history.index_of(&id).and_then(|i| self.history.feature_params(i))
527                .is_some_and(|p| super::batch::contains_expression(&p["transform"]));
528            if !expression_driven { self.history.fold_param_no_undo(&id, "transform", pose); }
529        }
530        for (id, fixed) in assembly_fixed {
531            self.history
532                .fold_param_no_undo(&id, "isFixed", serde_json::Value::Bool(fixed));
533        }
534
535        // Adopt the run's eager provenance (SOLID last-writer) + entity origin
536        // (face/edge first-writer) wholesale (both drive `creating_feature` + the
537        // Info tab's `creatingFeature` with no cold re-run), and INVALIDATE the
538        // object-info measurement cache + any in-flight query: the geometry changed,
539        // so cached measurements are stale and a pending reply is superseded (a
540        // re-selection re-queries against the fresh geometry).
541        self.provenance = provenance.into_iter().collect();
542        self.entity_origin = entity_origin.into_iter().collect();
543        self.info_cache.clear();
544        self.pending_query.clear();
545
546        // Fold the run's IMPORTED COLOURS into the engine's own metadata store —
547        // the seam between the kernel's (thread-local, never persisted by us)
548        // name-keyed store and the one the Info window edits and the document
549        // saves. NON-overwriting on purpose: an import re-stamps its colour on
550        // every replay, and a colour the user changed in the panel must win.
551        for (name, hex) in imported_colors {
552            if self.metadata.attribute(&name, "color").is_none() {
553                self.metadata.set_attribute(&name, "color", &hex);
554            }
555        }
556
557        // Reconcile the scene: move current displays out, reinsert in order.
558        let mut kept: std::collections::HashMap<String, crate::scene::SolidDisplay> = self
559            .scene
560            .drain()
561            .into_iter()
562            .map(|solid| (solid.name.clone(), solid))
563            .collect();
564        for (name, handle, maybe) in snapshot {
565            match maybe {
566                Some(display) => {
567                    self.superseded_displays.remove(&name);
568                    self.scene.insert_solid(display);
569                }
570                // "Unchanged": the runner last emitted `handle` for this name.
571                // That emit is the scene's display when its reply was applied,
572                // and a held superseded display when it was dropped — the
573                // handle says which, since handles are monotonic and never
574                // recycled within one runner. Neither holding it is a protocol
575                // breach (a reply lost between the runner and `pump`), and the
576                // app is not the place to crash on one, in any build: the
577                // solid is left out of this frame and the report names it.
578                None => {
579                    let kept_display = kept.remove(&name);
580                    let display = match kept_display {
581                        Some(display) if display.source_handle == handle => Some(display),
582                        _ => self
583                            .superseded_displays
584                            .remove(&name)
585                            .filter(|display| display.source_handle == handle),
586                    };
587                    match display {
588                        Some(display) => self.scene.insert_solid(display),
589                        None => {
590                            report.display_errors.push(format!(
591                                "{name}: the run kept resident handle {handle}, which no reply has displayed"
592                            ));
593                        }
594                    }
595                }
596            }
597        }
598        // Topology is kept only for a display whose handle survived the run,
599        // and so is the record of what was asked: a surviving handle is in
600        // flight, answered or not in the registry, and every other is gone.
601        self.scene.prune_exact_solids();
602        let live: std::collections::HashSet<u32> =
603            self.scene.solids().iter().map(|solid| solid.source_handle).collect();
604        self.topology_asked.retain(|handle| live.contains(handle));
605
606        // Keep every plane frame the run resolved (DATUM/PLANE/SKETCH);
607        // `refresh_construction_datums` filters to the D/P producers.
608        self.construction_frames = report.frames.clone();
609        // Keep every solved sketch profile so `refresh_committed_sketches` can
610        // synthesize the committed sketch sheet solids.
611        self.sketch_profiles = report.profiles.clone();
612        // ...and every path chain, so a sketch whose geometry closes NO region (an
613        // open chain — the reported single line) still has something to draw.
614        self.sketch_paths = report.paths.clone();
615        // ...and every published point, so a sketch holding ONLY points (a
616        // hole-placement sketch) still has something to draw.
617        self.sketch_points = report.points.clone();
618        // Keep every axis line the run published so the angle gizmo can resolve a
619        // revolve `axis` reference to a world line without re-running.
620        self.sketch_axes = report.axes.clone();
621        // ...and the wire-harness routing report, for the harness panel.
622        self.wire_harness_report = report.wire_harness.clone();
623        // ...and the ports tail's report, for the Qualify panel: the tail is not
624        // a feature, so nothing else carries what it refused or could not resolve.
625        self.ports_report = report.ports.clone();
626        // ...and the PMI report (every view's resolved annotations).
627        self.pmi_report = report.pmi.clone();
628        self.fold_plugin_annotation_data();
629        // Fold the per-feature timing / output-name pairs into id-keyed maps so the
630        // history-tree UI can look them up by feature id.
631        let timings: serde_json::Map<String, serde_json::Value> = report
632            .feature_timings
633            .iter()
634            .map(|(id, ms)| (id.clone(), serde_json::json!(ms)))
635            .collect();
636        let outputs: serde_json::Map<String, serde_json::Value> = report
637            .feature_outputs
638            .iter()
639            .map(|(id, names)| (id.clone(), serde_json::json!(names)))
640            .collect();
641        let report_json = with_approximations(
642            with_refusals(
643                serde_json::json!({
644                    "featureErrors": report.feature_errors,
645                    "featureNotes": report.feature_notes,
646                    "featureFulfilment": fulfilment_map(&report),
647                    "unresolved": report.unresolved,
648                    "displayErrors": report.display_errors,
649                    "featureTimings": timings,
650                    "featureOutputs": outputs,
651                }),
652                &report,
653            ),
654            &report,
655        )
656        .to_string();
657        self.release_unresolved_sketch_links(&report.unresolved);
658        self.finish_apply(report_json);
659    }
660
661    /// Release every sketch edge link whose edge this run could not resolve —
662    /// the kernel's own `unresolved` word, per feature, so an edge a LATER
663    /// feature consumed (gone from the final scene, present where the sketch
664    /// runs) is never mistaken for a lost one. For each such link the sketch
665    /// keeps its geometry as ordinary fixed construction geometry
666    /// ([`crate::sketch::external_ref::release_ref_json`]), drops the
667    /// `externalRefs` entry and takes the name out of `projectedEdges`. A
668    /// listed name that never materialized has nothing to keep and stays
669    /// listed (the report keeps naming it).
670    ///
671    /// Folded like the assembly pose write-back: no undo checkpoint, so undoing
672    /// the deletion that lost the edge restores the snapshot with the link
673    /// intact, and no run from here (re-entrancy); the flag makes `pump` run
674    /// once more. Nothing happens while a sketch is being edited (the editor
675    /// owns its doc and the rolled-back run never runs it) or while the
676    /// document is locked (a refused fold would be retried every run).
677    fn release_unresolved_sketch_links(&mut self, unresolved: &[String]) {
678        if unresolved.is_empty() || self.sketch_edit.is_some() || self.history.locked().is_some() {
679            return;
680        }
681        let mut released_any = false;
682        for index in 0..self.history.len() {
683            if !self.history.feature_type(index).is_some_and(|t| matches!(t.as_str(), "S" | "SKETCH")) {
684                continue;
685            }
686            let Some(id) = self.history.feature_id(index).filter(|id| !id.is_empty()) else {
687                continue;
688            };
689            let Some(mut persistent) = self.history.feature_persistent_data(index) else {
690                continue;
691            };
692            let mut refs: Vec<crate::sketch::ExternalRef> = persistent
693                .get("externalRefs")
694                .and_then(|v| serde_json::from_value(v.clone()).ok())
695                .unwrap_or_default();
696            if refs.is_empty() {
697                continue;
698            }
699            // `"{id}: {name}"`, possibly with the kernel's rename hint appended.
700            let lost: Vec<String> = refs
701                .iter()
702                .map(|r| r.edge_name.clone())
703                .filter(|name| {
704                    let line = format!("{id}: {name}");
705                    unresolved
706                        .iter()
707                        .any(|u| *u == line || u.starts_with(&format!("{line} (renamed:")))
708                })
709                .collect();
710            if lost.is_empty() {
711                continue;
712            }
713            let mut sketch = persistent.get("sketch").cloned().unwrap_or(serde_json::Value::Null);
714            for r in refs.iter().filter(|r| lost.contains(&r.edge_name)) {
715                crate::sketch::external_ref::release_ref_json(&mut sketch, r);
716            }
717            refs.retain(|r| !lost.contains(&r.edge_name));
718            if let Some(object) = persistent.as_object_mut() {
719                if !sketch.is_null() {
720                    object.insert("sketch".into(), sketch);
721                }
722                object.insert(
723                    "externalRefs".into(),
724                    serde_json::to_value(&refs).unwrap_or_else(|_| serde_json::Value::Array(Vec::new())),
725                );
726            }
727            let listed = brep_kernel::reference_names(
728                self.history.feature_params(index).as_ref().and_then(|p| p.get("projectedEdges")),
729            );
730            let kept: Vec<serde_json::Value> = listed
731                .into_iter()
732                .filter(|name| !lost.contains(name))
733                .map(serde_json::Value::String)
734                .collect();
735            self.history.fold_plugin_persistent_data(&id, persistent);
736            self.history.fold_param_no_undo(&id, "projectedEdges", serde_json::Value::Array(kept));
737            released_any = true;
738        }
739        if released_any {
740            self.sketch_links_released = true;
741        }
742    }
743
744    /// The shared post-apply TAIL: mark dirty, store the report JSON, re-sync an
745    /// armed gizmo, and rebuild the persistent committed-sketch + construction-datum
746    /// overlays. Called after a real run's [`apply_run_output`](Self::apply_run_output)
747    /// AND from [`rerun_history`](Self::rerun_history)'s parse-error branch, so both
748    /// paths run the identical continuation. Callers read the result via
749    /// [`Self::history_report`](Self::history_report_json).
750    fn finish_apply(&mut self, report_json: String) {
751        self.dirty = true;
752        self.history_report = report_json;
753        // Keep an armed gizmo glued to its feature as the model rebuilds. During a
754        // transform drag the re-sync is driven by `transform_drag_to` itself (which
755        // resolves the delta against the frozen grab frame first, then syncs), so
756        // skip it here to avoid a redundant double-feed per drag frame. Transform
757        // mode re-feeds the widget frame; dimension mode re-projects the annotation
758        // leaders onto the rebuilt (param-changed) geometry.
759        if self.transform_gizmo.drag.is_none() {
760            match self.transform_gizmo.mode {
761                GizmoMode::Transform => self.sync_transform_gizmo(),
762                GizmoMode::Dimension => self.refresh_feature_dimension_overlay(),
763                GizmoMode::None => {}
764            }
765        }
766        // Rebuild the persistent committed-sketch overlays against the reconciled
767        // scene (also covers `set_history_json`, which returns this call's result).
768        self.refresh_committed_sketches();
769        // Rebuild the persistent construction datum/plane overlays from the frames
770        // the run just surfaced (D/P features only; sketches render as curves).
771        self.refresh_construction_datums();
772        // Rebuild the BOARD's 3D bodies from the `pcb` block, for the same reason
773        // the sketch sheets are rebuilt here: the reconcile above kept only the
774        // run's own outputs. A document with no `pcb` block returns immediately
775        // inside.
776        self.refresh_board_geometry();
777        // Assembly documents: adopt the component projection and the solved
778        // constraint state the runner shipped, and fold that state back into the
779        // document (the pose-authority contract — see `assembly_ops`).
780        // Componentless documents return immediately inside.
781        self.adopt_assembly_sync();
782        // Component selection needs the new member projection above, not the
783        // previous run's assembly. This also completes a deferred Move Copy.
784        // Keep an armed COMPONENT Move gizmo glued to its (possibly re-solved)
785        // component: re-anchor at the fresh member bbox. Never during its own
786        // drag — the drag feed owns the widget frame (free-move live-follow).
787        if self.component_move.drag.is_none() {
788            self.component_move_sync();
789        }
790        // Rebuild the assembly-constraint viewport overlays from the rows the
791        // same reply carried (an inert no-op — empty group — for a document with
792        // no assembly state). ORDER MATTERS: the overlay read must follow the
793        // adopt.
794        self.refresh_constraint_overlay();
795        // PMI: re-pose the active view's exploded solids on the fresh displays
796        // and re-bake its annotation overlay from the run's report.
797        self.pmi_after_apply();
798        // Re-derive every display colour from the metadata store, LAST — after
799        // the sketch sheets, the datum overlays and the assembly sync have all
800        // settled the scene, so no display inserted above is missed. This is why
801        // a model colour now survives a feature edit: the freshly tessellated
802        // display arrives colourless and is re-coloured from the store, instead
803        // of the colour living only on the display that was just thrown away.
804        // A no-op when nothing changed, which is the common case.
805        self.sync_colors_from_metadata();
806    }
807
808    /// Load a whole history document (a saved part file parses as one); the
809    /// engine now OWNS this recipe. Rolls to the last feature and builds it.
810    ///
811    /// The document's top-level `metadata` field (the Properties-panel
812    /// name-keyed store) is lifted out into [`Self::metadata`] before the feature
813    /// list is handed to the kernel — loading a part REPLACES the store wholesale
814    /// (a document with no `metadata` clears it), mirroring the previous metadata
815    /// manager's load semantics. Round-trips with [`Self::history_request_json`].
816    ///
817    /// The top-level `workbench` field (the ACTIVE-WORKBENCH id the save embedded
818    /// — see [`Self::history_request_json`]) is lifted off the kernel recipe the
819    /// same way and applied through [`Self::apply_settings_json`] — the SAME seam
820    /// the toolbar's workbench dropdown writes through — so the palette / context
821    /// offers / workbench buttons react to a restored workbench exactly as they
822    /// do to a manual switch (settings generation bump included). Tolerances:
823    ///
824    /// * a legacy document WITHOUT the field (or with a non-string value) leaves
825    ///   the current workbench untouched — opening an old file never yanks the
826    ///   user out of their workbench;
827    /// * an unknown/stale id is stored RAW (never an error): the settings layer
828    ///   deliberately doesn't validate ids, and every consumer resolves through
829    ///   the app-side registry's `resolve()`, which falls back to the default
830    ///   workbench — so a file saved by a build with a workbench this build
831    ///   doesn't know still opens cleanly;
832    /// * the restored id is deliberately NOT persisted to the settings blob —
833    ///   that blob stays the user's boot preference; a document's workbench is
834    ///   session-scoped (the next explicit dropdown change persists as usual).
835    pub fn set_history_json(&mut self, request_json: &str) -> Result<String, String> {
836        // A locked history (a PLM revision this user may not change) is not
837        // replaced either: a fresh `History` would arrive unlocked, which is the
838        // one door `History::lock` cannot hold by itself. Opening another
839        // document is a new engine, and a reload after checkout unlocks first.
840        if let Some(reason) = self.history.locked() {
841            return Err(format!("this document is read-only: {reason}"));
842        }
843        // A document switch is a wholesale model replacement: drop the incremental
844        // cache so the new model starts from a clean slate (no cross-document
845        // staleness, no unbounded cache growth across many opens). The roll/edit
846        // hot path (`rerun_history`) deliberately KEEPS the cache for instant
847        // rollback; this is the ONE place the full clear belongs.
848        brep_kernel::clear_history_cache();
849        // Reset the delta runner's baseline in lockstep with the cache clear so the
850        // new document is a FULL rebuild (no reuse against the prior model's names).
851        self.runner.reset();
852        self.superseded_displays.clear();
853        self.pending_mesh_imports.clear();
854        self.mesh_preview_results.clear();
855        self.pending_topology.clear();
856        self.topology_asked.clear();
857        self.scene.clear_exact_solids();
858        // A probed-but-unconsumed STEP assembly belongs to the document being
859        // replaced: importing it into the NEW one would land a file the user never
860        // chose here (and hold its solids resident until they did). A probe
861        // still running is likewise the old document's: its answer is dropped.
862        self.pending_step_assembly = None;
863        self.pending_step_probes.clear();
864        self.step_probe_results.clear();
865        // Everything the previous document's run shipped belongs to THAT
866        // document: the assembly tail, the component projection, its consumed
867        // names, and the main-side session's generation stamp. The new
868        // document's first reply replaces them; until it lands, nothing must
869        // read the old one's.
870        self.assembly_sync = None;
871        self.assembly_components.clear();
872        self.assembly_session_generation = None;
873        self.consumed_names.clear();
874        // The open sheet, the open sheet form and the projection cache all
875        // name objects of the document being replaced.
876        self.forget_sheets();
877        // A preview belongs to the document being replaced.
878        self.expression_preview = None;
879        let mut document: serde_json::Value = serde_json::from_str(request_json)
880            .map_err(|error| format!("history parse: {error}"))?;
881        let thumbnail = document.as_object_mut().and_then(|o| o.remove("thumbnail"));
882        self.thumbnail_cache.replace(None);
883        // Pull `metadata` out of the document so the engine holds the single copy
884        // (kept off the History recipe the kernel executes).
885        let metadata_value = document
886            .as_object_mut()
887            .and_then(|object| object.remove("metadata"));
888        self.metadata.load_json(metadata_value.as_ref());
889        // Lift the saved active-workbench id off the kernel recipe (`metadata`'s
890        // sibling — the kernel would ignore the extra field, but the engine owns
891        // it) and apply it through the shared settings seam; see the doc comment
892        // for the legacy/unknown-id tolerances. Applied BEFORE the rebuild below
893        // so anything reading the settings post-run already sees the restored id.
894        if let Some(workbench_id) = document
895            .as_object_mut()
896            .and_then(|object| object.remove("workbench"))
897            .as_ref()
898            .and_then(serde_json::Value::as_str)
899        {
900            let _ = self.apply_settings_json(
901                &serde_json::json!({ "workbench": workbench_id }).to_string(),
902            );
903        }
904        // Stamp each sketch's per-loop ids onto its geometries before the model
905        // is built. Deriving already yields the right ids, so this renames
906        // nothing — it PERSISTS them, which is what lets a loop keep its identity
907        // when the edge the id came from is deleted. Doing it here (rather than
908        // only on sketch commit) covers every document, including one built by a
909        // script that never enters sketch mode. See the kernel's
910        // `features/sketch/loop_ids`.
911        stamp_sketch_loop_ids(&mut document);
912        // SEED this thread's kernel parts library from the document's block.
913        // The per-run request no longer carries the block (see
914        // `History::parts_library`), so this explicit install is the ONE door
915        // that seeds a loaded document — it is what `parts_library_json()`
916        // (SAVE), the mutation-path session re-run and the export lanes all
917        // resolve ACOMPs against, and it bumps the revision so the next run
918        // hands the fresh library to the background runner. A run that heals or
919        // GCs it ships the result back (`apply_run_output`).
920        let library = document
921            .get("partsLibrary")
922            .and_then(|block| serde_json::from_value(block.clone()).ok())
923            .unwrap_or_default();
924        brep_kernel::install_parts_library(&library);
925        self.history = History::from_request_json(&document.to_string())?;
926        self.document_thumbnail.replace(thumbnail.map(|image| (self.history.edit_serial(), image)));
927        Ok(self.rerun_history())
928    }
929
930    /// The whole history request document (persistence / debugging), with the
931    /// engine-owned extras folded back in on top of the kernel recipe so
932    /// save→open round-trips them:
933    ///
934    /// * `metadata` — the Properties-panel store, written only when non-empty so
935    ///   an un-annotated model persists as before;
936    /// * `workbench` — the CURRENT active-workbench id
937    ///   (`self.settings.workbench`), ALWAYS written so a saved part reopens in
938    ///   the workbench it was saved from (restored by
939    ///   [`Self::set_history_json`]). Always-embed keeps the invariant simple:
940    ///   the serialized field tracks the LIVE setting, never a stale stored copy
941    ///   — the load lifts it off the kernel recipe entirely, so this is the ONE
942    ///   place it is (re)written. Note the deliberate consequence: switching
943    ///   workbench changes this document, so the file panel's dirty flag flips —
944    ///   consistent with the `metadata` precedent, and semantically true now
945    ///   that the workbench is part of the saved file.
946    pub fn history_request_json(&self) -> String {
947        let mut document: serde_json::Value =
948            serde_json::from_str(&self.history.request_json())
949                .unwrap_or_else(|_| serde_json::json!({}));
950        if let Some(object) = document.as_object_mut() {
951            if !self.metadata.is_empty() {
952                object.insert("metadata".into(), self.metadata.to_json());
953            }
954            object.insert("thumbnail".into(), self.model_thumbnail());
955            object.insert(
956                "workbench".into(),
957                serde_json::Value::String(self.settings.workbench.clone()),
958            );
959        }
960        document.to_string()
961    }
962
963    /// Cache the small portable PNG by scene content, not by camera position.
964    /// The picture is the DOCUMENT's, so it is rendered only while the scene is
965    /// the document's model as built. A run the scene has not caught up with
966    /// (an edit whose rebuild is still to come) gets an explicitly pending,
967    /// empty image rather than a picture of the previous geometry; plugin work
968    /// in flight is not that, since a candidate keeps its own scene until it
969    /// commits. A transient presentation — an expression preview (a family
970    /// member shown in the document's place) or an illustration — gets the
971    /// document's own last picture (the one it was opened with, or the one its
972    /// last save rendered) rather than what is on screen. A just-opened file
973    /// keeps its embedded image while its unchanged recipe is being rebuilt.
974    /// The document's picture is keyed by the history's edit serial, which
975    /// moves on user edits, undo and redo only (a run's write-back ticks the
976    /// revision). The same built model renders the same bytes every time.
977    fn model_thumbnail(&self) -> serde_json::Value {
978        let pending = self.run_generation != self.applied_generation();
979        let transient = self.expression_preview.is_some() || self.illustration_snapshot.is_some();
980        let mut key = vec![self.history.revision(), self.applied_generation(),
981            self.scene.visibility_revision(), self.settings_generation, pending as u64, transient as u64];
982        key.extend(self.scene.solids().iter().map(|s| s.revision));
983        if let Some((old, image)) = self.thumbnail_cache.borrow().as_ref() {
984            if *old == key { return image.clone(); }
985        }
986        let image = if pending || transient {
987            self.document_thumbnail.borrow().as_ref().filter(|(serial, _)| *serial == self.history.edit_serial())
988                .map(|(_, image)| image.clone())
989                .unwrap_or_else(|| crate::thumbnail::empty_embedded("pending"))
990        } else {
991            let capture = crate::thumbnail::capture(&self.scene);
992            let image = match crate::thumbnail::render_png(&capture, crate::thumbnail::SIZE) {
993                Some(png) => crate::thumbnail::embedded_png(&png, crate::thumbnail::SIZE, "ready"),
994                None => crate::thumbnail::empty_embedded("empty"),
995            };
996            self.document_thumbnail.replace(Some((self.history.edit_serial(), image.clone())));
997            image
998        };
999        self.thumbnail_cache.replace(Some((key, image.clone())));
1000        image
1001    }
1002
1003    /// The tree listing `{ step, features:[{index,type,id}] }` for the UI panel.
1004    pub fn history_listing_json(&self) -> String {
1005        self.history.listing_json()
1006    }
1007
1008    /// The last build report JSON.
1009    pub fn history_report_json(&self) -> String {
1010        self.history_report.clone()
1011    }
1012
1013    pub fn history_len(&self) -> usize {
1014        self.history.len()
1015    }
1016
1017    /// The rolled-to (selected) feature index.
1018    pub fn history_rollback(&self) -> usize {
1019        self.history.rollback()
1020    }
1021
1022    /// A monotonic counter of mutation opportunities on the history document —
1023    /// the cache key for anything derived from it. See [`crate::history::History::revision`].
1024    pub fn history_revision(&self) -> u64 {
1025        self.history.revision()
1026    }
1027
1028    pub fn feature_type_at(&self, index: usize) -> Option<String> {
1029        self.history.feature_type(index)
1030    }
1031
1032    pub fn feature_id_at(&self, index: usize) -> Option<String> {
1033        self.history.feature_id(index)
1034    }
1035
1036    /// The `inputParams` document of feature `index` (`"null"` if none) — the
1037    /// dialog's editing-buffer source.
1038    pub fn feature_params_json(&self, index: usize) -> String {
1039        self.history
1040            .feature_params(index)
1041            .map(|v| v.to_string())
1042            .unwrap_or_else(|| "null".to_string())
1043    }
1044
1045    /// Mint the id for a NEW feature: `{base}{N}` where `base` is the feature's
1046    /// shortName ([`crate::features::feature_short_name`]) and `N` is the part
1047    /// history's persistent GLOBAL counter (monotonic, never reused, round-trips
1048    /// save/load — see [`History::next_feature_id`]). `&mut` because the counter
1049    /// advances; if the caller's `add_feature` then fails the number is simply
1050    /// skipped (monotonic-with-gaps is the contract, not an error).
1051    pub fn next_feature_id(&mut self, base: &str) -> String {
1052        self.history.next_feature_id(base)
1053    }
1054
1055    /// Adopt an edited document as one undo step and rebuild through the normal
1056    /// runner, preserving the tab's scene settings and history stack.
1057    pub fn edit_document_json(&mut self, document: &str) -> Result<String, String> {
1058        let value: serde_json::Value = serde_json::from_str(document).map_err(|e| e.to_string())?;
1059        let library = value.get("partsLibrary").map(|v| serde_json::from_value(v.clone()))
1060            .transpose().map_err(|e| format!("parts library: {e}"))?;
1061        self.history.adopt_document_checkpointed(document)?;
1062        // The runner's library channel reads the resident store. Updating only
1063        // History left it serving the old snapshot after Update Components.
1064        if let Some(library) = library {
1065            brep_kernel::install_parts_library(&library);
1066        }
1067        Ok(self.rerun_history())
1068    }
1069
1070    /// Publish derived changes folded into the current user edit, without adding
1071    /// another undo step (for example PCB placement and its assembly pose).
1072    pub fn rebuild_current_history(&mut self) -> String {
1073        self.rerun_history()
1074    }
1075
1076    /// Roll the model to feature `index`: re-run `features[0..=index]`.
1077    pub fn roll_to(&mut self, index: usize) -> String {
1078        self.history.set_rollback(index);
1079        self.rerun_history()
1080    }
1081
1082    /// Replace feature `id`'s input params and re-run at the current rollback →
1083    /// the viewport updates live.
1084    pub fn update_feature_params(
1085        &mut self,
1086        id: &str,
1087        input_params_json: &str,
1088    ) -> Result<String, String> {
1089        let mut params: serde_json::Value = serde_json::from_str(input_params_json)
1090            .map_err(|e| format!("feature params parse: {e}"))?;
1091        let index = self
1092            .history
1093            .index_of(id)
1094            .ok_or_else(|| format!("no feature with id '{id}'"))?;
1095        self.stamp_face_transform_pivot(index, &mut params);
1096        self.history.set_feature_params(index, params);
1097        Ok(self.rerun_history())
1098    }
1099
1100    /// Replace the `inputParams` of MANY features as ONE model edit — the
1101    /// [`Self::update_feature_params`] batch sibling ([`Self::add_features`] is
1102    /// the append-only one). ONE undo checkpoint and ONE history re-run for the
1103    /// whole set.
1104    ///
1105    /// The lane that needs it: a PACKED BOM row rolls up every occurrence whose
1106    /// occurrence data matches, so editing one of its cells writes the same key
1107    /// into N ACOMP features. Looping `update_feature_params` would cost N
1108    /// re-runs and — worse — N undo entries, so taking back one visible edit
1109    /// would need N presses of undo.
1110    ///
1111    /// Unknown ids are reported (the whole batch is refused before anything is
1112    /// written, so a typo can never half-apply); an empty batch is a no-op that
1113    /// neither checkpoints nor runs.
1114    pub fn update_many_feature_params(
1115        &mut self,
1116        edits: &[(String, serde_json::Value)],
1117    ) -> Result<String, String> {
1118        if edits.is_empty() {
1119            return Ok(self.history_report.clone());
1120        }
1121        let mut resolved: Vec<(usize, serde_json::Value)> = Vec::with_capacity(edits.len());
1122        for (id, params) in edits {
1123            let index = self
1124                .history
1125                .index_of(id)
1126                .ok_or_else(|| format!("no feature with id '{id}'"))?;
1127            let mut params = params.clone();
1128            self.stamp_face_transform_pivot(index, &mut params);
1129            resolved.push((index, params));
1130        }
1131        self.history.set_many_feature_params(&resolved);
1132        Ok(self.rerun_history())
1133    }
1134
1135    /// Append a feature (a full `{type, inputParams, …}` descriptor) and roll to
1136    /// it. The caller assigns a unique `id` (see [`Self::next_feature_id`]).
1137    pub fn add_feature(&mut self, feature_json: &str) -> Result<String, String> {
1138        let feature: serde_json::Value =
1139            serde_json::from_str(feature_json).map_err(|e| format!("feature parse: {e}"))?;
1140        if !self.append_plugin_features(std::slice::from_ref(&feature))? {
1141            self.history.push_feature(feature);
1142        }
1143        let last = self.history.len().saturating_sub(1);
1144        self.history.set_rollback(last);
1145        Ok(self.rerun_history())
1146    }
1147
1148    /// Append MANY features and roll to the last — [`Self::add_feature`]'s batch
1149    /// sibling, and the reason it exists: `add_feature` re-runs the WHOLE history
1150    /// per call, so a lane that appends N features by looping it costs N rebuilds
1151    /// (O(N²) work on an N-part STEP-assembly import). This pushes all of them,
1152    /// then re-runs ONCE — one rebuild, one undo checkpoint, one
1153    /// [`applied_generation`](Self::applied_generation) bump.
1154    ///
1155    /// Deliberately NOT [`Self::set_history_json`]: that is the document-SWITCH
1156    /// path (it clears the kernel history cache and resets the runner's delta
1157    /// baseline, forcing a full cold rebuild), which is the wrong mechanism for an
1158    /// append onto the live document.
1159    ///
1160    /// An empty batch is a no-op — no checkpoint, no run, no generation bump —
1161    /// and returns the standing report. The caller assigns each feature's unique
1162    /// `id` (see [`Self::next_feature_id`]).
1163    pub fn add_features(&mut self, features: &[serde_json::Value]) -> String {
1164        if features.is_empty() {
1165            return self.history_report.clone();
1166        }
1167        match self.append_plugin_features(features) {
1168            Ok(true) => {},
1169            Ok(false) => self.history.push_features(features.to_vec()),
1170            Err(error) => return serde_json::json!({"error":error}).to_string(),
1171        }
1172        let last = self.history.len().saturating_sub(1);
1173        self.history.set_rollback(last);
1174        self.rerun_history()
1175    }
1176
1177    /// Delete the feature with id `id` (no-op if absent) and re-run, clamping the
1178    /// rolled-to step.
1179    pub fn delete_feature(&mut self, id: &str) -> String {
1180        match self.history.index_of(id) {
1181            Some(index) => self.delete_feature_at(index),
1182            None => self.rerun_history(),
1183        }
1184    }
1185
1186    /// Delete the feature at `index` (no-op when out of range) and re-run,
1187    /// clamping the rolled-to step.
1188    ///
1189    /// The POSITIONAL twin of [`Self::delete_feature`], and the only way to
1190    /// remove a feature whose `inputParams` carry no `id` — a shape a hand-built
1191    /// history JSON can still contain, and one an id-keyed delete can never
1192    /// address.
1193    pub fn delete_feature_at(&mut self, index: usize) -> String {
1194        if index < self.history.len() {
1195            self.history.remove_feature(index);
1196            let step = self
1197                .history
1198                .rollback()
1199                .min(self.history.len().saturating_sub(1));
1200            self.history.set_rollback(step);
1201        }
1202        self.rerun_history()
1203    }
1204
1205    /// Move feature `index` one slot up/down (reorder), keeping it selected.
1206    pub fn reorder_feature(&mut self, index: usize, up: bool) -> String {
1207        let len = self.history.len();
1208        if len >= 2 {
1209            let target = if up {
1210                index.checked_sub(1)
1211            } else if index + 1 < len {
1212                Some(index + 1)
1213            } else {
1214                None
1215            };
1216            if let Some(target) = target {
1217                self.history.swap(index, target);
1218                self.history.set_rollback(target);
1219            }
1220        }
1221        self.rerun_history()
1222    }
1223
1224}
1225
1226impl EngineState {
1227    /// Whether an undo step is available (to enable the toolbar's Undo button).
1228    pub fn can_undo(&self) -> bool {
1229        self.history.can_undo()
1230    }
1231
1232    /// Whether a redo step is available.
1233    pub fn can_redo(&self) -> bool {
1234        self.history.can_redo()
1235    }
1236
1237    /// Undo the last model mutation: restore the previous document + rolled-to
1238    /// step, then re-run + reconcile the scene. Returns the build report; a no-op
1239    /// (empty undo stack) returns the last report unchanged.
1240    pub fn undo(&mut self) -> String {
1241        if self.history.undo() {
1242            self.reinstall_rewound_parts_library();
1243            self.rerun_history()
1244        } else {
1245            self.history_report.clone()
1246        }
1247    }
1248
1249    /// Redo the last undone model mutation (symmetric with [`Self::undo`]).
1250    pub fn redo(&mut self) -> String {
1251        if self.history.redo() {
1252            self.reinstall_rewound_parts_library();
1253            self.rerun_history()
1254        } else {
1255            self.history_report.clone()
1256        }
1257    }
1258
1259    /// Push the just-rewound `partsLibrary` block back into the kernel's
1260    /// main-side store, so time travel moves the LIBRARY with the document.
1261    ///
1262    /// Without this, undo only half-works on anything that edits a library
1263    /// entry. The undo snapshot carries the block (`History::Snapshot`), but the
1264    /// block is a MIRROR: the per-run request does not carry it
1265    /// ([`History::prefix_request`] omits it) and a run that heals or GCs the
1266    /// store writes its result back over the block (`apply_run_output`). So a
1267    /// rewound block that was never pushed into the store is simply overwritten
1268    /// again, and the undo silently does nothing — which is what
1269    /// [`Self::set_part_attribute`](crate::engine_state::EngineState::set_part_attribute)
1270    /// would hit on its first undo.
1271    ///
1272    /// `install_parts_library` matches the store to the block BY CONTENT
1273    /// IDENTITY: an identical entry is kept verbatim (so a heal this side
1274    /// derived is not clobbered), a changed one is replaced and marked dirty
1275    /// (so the ACOMP self-heal re-derives every instance), and one absent from
1276    /// the block is dropped. An unchanged block is therefore a no-op, which is
1277    /// the overwhelmingly common undo.
1278    pub(super) fn reinstall_rewound_parts_library(&mut self) {
1279        let library = serde_json::from_value(self.history.parts_library().clone())
1280            .unwrap_or_default();
1281        brep_kernel::install_parts_library(&library);
1282    }
1283
1284    // --- Selection (Esc clears / viewport click selects) ------------------
1285
1286}
1287
1288/// Stamp per-loop ids onto every SKETCH feature's geometries in a history
1289/// document, in place.
1290///
1291/// The persistence half of per-loop face naming. The kernel DERIVES a loop's id
1292/// the same way every run, so this renames nothing; what it adds is durability —
1293/// a stored id survives deleting the edge it was originally derived from, which
1294/// derivation alone cannot. Running it on document LOAD (not only on sketch
1295/// commit) means a model built by a script, an import, or any other path that
1296/// never opens the sketch editor still gets its ids written down.
1297///
1298/// Assemblies: a parts-library entry embeds a FULL sub-part history
1299/// (`partsLibrary[*].document`), whose features can include sketches of its own,
1300/// so the walk recurses into each one. Without that, a sketch inside an imported
1301/// assembly part would derive correct names but carry no stored ids — exactly the
1302/// case (deleting the edge an id came from) that persisting exists to cover.
1303/// Depth is bounded: a sub-document's own library is seeded from the kernel store
1304/// rather than nested inside the entry, so one level of recursion reaches all of
1305/// them, and `MAX_LIBRARY_DEPTH` stops a malformed self-referential document.
1306///
1307/// Malformed features are skipped rather than rejected: this is a best-effort
1308/// enrichment on the way to the kernel, which validates the document itself.
1309fn stamp_sketch_loop_ids(document: &mut serde_json::Value) {
1310    /// Depth cap for the embedded sub-document walk — a guard against a
1311    /// hand-edited or corrupt document that nests libraries into each other.
1312    const MAX_LIBRARY_DEPTH: usize = 8;
1313    stamp_sketch_loop_ids_to_depth(document, MAX_LIBRARY_DEPTH);
1314}
1315
1316/// [`stamp_sketch_loop_ids`] with the remaining recursion budget.
1317fn stamp_sketch_loop_ids_to_depth(document: &mut serde_json::Value, depth: usize) {
1318    if let Some(features) = document
1319        .get_mut("features")
1320        .and_then(serde_json::Value::as_array_mut)
1321    {
1322        for feature in features {
1323            if feature.get("type").and_then(serde_json::Value::as_str) != Some("S") {
1324                continue;
1325            }
1326            let Some(sketch) = feature
1327                .get_mut("persistentData")
1328                .and_then(|data| data.get_mut("sketch"))
1329            else {
1330                continue;
1331            };
1332            brep_kernel::assign_sketch_loop_ids(sketch);
1333        }
1334    }
1335    if depth == 0 {
1336        return;
1337    }
1338    // Each library entry's embedded sub-part history gets the same treatment.
1339    let Some(library) = document
1340        .get_mut("partsLibrary")
1341        .and_then(serde_json::Value::as_object_mut)
1342    else {
1343        return;
1344    };
1345    for (_, entry) in library.iter_mut() {
1346        let Some(embedded) = entry.get_mut("document") else {
1347            continue;
1348        };
1349        stamp_sketch_loop_ids_to_depth(embedded, depth - 1);
1350    }
1351}
1352
1353impl EngineState {
1354    /// Load a whole model document (a saved `.nbrep` recipe) and FRAME it:
1355    /// [`set_history_json`](Self::set_history_json) (which rolls to the last
1356    /// feature) followed by [`zoom_to_fit`](Self::zoom_to_fit). The one call the
1357    /// file panel's **Open** needs — the model IS the engine-owned history, so
1358    /// opening a file is loading its request JSON and reframing. Returns the
1359    /// build-report JSON.
1360    pub fn load_model_and_fit(&mut self, request_json: &str) -> Result<String, String> {
1361        // Frame once the run lands, not now: under a background runner (native
1362        // thread / wasm worker) the freshly loaded model is not resident yet when
1363        // `set_history_json` returns, so an immediate `zoom_to_fit` would frame the
1364        // OLD scene. Set BEFORE the submit so the Inline runner's in-call `pump`
1365        // still frames synchronously. See [`EngineState::pending_fit`].
1366        self.pending_fit = true;
1367        let result = self.set_history_json(request_json);
1368        if result.is_err() {
1369            // A rejected document submits no run, so the armed fit would otherwise
1370            // fire on the OLD scene next frame — disarm it.
1371            self.pending_fit = false;
1372        }
1373        result
1374    }
1375}
1376
1377
1378
1379
1380
1381
1382/// The run report's `featureRefusals` object, added only when a feature failed
1383/// with a TYPED refusal: feature id → the kernel's refusal as it serializes
1384/// (`class` and its payload, `stage`, `message` — the text `featureErrors`
1385/// carries for the same feature) plus `step`, the motion step that refused,
1386/// when the feature records one (Transform Face: `rotation` / `translation`).
1387/// Absent otherwise, so a report with no typed refusal is byte-for-byte what it
1388/// was before this key existed.
1389fn with_refusals(
1390    mut value: serde_json::Value,
1391    report: &crate::pipeline::SceneBuildReport,
1392) -> serde_json::Value {
1393    if report.feature_refusals.is_empty() {
1394        return value;
1395    }
1396    let refusals: serde_json::Map<String, serde_json::Value> = report
1397        .feature_refusals
1398        .iter()
1399        .map(|(id, refusal, step)| {
1400            let mut value = serde_json::to_value(refusal).unwrap_or(serde_json::Value::Null);
1401            if let (Some(step), serde_json::Value::Object(object)) = (step, &mut value) {
1402                object.insert("step".into(), serde_json::Value::String(step.clone()));
1403            }
1404            (id.clone(), value)
1405        })
1406        .collect();
1407    if let serde_json::Value::Object(object) = &mut value {
1408        object.insert("featureRefusals".into(), serde_json::Value::Object(refusals));
1409    }
1410    value
1411}
1412
1413/// The run report's `featureApproximations` object, added only when a feature
1414/// SUCCEEDED carrying a MEASURED approximation: feature id → the kernel's
1415/// approximations as they serialize (`code`, `body`, `measured`, `bar`,
1416/// `volume_bound`, `edges[{edge_id, curve_ref, face_ref, surface_ref,
1417/// off_carrier_mm, origin}]`, `message`), each plus a one-line `summary` the
1418/// history tree shows as the feature's leaf. Absent otherwise, so a report with
1419/// no approximation is byte-for-byte what it was before this key existed — the
1420/// same contract as `featureRefusals`. Distinct from `featureRefusals` (the
1421/// result does not stand) and `featureFulfilment` (what was done of what was
1422/// asked): an approximation's result stands, and this says by how much it is
1423/// not exact.
1424fn with_approximations(
1425    mut value: serde_json::Value,
1426    report: &crate::pipeline::SceneBuildReport,
1427) -> serde_json::Value {
1428    if report.feature_approximations.is_empty() {
1429        return value;
1430    }
1431    let approximations: serde_json::Map<String, serde_json::Value> = report
1432        .feature_approximations
1433        .iter()
1434        .map(|(id, approximations)| {
1435            let entries: Vec<serde_json::Value> = approximations
1436                .iter()
1437                .map(|approximation| {
1438                    let mut value =
1439                        serde_json::to_value(approximation).unwrap_or(serde_json::Value::Null);
1440                    if let serde_json::Value::Object(object) = &mut value {
1441                        object.insert(
1442                            "summary".into(),
1443                            serde_json::Value::String(approximation_summary(approximation)),
1444                        );
1445                    }
1446                    value
1447                })
1448                .collect();
1449            (id.clone(), serde_json::Value::Array(entries))
1450        })
1451        .collect();
1452    if let serde_json::Value::Object(object) = &mut value {
1453        object.insert("featureApproximations".into(), serde_json::Value::Object(approximations));
1454    }
1455    value
1456}
1457
1458/// One line for an approximation, for the history tree's leaf: the marker
1459/// word, the code, the body, the measurement against its bar and the volume
1460/// bound when the code implies one. Code-agnostic on purpose — the units of
1461/// `measured` are the code's (mm² for `import.shell_closure`), so only the
1462/// volume bound, which every code states in mm³, carries a unit here; the
1463/// kernel's `message` has the full text with units, faces and edges.
1464pub fn approximation_summary(approximation: &brep_kernel::Approximation) -> String {
1465    let ratio = if approximation.bar > 0.0 {
1466        format!(" ({:.1}x)", approximation.measured / approximation.bar)
1467    } else {
1468        String::new()
1469    };
1470    let bound = approximation
1471        .volume_bound
1472        .map(|bound| format!("; volume determined to ±{bound:.3e} mm³"))
1473        .unwrap_or_default();
1474    format!(
1475        "approximate ({}): {} measured {:.3e} against a bar of {:.3e}{ratio}{bound}",
1476        approximation.code, approximation.body, approximation.measured, approximation.bar
1477    )
1478}
1479
1480/// The run report's `featureFulfilment` object: feature id → the typed
1481/// fulfilment (`requested`, `applied`, `rejected[{name, kind, reason}]`) plus a
1482/// one-line `summary` the tree and the automation report show verbatim. Only the
1483/// features that reported one appear, so an absent key means "did everything".
1484fn fulfilment_map(report: &crate::pipeline::SceneBuildReport) -> serde_json::Map<String, serde_json::Value> {
1485    report
1486        .feature_fulfilment
1487        .iter()
1488        .map(|(id, fulfilment)| {
1489            let mut value = serde_json::to_value(fulfilment).unwrap_or(serde_json::Value::Null);
1490            if let serde_json::Value::Object(object) = &mut value {
1491                object.insert("summary".into(), serde_json::Value::String(fulfilment.summary()));
1492            }
1493            (id.clone(), value)
1494        })
1495        .collect()
1496}