Skip to main content

brep_render/
history.rs

1//! [`History`] — the engine-owned, editable model recipe: the ordered feature
2//! history plus the rollback index (the feature the model is currently built up
3//! to). This is the SINGLE SOURCE OF TRUTH for the model — the UI keeps NO copy;
4//! it mutates and reads the history only through [`crate::engine_state::EngineState`]
5//! methods. That keeps one engine-owned history (UI-agnostic) and converges with
6//! the in-flight "whole history in Rust" pipeline migration — later this sinks
7//! into `brep-kernel-rs` proper without touching the UI.
8//!
9//! Rolling to a step re-runs `features[0..=rollback]` through the SAME kernel
10//! pipeline: the full feature list stays in the request and `stopAtId` (the
11//! editor's "stop at the expanded feature") halts execution AFTER the rolled-to
12//! feature, so the kernel's incremental history cache is RETAINED across rolls
13//! (no thrash) and the viewport shows the model as of that step.
14
15use serde_json::Value;
16
17/// The cap on the undo (and redo) stack depth — old entries fall off the bottom.
18const MAX_UNDO: usize = 100;
19
20/// A restorable model state: the whole document PLUS the rolled-to step, captured
21/// together so an undo returns both the geometry and the view to the state they
22/// were in right before the mutation.
23#[derive(Debug, Clone)]
24struct Snapshot {
25    request: Value,
26    rollback: usize,
27    /// The parts-library block as it stood before the mutation. An `Rc`, so
28    /// capturing it costs a pointer bump however large the library is — undo
29    /// and redo still rewind it exactly as they did when it lived inside
30    /// `request` (a redo of a component insert must restore the entry its
31    /// ACOMP references).
32    parts_library: std::rc::Rc<Value>,
33    /// Names this undo step, so a caller can later ask whether the step it
34    /// took is still the newest one ([`History::undo_top`]). Drawn from one
35    /// process-wide counter; a redo entry keeps no serial of its own.
36    serial: u64,
37    /// The rename (`old`, `new`) the step FROM this snapshot made, if it was an
38    /// entity rename ([`History::note_rename`]): undo and redo report it, so the
39    /// engine moves the name-keyed records it holds outside the document.
40    renamed: Option<(String, String)>,
41}
42
43/// Hands out every [`Snapshot::serial`] in this process.
44static NEXT_STEP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
45
46fn next_step() -> u64 {
47    NEXT_STEP.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
48}
49
50/// The engine-owned mutable history.
51#[derive(Debug, Clone)]
52pub struct History {
53    /// The whole `HistoryRequest` document
54    /// (`{expressions, configurator, features: [...]}`).
55    ///
56    /// PRIVATE and reached only through [`Self::document`] /
57    /// [`Self::document_mut`] — the `_mut` door bumps [`Self::revision`], which
58    /// is what lets a per-frame cache key off the document without having to
59    /// enumerate the mutation sites. Naming the field `document` (not
60    /// `request`) is what makes that total: the compiler, not a reviewer, finds
61    /// a site that bypasses the doors.
62    document: Value,
63    /// A ticket drawn from one process-wide counter on construction and again on
64    /// every `&mut` reach into [`Self::document`]. Deliberately coarse — it
65    /// counts mutation OPPORTUNITIES, so it moves when nothing actually changed
66    /// (a cache then rebuilds once, harmlessly) but it cannot fail to move when
67    /// something did.
68    ///
69    /// Drawn from a shared counter rather than incremented per instance, because
70    /// a `History` is not only mutated, it is REPLACED: `set_history_json`
71    /// installs a fresh one on the engine a document ALREADY owns — the
72    /// `?loadModel=` boot drain, a recovery restore, an STL import accept, New.
73    /// A per-instance counter restarts there, so a replacement would hand a
74    /// cache a revision it had already seen for the same document and the cache
75    /// would serve the PREVIOUS model's values. One counter makes the guarantee
76    /// the same for both: no two states of any `History` in this process ever
77    /// share a revision.
78    revision: u64,
79    /// Index into `features` the model is rolled to (clamped to the last).
80    rollback: usize,
81    /// Undo/redo over the MODEL document. A snapshot is pushed BEFORE each model
82    /// mutation (edit / add / delete / reorder); roll-to-step is view state and
83    /// is NOT snapshotted. Rapid same-target edits (a slider drag) coalesce into a
84    /// single undo entry via `last_edit_key`. The stacks live here in the engine
85    /// core — the model is engine-owned, so its undo history is too; the UI only
86    /// triggers `undo()` / `redo()`.
87    undo_stack: Vec<Snapshot>,
88    redo_stack: Vec<Snapshot>,
89    /// The rename the last undo, redo or retract crossed, as it applies to the
90    /// state now restored (`old` -> `new`); taken by [`Self::take_travel_rename`].
91    travel_rename: Option<(String, String)>,
92    /// The coalescing token of the most recently recorded edit (see `checkpoint`).
93    last_edit_key: Option<String>,
94    /// The persistent GLOBAL feature counter: bumped by one on every new-feature
95    /// mint ([`Self::next_feature_id`]), so a new id is `{shortName}{counter}`.
96    /// MONOTONIC and NEVER reused — deleting a feature does not free its number,
97    /// and (deliberately) undo does NOT rewind it, so re-doing an add can't collide
98    /// with a number already handed out. It is kept OFF `self.document` in memory
99    /// (so the undo snapshots that clone `request` never rewind it) and folded into
100    /// the serialized document under `"featureCounter"` so it round-trips save/load
101    /// (see [`Self::request_json`] / [`Self::from_request_json`]).
102    feature_counter: u64,
103    /// The assemblies PARTS LIBRARY block (`partsLibrary`), kept OFF
104    /// `self.document` for the same reason as `feature_counter`: every per-edit
105    /// pass over the document — the undo checkpoint clone, the kernel request
106    /// built by [`Self::prefix_request`], the assembly pose fold's serialize →
107    /// parse round trip — would otherwise copy the whole library, which for an
108    /// imported STEP assembly is megabytes of embedded part payload PER EDIT
109    /// and froze the browser UI. Folded back in by [`Self::request_json`] so
110    /// the SAVED document is byte-identical to before, and lifted back out by
111    /// [`Self::from_request_json`] / the adopt doors.
112    ///
113    /// `Rc` because undo/redo MUST rewind it (a redo of a component insert has
114    /// to restore the entry its ACOMP references) while a checkpoint must stay
115    /// a pointer copy — the whole point of moving it off `request`.
116    parts_library: std::rc::Rc<Value>,
117    /// Why the latest edit of a part's pins or ports was not followed to the
118    /// other side, naming the label that blocks it (see the pins-and-ports
119    /// block below). `None` once an edit binds, and after undo, redo or a
120    /// replaced document, which restore both sides together.
121    pin_port_hold: Option<String>,
122    /// A symbol edit changed the part's declared connection points, which only
123    /// a history run publishes. The engine's `pump` re-runs and clears it, so
124    /// no host has to remember to.
125    ports_followed: bool,
126    /// A ticket (from the same counter as [`Self::revision`]) redrawn on every
127    /// USER edit: every undo checkpoint, coalesced or not, and every undo and
128    /// redo. Machine writes (a solver fold, a parts-library heal, a
129    /// `_no_undo` block) and rolling do not move it. See [`Self::edit_serial`].
130    edit_serial: u64,
131    /// Why this document may not change — a PLM revision that is released, or
132    /// that this user has not checked out (`BREP_app`'s `Document::access`).
133    /// `None`: editable, as every file-based document always is. See
134    /// [`Self::lock`].
135    lock: Option<String>,
136    /// Where a mutation lands while [`Self::lock`] holds: a copy of the
137    /// document taken by [`Self::document_mut`] and thrown away by the next.
138    scratch: Value,
139    /// How many mutations were refused since construction — the count a host
140    /// watches to tell the user "check out to edit" ([`Self::refused_edits`]).
141    refused: u64,
142    /// Of those, the ones that were a USER's edit ([`Self::refused_user_edits`]).
143    refused_user: u64,
144    /// Set while an agent's staged feature evaluates
145    /// (`EngineState::stage_feature_begin`): USER edits are refused — at
146    /// their checkpoint or [`Self::refuse_user`] — while the run's own
147    /// write-back still lands. Unlike [`Self::lock`] it never touches a
148    /// write-back. See [`Self::set_busy`].
149    busy: Option<String>,
150    /// A user edit was refused for `busy` this frame: its `document_mut`
151    /// reach lands on the scratch copy. Cleared at the top of every pump
152    /// ([`Self::begin_frame`]), before any run lands.
153    refuse_next: bool,
154    /// User edits refused for `busy`, counted since construction.
155    busy_refused: u64,
156    /// The open undo group ([`Self::group_begin`]): `(token, step)`, where
157    /// `step` is the undo step the group's first edit took. Every later edit
158    /// while it is still the newest step folds into it, so a script's run is
159    /// one undo step however many edits it made.
160    group: Option<(u64, Option<u64>)>,
161}
162
163/// Hands out every revision ticket in this process — see [`History::revision`].
164/// Relaxed is enough: the value is only ever compared for equality against one
165/// a single thread read earlier, never used to order anything.
166static NEXT_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
167
168fn next_revision() -> u64 {
169    NEXT_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
170}
171
172impl Default for History {
173    fn default() -> Self {
174        Self {
175            document: empty_request(),
176            revision: next_revision(),
177            edit_serial: next_revision(),
178            rollback: 0,
179            undo_stack: Vec::new(),
180            redo_stack: Vec::new(),
181            travel_rename: None,
182            last_edit_key: None,
183            group: None,
184            feature_counter: 0,
185            parts_library: std::rc::Rc::new(Value::Null),
186            pin_port_hold: None,
187            ports_followed: false,
188            lock: None,
189            scratch: Value::Null,
190            refused: 0,
191            refused_user: 0,
192            busy: None,
193            refuse_next: false,
194            busy_refused: 0,
195        }
196    }
197}
198
199fn empty_request() -> Value {
200    serde_json::json!({ "expressions": "", "configurator": {}, "features": [] })
201}
202
203/// The trailing run of ASCII digits of `id` read as a number (`"P.CU12"` → 12,
204/// `"Box"` → 0). Trailing digits are ASCII (one byte each), so the slice boundary
205/// is always a valid char boundary; a missing/overflowing run yields 0.
206fn trailing_number(id: &str) -> u64 {
207    let digit_bytes = id
208        .bytes()
209        .rev()
210        .take_while(u8::is_ascii_digit)
211        .count();
212    id[id.len() - digit_bytes..].parse().unwrap_or(0)
213}
214
215impl History {
216    pub(crate) fn fold_plugin_persistent_data(&mut self, id: &str, data: Value) {
217        let Some(index) = self.index_of(id) else { return; };
218        if self.features()[index].get("persistentData") == Some(&data) { return; }
219        if let Some(features) = self.document_mut().get_mut("features").and_then(Value::as_array_mut) {
220            features[index]["persistentData"] = data;
221        }
222    }
223
224    /// Publish a successfully recomputed staged transaction as exactly one undo step.
225    /// The caller must check its captured revision before reaching this door.
226    pub(crate) fn commit_staged(&mut self, staged: &Self) -> Result<(), String> {
227        if self.refuse_user() {
228            return Err(format!("the document is read-only: {}", self.locked().unwrap_or("locked")));
229        }
230        self.checkpoint(None);
231        *self.document_mut() = staged.document.clone();
232        self.parts_library = staged.parts_library.clone();
233        self.feature_counter = staged.feature_counter;
234        self.rollback = staged.rollback;
235        self.pin_port_hold = None;
236        Ok(())
237    }
238
239    /// Load a whole history document (a saved part file parses as one). Rolls to
240    /// the last feature. Ensures a `features` array exists.
241    pub fn from_request_json(json: &str) -> Result<Self, String> {
242        let mut request: Value =
243            serde_json::from_str(json).map_err(|e| format!("history parse: {e}"))?;
244        if !request.get("features").map(Value::is_array).unwrap_or(false) {
245            if let Some(obj) = request.as_object_mut() {
246                obj.insert("features".into(), Value::Array(Vec::new()));
247            } else {
248                request = empty_request();
249            }
250        }
251        // Lift the persistent feature counter OUT of the document so it lives ONLY
252        // in the struct field: kept off `self.document`, the undo snapshots (which
253        // clone `request`) can never rewind it, and it can't be double-folded on
254        // re-serialize. A document with no stored counter (fresh or saved before
255        // this field existed) safe-inits below.
256        let stored = request
257            .as_object_mut()
258            .and_then(|obj| obj.remove("featureCounter"))
259            .and_then(|value| value.as_u64());
260        // Lift the parts-library block out of the document for the same reason
261        // (see the `parts_library` field): every per-edit copy of `request`
262        // would otherwise carry megabytes of embedded part payload.
263        let parts_library = request
264            .as_object_mut()
265            .and_then(|obj| obj.remove("partsLibrary"))
266            .unwrap_or(Value::Null);
267        let mut history = Self {
268            document: request,
269            rollback: 0,
270            parts_library: std::rc::Rc::new(parts_library),
271            ..Self::default()
272        };
273        history.rollback = history.len().saturating_sub(1);
274        // Safe init when unstored: start ABOVE the largest numeric suffix already
275        // present among feature ids so the next mint (`{shortName}{counter+1}`)
276        // cannot collide with an existing id. This holds because no shortName ends
277        // in a digit (verified — even `IMPORT3D` ends in `D`), so an id's trailing
278        // digits ARE its numeric suffix and `counter+1` strictly exceeds them all.
279        // A STORED counter is floored the same way: a document whose counter is
280        // behind its own ids (hand-written, or saved by an older build) would
281        // otherwise mint an id it already has, which the append now refuses.
282        history.feature_counter = stored.unwrap_or(0).max(history.max_id_suffix());
283        Ok(history)
284    }
285
286    /// The largest trailing-integer suffix among all existing feature ids (0 when
287    /// none carry one) — the floor for a safe counter init on a document with no
288    /// stored `featureCounter` (see [`Self::from_request_json`]).
289    fn max_id_suffix(&self) -> u64 {
290        self.features()
291            .iter()
292            .filter_map(|f| {
293                f.get("inputParams")
294                    .and_then(|p| p.get("id"))
295                    .and_then(Value::as_str)
296            })
297            .map(trailing_number)
298            .max()
299            .unwrap_or(0)
300    }
301
302    /// The whole document, read-only.
303    fn document(&self) -> &Value {
304        &self.document
305    }
306
307    /// The whole document for mutation. Bumps [`Self::revision`] — this is the
308    /// only way to reach `self.document` mutably.
309    ///
310    /// It is NOT the only door a cache keyed on the revision has to cover. The
311    /// `partsLibrary` block is held in [`Self::parts_library`], beside the
312    /// document rather than inside it, and [`Self::request_json`] folds it back
313    /// in — so it is part of the saved document and has its own two setters,
314    /// which bump the revision themselves. Anything else lifted out of
315    /// `self.document` into a field of its own owes the same.
316    ///
317    /// While the history is [locked](Self::lock), the reach lands on a SCRATCH
318    /// copy that the next reach replaces, and the refusal is counted: every
319    /// mutation that goes through this door — a user edit, and equally a
320    /// solver fold or a pin settle — leaves [`Self::request_json`] exactly as
321    /// it was. The revision does not move either, since nothing changed.
322    fn document_mut(&mut self) -> &mut Value {
323        if self.lock.is_some() || self.refuse_next {
324            self.refused += 1;
325            self.scratch = self.document.clone();
326            return &mut self.scratch;
327        }
328        self.revision = next_revision();
329        &mut self.document
330    }
331
332    /// Refuse every change to the saved document until [`Self::unlock`]:
333    /// [`Self::request_json`] stays byte for byte what it is now, whatever is
334    /// called. `reason` is the sentence a host shows ("released", "checked out
335    /// by grace", "not checked out"). Rolling ([`Self::set_rollback`]) is view
336    /// state and stays free, and so does reading.
337    ///
338    /// The three writes that do not pass `Self::document_mut` — the parts
339    /// library, the feature counter and the undo/redo stacks — check the lock
340    /// themselves; `a_locked_history_keeps_its_saved_bytes` calls every
341    /// mutator and pins the invariant.
342    pub fn lock(&mut self, reason: impl Into<String>) {
343        self.lock = Some(reason.into());
344        // A typing run from before the lock must not coalesce with the first
345        // edit after the next checkout into one undo entry.
346        self.break_coalescing();
347    }
348
349    /// Allow changes again (a checkout took the lock).
350    pub fn unlock(&mut self) {
351        self.lock = None;
352        self.scratch = Value::Null;
353    }
354
355    /// Why the document may not change, or `None` when it may.
356    pub fn locked(&self) -> Option<&str> {
357        self.lock.as_deref()
358    }
359
360    /// Mutations refused while locked, counted since this history was built.
361    /// A host compares it frame to frame to tell the user an edit was refused.
362    pub fn refused_edits(&self) -> u64 {
363        self.refused
364    }
365
366    /// Refused mutations that were a user's edit: every one that takes an undo
367    /// checkpoint, an undo, redo or retract, a feature id minted, a parts-library
368    /// edit. A kernel write-back (a solver fold, a pin settle, a parts-library
369    /// heal) is refused just the same but not counted here: it is nobody's edit,
370    /// so a host tells the user about THIS count, not [`Self::refused_edits`].
371    pub fn refused_user_edits(&self) -> u64 {
372        self.refused_user
373    }
374
375    /// Count a refused write that does not pass [`Self::document_mut`], and
376    /// say whether to refuse it.
377    fn refuse(&mut self) -> bool {
378        if self.lock.is_some() {
379            self.refused += 1;
380            return true;
381        }
382        false
383    }
384
385    /// [`Self::refuse`] for a write only a user makes — refused, too, while
386    /// the history is [busy](Self::set_busy).
387    fn refuse_user(&mut self) -> bool {
388        let refused = self.refuse();
389        if refused {
390            self.refused_user += 1;
391            return true;
392        }
393        if self.busy.is_some() {
394            self.busy_refused += 1;
395            self.refuse_next = true;
396            return true;
397        }
398        false
399    }
400
401    /// Refuse USER edits while an agent's staged feature evaluates (`Some`),
402    /// or accept them again (`None`). A run's write-back is never refused
403    /// for this; a user's edit is, and counted ([`Self::busy_refused`]).
404    pub fn set_busy(&mut self, reason: Option<String>) {
405        self.busy = reason;
406        self.refuse_next = false;
407        if self.busy.is_some() {
408            self.break_coalescing();
409        }
410    }
411
412    /// Why user edits are being refused just now, if they are.
413    pub fn busy(&self) -> Option<&str> {
414        self.busy.as_deref()
415    }
416
417    /// User edits refused while busy, counted since construction.
418    pub fn busy_refused(&self) -> u64 {
419        self.busy_refused
420    }
421
422    /// The top of a frame's pump: a refused user edit's scratch redirect
423    /// ends here, before any run's write-back lands.
424    pub fn begin_frame(&mut self) {
425        self.refuse_next = false;
426    }
427
428    /// A monotonic counter of mutation opportunities on the document — the
429    /// cache key for anything derived from it that would otherwise be rebuilt
430    /// every frame (see the `__brepParams` blob in `BREP_app`).
431    pub fn revision(&self) -> u64 {
432        self.revision
433    }
434
435    /// Moves on every user edit of the model and on every undo and redo, and
436    /// on nothing else: not on a run's write-back, not on rolling. What a
437    /// transient view of the model (the family-row preview) keys on to know
438    /// that the user changed the model under it.
439    pub fn edit_serial(&self) -> u64 {
440        self.edit_serial
441    }
442
443    /// The features slice (empty if none).
444    pub fn features(&self) -> &[Value] {
445        self.document()
446            .get("features")
447            .and_then(Value::as_array)
448            .map(Vec::as_slice)
449            .unwrap_or(&[])
450    }
451
452    fn features_mut(&mut self) -> &mut Vec<Value> {
453        let obj = self
454            .document_mut()
455            .as_object_mut()
456            .expect("history request is a JSON object");
457        obj.entry("features")
458            .or_insert_with(|| Value::Array(Vec::new()));
459        obj.get_mut("features")
460            .and_then(Value::as_array_mut)
461            .expect("features is a JSON array")
462    }
463
464    pub fn len(&self) -> usize {
465        self.features().len()
466    }
467
468    pub fn is_empty(&self) -> bool {
469        self.len() == 0
470    }
471
472    /// The rolled-to index, clamped to a valid feature (0 when empty).
473    pub fn rollback(&self) -> usize {
474        self.rollback.min(self.len().saturating_sub(1))
475    }
476
477    pub fn set_rollback(&mut self, index: usize) {
478        self.rollback = if self.is_empty() {
479            0
480        } else {
481            index.min(self.len() - 1)
482        };
483        // Rolling to a step is a view move, not a model edit: it records NO undo
484        // snapshot, but it DOES break the edit-coalescing run so the next edit
485        // starts a fresh undo entry rather than merging with a pre-roll edit.
486        self.last_edit_key = None;
487    }
488
489    pub fn feature_type(&self, index: usize) -> Option<String> {
490        self.features()
491            .get(index)?
492            .get("type")
493            .and_then(Value::as_str)
494            .map(String::from)
495    }
496
497    pub fn feature_id(&self, index: usize) -> Option<String> {
498        self.features()
499            .get(index)?
500            .get("inputParams")
501            .and_then(|p| p.get("id"))
502            .and_then(Value::as_str)
503            .map(String::from)
504    }
505
506    pub fn index_of(&self, id: &str) -> Option<usize> {
507        self.features().iter().position(|f| {
508            f.get("inputParams")
509                .and_then(|p| p.get("id"))
510                .and_then(Value::as_str)
511                == Some(id)
512        })
513    }
514
515    /// The `inputParams` document of the feature at `index` (for the dialog).
516    pub fn feature_params(&self, index: usize) -> Option<Value> {
517        self.features().get(index)?.get("inputParams").cloned()
518    }
519
520    /// SOLVER write-back fold (the assembly pose-authority contract): set ONE
521    /// `inputParams` key of the feature whose `inputParams.id == id`, WITHOUT an
522    /// undo checkpoint and WITHOUT breaking edit coalescing — a solve write-back
523    /// is the kernel adopting its own result, not a user edit, so it must never
524    /// mint an undo entry (undoing a user action then re-running re-solves and
525    /// re-folds anyway). Returns whether a feature matched.
526    pub fn fold_param_no_undo(&mut self, id: &str, key: &str, value: Value) -> bool {
527        let Some(index) = self.index_of(id) else {
528            return false;
529        };
530        if let Some(feature) = self.features_mut().get_mut(index) {
531            if let Some(params) = feature
532                .get_mut("inputParams")
533                .and_then(Value::as_object_mut)
534            {
535                params.insert(key.to_string(), value);
536                return true;
537            }
538        }
539        false
540    }
541
542    pub fn set_feature_params(&mut self, index: usize, params: Value) {
543        if index >= self.len() {
544            return;
545        }
546        // Coalesce a slider drag (many consecutive edits of the SAME feature) into
547        // one undo entry, keyed by the feature index.
548        self.checkpoint(Some(&format!("param:{index}")));
549        if let Some(feat) = self.features_mut().get_mut(index) {
550            if let Some(obj) = feat.as_object_mut() {
551                obj.insert("inputParams".into(), params);
552            }
553        }
554    }
555
556    /// Replace the `inputParams` of MANY features as ONE mutation —
557    /// [`Self::set_feature_params`]'s batch sibling, and the reason it exists:
558    /// a packed BOM row rolls up N occurrences, so editing one cell writes N
559    /// features. A `set_feature_params` loop would mint N undo entries (each
560    /// keyed `param:{index}`, so none of them coalesce with each other), and
561    /// the user would have to press undo N times to take back ONE edit.
562    ///
563    /// Exactly ONE checkpoint covers the whole batch. The coalesce key names
564    /// the SET of indices, so a run of edits to the SAME set (typing into one
565    /// packed cell) still merges into a single entry, while switching to a
566    /// different set starts a new one — the `param:{index}` rule, lifted to a
567    /// group. Out-of-range indices are skipped; an empty batch is a no-op (no
568    /// checkpoint, so a fan-out that matched nothing leaves no empty entry).
569    pub fn set_many_feature_params(&mut self, edits: &[(usize, Value)]) {
570        let len = self.len();
571        let mut in_range: Vec<&(usize, Value)> =
572            edits.iter().filter(|(index, _)| *index < len).collect();
573        if in_range.is_empty() {
574            return;
575        }
576        // The key must not depend on the caller's ordering, or the same packed
577        // row could produce two different keys and stop coalescing.
578        in_range.sort_by_key(|(index, _)| *index);
579        let key: Vec<String> = in_range
580            .iter()
581            .map(|(index, _)| index.to_string())
582            .collect();
583        self.checkpoint(Some(&format!("params:{}", key.join(","))));
584        for (index, params) in in_range {
585            if let Some(feature) = self.features_mut().get_mut(*index) {
586                if let Some(object) = feature.as_object_mut() {
587                    object.insert("inputParams".into(), params.clone());
588                }
589            }
590        }
591    }
592
593    pub fn push_feature(&mut self, feature: Value) {
594        self.checkpoint(None);
595        self.features_mut().push(feature);
596    }
597
598    /// Append MANY features as ONE mutation — the batch an import lane needs
599    /// (`EngineState::add_features`). Distinct from a `push_feature` loop in the
600    /// two ways that matter: exactly ONE undo checkpoint (an N-instance assembly
601    /// import undoes in one step, not N), and the caller re-runs once instead of
602    /// once per feature. No-op for an empty batch (no checkpoint, so an import
603    /// that produced nothing leaves no empty undo entry).
604    pub fn push_features(&mut self, features: Vec<Value>) {
605        if features.is_empty() {
606            return;
607        }
608        self.checkpoint(None);
609        self.features_mut().extend(features);
610    }
611
612    pub fn remove_feature(&mut self, index: usize) {
613        if index >= self.len() {
614            return;
615        }
616        self.checkpoint(None);
617        self.features_mut().remove(index);
618    }
619
620    pub fn swap(&mut self, a: usize, b: usize) {
621        let len = self.len();
622        if a < len && b < len && a != b {
623            self.checkpoint(None);
624            self.features_mut().swap(a, b);
625        }
626    }
627
628    /// Mint the id for a NEW feature: `{base}{N}` where `base` is the feature's
629    /// shortName and `N` is this history's persistent GLOBAL counter, bumped by one
630    /// on every mint (`P.CU` → `P.CU7`, `S` → `S8`). GLOBAL across all feature
631    /// types, MONOTONIC, and NEVER reused — a delete does not free a number and
632    /// undo does not rewind the counter — and it persists across save/load, so two
633    /// features can never receive the same id over the document's whole lifetime.
634    pub fn next_feature_id(&mut self, base: &str) -> String {
635        // Locked, the counter is saved state and does not move; the id is
636        // still minted, for a feature whose push will be refused anyway.
637        if self.refuse_user() {
638            return format!("{base}{}", self.feature_counter + 1);
639        }
640        self.feature_counter += 1;
641        format!("{base}{}", self.feature_counter)
642    }
643
644    /// Commit IDs reserved on a transaction's cloned history. Document adoption
645    /// deliberately ignores serialized counters, so the transaction must carry
646    /// its allocation high-water mark separately. Explicit committed IDs also
647    /// set a floor; undo keeps this monotonic, while rollback restores a clone.
648    pub(crate) fn retain_feature_allocations(&mut self, staged: &Self) {
649        if self.refuse_user() {
650            return;
651        }
652        self.feature_counter = self
653            .feature_counter
654            .max(staged.feature_counter)
655            .max(self.max_id_suffix());
656    }
657
658    /// The `stopAtId`-truncated request that stops AFTER the rolled-to feature —
659    /// the roll-to-step request the pipeline runs. Empty history → empty request.
660    pub fn prefix_request(&self) -> Value {
661        let mut request = self.document().clone();
662        if let Some(id) = self.feature_id(self.rollback()) {
663            if let Some(obj) = request.as_object_mut() {
664                obj.insert("stopAtId".into(), Value::String(id));
665            }
666        }
667        request
668    }
669
670    /// The request that stops BEFORE feature `index` — the scene that feature
671    /// resolves its references against, wherever the model is rolled to. `None`
672    /// when there is no feature at `index`.
673    pub fn request_before(&self, index: usize) -> Option<Value> {
674        let id = self.feature_id(index)?;
675        let mut request = self.document().clone();
676        request.as_object_mut()?.insert("stopBeforeId".into(), Value::String(id));
677        Some(request)
678    }
679
680    /// The tree listing for the UI: `{ step, features: [{index, type, id}] }`.
681    pub fn listing_json(&self) -> String {
682        let features: Vec<Value> = self
683            .features()
684            .iter()
685            .enumerate()
686            .map(|(index, _)| {
687                serde_json::json!({
688                    "index": index,
689                    "type": self.feature_type(index).unwrap_or_else(|| "?".into()),
690                    "id": self.feature_id(index).unwrap_or_else(|| "(no id)".into()),
691                })
692            })
693            .collect();
694        serde_json::json!({ "step": self.rollback(), "features": features }).to_string()
695    }
696
697    /// The whole request document (for persistence / debugging), with the
698    /// persistent global feature counter folded back in under `"featureCounter"`
699    /// so it round-trips through save/load (the twin of [`Self::from_request_json`],
700    /// which lifts it back out). Written only when non-zero, so a document that has
701    /// never minted a feature persists byte-for-byte as before (mirrors the
702    /// metadata field's "un-annotated model persists unchanged" convention).
703    pub fn request_json(&self) -> String {
704        let has_library = self
705            .parts_library
706            .as_object()
707            .map(|map| !map.is_empty())
708            .unwrap_or(false);
709        if self.feature_counter == 0 && !has_library {
710            return self.document().to_string();
711        }
712        let mut document = self.document().clone();
713        if let Some(obj) = document.as_object_mut() {
714            if self.feature_counter != 0 {
715                obj.insert("featureCounter".into(), Value::from(self.feature_counter));
716            }
717            if has_library {
718                obj.insert("partsLibrary".into(), (*self.parts_library).clone());
719            }
720        }
721        document.to_string()
722    }
723
724    /// [`Self::request_json`] as a value, for a caller that edits it: the
725    /// same document, never printed and parsed back (an assembly's library
726    /// is megabytes).
727    pub fn request_value(&self) -> Value {
728        let mut document = self.document().clone();
729        if let Some(obj) = document.as_object_mut() {
730            if self.feature_counter != 0 {
731                obj.insert("featureCounter".into(), Value::from(self.feature_counter));
732            }
733            if self.parts_library.as_object().is_some_and(|map| !map.is_empty()) {
734                obj.insert("partsLibrary".into(), (*self.parts_library).clone());
735            }
736        }
737        document
738    }
739
740    /// The document WITHOUT the parts-library block — for the kernel round
741    /// trips that never read it. The assembly pose fold
742    /// (`assembly_apply_document_json`) only rewrites the `assembly` block and
743    /// per-feature `inputParams`, so handing it the library would serialize,
744    /// parse and re-serialize megabytes of part payload on every edit for
745    /// nothing. [`Self::request_json`] is the SAVE door and still carries it.
746    pub fn request_json_without_parts_library(&self) -> String {
747        if self.feature_counter == 0 {
748            return self.document().to_string();
749        }
750        let mut document = self.document().clone();
751        if let Some(obj) = document.as_object_mut() {
752            obj.insert("featureCounter".into(), Value::from(self.feature_counter));
753        }
754        document.to_string()
755    }
756
757    // --- Undo / redo over the model document ------------------------------
758
759    fn snapshot(&self) -> Snapshot {
760        Snapshot {
761            request: self.document().clone(),
762            rollback: self.rollback,
763            parts_library: self.parts_library.clone(),
764            serial: next_step(),
765            renamed: None,
766        }
767    }
768
769    fn restore(&mut self, snap: Snapshot) {
770        self.edit_serial = next_revision();
771        *self.document_mut() = snap.request;
772        self.parts_library = snap.parts_library;
773        // A snapshot holds both sides as they stood together, so whatever the
774        // last pin or port edit held is no longer on screen.
775        self.pin_port_hold = None;
776        let last = self.len().saturating_sub(1);
777        self.rollback = snap.rollback.min(last);
778    }
779
780    /// Record a pre-mutation snapshot for undo. `coalesce_key` groups a run of
781    /// rapid same-target edits (one slider drag) into a SINGLE undo entry: while
782    /// the same non-empty key repeats, no new snapshot is pushed. A `None` key
783    /// never coalesces, so every structural add/delete/reorder is its own entry.
784    /// Any new snapshot clears the redo stack (a fresh edit forks the timeline)
785    /// and the oldest entry falls off once the stack passes [`MAX_UNDO`].
786    ///
787    /// A run has no time limit: only another key, an undo or
788    /// [`Self::break_coalescing`] ends it. The PMI label drag and the sheet
789    /// view, dimension and ordinate moves call that on release; nothing else
790    /// does, and a typing run has no release. So a param slider or
791    /// field (`param:{index}`) or an eCAD field (`component:{id}:text`) edited,
792    /// left, and edited again later with nothing in between is ONE undo step
793    /// across the pause, even across a Save. An eCAD host should call it when
794    /// focus leaves the editor's fields. Param runs are left as they are, a
795    /// decision not yet taken.
796    fn checkpoint(&mut self, coalesce_key: Option<&str>) {
797        // Locked, the edit this checkpoint precedes is refused at
798        // `document_mut`: no undo entry for an edit that never happened.
799        if self.lock.is_some() {
800            self.refused_user += 1;
801            return;
802        }
803        // Busy (an agent's staged feature is evaluating): the user's edit is
804        // refused the same way, landing on the scratch copy.
805        if self.busy.is_some() {
806            self.busy_refused += 1;
807            self.refuse_next = true;
808            return;
809        }
810        // Before the coalesce return: the second keystroke of a typing run is
811        // an edit too.
812        self.edit_serial = next_revision();
813        if coalesce_key.is_some() && coalesce_key == self.last_edit_key.as_deref() {
814            return;
815        }
816        if let Some((_, Some(step))) = self.group {
817            if self.undo_top() == Some(step) {
818                return;
819            }
820        }
821        self.undo_stack.push(self.snapshot());
822        if self.undo_stack.len() > MAX_UNDO {
823            self.undo_stack.remove(0);
824        }
825        self.redo_stack.clear();
826        self.last_edit_key = coalesce_key.map(str::to_string);
827        if let Some((_, step)) = &mut self.group {
828            *step = self.undo_stack.last().map(|snapshot| snapshot.serial);
829        }
830    }
831
832    /// Open an undo group: every edit until [`Self::group_end`] is one undo
833    /// step. A group already open is replaced. The token names this group to
834    /// its end.
835    pub fn group_begin(&mut self) -> u64 {
836        let token = next_step();
837        self.group = Some((token, None));
838        self.last_edit_key = None;
839        token
840    }
841
842    /// Close group `token`. With `rollback`, take its step back as though its
843    /// edits had never been made ([`Self::retract`]), while that step is still
844    /// the newest; answers whether it did. A token that is not the open group
845    /// closes nothing.
846    pub fn group_end(&mut self, token: u64, rollback: bool) -> Result<bool, String> {
847        let Some((open, step)) = self.group else {
848            return Err("no undo group is open".into());
849        };
850        if open != token {
851            return Err("that undo group is not the open one".into());
852        }
853        self.group = None;
854        self.last_edit_key = None;
855        Ok(rollback && step.is_some_and(|step| self.retract(step)))
856    }
857
858    /// The open undo group's token, if any.
859    pub fn group_open(&self) -> Option<u64> {
860        self.group.map(|(token, _)| token)
861    }
862
863    /// Whether an undo step is available (for enabling the toolbar button).
864    pub fn can_undo(&self) -> bool {
865        !self.undo_stack.is_empty()
866    }
867
868    /// Whether a redo step is available.
869    pub fn can_redo(&self) -> bool {
870        !self.redo_stack.is_empty()
871    }
872
873    /// Undo the last model mutation: push the current state onto the redo stack
874    /// and restore the previous document + rolled-to step. Returns whether it
875    /// changed anything (false when the undo stack is empty).
876    pub fn undo(&mut self) -> bool {
877        if self.refuse_user() {
878            return false;
879        }
880        let Some(prev) = self.undo_stack.pop() else {
881            return false;
882        };
883        let mut redo = self.snapshot();
884        redo.renamed = prev.renamed.clone();
885        self.travel_rename = prev.renamed.clone().map(|(old, new)| (new, old));
886        self.redo_stack.push(redo);
887        self.restore(prev);
888        // A distinct undo breaks any coalescing run so the next edit is fresh.
889        self.last_edit_key = None;
890        true
891    }
892
893    /// Redo the last undone model mutation (symmetric with [`Self::undo`]).
894    pub fn redo(&mut self) -> bool {
895        if self.refuse_user() {
896            return false;
897        }
898        let Some(next) = self.redo_stack.pop() else {
899            return false;
900        };
901        let mut undo = self.snapshot();
902        undo.renamed = next.renamed.clone();
903        self.travel_rename = next.renamed.clone();
904        self.undo_stack.push(undo);
905        self.restore(next);
906        self.last_edit_key = None;
907        true
908    }
909}
910
911// ============================================================================
912// Assembly document accessors (appended — the assemblies Wave-3 slice). A
913// SEPARATE `impl` block so concurrent edits to the primary block don't
914// conflict; purely additive over the existing history API.
915// ============================================================================
916impl History {
917    /// ADOPT a whole replacement document — the assembly FOLD's write-back lane
918    /// (`assembly_apply_document_json` returns the document with the solved
919    /// `assembly` block + poses/isFixed folded into the features; the engine
920    /// adopts it before persisting or re-running — the pose-authority contract).
921    ///
922    /// `checkpoint` chooses the undo semantics: a USER constraint mutation
923    /// records an undo snapshot (so constraint edits stay undoable like any
924    /// model edit); the silent post-run pose fold passes `false` (solver
925    /// write-back is not a user edit — undoing the user's LAST edit must not
926    /// strand an extra fold step in between).
927    ///
928    /// A stray `featureCounter` in the adopted document is stripped (the
929    /// in-memory counter stays authoritative — `request_json` re-folds it on
930    /// serialize, exactly like `from_request_json` lifts it on load). The
931    /// rollback index is preserved (the fold never changes the feature count).
932    pub fn adopt_document(&mut self, document_json: &str) -> Result<(), String> {
933        // Locked, say so: a caller that checks the result (an eCAD block sync
934        // recording what it wrote) must not believe a refused write landed.
935        if let Some(reason) = &self.lock {
936            let error = format!("the document is read-only: {reason}");
937            self.refused += 1;
938            return Err(error);
939        }
940        let document: Value = serde_json::from_str(document_json)
941            .map_err(|error| format!("adopt document parse: {error}"))?;
942        self.adopt_document_value(document)
943    }
944
945    /// [`Self::adopt_document`] for a caller that already holds the parsed
946    /// document: an assembly's parts library is megabytes, and printing it only
947    /// to parse it back was most of an Update Components commit at 500 parts.
948    pub fn adopt_document_value(&mut self, mut document: Value) -> Result<(), String> {
949        if let Some(reason) = &self.lock {
950            let error = format!("the document is read-only: {reason}");
951            self.refused += 1;
952            return Err(error);
953        }
954        if !document.is_object() {
955            return Err("adopt document: not a JSON object".into());
956        }
957        let mut adopted_library = None;
958        if let Some(obj) = document.as_object_mut() {
959            obj.remove("featureCounter");
960            // A block PRESENT in the adopted document replaces the field; one
961            // ABSENT leaves it alone (the fold lane is handed a library-free
962            // document by `request_json_without_parts_library` and must not
963            // silently drop the library on the way back).
964            adopted_library = obj.remove("partsLibrary");
965            if !obj.get("features").map(Value::is_array).unwrap_or(false) {
966                obj.insert("features".into(), Value::Array(Vec::new()));
967            }
968        }
969        *self.document_mut() = document;
970        // A replaced document is not the one a pin or port edit was held on.
971        self.pin_port_hold = None;
972        if let Some(library) = adopted_library {
973            self.set_parts_library(library);
974            }
975        Ok(())
976    }
977
978    /// Same adoption with an undo snapshot recorded FIRST (never coalesced) —
979    /// the user-mutation twin of [`Self::adopt_document`].
980    pub fn adopt_document_checkpointed(&mut self, document_json: &str) -> Result<(), String> {
981        // Validate BEFORE snapshotting so a parse failure never pushes a
982        // phantom undo entry.
983        let probe: Value = serde_json::from_str(document_json)
984            .map_err(|error| format!("adopt document parse: {error}"))?;
985        if !probe.is_object() {
986            return Err("adopt document: not a JSON object".into());
987        }
988        self.checkpoint(None);
989        self.adopt_document_value(probe)
990    }
991
992    /// [`Self::adopt_document_checkpointed`] for an already parsed document.
993    pub fn adopt_document_value_checkpointed(&mut self, document: Value) -> Result<(), String> {
994        if !document.is_object() {
995            return Err("adopt document: not a JSON object".into());
996        }
997        self.checkpoint(None);
998        self.adopt_document_value(document)
999    }
1000
1001    /// Replace the document's `partsLibrary` block (the assemblies parts
1002    /// library) — the caller feeds `brep_kernel::parts_library_json()` here
1003    /// (never an echo of a loaded block), so SAVE serializes the kernel
1004    /// store with its heals and GC. An empty map clears the field, so a
1005    /// non-assembly document serializes byte-identically to before.
1006    ///
1007    /// The block is held in the `parts_library` FIELD rather than on
1008    /// `self.document`; [`Self::request_json`] folds it back into the saved
1009    /// document. The on-disk shape is unchanged.
1010    pub fn set_parts_library(&mut self, library: Value) {
1011        if self.refuse() {
1012            return;
1013        }
1014        let empty = library.as_object().map(|m| m.is_empty()).unwrap_or(true);
1015        self.parts_library = std::rc::Rc::new(if empty { Value::Null } else { library });
1016        // The block is part of the saved document, so this is a document
1017        // mutation and owes the revision a tick — `document_mut` never sees it.
1018        self.revision = next_revision();
1019    }
1020
1021    /// Replace the `partsLibrary` block as a USER EDIT: one undo checkpoint,
1022    /// and the mirror flag CLEARED so the next run ships the block to the
1023    /// runner instead of assuming the kernel store already agrees.
1024    ///
1025    /// [`Self::set_parts_library`] is the other door and means the opposite —
1026    /// "this block came OUT of the kernel store" — so it must not be reused
1027    /// here: a part-attribute edit is authored on this side and the runner has
1028    /// never seen it. `coalesce_key` follows the `param:{index}` rule so a run
1029    /// of keystrokes into one attribute is one undo entry.
1030    pub fn set_parts_library_edited(&mut self, library: Value, coalesce_key: Option<&str>) {
1031        if self.refuse_user() {
1032            return;
1033        }
1034        self.checkpoint(coalesce_key);
1035        let empty = library.as_object().map(|m| m.is_empty()).unwrap_or(true);
1036        self.parts_library = std::rc::Rc::new(if empty { Value::Null } else { library });
1037        // As [`Self::set_parts_library`]: `checkpoint` records an undo entry
1038        // and moves nothing a cache can see.
1039        self.revision = next_revision();
1040    }
1041
1042    /// The `partsLibrary` block (`Value::Null` when the document has none).
1043    /// The component namespace of this document ([`brep_kernel::component_namespace`]):
1044    /// its components and, below each, its part's. Built from the document and
1045    /// the library block as they stand; callers cache it by [`Self::revision`].
1046    pub fn component_namespace(&self) -> brep_kernel::ComponentNamespace {
1047        brep_kernel::component_namespace_with_library(self.document(), self.parts_library())
1048    }
1049    pub fn parts_library(&self) -> &Value {
1050        &self.parts_library
1051    }
1052
1053    /// Top-level block `key` of the document as it stood before the NEWEST
1054    /// undoable edit (`None` with nothing to undo, or when that document had
1055    /// no such block): what a caller reads to tell whether the newest step is
1056    /// the one it means to take back.
1057    pub fn undo_top_block(&self, key: &str) -> Option<&Value> {
1058        self.undo_stack.last().and_then(|snapshot| snapshot.request.get(key))
1059    }
1060
1061    /// The `partsLibrary` block as it stood before each undoable edit, newest
1062    /// first: where a caller finds a library entry as it was when it appeared.
1063    pub fn undo_parts_libraries(&self) -> impl Iterator<Item = &Value> + '_ {
1064        self.undo_stack.iter().rev().map(|snapshot| snapshot.parts_library.as_ref())
1065    }
1066
1067    /// The document's `assembly` block (`{constraints, idCounter}`), if any.
1068    pub fn assembly_block(&self) -> Option<&Value> {
1069        self.document().get("assembly")
1070    }
1071
1072    /// Replace the `assembly` block (`{constraints, idCounter}`) — the STATE
1073    /// half of the assembly write-back, which the engine folds from the run's
1074    /// reply after every run and from the live session after a constraint
1075    /// mutation. `checkpoint` = true makes it an undoable USER edit (a
1076    /// mutation); false writes it silently, because a solver adopting its own
1077    /// result is not a user edit and must never mint an undo entry — undoing a
1078    /// user action then re-running re-solves and re-folds anyway.
1079    pub fn set_assembly_block(&mut self, block: Value, checkpoint: bool) {
1080        if checkpoint {
1081            self.checkpoint(None);
1082        }
1083        if let Some(object) = self.document_mut().as_object_mut() {
1084            object.insert("assembly".into(), block);
1085        }
1086    }
1087
1088    /// The document's `wireHarness` block (`{connections, idCounter,
1089    /// buildBundles}`), if any.
1090    pub fn wire_harness_block(&self) -> Option<&Value> {
1091        self.document().get("wireHarness")
1092    }
1093
1094    /// Replace (or, with `None`, remove) the `wireHarness` block. A USER edit:
1095    /// snapshotted for undo, never coalesced — each add / edit / remove of a
1096    /// connection is its own undo step, like a feature add or delete.
1097    pub fn set_wire_harness_block(&mut self, block: Option<Value>) {
1098        self.checkpoint(None);
1099        if let Some(object) = self.document_mut().as_object_mut() {
1100            match block {
1101                Some(block) => {
1102                    object.insert("wireHarness".into(), block);
1103                }
1104                None => {
1105                    object.shift_remove("wireHarness");
1106                }
1107            }
1108        }
1109    }
1110}
1111
1112// ============================================================================
1113// PMI block accessors (the PMI workbench slice). A SEPARATE `impl` block —
1114// purely additive over the history API.
1115// ============================================================================
1116impl History {
1117    /// The document's `pmi` block (`{views, idCounter}`), if any.
1118    pub fn pmi_block(&self) -> Option<&Value> {
1119        self.document().get("pmi")
1120    }
1121
1122    /// Replace (or, with `None`, remove) the `pmi` block as a USER edit:
1123    /// snapshotted for undo. `coalesce_key` groups a run of rapid same-target
1124    /// edits (a label drag: `pmi:label:{id}`) into ONE undo entry; `None`
1125    /// makes the edit its own step (a view capture, an annotation add / edit
1126    /// / delete).
1127    pub fn set_pmi_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1128        self.checkpoint(coalesce_key);
1129        self.put_pmi_block(block);
1130    }
1131
1132    /// Replace the `pmi` block WITHOUT an undo checkpoint — for a write that
1133    /// belongs to the checkpoint just taken (an import lifting a file's PMI
1134    /// beside the feature it added, so one undo removes both).
1135    pub fn set_pmi_block_no_undo(&mut self, block: Option<Value>) {
1136        self.put_pmi_block(block);
1137    }
1138
1139    fn put_pmi_block(&mut self, block: Option<Value>) {
1140        if let Some(object) = self.document_mut().as_object_mut() {
1141            match block {
1142                Some(block) => {
1143                    object.insert("pmi".into(), block);
1144                }
1145                None => {
1146                    object.shift_remove("pmi");
1147                }
1148            }
1149        }
1150    }
1151
1152    /// End a coalescing run (a label drag released): the next edit with the
1153    /// same key starts a fresh undo entry.
1154    pub fn break_coalescing(&mut self) {
1155        self.last_edit_key = None;
1156    }
1157}
1158
1159// ============================================================================
1160// CAM block accessors (the CAM workbench slice). A SEPARATE `impl` block,
1161// purely additive over the history API, on the PMI block's pattern.
1162//
1163// `cam` is a top-level document key like `pmi` and `sheets`: the user's
1164// setups, tools, operations and post settings. The kernel never reads it and
1165// `HistoryRequest` has no field for it — the document's unknown-key
1166// pass-through ([`Self::request_json`] serializes the raw document) is what
1167// round-trips it through save, load and undo. Derived data (toolpaths, mesh
1168// snapshots, stock states) is never written here: it is regenerated.
1169// ============================================================================
1170impl History {
1171    /// The document's `cam` block (`{setups, tools, operations, ncPrograms,
1172    /// idCounter}`), if any.
1173    pub fn cam_block(&self) -> Option<&Value> {
1174        self.document().get("cam")
1175    }
1176
1177    /// Replace (or, with `None`, remove) the `cam` block as a USER edit:
1178    /// snapshotted for undo. `coalesce_key` groups a run of rapid same-target
1179    /// edits (typing in one field of one operation: `cam:op:{id}:{field}`)
1180    /// into ONE undo entry; `None` makes the edit its own step (a setup, tool
1181    /// or operation add / delete, a pick committed).
1182    pub fn set_cam_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1183        let coalesce_key = coalesce_key.map(|change| format!("cam:{change}"));
1184        self.checkpoint(coalesce_key.as_deref());
1185        self.put_cam_block(block);
1186    }
1187
1188    /// Replace the `cam` block WITHOUT an undo checkpoint — for a write that
1189    /// belongs to the checkpoint just taken (an import lifting a file's CAM
1190    /// data beside the feature it added, so one undo removes both).
1191    pub fn set_cam_block_no_undo(&mut self, block: Option<Value>) {
1192        self.put_cam_block(block);
1193    }
1194
1195    fn put_cam_block(&mut self, block: Option<Value>) {
1196        if let Some(object) = self.document_mut().as_object_mut() {
1197            match block {
1198                Some(block) => {
1199                    object.insert("cam".into(), block);
1200                }
1201                None => {
1202                    object.shift_remove("cam");
1203                }
1204            }
1205        }
1206    }
1207}
1208
1209// ============================================================================
1210// SHEETS block accessors (the drawing-sheet slice).
1211//
1212// `sheets` is a top-level document key like `pmi` and `partAttributes`: a
1213// sheet places saved PMI views and adds no geometry, so the kernel never needs
1214// it and `HistoryRequest` has no field for it — the document's unknown-key
1215// pass-through ([`Self::request_json`] serializes the raw document) is what
1216// round-trips it through save, load and undo. Absent on every document without
1217// a sheet, so those files re-serialize byte-identically.
1218// ============================================================================
1219impl History {
1220    /// The document's `sheets` block (`{sheets, idCounter}`), if any.
1221    pub fn sheets_block(&self) -> Option<&Value> {
1222        self.document().get(crate::sheets::SHEETS)
1223    }
1224
1225    /// Replace (or, with `None`, remove) the `sheets` block as a USER edit:
1226    /// snapshotted for undo. `coalesce_key` groups a run of rapid same-target
1227    /// edits (dragging a placed view: `sheet:view:{id}`) into ONE undo entry,
1228    /// exactly as the PMI label drag's does.
1229    pub fn set_sheets_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1230        self.checkpoint(coalesce_key);
1231        if let Some(object) = self.document_mut().as_object_mut() {
1232            match block {
1233                Some(block) => {
1234                    object.insert(crate::sheets::SHEETS.into(), block);
1235                }
1236                None => {
1237                    object.shift_remove(crate::sheets::SHEETS);
1238                }
1239            }
1240        }
1241    }
1242}
1243
1244// ============================================================================
1245// PART ATTRIBUTES block accessors — the BOM attributes of the document ITSELF.
1246//
1247// `partAttributes` is a top-level document key (see
1248// `engine_state::bom`'s attributes block), so a document carries the BOM data
1249// of the PART it is. On a part in an assembly's library that record is written
1250// through the library entry's embedded document; on the document you have OPEN
1251// it is written here, by the toolbar's Properties dialog. Same key, same
1252// shape, two doors — which is what makes a part's Part Number the same value
1253// whether it is read from the assembly's BOM or from the part's own tab.
1254// ============================================================================
1255impl History {
1256    /// The document's own `partAttributes` record, if any.
1257    pub fn part_attributes_block(&self) -> Option<&Value> {
1258        self.document().get(crate::engine_state::PART_ATTRIBUTES)
1259    }
1260
1261    /// Replace (or, with `None`, remove) the document's own `partAttributes`
1262    /// record as a USER edit: snapshotted for undo. `coalesce_key` groups a run
1263    /// of edits to ONE field (a typing run in the Properties dialog) into a
1264    /// single undo entry, exactly as the PMI block's does.
1265    pub fn set_part_attributes_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1266        self.checkpoint(coalesce_key);
1267        if let Some(object) = self.document_mut().as_object_mut() {
1268            match block {
1269                Some(block) => {
1270                    object.insert(crate::engine_state::PART_ATTRIBUTES.into(), block);
1271                }
1272                None => {
1273                    object.shift_remove(crate::engine_state::PART_ATTRIBUTES);
1274                }
1275            }
1276        }
1277    }
1278}
1279
1280// ============================================================================
1281// Expressions / configurator accessors (appended — the expressions/parameters
1282// panel slice). A SEPARATE `impl` block so concurrent edits to the primary block
1283// don't conflict; purely additive over the existing history API.
1284//
1285// The history document carries an `expressions` source string — the variable
1286// sheet feature params evaluate against (a numeric param may be the string
1287// `"boxW"`, evaluated by the pipeline's shared expression env). The panel edits
1288// this and re-runs; the `configurator` object (typed named inputs) is exposed
1289// read-only for display.
1290// ============================================================================
1291impl History {
1292    /// The history document's `expressions` source string (empty when absent or
1293    /// stored as `null`). The panel's editor binds to this.
1294    pub fn expressions(&self) -> String {
1295        self.document()
1296            .get("expressions")
1297            .and_then(Value::as_str)
1298            .unwrap_or("")
1299            .to_string()
1300    }
1301
1302    /// Replace the `expressions` source string. Snapshotted for undo, coalescing a
1303    /// run of keystroke edits into ONE undo entry (like a slider drag) via the
1304    /// shared `"expressions"` coalesce key, so a distinct add/edit/roll starts a
1305    /// fresh entry. A no-op re-set (same text) still records under the same key.
1306    pub fn set_expressions(&mut self, expressions: &str) {
1307        self.checkpoint(Some("expressions"));
1308        if let Some(obj) = self.document_mut().as_object_mut() {
1309            obj.insert(
1310                "expressions".into(),
1311                Value::String(expressions.to_string()),
1312            );
1313        }
1314    }
1315
1316    /// The `configurator` object (typed named inputs), or `{}` when absent —
1317    /// read-only for the panel's display (deeper configurator editing deferred).
1318    pub fn configurator(&self) -> Value {
1319        self.document()
1320            .get("configurator")
1321            .cloned()
1322            .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
1323    }
1324}
1325
1326// ============================================================================
1327// Feature `persistentData` accessors (appended — the engine-native sketch mode
1328// slice). A SEPARATE `impl` block (like the expressions accessors above) so
1329// concurrent edits don't conflict; purely additive over the primary history API.
1330//
1331// A feature's `persistentData` is the kernel-persisted, non-input state (a
1332// SKETCH feature stores its solved `{points, geometries, constraints}` under the
1333// `sketch` key and the plane `basis` there). Sketch mode reads that state on
1334// enter and writes the edited doc back on commit — mirroring how the ref-select
1335// slice reads/writes `inputParams` through `feature_params` / `set_feature_params`.
1336// ============================================================================
1337impl History {
1338    /// The `persistentData` document of the feature at `index` (`None` if the
1339    /// feature or the field is absent) — the read twin of [`Self::feature_params`].
1340    pub fn feature_persistent_data(&self, index: usize) -> Option<Value> {
1341        self.features().get(index)?.get("persistentData").cloned()
1342    }
1343
1344    /// Set a single `key` inside the feature-at-`index`'s `persistentData` object,
1345    /// creating (or replacing a non-object) `persistentData` as needed. Snapshotted
1346    /// for undo (a structural edit — never coalesced), like an add/delete.
1347    pub fn set_feature_persistent_field(&mut self, index: usize, key: &str, value: Value) {
1348        self.set_feature_persistent_field_coalesced(index, key, value, None);
1349    }
1350
1351    /// [`Self::set_feature_persistent_field`] with an optional COALESCE key: a
1352    /// run of same-key writes (a gizmo drag moving a spline anchor, frame after
1353    /// frame) records ONE undo entry, exactly as a slider drag on a param does.
1354    pub fn set_feature_persistent_field_coalesced(
1355        &mut self,
1356        index: usize,
1357        key: &str,
1358        value: Value,
1359        coalesce_key: Option<&str>,
1360    ) {
1361        if index >= self.len() {
1362            return;
1363        }
1364        self.checkpoint(coalesce_key);
1365        if let Some(feat) = self.features_mut().get_mut(index).and_then(Value::as_object_mut) {
1366            let entry = feat
1367                .entry("persistentData")
1368                .or_insert_with(|| Value::Object(serde_json::Map::new()));
1369            if !entry.is_object() {
1370                *entry = Value::Object(serde_json::Map::new());
1371            }
1372            if let Some(obj) = entry.as_object_mut() {
1373                obj.insert(key.to_string(), value);
1374            }
1375        }
1376    }
1377
1378    /// Write several `persistentData` fields of the feature at `index` as ONE
1379    /// user edit: one undo checkpoint covers them all, and there is none when
1380    /// every field already holds its value, so an action that changed nothing
1381    /// leaves no undo step that does nothing. Returns whether anything changed.
1382    ///
1383    /// Leaving a sketch writes its geometry, its dimension label offsets and
1384    /// its external references this way. Written one field at a time they were
1385    /// three undo steps, and only the third Ctrl+Z took the drawing back.
1386    pub fn set_feature_persistent_fields(&mut self, index: usize, fields: Vec<(&str, Value)>) -> bool {
1387        let Some(feature) = self.features().get(index) else {
1388            return false;
1389        };
1390        let current = feature.get("persistentData");
1391        if fields.iter().all(|(key, value)| current.and_then(|data| data.get(*key)) == Some(value)) {
1392            return false;
1393        }
1394        self.checkpoint(None);
1395        if let Some(feat) = self.features_mut().get_mut(index).and_then(Value::as_object_mut) {
1396            let entry = feat
1397                .entry("persistentData")
1398                .or_insert_with(|| Value::Object(serde_json::Map::new()));
1399            if !entry.is_object() {
1400                *entry = Value::Object(serde_json::Map::new());
1401            }
1402            if let Some(obj) = entry.as_object_mut() {
1403                for (key, value) in fields {
1404                    obj.insert(key.to_string(), value);
1405                }
1406            }
1407        }
1408        true
1409    }
1410
1411    /// The undo step on top of the stack right now, as a token for
1412    /// [`Self::retract`] and [`Self::set_feature_persistent_fields_in_step`];
1413    /// `None` when there is nothing to undo.
1414    pub fn undo_top(&self) -> Option<u64> {
1415        self.undo_stack.last().map(|snapshot| snapshot.serial)
1416    }
1417
1418    /// Take back undo step `step` as though its edit had never been made:
1419    /// restore the state it holds and DROP it, leaving no redo entry. Only while
1420    /// `step` is still the newest step; otherwise nothing happens and this
1421    /// returns false, and the caller undoes the ordinary way.
1422    ///
1423    /// Cancelling a sketch created in the same session uses it, so the cancel
1424    /// leaves no undo step behind: two presses, one of which brought the
1425    /// cancelled sketch back, before. It cannot restore a redo stack the step's
1426    /// own edit cleared when it was taken. Neither could the cancel it replaces.
1427    pub fn retract(&mut self, step: u64) -> bool {
1428        if self.refuse_user() {
1429            return false;
1430        }
1431        if self.undo_top() != Some(step) {
1432            return false;
1433        }
1434        let Some(snapshot) = self.undo_stack.pop() else {
1435            return false;
1436        };
1437        self.travel_rename = snapshot.renamed.clone().map(|(old, new)| (new, old));
1438        self.restore(snapshot);
1439        self.last_edit_key = None;
1440        true
1441    }
1442
1443    /// Mark the newest undo step as the rename `old` -> `new` (called straight
1444    /// after the edit that made it). Undo, redo and retract then report the
1445    /// rename to apply through [`Self::take_travel_rename`].
1446    pub fn note_rename(&mut self, old: &str, new: &str) {
1447        if let Some(top) = self.undo_stack.last_mut() {
1448            top.renamed = Some((old.to_string(), new.to_string()));
1449        }
1450    }
1451
1452    /// The rename the last undo, redo or retract crossed (`old` -> `new` as it
1453    /// applies now), once.
1454    pub fn take_travel_rename(&mut self) -> Option<(String, String)> {
1455        self.travel_rename.take()
1456    }
1457
1458    /// [`Self::set_feature_persistent_fields`] as part of undo step `step`,
1459    /// with no checkpoint of its own, while `step` is still the newest step;
1460    /// otherwise an ordinary write with its own step. Finishing a sketch
1461    /// created in the same session writes this way, so creating, drawing and
1462    /// finishing it is one undo step.
1463    pub fn set_feature_persistent_fields_in_step(
1464        &mut self,
1465        index: usize,
1466        fields: Vec<(&str, Value)>,
1467        step: u64,
1468    ) -> bool {
1469        if self.undo_top() != Some(step) {
1470            return self.set_feature_persistent_fields(index, fields);
1471        }
1472        let Some(feat) = self.features_mut().get_mut(index).and_then(Value::as_object_mut) else {
1473            return false;
1474        };
1475        let entry = feat
1476            .entry("persistentData")
1477            .or_insert_with(|| Value::Object(serde_json::Map::new()));
1478        if !entry.is_object() {
1479            *entry = Value::Object(serde_json::Map::new());
1480        }
1481        if let Some(obj) = entry.as_object_mut() {
1482            for (key, value) in fields {
1483                obj.insert(key.to_string(), value);
1484            }
1485        }
1486        true
1487    }
1488}
1489
1490// ============================================================================
1491// eCAD block accessors (the eCAD documents slice).
1492//
1493// The four eCAD workbenches keep their documents as top-level keys: `diagram`
1494// (the wiring diagram) and `pcb` (schematic and board) are blocks of an
1495// ASSEMBLY document, since a board is an assembly; `symbol` and `pads` are
1496// blocks of a PART document, since a part carries its own symbol and pads.
1497// Like `sheets`, the kernel never reads them and `HistoryRequest` has no field
1498// for them: the raw document is what carries them through save, load, undo and
1499// the assembly fold. Absent on every document the eCAD editors never wrote, so
1500// those files re-serialize byte-identically.
1501//
1502// None of these setters runs the history. The tab's dirty dot and the autosave
1503// see the edit through [`History::revision`], which every write here moves. The
1504// two symbol setters also carry a pin edit to the part's PORT features (the
1505// pins-and-ports block below), and the engine's `pump` runs the history when
1506// that moved a port.
1507// ============================================================================
1508
1509/// The assembly document's wiring diagram (an eCAD `Document`).
1510pub const DIAGRAM: &str = "diagram";
1511/// The assembly document's schematic and board (an eCAD `Document`).
1512pub const PCB: &str = "pcb";
1513/// The part document's schematic symbol (an eCAD `Symbol`). Defined AS the
1514/// kernel's key: the pin/port binding (`brep_kernel` `part_pins`) reads the same
1515/// block, so the two can never name different keys.
1516pub const SYMBOL: &str = brep_kernel::SYMBOL_BLOCK;
1517/// The part document's footprint pads (an eCAD `Footprint`), defined AS the
1518/// kernel's key for the same reason.
1519pub const PADS: &str = brep_kernel::PADS_BLOCK;
1520/// The part's declared connection points (`ports.rs`) — data, not history,
1521/// and a sibling of `symbol` and `pads`.
1522pub const PORTS: &str = brep_kernel::PORTS_BLOCK;
1523/// The part's mount frame (`brep_kernel` `part_mount`): how it sits on its
1524/// footprint, applied to every instance. Never written as identity.
1525pub const MOUNT: &str = brep_kernel::MOUNT_BLOCK;
1526
1527impl History {
1528    /// The document's `diagram` block, if any.
1529    pub fn diagram_block(&self) -> Option<&Value> {
1530        self.document().get(DIAGRAM)
1531    }
1532
1533    /// The document's `pcb` block, if any.
1534    pub fn pcb_block(&self) -> Option<&Value> {
1535        self.document().get(PCB)
1536    }
1537
1538    /// The document's `symbol` block, if any.
1539    pub fn symbol_block(&self) -> Option<&Value> {
1540        self.document().get(SYMBOL)
1541    }
1542
1543    /// The document's `pads` block, if any.
1544    pub fn pads_block(&self) -> Option<&Value> {
1545        self.document().get(PADS)
1546    }
1547
1548    /// The document's `mount` block (its mount frame), if any.
1549    pub fn mount_block(&self) -> Option<&Value> {
1550        self.document().get(MOUNT).filter(|block| !block.is_null())
1551    }
1552
1553    /// Replace (or, with `None`, remove) the `mount` block as one undoable
1554    /// USER edit. The caller passes `None` for identity
1555    /// (`brep_kernel::mount_block_of`), so an identity mount leaves no key.
1556    pub fn set_mount_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1557        self.set_ecad_block(MOUNT, block, coalesce_key);
1558    }
1559
1560    /// The document's `ports` block (its declared connection points), if any.
1561    pub fn ports_block(&self) -> Option<&Value> {
1562        self.document().get(PORTS)
1563    }
1564
1565    /// The part's declared connection points, in block order.
1566    pub fn declared_points(&self) -> Vec<brep_kernel::DeclaredPoint> {
1567        brep_kernel::declared_points(self.document())
1568    }
1569
1570    /// The symbol's pin labels in pin order, or `None` without a symbol.
1571    pub fn pin_labels(&self) -> Option<Vec<String>> {
1572        brep_kernel::pin_labels(self.document())
1573    }
1574
1575    /// The symbol's pins with the UNIT each belongs to, in pin order, or `None`
1576    /// without a symbol. [`Self::pin_labels`] with the unit kept, for a caller
1577    /// that must say WHICH group a pin binds into.
1578    pub fn pins(&self) -> Option<Vec<brep_kernel::DeclaredPin>> {
1579        brep_kernel::pins(self.document())
1580    }
1581
1582    /// The port group the pins of symbol unit `unit` bind into, when one is
1583    /// mapped. The unit map's rule is the kernel's ([`brep_kernel::unit_groups`]).
1584    pub fn port_group_for_unit(&self, unit: u32) -> Option<String> {
1585        brep_kernel::port_group_for_unit(self.document(), unit)
1586    }
1587
1588    /// Replace (or, with `None`, remove) the `diagram` block as a USER edit.
1589    /// See `Self::set_ecad_block` for `coalesce_key`.
1590    pub fn set_diagram_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1591        self.set_ecad_block(DIAGRAM, block, coalesce_key);
1592    }
1593
1594    /// Replace (or, with `None`, remove) the `pcb` block as a USER edit.
1595    /// See `Self::set_ecad_block` for `coalesce_key`.
1596    pub fn set_pcb_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1597        self.set_ecad_block(PCB, block, coalesce_key);
1598    }
1599
1600    /// Replace (or, with `None`, remove) the `symbol` block as a USER edit,
1601    /// and follow it to the part's ports in the same undo step (see
1602    /// `Self::follow_pins`). See `Self::set_ecad_block` for `coalesce_key`.
1603    pub fn set_symbol_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1604        self.set_ecad_block(SYMBOL, block, coalesce_key);
1605        self.follow_pins(None);
1606    }
1607
1608    /// Replace (or, with `None`, remove) the `pads` block as a USER edit.
1609    /// See `Self::set_ecad_block` for `coalesce_key`.
1610    pub fn set_pads_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1611        self.set_ecad_block(PADS, block, coalesce_key);
1612    }
1613
1614    /// Write the `symbol` block WITHOUT an undo checkpoint, for a write that
1615    /// belongs to the checkpoint just taken: a KiCad import adds its Import 3D
1616    /// feature (one checkpoint) and writes the symbol and pads it read beside
1617    /// it, so one undo removes the whole import. The PMI import's
1618    /// [`Self::set_pmi_block_no_undo`] is the precedent.
1619    ///
1620    /// Skipping the checkpoint is deliberate, and costs the tab nothing: the
1621    /// write still goes through `document_mut`, which moves the revision the
1622    /// unsaved dot and the autosave key on.
1623    pub fn set_symbol_block_no_undo(&mut self, block: Option<Value>) {
1624        // No checkpoint marks where this write starts, so its base is the
1625        // document just before it.
1626        let base = self.document().clone();
1627        self.put_ecad_block(SYMBOL, block);
1628        self.follow_pins(Some(base));
1629    }
1630
1631    /// The `pads` twin of [`Self::set_symbol_block_no_undo`].
1632    pub fn set_pads_block_no_undo(&mut self, block: Option<Value>) {
1633        self.put_ecad_block(PADS, block);
1634    }
1635
1636    /// Replace (or, with `None`, remove) the `ports` block as a USER edit, and
1637    /// follow it to the part's pins in the same undo step (see
1638    /// `Self::follow_ports`).
1639    pub fn set_ports_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
1640        self.set_ecad_block(PORTS, block, coalesce_key);
1641        self.follow_ports();
1642        self.ports_followed = true;
1643    }
1644
1645    /// The `ports` twin of [`Self::set_symbol_block_no_undo`] — for a write
1646    /// that belongs to the checkpoint just taken (the KiCad import).
1647    pub fn set_ports_block_no_undo(&mut self, block: Option<Value>) {
1648        self.put_ecad_block(PORTS, block);
1649        self.ports_followed = true;
1650    }
1651
1652    /// Write block `key`, snapshotted for undo. `coalesce_key` is eCAD's own
1653    /// `Change::coalesce`, passed as the editor reported it: typing in one
1654    /// field of one object reports `component:{uuid}:text` on every frame, and
1655    /// a run of writes with that key is ONE undo entry. It is namespaced by the
1656    /// block here (`diagram:component:{uuid}:text`), so a run in one block never
1657    /// swallows an edit to another. `None` (a drag, a placement, the editor's
1658    /// own undo) is its own step.
1659    fn set_ecad_block(&mut self, key: &str, block: Option<Value>, coalesce_key: Option<&str>) {
1660        let coalesce_key = coalesce_key.map(|change| format!("{key}:{change}"));
1661        self.checkpoint(coalesce_key.as_deref());
1662        self.put_ecad_block(key, block);
1663    }
1664
1665    fn put_ecad_block(&mut self, key: &str, block: Option<Value>) {
1666        if let Some(object) = self.document_mut().as_object_mut() {
1667            match block {
1668                Some(block) => {
1669                    object.insert(key.into(), block);
1670                }
1671                None => {
1672                    object.shift_remove(key);
1673                }
1674            }
1675        }
1676    }
1677}
1678
1679// ============================================================================
1680// Pins and points: a part's symbol pins ARE its declared connection points,
1681// bound by NAME (eCAD plan decision 8; `brep_kernel` `part_pins` holds the
1682// rules).
1683//
1684// The binding lives HERE, inside the writes, so no caller can edit one side
1685// without the other: the symbol setters follow a pin edit to the points, and
1686// every mutator that can add, remove or rename a point follows it to the pins,
1687// inside the same undo step. Undo, redo and a replaced document need nothing,
1688// since a snapshot restores both sides together.
1689//
1690// Each follow diffs against the RUN BASE: the document the current coalesced
1691// run started from. Typing `10` over pin `2` is four writes under one eCAD key
1692// (`2`, ``, `1`, `10`). The two in the middle cannot bind (no label, and a
1693// label pin 1 already has), so they are HELD: the user's edit stands, the
1694// other side keeps what the last bound write gave it, and `pin_port_hold`
1695// names why. Replaying from the base makes the last keystroke decide
1696// whichever came before it.
1697// ============================================================================
1698
1699impl History {
1700    /// Why the latest pin or port edit was not followed to the other side, in
1701    /// words that name the label (`two pins are labelled '1'`), or `None`.
1702    pub fn pin_port_hold(&self) -> Option<&str> {
1703        self.pin_port_hold.as_deref()
1704    }
1705
1706    /// Everything about this part's pins and connection points that does not
1707    /// pair, by name; `None` for a document without a symbol.
1708    pub fn pin_point_report(&self) -> Option<brep_kernel::PinPointReport> {
1709        brep_kernel::pin_point_report(self.document())
1710    }
1711
1712    /// Whether a symbol edit has changed the declared points since the history
1713    /// last ran, clearing it. The engine re-runs when it was set.
1714    pub(crate) fn take_ports_followed(&mut self) -> bool {
1715        std::mem::take(&mut self.ports_followed)
1716    }
1717
1718    /// Whether the next [`crate::engine_state::EngineState::pump`] will re-run
1719    /// for a moved point, without clearing it — so the app can hand a document
1720    /// that is not in front its own parts library before that run is submitted.
1721    pub fn ports_follow_pending(&self) -> bool {
1722        self.ports_followed
1723    }
1724
1725    /// The document the current coalesced run started from. Right after a
1726    /// checkpointing write it is the top of the undo stack: [`Self::checkpoint`]
1727    /// pushes the pre-write state unless the write joins a run, and a run's
1728    /// first write pushed the state the run started from. Eviction takes the
1729    /// OLDEST entry, never the top. The stack is never empty after a
1730    /// checkpoint, so the fallback (the current document, which binds nothing)
1731    /// is never taken by a follow. Borrowed: a follow runs on every write of a
1732    /// drag, so the base is compared in place and never copied.
1733    fn run_base(&self) -> &Value {
1734        self.undo_stack
1735            .last()
1736            .map(|snapshot| &snapshot.request)
1737            .unwrap_or_else(|| self.document())
1738    }
1739
1740    /// Carry the symbol edit between the base (`base`, else the run base) and
1741    /// now to the connection points and the pads: a renamed pin renames its
1742    /// point in place (so the point keeps its placement), a removed pin removes
1743    /// its point, and a new pin gets a new point in the part's first port
1744    /// group.
1745    fn follow_pins(&mut self, base: Option<Value>) {
1746        let mut document = self.document().clone();
1747        let outcome = {
1748            let base = base.as_ref().unwrap_or_else(|| self.run_base());
1749            brep_kernel::follow_pin_edit(base, &mut document)
1750        };
1751        self.settle(outcome, document);
1752    }
1753
1754    /// Carry a connection-point edit between the run base and now to the pins
1755    /// and pads. Only an edit that changed the declared points is followed, so
1756    /// an unrelated edit neither binds nor clears a standing hold.
1757    fn follow_ports(&mut self) {
1758        if self.symbol_block().is_none() {
1759            return;
1760        }
1761        if brep_kernel::declared_points(self.run_base()) == brep_kernel::declared_points(self.document()) {
1762            return;
1763        }
1764        let mut document = self.document().clone();
1765        let outcome = brep_kernel::follow_point_edit(self.run_base(), &mut document);
1766        self.settle(outcome, document);
1767    }
1768
1769    /// Adopt a follow's result, or record why it was held. The write goes
1770    /// through `document_mut`, not a checkpoint: it belongs to the step the
1771    /// user's own write just took. The rolled-to step keeps its meaning: a
1772    /// model rolled to its last feature is still rolled to its last feature
1773    /// once a port is appended or removed, and one rolled back stays on the
1774    /// same feature.
1775    fn settle(&mut self, outcome: Result<Vec<brep_kernel::PinPointChange>, String>, document: Value) {
1776        let changes = match outcome {
1777            Ok(changes) => changes,
1778            Err(reason) => {
1779                self.pin_port_hold = Some(reason);
1780                return;
1781            }
1782        };
1783        self.pin_port_hold = None;
1784        if changes.is_empty() {
1785            return;
1786        }
1787        let moves_a_port = changes.iter().any(|change| {
1788            use brep_kernel::PinPointChange::*;
1789            // Exhaustive on purpose: a new kind of change must say whether
1790            // it touches the geometry a run publishes.
1791            match change {
1792                PointRenamed { .. } | PointAdded { .. } | PointRemoved { .. } => true,
1793                PinRelabelled { .. } | PinAdded { .. } | PinRemoved { .. }
1794                | PadsRenumbered { .. } | PadsAmbiguous { .. } => false,
1795            }
1796        });
1797        let at_end = self.rollback + 1 >= self.len();
1798        let rolled_to = self.feature_id(self.rollback());
1799        *self.document_mut() = document;
1800        let len = self.len();
1801        self.rollback = if len == 0 {
1802            0
1803        } else if at_end {
1804            len - 1
1805        } else {
1806            rolled_to
1807                .and_then(|id| self.index_of(&id))
1808                .unwrap_or_else(|| self.rollback.saturating_sub(1))
1809                .min(len - 1)
1810        };
1811        self.ports_followed |= moves_a_port;
1812    }
1813}
1814
1815
1816// ============================================================================
1817// Named top-level blocks the APP owns (appended — the document-classes slice).
1818// The history holds the document as a JSON value, so a key the kernel never
1819// reads (`documentClass`, a family's `familyTable`, a template's
1820// `templateInputs`, a member's `familySource`) rides save, open and every undo
1821// snapshot untouched. These are the doors that change one: the user-edit one
1822// records an undo step, the other is for a write that is bookkeeping rather
1823// than an edit (the class a load reads off the file's extension).
1824// ============================================================================
1825impl History {
1826    /// The document's top-level block `key`, if present.
1827    pub fn document_block(&self, key: &str) -> Option<&Value> {
1828        self.document().get(key)
1829    }
1830
1831    /// Replace (or, with `None`, remove) top-level block `key` as a USER edit:
1832    /// snapshotted for undo. `coalesce_key` groups a typing run into one step,
1833    /// namespaced by the block so a run in one never swallows another's.
1834    pub fn set_document_block(&mut self, key: &str, block: Option<Value>, coalesce_key: Option<&str>) {
1835        let coalesce_key = coalesce_key.map(|change| format!("block:{key}:{change}"));
1836        self.checkpoint(coalesce_key.as_deref());
1837        self.set_document_block_no_undo(key, block);
1838    }
1839
1840    /// [`Self::set_document_block`] with no undo step.
1841    pub fn set_document_block_no_undo(&mut self, key: &str, block: Option<Value>) {
1842        if let Some(object) = self.document_mut().as_object_mut() {
1843            match block {
1844                Some(block) => {
1845                    object.insert(key.to_string(), block);
1846                }
1847                None => {
1848                    // `shift_remove`: with `preserve_order`, `remove` moves the
1849                    // last key into the gap, and the reordered document then
1850                    // reads as an unsaved change.
1851                    object.shift_remove(key);
1852                }
1853            }
1854        }
1855    }
1856}
1857