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