BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! [`History`] — the engine-owned, editable model recipe: the ordered feature
//! history plus the rollback index (the feature the model is currently built up
//! to). This is the SINGLE SOURCE OF TRUTH for the model — the UI keeps NO copy;
//! it mutates and reads the history only through [`crate::engine_state::EngineState`]
//! methods. That keeps one engine-owned history (UI-agnostic) and converges with
//! the in-flight "whole history in Rust" pipeline migration — later this sinks
//! into `brep-kernel-rs` proper without touching the UI.
//!
//! Rolling to a step re-runs `features[0..=rollback]` through the SAME kernel
//! pipeline: the full feature list stays in the request and `stopAtId` (the
//! editor's "stop at the expanded feature") halts execution AFTER the rolled-to
//! feature, so the kernel's incremental history cache is RETAINED across rolls
//! (no thrash) and the viewport shows the model as of that step.

use serde_json::Value;

/// The cap on the undo (and redo) stack depth — old entries fall off the bottom.
const MAX_UNDO: usize = 100;

/// A restorable model state: the whole document PLUS the rolled-to step, captured
/// together so an undo returns both the geometry and the view to the state they
/// were in right before the mutation.
#[derive(Debug, Clone)]
struct Snapshot {
    request: Value,
    rollback: usize,
}

/// The engine-owned mutable history.
#[derive(Debug, Clone)]
pub struct History {
    /// The whole `HistoryRequest` document
    /// (`{expressions, configurator, features: [...]}`).
    request: Value,
    /// Index into `features` the model is rolled to (clamped to the last).
    rollback: usize,
    /// Undo/redo over the MODEL document. A snapshot is pushed BEFORE each model
    /// mutation (edit / add / delete / reorder); roll-to-step is view state and
    /// is NOT snapshotted. Rapid same-target edits (a slider drag) coalesce into a
    /// single undo entry via `last_edit_key`. The stacks live here in the engine
    /// core — the model is engine-owned, so its undo history is too; the UI only
    /// triggers `undo()` / `redo()`.
    undo_stack: Vec<Snapshot>,
    redo_stack: Vec<Snapshot>,
    /// The coalescing token of the most recently recorded edit (see `checkpoint`).
    last_edit_key: Option<String>,
    /// The persistent GLOBAL feature counter: bumped by one on every new-feature
    /// mint ([`Self::next_feature_id`]), so a new id is `{shortName}{counter}`.
    /// MONOTONIC and NEVER reused — deleting a feature does not free its number,
    /// and (deliberately) undo does NOT rewind it, so re-doing an add can't collide
    /// with a number already handed out. It is kept OFF `self.request` in memory
    /// (so the undo snapshots that clone `request` never rewind it) and folded into
    /// the serialized document under `"featureCounter"` so it round-trips save/load
    /// (see [`Self::request_json`] / [`Self::from_request_json`]).
    feature_counter: u64,
}

impl Default for History {
    fn default() -> Self {
        Self {
            request: empty_request(),
            rollback: 0,
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            last_edit_key: None,
            feature_counter: 0,
        }
    }
}

fn empty_request() -> Value {
    serde_json::json!({ "expressions": "", "configurator": {}, "features": [] })
}

/// The trailing run of ASCII digits of `id` read as a number (`"P.CU12"` → 12,
/// `"Box"` → 0). Trailing digits are ASCII (one byte each), so the slice boundary
/// is always a valid char boundary; a missing/overflowing run yields 0.
fn trailing_number(id: &str) -> u64 {
    let digit_bytes = id
        .bytes()
        .rev()
        .take_while(u8::is_ascii_digit)
        .count();
    id[id.len() - digit_bytes..].parse().unwrap_or(0)
}

impl History {
    /// Load a whole history document (a saved part file parses as one). Rolls to
    /// the last feature. Ensures a `features` array exists.
    pub fn from_request_json(json: &str) -> Result<Self, String> {
        let mut request: Value =
            serde_json::from_str(json).map_err(|e| format!("history parse: {e}"))?;
        if !request.get("features").map(Value::is_array).unwrap_or(false) {
            if let Some(obj) = request.as_object_mut() {
                obj.insert("features".into(), Value::Array(Vec::new()));
            } else {
                request = empty_request();
            }
        }
        // Lift the persistent feature counter OUT of the document so it lives ONLY
        // in the struct field: kept off `self.request`, the undo snapshots (which
        // clone `request`) can never rewind it, and it can't be double-folded on
        // re-serialize. A document with no stored counter (fresh or saved before
        // this field existed) safe-inits below.
        let stored = request
            .as_object_mut()
            .and_then(|obj| obj.remove("featureCounter"))
            .and_then(|value| value.as_u64());
        let mut history = Self {
            request,
            rollback: 0,
            ..Self::default()
        };
        history.rollback = history.len().saturating_sub(1);
        // Safe init when unstored: start ABOVE the largest numeric suffix already
        // present among feature ids so the next mint (`{shortName}{counter+1}`)
        // cannot collide with an existing id. This holds because no shortName ends
        // in a digit (verified — even `IMPORT3D` ends in `D`), so an id's trailing
        // digits ARE its numeric suffix and `counter+1` strictly exceeds them all.
        history.feature_counter = stored.unwrap_or_else(|| history.max_id_suffix());
        Ok(history)
    }

    /// The largest trailing-integer suffix among all existing feature ids (0 when
    /// none carry one) — the floor for a safe counter init on a document with no
    /// stored `featureCounter` (see [`Self::from_request_json`]).
    fn max_id_suffix(&self) -> u64 {
        self.features()
            .iter()
            .filter_map(|f| {
                f.get("inputParams")
                    .and_then(|p| p.get("id"))
                    .and_then(Value::as_str)
            })
            .map(trailing_number)
            .max()
            .unwrap_or(0)
    }

    /// The features slice (empty if none).
    pub fn features(&self) -> &[Value] {
        self.request
            .get("features")
            .and_then(Value::as_array)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    fn features_mut(&mut self) -> &mut Vec<Value> {
        let obj = self
            .request
            .as_object_mut()
            .expect("history request is a JSON object");
        obj.entry("features")
            .or_insert_with(|| Value::Array(Vec::new()));
        obj.get_mut("features")
            .and_then(Value::as_array_mut)
            .expect("features is a JSON array")
    }

    pub fn len(&self) -> usize {
        self.features().len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The rolled-to index, clamped to a valid feature (0 when empty).
    pub fn rollback(&self) -> usize {
        self.rollback.min(self.len().saturating_sub(1))
    }

    pub fn set_rollback(&mut self, index: usize) {
        self.rollback = if self.is_empty() {
            0
        } else {
            index.min(self.len() - 1)
        };
        // Rolling to a step is a view move, not a model edit: it records NO undo
        // snapshot, but it DOES break the edit-coalescing run so the next edit
        // starts a fresh undo entry rather than merging with a pre-roll edit.
        self.last_edit_key = None;
    }

    pub fn feature_type(&self, index: usize) -> Option<String> {
        self.features()
            .get(index)?
            .get("type")
            .and_then(Value::as_str)
            .map(String::from)
    }

    pub fn feature_id(&self, index: usize) -> Option<String> {
        self.features()
            .get(index)?
            .get("inputParams")
            .and_then(|p| p.get("id"))
            .and_then(Value::as_str)
            .map(String::from)
    }

    pub fn index_of(&self, id: &str) -> Option<usize> {
        self.features().iter().position(|f| {
            f.get("inputParams")
                .and_then(|p| p.get("id"))
                .and_then(Value::as_str)
                == Some(id)
        })
    }

    /// The `inputParams` document of the feature at `index` (for the dialog).
    pub fn feature_params(&self, index: usize) -> Option<Value> {
        self.features().get(index)?.get("inputParams").cloned()
    }

    pub fn set_feature_params(&mut self, index: usize, params: Value) {
        if index >= self.len() {
            return;
        }
        // Coalesce a slider drag (many consecutive edits of the SAME feature) into
        // one undo entry, keyed by the feature index.
        self.checkpoint(Some(&format!("param:{index}")));
        if let Some(feat) = self.features_mut().get_mut(index) {
            if let Some(obj) = feat.as_object_mut() {
                obj.insert("inputParams".into(), params);
            }
        }
    }

    pub fn push_feature(&mut self, feature: Value) {
        self.checkpoint(None);
        self.features_mut().push(feature);
    }

    pub fn remove_feature(&mut self, index: usize) {
        if index >= self.len() {
            return;
        }
        self.checkpoint(None);
        self.features_mut().remove(index);
    }

    pub fn swap(&mut self, a: usize, b: usize) {
        let len = self.len();
        if a < len && b < len && a != b {
            self.checkpoint(None);
            self.features_mut().swap(a, b);
        }
    }

    /// Mint the id for a NEW feature: `{base}{N}` where `base` is the feature's
    /// shortName and `N` is this history's persistent GLOBAL counter, bumped by one
    /// on every mint (`P.CU` → `P.CU7`, `S` → `S8`). GLOBAL across all feature
    /// types, MONOTONIC, and NEVER reused — a delete does not free a number and
    /// undo does not rewind the counter — and it persists across save/load, so two
    /// features can never receive the same id over the document's whole lifetime.
    pub fn next_feature_id(&mut self, base: &str) -> String {
        self.feature_counter += 1;
        format!("{base}{}", self.feature_counter)
    }

    /// The `stopAtId`-truncated request that stops AFTER the rolled-to feature —
    /// the roll-to-step request the pipeline runs. Empty history → empty request.
    pub fn prefix_request(&self) -> Value {
        let mut request = self.request.clone();
        if let Some(id) = self.feature_id(self.rollback()) {
            if let Some(obj) = request.as_object_mut() {
                obj.insert("stopAtId".into(), Value::String(id));
            }
        }
        request
    }

    /// The tree listing for the UI: `{ step, features: [{index, type, id}] }`.
    pub fn listing_json(&self) -> String {
        let features: Vec<Value> = self
            .features()
            .iter()
            .enumerate()
            .map(|(index, _)| {
                serde_json::json!({
                    "index": index,
                    "type": self.feature_type(index).unwrap_or_else(|| "?".into()),
                    "id": self.feature_id(index).unwrap_or_else(|| "(no id)".into()),
                })
            })
            .collect();
        serde_json::json!({ "step": self.rollback(), "features": features }).to_string()
    }

    /// The whole request document (for persistence / debugging), with the
    /// persistent global feature counter folded back in under `"featureCounter"`
    /// so it round-trips through save/load (the twin of [`Self::from_request_json`],
    /// which lifts it back out). Written only when non-zero, so a document that has
    /// never minted a feature persists byte-for-byte as before (mirrors the
    /// metadata field's "un-annotated model persists unchanged" convention).
    pub fn request_json(&self) -> String {
        if self.feature_counter == 0 {
            return self.request.to_string();
        }
        let mut document = self.request.clone();
        if let Some(obj) = document.as_object_mut() {
            obj.insert("featureCounter".into(), Value::from(self.feature_counter));
        }
        document.to_string()
    }

    // --- Undo / redo over the model document ------------------------------

    fn snapshot(&self) -> Snapshot {
        Snapshot {
            request: self.request.clone(),
            rollback: self.rollback,
        }
    }

    fn restore(&mut self, snap: Snapshot) {
        self.request = snap.request;
        let last = self.len().saturating_sub(1);
        self.rollback = snap.rollback.min(last);
    }

    /// Record a pre-mutation snapshot for undo. `coalesce_key` groups a run of
    /// rapid same-target edits (one slider drag) into a SINGLE undo entry: while
    /// the same non-empty key repeats, no new snapshot is pushed. A `None` key
    /// never coalesces, so every structural add/delete/reorder is its own entry.
    /// Any new snapshot clears the redo stack (a fresh edit forks the timeline)
    /// and the oldest entry falls off once the stack passes [`MAX_UNDO`].
    fn checkpoint(&mut self, coalesce_key: Option<&str>) {
        if coalesce_key.is_some() && coalesce_key == self.last_edit_key.as_deref() {
            return;
        }
        self.undo_stack.push(self.snapshot());
        if self.undo_stack.len() > MAX_UNDO {
            self.undo_stack.remove(0);
        }
        self.redo_stack.clear();
        self.last_edit_key = coalesce_key.map(str::to_string);
    }

    /// Whether an undo step is available (for enabling the toolbar button).
    pub fn can_undo(&self) -> bool {
        !self.undo_stack.is_empty()
    }

    /// Whether a redo step is available.
    pub fn can_redo(&self) -> bool {
        !self.redo_stack.is_empty()
    }

    /// Undo the last model mutation: push the current state onto the redo stack
    /// and restore the previous document + rolled-to step. Returns whether it
    /// changed anything (false when the undo stack is empty).
    pub fn undo(&mut self) -> bool {
        let Some(prev) = self.undo_stack.pop() else {
            return false;
        };
        self.redo_stack.push(self.snapshot());
        self.restore(prev);
        // A distinct undo breaks any coalescing run so the next edit is fresh.
        self.last_edit_key = None;
        true
    }

    /// Redo the last undone model mutation (symmetric with [`Self::undo`]).
    pub fn redo(&mut self) -> bool {
        let Some(next) = self.redo_stack.pop() else {
            return false;
        };
        self.undo_stack.push(self.snapshot());
        self.restore(next);
        self.last_edit_key = None;
        true
    }
}

// ============================================================================
// Expressions / configurator accessors (appended — the expressions/parameters
// panel slice). A SEPARATE `impl` block so concurrent edits to the primary block
// don't conflict; purely additive over the existing history API.
//
// The history document carries an `expressions` source string — the variable
// sheet feature params evaluate against (a numeric param may be the string
// `"boxW"`, evaluated by the pipeline's shared expression env). The panel edits
// this and re-runs; the `configurator` object (typed named inputs) is exposed
// read-only for display.
// ============================================================================
impl History {
    /// The history document's `expressions` source string (empty when absent or
    /// stored as `null`). The panel's editor binds to this.
    pub fn expressions(&self) -> String {
        self.request
            .get("expressions")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string()
    }

    /// Replace the `expressions` source string. Snapshotted for undo, coalescing a
    /// run of keystroke edits into ONE undo entry (like a slider drag) via the
    /// shared `"expressions"` coalesce key, so a distinct add/edit/roll starts a
    /// fresh entry. A no-op re-set (same text) still records under the same key.
    pub fn set_expressions(&mut self, expressions: &str) {
        self.checkpoint(Some("expressions"));
        if let Some(obj) = self.request.as_object_mut() {
            obj.insert(
                "expressions".into(),
                Value::String(expressions.to_string()),
            );
        }
    }

    /// The `configurator` object (typed named inputs), or `{}` when absent —
    /// read-only for the panel's display (deeper configurator editing deferred).
    pub fn configurator(&self) -> Value {
        self.request
            .get("configurator")
            .cloned()
            .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
    }
}

// ============================================================================
// Feature `persistentData` accessors (appended — the engine-native sketch mode
// slice). A SEPARATE `impl` block (like the expressions accessors above) so
// concurrent edits don't conflict; purely additive over the primary history API.
//
// A feature's `persistentData` is the kernel-persisted, non-input state (a
// SKETCH feature stores its solved `{points, geometries, constraints}` under the
// `sketch` key and the plane `basis` there). Sketch mode reads that state on
// enter and writes the edited doc back on commit — mirroring how the ref-select
// slice reads/writes `inputParams` through `feature_params` / `set_feature_params`.
// ============================================================================
impl History {
    /// The `persistentData` document of the feature at `index` (`None` if the
    /// feature or the field is absent) — the read twin of [`Self::feature_params`].
    pub fn feature_persistent_data(&self, index: usize) -> Option<Value> {
        self.features().get(index)?.get("persistentData").cloned()
    }

    /// Set a single `key` inside the feature-at-`index`'s `persistentData` object,
    /// creating (or replacing a non-object) `persistentData` as needed. Snapshotted
    /// for undo (a structural edit — never coalesced), like an add/delete.
    pub fn set_feature_persistent_field(&mut self, index: usize, key: &str, value: Value) {
        if index >= self.len() {
            return;
        }
        self.checkpoint(None);
        if let Some(feat) = self.features_mut().get_mut(index).and_then(Value::as_object_mut) {
            let entry = feat
                .entry("persistentData")
                .or_insert_with(|| Value::Object(serde_json::Map::new()));
            if !entry.is_object() {
                *entry = Value::Object(serde_json::Map::new());
            }
            if let Some(obj) = entry.as_object_mut() {
                obj.insert(key.to_string(), value);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn seed() -> History {
        History::from_request_json(
            r#"{"features":[
                {"type":"P.CU","inputParams":{"id":"Box","sizeX":20}},
                {"type":"P.CY","inputParams":{"id":"Pin","radius":6}},
                {"type":"B","inputParams":{"id":"Cut","boolean":{"operation":"SUBTRACT","targets":["Pin"]}}}
            ]}"#,
        )
        .unwrap()
    }

    #[test]
    fn loads_and_rolls_to_last() {
        let h = seed();
        assert_eq!(h.len(), 3);
        assert_eq!(h.rollback(), 2);
        assert_eq!(h.feature_type(0).as_deref(), Some("P.CU"));
        assert_eq!(h.feature_id(2).as_deref(), Some("Cut"));
    }

    #[test]
    fn prefix_request_stops_at_rolled_step() {
        let mut h = seed();
        h.set_rollback(0);
        let req = h.prefix_request();
        assert_eq!(req["stopAtId"].as_str(), Some("Box"));
        // The full feature list is retained (cache retention), only stopAtId moves.
        assert_eq!(req["features"].as_array().unwrap().len(), 3);
    }

    #[test]
    fn edit_add_delete_reorder() {
        let mut h = seed();
        // edit params of "Pin"
        let idx = h.index_of("Pin").unwrap();
        h.set_feature_params(idx, serde_json::json!({"id":"Pin","radius":9}));
        assert_eq!(h.feature_params(idx).unwrap()["radius"], 9);
        // add
        h.push_feature(serde_json::json!({"type":"P.CU","inputParams":{"id":"Box"}}));
        // the persistent counter mints the next id (seed ids carry no numeric
        // suffix → the counter safe-inits to 0, so the first mint is 1).
        assert_eq!(h.next_feature_id("Box"), "Box1");
        // reorder swap 0<->1
        h.swap(0, 1);
        assert_eq!(h.feature_id(0).as_deref(), Some("Pin"));
        // delete "Cut"
        let cut = h.index_of("Cut").unwrap();
        h.remove_feature(cut);
        assert!(h.index_of("Cut").is_none());
    }

    #[test]
    fn undo_redo_over_edit_and_add() {
        let mut h = seed();
        // A freshly loaded history has nothing to undo/redo.
        assert!(!h.can_undo());
        assert!(!h.can_redo());
        // A roll is view state: it records NO undo entry.
        h.set_rollback(0);
        assert!(!h.can_undo());

        // Edit a param → undo reverts it, redo re-applies it.
        let box_idx = h.index_of("Box").unwrap();
        assert_eq!(h.feature_params(box_idx).unwrap()["sizeX"], 20);
        h.set_feature_params(box_idx, serde_json::json!({ "id": "Box", "sizeX": 50 }));
        assert_eq!(h.feature_params(box_idx).unwrap()["sizeX"], 50);
        assert!(h.can_undo());
        assert!(h.undo());
        assert_eq!(h.feature_params(box_idx).unwrap()["sizeX"], 20);
        assert!(h.can_redo());
        assert!(h.redo());
        assert_eq!(h.feature_params(box_idx).unwrap()["sizeX"], 50);

        // Add a feature → undo removes it, redo brings it back.
        let n = h.len();
        h.push_feature(serde_json::json!({ "type": "P.CU", "inputParams": { "id": "Extra" } }));
        assert_eq!(h.len(), n + 1);
        assert!(h.undo());
        assert_eq!(h.len(), n);
        assert!(h.index_of("Extra").is_none());
        assert!(h.redo());
        assert_eq!(h.len(), n + 1);
        assert!(h.index_of("Extra").is_some());

        // A NEW mutation forks the timeline (clears redo).
        h.undo();
        assert!(h.can_redo());
        h.push_feature(serde_json::json!({ "type": "P.CU", "inputParams": { "id": "Fork" } }));
        assert!(!h.can_redo());
    }

    #[test]
    fn drag_edits_coalesce_into_one_undo() {
        let mut h = seed();
        h.set_rollback(0);
        let box_idx = h.index_of("Box").unwrap();
        // Simulate a slider DRAG: many consecutive edits of the same feature.
        for v in [21, 22, 23, 24, 25] {
            h.set_feature_params(box_idx, serde_json::json!({ "id": "Box", "sizeX": v }));
        }
        assert_eq!(h.feature_params(box_idx).unwrap()["sizeX"], 25);
        // ONE undo reverts the WHOLE drag to the pre-drag value — and that is the
        // only undo entry the drag produced.
        assert!(h.undo());
        assert_eq!(h.feature_params(box_idx).unwrap()["sizeX"], 20);
        assert!(!h.can_undo());

        // A roll between two edits of the same feature breaks coalescing, so the
        // two edits become two distinct undo entries.
        h.set_feature_params(box_idx, serde_json::json!({ "id": "Box", "sizeX": 30 }));
        h.set_rollback(0);
        h.set_feature_params(box_idx, serde_json::json!({ "id": "Box", "sizeX": 40 }));
        assert!(h.undo());
        assert_eq!(h.feature_params(box_idx).unwrap()["sizeX"], 30);
        assert!(h.undo());
        assert_eq!(h.feature_params(box_idx).unwrap()["sizeX"], 20);
    }

    #[test]
    fn expressions_get_set_and_undo_coalesces() {
        let mut h = seed();
        assert_eq!(h.expressions(), ""); // seed has no expressions field
        h.set_expressions("boxW = 30;");
        assert_eq!(h.expressions(), "boxW = 30;");
        // Consecutive expression edits coalesce into a single undo entry.
        h.set_expressions("boxW = 40;");
        h.set_expressions("boxW = 50;");
        assert_eq!(h.expressions(), "boxW = 50;");
        assert!(h.undo());
        // ONE undo reverts the whole coalesced run to the pre-edit (empty) value.
        assert_eq!(h.expressions(), "");
        // The configurator accessor returns an object (empty here).
        assert!(h.configurator().is_object());
    }

    #[test]
    fn next_feature_id_is_shortname_plus_global_counter() {
        let mut h = History::default();
        // A NEW feature's id is `{shortName}{N}` with N the global counter, bumped
        // once per mint — the exact ids for a couple of types (incl. dotted ones).
        assert_eq!(h.next_feature_id("S"), "S1");
        assert_eq!(h.next_feature_id("P.CU"), "P.CU2");
        assert_eq!(h.next_feature_id("E"), "E3");
    }

    #[test]
    fn counter_is_global_across_types_and_never_reused_on_delete() {
        let mut h = History::default();
        // Sketch, then cube, then extrude → S1, P.CU2, E3 (ONE global counter,
        // not per-type).
        let s = h.next_feature_id("S");
        h.push_feature(serde_json::json!({ "type": "S", "inputParams": { "id": s } }));
        let cu = h.next_feature_id("P.CU");
        h.push_feature(serde_json::json!({ "type": "P.CU", "inputParams": { "id": cu } }));
        let e = h.next_feature_id("E");
        h.push_feature(serde_json::json!({ "type": "E", "inputParams": { "id": e } }));
        assert_eq!(h.feature_id(0).as_deref(), Some("S1"));
        assert_eq!(h.feature_id(1).as_deref(), Some("P.CU2"));
        assert_eq!(h.feature_id(2).as_deref(), Some("E3"));

        // Delete the FIRST feature (S1): its number 1 must NOT be reused — the next
        // mint is strictly greater than every number handed out so far.
        let idx = h.index_of("S1").unwrap();
        h.remove_feature(idx);
        assert_eq!(h.next_feature_id("P.CY"), "P.CY4");
    }

    #[test]
    fn counter_persists_across_serialize_reload() {
        let mut h = History::default();
        let first = h.next_feature_id("S"); // S1
        h.push_feature(serde_json::json!({ "type": "S", "inputParams": { "id": first } }));

        // Serialize → reload through the REAL persistence path (`request_json` →
        // `from_request_json`), not a hand-built document.
        let json = h.request_json();
        assert!(json.contains("\"featureCounter\":1"), "counter is folded in: {json}");
        let mut reloaded = History::from_request_json(&json).unwrap();

        // The counter CONTINUES from where it left off — no restart, and the new id
        // cannot collide with the persisted S1.
        assert_eq!(reloaded.next_feature_id("P.CU"), "P.CU2");
    }

    #[test]
    fn unmutated_document_omits_the_counter_key() {
        // The seed's ids carry no numeric suffix → counter safe-inits to 0 → the
        // document persists byte-for-byte with NO `featureCounter` key.
        let h = seed();
        assert!(!h.request_json().contains("featureCounter"));
    }

    #[test]
    fn undo_does_not_rewind_the_counter() {
        // Snapshots capture only `request` + `rollback`; the counter lives OFF the
        // request, so undoing an add (a delete) must NOT free the number — otherwise
        // a redo/new-add could reuse it.
        let mut h = History::default();
        let a = h.next_feature_id("P.CU"); // P.CU1
        h.push_feature(serde_json::json!({ "type": "P.CU", "inputParams": { "id": a } }));
        assert!(h.undo());
        assert!(h.index_of("P.CU1").is_none());
        assert_eq!(h.next_feature_id("P.CU"), "P.CU2");
    }

    #[test]
    fn counter_safe_inits_above_existing_id_suffixes() {
        // A legacy document with NO stored counter: safe-init lifts the counter above
        // the largest existing numeric suffix so a new id can't collide.
        let mut h = History::from_request_json(
            r#"{"features":[
                {"type":"P.CU","inputParams":{"id":"P.CU5"}},
                {"type":"S","inputParams":{"id":"S2"}}
            ]}"#,
        )
        .unwrap();
        // Max suffix is 5 → the next mint is 6.
        assert_eq!(h.next_feature_id("E"), "E6");
    }

    #[test]
    fn trailing_number_reads_the_suffix() {
        assert_eq!(trailing_number("P.CU12"), 12);
        assert_eq!(trailing_number("S1"), 1);
        assert_eq!(trailing_number("Box"), 0);
        assert_eq!(trailing_number("IMPORT3D"), 0); // ends in a letter
    }
}