Skip to main content

brep_render/engine_state/
history_ops.rs

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