BREP_app 0.2.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
//! Assembly Constraints panel — the schema-driven constraint collection widget
//! (build-spec §8.3), driven EXACTLY like the feature history panel: a TREE of
//! constraints, and activating one replaces the whole panel with that
//! constraint's dialog, drawn by the SHARED [`crate::form_view`]. The kernel's
//! `constraint_schema_catalogue` supplies the nine schemas and
//! [`brep_render::features::form_fields_from_schema`] maps each into the shared
//! form fields; this panel supplies the engine side and owns nothing about
//! layout.
//!
//! # The two modes, and what decides them
//!
//! Unlike the history panel, the mode is NOT panel-local state: it is READ from
//! the constraint's own `open` flag, which the kernel already maintains as an
//! ACCORDION (`EngineState::assembly_set_constraint_open` closes every other row
//! when one opens, so at most one is ever open). That matters because two other
//! surfaces open a constraint WITHOUT going through this panel — the context
//! bar's add-from-selection (`panels::context_bar`) and a viewport constraint
//! label click (`EngineState::constraint_label_clicked`). Deriving the mode from
//! `open` makes both of them open the form for free; a panel-local mode would
//! leave them setting a flag nothing renders. It also supplies the validity
//! guard for nothing: a deleted or undone constraint has no row, so there is no
//! open row, so the panel is back in the tree.
//!
//! ## Tree mode
//!
//! * Header: **Solve** (manual solve — works with auto-solve off), the
//!   **auto-solve** toggle (`settings.assembly_auto_solve`, consulted by the
//!   engine's mutation path), the **DOF readout** (dof/rank/redundant +
//!   over-/under-constrained wording), **Show Constraint Graphics**
//!   (`settings.show_constraint_graphics` — the render flag lane G consumes),
//!   and **Update components (N)** — the shell-owned
//!   [`UpdateComponents`] checker supplies N (source-signature comparison,
//!   build-spec §8.6); clicking runs the batch refresh through the
//!   document-transport lane.
//! * `+` dropdown of the nine types (catalogue order), pre-seeding `elements`
//!   from the current selection filtered by the type's `selectionFilter`.
//! * Per row: enable checkbox / **edit** (`✎`) / delete / drag-reorder; status
//!   label + color from the ONE map ([`brep_render::assembly_status`]);
//!   distance/angle rows append the evaluated value (`… 12.5` / `… 90°`).
//! * The edit button, the `[+]` box and a plain click on the row label all OPEN
//!   that constraint's form — the same three-affordance shape the history tree
//!   uses, and the same `SetOpen` engine call the expand-collapse used to make.
//!
//! ## Form mode
//!
//! One constraint's dialog fills the panel: the row's (value-free) label as the
//! title, its status as the banner in the ONE map's colour, the schema fields —
//! `elements` reference chips reuse the engine's modal ref-select in its
//! CONSTRAINT flavour (`begin_ref_select_for_constraint`), including
//! `{solid}@x,y,z` vertex refs — and ONE bottom button back to the tree. Editing
//! is LIVE (every change commits and re-solves per the auto-solve setting);
//! there is no Cancel and no buffer, exactly as in the feature dialogs. Nothing
//! ROLLS: assembly constraints have no rollback, which the form view is told
//! through [`crate::form_view::FormViewSpec::rollback`].

use crate::form_view::{form_view, FormViewSpec};
use crate::panels::tree::{self, TreeRow};
use crate::panels::update_components::UpdateComponents;
use crate::store::ModelStore;
use brep_render::assembly_status;
use brep_render::engine_state::EngineState;
use brep_render::features::form_fields_from_schema;
use eframe::egui;
use serde_json::Value;
use std::collections::HashMap;

/// The red of the per-row delete affordance (matches the history panel).
const DELETE_RED: egui::Color32 = egui::Color32::from_rgb(0xd8, 0x54, 0x4f);

/// One constraint row's per-frame snapshot (owned, so the draw loop can defer
/// `&mut state` mutations — the shared panel pattern).
struct ConstraintRow {
    id: String,
    type_id: String,
    /// `label id` + the evaluated value suffix (`Distance DIST3  12.5`).
    label: String,
    /// The same label WITHOUT the evaluated suffix (`Distance DIST3`) — the
    /// form's title, and therefore the scope key for its per-field widget ids
    /// and transient view state ([`FormViewSpec::title`]). It must be STABLE:
    /// `label` changes as the solver re-evaluates the measure, and re-keying the
    /// widgets mid-edit would hand the `distance` field a fresh (empty) edit
    /// buffer and eat what the user was typing.
    title: String,
    enabled: bool,
    open: bool,
    status: String,
    input_params: Value,
}

/// A deferred engine mutation (one per frame).
enum Action {
    Add(String, Value),
    SetEnabled(String, bool),
    SetOpen(String, bool),
    Delete(String),
    Move(String, usize),
    UpdateParams(String, Value),
    Solve,
    /// Run the update-components batch refresh (the header button).
    UpdateComponents,
    BeginRefSelect {
        id: String,
        path: Vec<String>,
        label: String,
        filter: Vec<String>,
        multiple: bool,
        seed: Vec<String>,
    },
}

/// The Assembly Constraints panel's transient UI state.
#[derive(Default)]
pub struct AssemblyConstraintsPanel {
    /// Per-frame widget screen rects for the headed verifier.
    hits: HashMap<String, egui::Rect>,
    /// The row index currently drag-reordered (`None` = not dragging).
    drag_src: Option<usize>,
}

impl AssemblyConstraintsPanel {
    pub fn new() -> Self {
        Self::default()
    }

    /// Draw the constraints panel. Every effect routes through the engine
    /// (`EngineState`); the two header toggles also persist through `model_store`
    /// (the settings key — the toolbar's wireframe-toggle pattern). `updates`
    /// is the shell-owned outdated checker (kept current by the shell's
    /// per-frame `ensure_current`); `model_store` feeds the batch refresh.
    pub fn show(
        &mut self,
        ui: &mut egui::Ui,
        state: &mut EngineState,
        model_store: &dyn ModelStore,
        updates: &mut UpdateComponents,
    ) {
        self.hits.clear();
        // The panel's VISIBLE region (the enclosing dock pane's scroll viewport),
        // published exactly as the history panel publishes `panel:clip`: every
        // other rect here is a raw LAYOUT rect, so a long constraint list — or a
        // long form — runs past the pane's bottom where egui clips it and it
        // stops being clickable even though the rect is still published. The
        // headed verifier intersects against this to know when it must scroll
        // first.
        self.hits.insert("acon:panel:clip".into(), ui.clip_rect());
        state.ensure_assembly_synced();

        // --- snapshots (owned) -------------------------------------------------
        let catalogue = brep_render::brep_kernel::constraint_schema_catalogue();
        let schemas: Vec<Value> = catalogue.as_array().cloned().unwrap_or_default();
        let statuses = state.assembly_statuses_value();
        let overlay = state.assembly_overlay_value();
        let dof = state.assembly_dof_value();
        let constraint_state = state.assembly_state_value();
        let rows = snapshot_rows(&constraint_state, &statuses, &overlay, &schemas);

        ui.spacing_mut().item_spacing.y = 2.0;

        let mut action: Option<Action> = None;
        // The form's EXIT, kept out of `action` on purpose. The panel applies one
        // `Action` per frame, and leaving the form can legitimately coincide with
        // a param commit: a focused `Scalar` commits on FOCUS LOSS, so clicking
        // "Return to tree" while one is focused produces `changed` AND
        // `exit_clicked` in the same frame. Sharing one slot would drop whatever
        // the user had just typed.
        let mut close: Option<String> = None;

        // --- THE MODE SWITCH: the tree, or ONE constraint's form --------------
        // Read from the constraint's own `open` flag rather than from panel
        // state — see the module doc: the kernel keeps it an accordion (at most
        // one open) and two other surfaces set it without going through here.
        match rows.iter().find(|row| row.open) {
            Some(row) => self.show_form(ui, row, &schemas, &mut action, &mut close),
            None => self.show_tree(
                ui,
                state,
                model_store,
                updates,
                &rows,
                &schemas,
                &dof,
                &mut action,
            ),
        }

        // --- apply the one deferred engine mutation ----------------------------
        let result: Result<(), String> = match action {
            Some(Action::Add(type_id, params)) => state
                .assembly_add_constraint(&type_id, &params.to_string())
                .map(|_id| ()),
            Some(Action::SetEnabled(id, enabled)) => {
                state.assembly_set_constraint_enabled(&id, enabled)
            }
            Some(Action::SetOpen(id, open)) => state.assembly_set_constraint_open(&id, open),
            Some(Action::Delete(id)) => state.assembly_remove_constraint(&id),
            Some(Action::Move(id, index)) => state.assembly_move_constraint(&id, index),
            Some(Action::UpdateParams(id, params)) => {
                state.assembly_update_constraint(&id, &params.to_string())
            }
            Some(Action::Solve) => state.assembly_run_solve(),
            // The batch refresh pushes its own per-entry + summary notices;
            // only a whole-batch failure routes to the shared toast below.
            Some(Action::UpdateComponents) => updates.run(state, model_store).map(|_| ()),
            Some(Action::BeginRefSelect {
                id,
                path,
                label,
                filter,
                multiple,
                seed,
            }) => {
                state.begin_ref_select_for_constraint(&id, path, label, filter, multiple, seed);
                Ok(())
            }
            None => Ok(()),
        };
        if let Err(error) = result {
            state.push_notice(format!("Assembly constraints: {error}"));
        }
        // Leaving the form is a SECOND mutation, applied after the action so a
        // commit and an exit in the same frame both land (see `close` above).
        if let Some(id) = close {
            if let Err(error) = state.assembly_set_constraint_open(&id, false) {
                state.push_notice(format!("Assembly constraints: {error}"));
            }
        }

        // --- verifier hooks (wasm only) ----------------------------------------
        #[cfg(target_arch = "wasm32")]
        {
            let listing: Vec<Value> = rows
                .iter()
                .map(|row| {
                    serde_json::json!({
                        "id": row.id,
                        "type": row.type_id,
                        "label": row.label,
                        "enabled": row.enabled,
                        "open": row.open,
                        "status": row.status,
                        "statusLabel": assembly_status::status_label(&row.status),
                        "statusColor": assembly_status::status_color_hex(&row.status),
                    })
                })
                .collect();
            publish(
                "__brepAssemblyConstraints",
                &serde_json::json!({
                    "rows": listing,
                    "dof": dof,
                    "updateCount": updates.outdated_count(),
                })
                .to_string(),
            );
            publish("__brepAssemblyConstraintsHit", &self.hits_json());
        }
    }

    /// Draw the constraint TREE — the solver header, one row per constraint, and
    /// the add-constraint dropdown.
    #[allow(clippy::too_many_arguments)]
    fn show_tree(
        &mut self,
        ui: &mut egui::Ui,
        state: &mut EngineState,
        model_store: &dyn ModelStore,
        updates: &mut UpdateComponents,
        rows: &[ConstraintRow],
        schemas: &[Value],
        dof: &Value,
        action: &mut Option<Action>,
    ) {

        // --- Solver accordion: solve / auto-solve / graphics / update / status.
        // Grouped above the constraint list and STACKED vertically (this used
        // to be one wrapping row of controls). Default-open so the Solve button
        // and status stay visible (and the headed-verify rects stay populated).
        egui::CollapsingHeader::new("Solver")
            .id_salt("acon-solver")
            .default_open(true)
            .show(ui, |ui| {
                ui.spacing_mut().item_spacing.y = 4.0;
                let full = egui::vec2(ui.available_width(), 0.0);

                let solve = ui
                    .add(egui::Button::new("\u{25B6} Solve").min_size(full))
                    .on_hover_text(
                        "Solve the assembly constraints now (works with auto-solve off)",
                    );
                self.hits.insert("acon:solve".into(), solve.rect);
                if solve.clicked() {
                    *action = Some(Action::Solve);
                }

                let mut auto = state.settings.assembly_auto_solve;
                let auto_resp = ui
                    .checkbox(&mut auto, "Auto-solve")
                    .on_hover_text("Re-solve after every constraint change");
                self.hits.insert("acon:autosolve".into(), auto_resp.rect);
                if auto_resp.changed() {
                    state.settings.assembly_auto_solve = auto;
                    state.settings_generation = state.settings_generation.wrapping_add(1);
                    let _ = model_store.write(crate::store::SETTINGS_KEY, &state.settings_json());
                }

                let mut graphics = state.settings.show_constraint_graphics;
                let graphics_resp = ui
                    .checkbox(&mut graphics, "Show constraint graphics")
                    .on_hover_text("Draw per-constraint leaders + labels in the viewport");
                self.hits.insert("acon:graphics".into(), graphics_resp.rect);
                if graphics_resp.changed() {
                    state.settings.show_constraint_graphics = graphics;
                    state.settings_generation = state.settings_generation.wrapping_add(1);
                    state.dirty = true;
                    let _ = model_store.write(crate::store::SETTINGS_KEY, &state.settings_json());
                }

                // Update components: N = the checker's source-signature
                // comparison (build-spec §8.6); enabled only when outdated.
                let outdated = updates.outdated_count();
                let mut hover =
                    "Refresh outdated parts from their source — every instance follows".to_string();
                if !updates.missing().is_empty() {
                    hover.push_str(&format!(
                        "; no source document for {}",
                        updates.missing().join(", ")
                    ));
                }
                // The note must survive the DISABLED state too (count 0 with
                // source-less parts is exactly when it matters): egui suppresses
                // plain hover text on disabled widgets.
                let update = ui
                    .add_enabled(
                        outdated > 0,
                        egui::Button::new(format!("Update components ({outdated})"))
                            .min_size(full),
                    )
                    .on_hover_text(hover.clone())
                    .on_disabled_hover_text(hover);
                self.hits.insert("acon:update".into(), update.rect);
                if update.clicked() {
                    *action = Some(Action::UpdateComponents);
                }

                // Solve status: "No constraints solved yet", the DOF summary, or
                // the last solve error.
                ui.label(egui::RichText::new(dof_summary(dof)).weak());
            });
        ui.add_space(4.0);

        // --- ROOT: `[-] Assembly Constraints (N)` ------------------------------
        tree::node(
            ui,
            TreeRow {
                guides: &[],
                is_last: true,
                expandable: true,
                expanded: true,
                root: true,
                glyph: None,
                label: "Assembly Constraints",
                selected: false,
                draggable: false,
            },
            |ui| {
                ui.label(egui::RichText::new(format!("{}", rows.len())).weak());
            },
        );
        if rows.is_empty() {
            let g = tree::child_guides(&[], true);
            tree::node(ui, TreeRow::leaf(&g, true, "(no constraints)"), |_| {});
        }

        // --- rows --------------------------------------------------------------
        let mut row_rects: Vec<(usize, egui::Rect)> = Vec::with_capacity(rows.len());
        let mut drag_move: Option<(usize, usize)> = None;
        let n = rows.len();
        for (i, row) in rows.iter().enumerate() {
            let rect = self.render_row(ui, row, i + 1 == n, action);
            row_rects.push((i, rect));
        }

        // --- resolve an in-flight drag (the history panel's algorithm) ---------
        if let Some(src) = self.drag_src {
            let released = ui.input(|i| i.pointer.any_released());
            let ptr = ui.input(|i| i.pointer.interact_pos());
            match (ptr, released) {
                (Some(p), released) => {
                    let target = row_rects
                        .iter()
                        .min_by(|a, b| {
                            let da = (a.1.center().y - p.y).abs();
                            let db = (b.1.center().y - p.y).abs();
                            da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
                        })
                        .map(|(index, _)| *index)
                        .unwrap_or(src);
                    if released && target == src {
                        // NOT a reorder — a press that STARTED and ENDED on the
                        // same row. egui reclassifies a press as a DRAG once it
                        // outlives `max_click_duration` (0.8 s) or drifts past
                        // `max_click_dist` (6 pt), so an ordinary human click on a
                        // label — which routinely lingers or wobbles a few pixels
                        // — fires `drag_started` and NEVER `clicked`. Before the
                        // form mode that landed in the reorder arm and did nothing
                        // at all (`src == target` is skipped below); the history
                        // tree routes the same gesture to "open that row", and so
                        // does this one.
                        if let Some(row) = rows.get(src) {
                            *action = Some(Action::SetOpen(row.id.clone(), true));
                        }
                        self.drag_src = None;
                    } else if released {
                        drag_move = Some((src, target));
                        self.drag_src = None;
                    } else if target != src {
                        if let Some((_, rect)) =
                            row_rects.iter().find(|(index, _)| *index == target)
                        {
                            let y = if target >= src { rect.bottom() } else { rect.top() };
                            ui.painter().hline(
                                rect.x_range(),
                                y,
                                egui::Stroke::new(2.0, ui.visuals().selection.bg_fill),
                            );
                        }
                    }
                }
                (None, true) => self.drag_src = None,
                _ => {}
            }
        }
        if let Some((src, target)) = drag_move {
            if src != target {
                if let Some(row) = rows.get(src) {
                    *action = Some(Action::Move(row.id.clone(), target));
                }
            }
        }

        // --- `+` dropdown of the nine types ------------------------------------
        ui.add_space(6.0);
        let mut add_type: Option<String> = None;
        let combo = egui::ComboBox::from_id_salt("acon-add")
            .selected_text("\u{FF0B} Add constraint")
            .width(ui.available_width())
            .show_ui(ui, |ui| {
                for schema in schemas {
                    let type_id = schema.get("type").and_then(Value::as_str).unwrap_or("");
                    let label = schema
                        .get("longName")
                        .and_then(Value::as_str)
                        .unwrap_or(type_id);
                    let item = ui.selectable_label(false, label);
                    self.hits
                        .insert(format!("acon:add:{type_id}"), item.rect);
                    if item.clicked() {
                        add_type = Some(type_id.to_string());
                    }
                }
            });
        self.hits.insert("acon:add".into(), combo.response.rect);
        if let Some(type_id) = add_type {
            // Per-type selection context: pre-seed `elements` from the current
            // selection, filtered + capped by the schema's own declaration.
            let seed = seeded_elements(state, schemas, &type_id);
            *action = Some(Action::Add(type_id, seed));
        }
    }

    /// One constraint row. Returns the header row rect (drag-target
    /// hit-testing). Nothing expands here any more: activating a row swaps the
    /// whole panel to that constraint's form.
    fn render_row(
        &mut self,
        ui: &mut egui::Ui,
        row: &ConstraintRow,
        is_last: bool,
        action: &mut Option<Action>,
    ) -> egui::Rect {
        let mut enabled = row.enabled;
        let mut enabled_rect = egui::Rect::NOTHING;
        let mut enabled_clicked = false;
        let mut del_rect = egui::Rect::NOTHING;
        let mut del_clicked = false;
        let mut edit_rect = egui::Rect::NOTHING;
        let mut edit_clicked = false;

        let status_label = assembly_status::status_label(&row.status);
        let [r, g, b] = assembly_status::status_color_rgb(&row.status);
        let status_color = egui::Color32::from_rgb(r, g, b);

        let resp = tree::node(
            ui,
            TreeRow::branch(&[], is_last, row.open, &row.label).draggable(true),
            |ui| {
                // right-to-left: delete X, enable checkbox, then the status.
                let del = ui.add(
                    egui::Button::new(egui::RichText::new("\u{2715}").color(DELETE_RED))
                        .stroke(egui::Stroke::new(1.0, DELETE_RED))
                        .small(),
                );
                del_rect = del.rect;
                del_clicked = del.clicked();
                ui.add_space(4.0);

                // The discoverable way into the dialog — the history tree's own
                // affordance, same glyph, same `small()` sizing, so a third
                // control costs the label as little width as possible.
                let edit = ui
                    .add(egui::Button::new("\u{270E}").small())
                    .on_hover_text("Edit this constraint");
                edit_rect = edit.rect;
                edit_clicked = edit.clicked();
                ui.add_space(4.0);

                let cb = ui
                    .add(egui::Checkbox::new(&mut enabled, ""))
                    .on_hover_text("Enable/disable this constraint");
                enabled_rect = cb.rect;
                enabled_clicked = cb.clicked();

                ui.label(egui::RichText::new(status_label).color(status_color).small());
            },
        );
        self.hits.insert(format!("acon:row:{}", row.id), resp.label.rect);
        self.hits.insert(format!("acon:box:{}", row.id), resp.box_rect);
        self.hits.insert(format!("acon:del:{}", row.id), del_rect);
        self.hits.insert(format!("acon:edit:{}", row.id), edit_rect);
        self.hits
            .insert(format!("acon:enable:{}", row.id), enabled_rect);

        if del_clicked {
            *action = Some(Action::Delete(row.id.clone()));
        } else if enabled_clicked {
            *action = Some(Action::SetEnabled(row.id.clone(), enabled));
        } else if edit_clicked || resp.toggled || resp.label.clicked() {
            // The EDIT button, the `[+]` box and a plain label click all OPEN the
            // form — the same `SetOpen` call the expand-collapse used to make, so
            // the engine sees exactly what it saw before this panel grew a form
            // mode. (`!row.open` is `true` here: the tree only draws when no row
            // is open. Left as written so the two modes cannot disagree.)
            *action = Some(Action::SetOpen(row.id.clone(), !row.open));
        }
        if resp.label.drag_started() {
            self.drag_src = Some(index_of_hit(&self.hits, &row.id));
        }
        resp.row_rect
    }

    /// Draw ONE constraint's dialog filling the whole panel, through the SHARED
    /// [`form_view`] — the same function the feature dialogs use. This panel
    /// supplies the schema, the live params and the status; the form supplies
    /// every pixel of layout and hands back the intents the engine must act on.
    /// Editing is LIVE; the one bottom button closes the row.
    fn show_form(
        &mut self,
        ui: &mut egui::Ui,
        row: &ConstraintRow,
        schemas: &[Value],
        action: &mut Option<Action>,
        close: &mut Option<String>,
    ) {
        let Some(schema) = schemas.iter().find(|schema| {
            schema.get("type").and_then(Value::as_str) == Some(row.type_id.as_str())
        }) else {
            // A row whose type has no schema has no form to show — close it so
            // the panel can never be stranded on an empty mode.
            *close = Some(row.id.clone());
            return;
        };
        let fields = form_fields_from_schema(schema);
        let mut params = row.input_params.clone();

        // The row's status is the panel's headline readout for a constraint, and
        // the row is not on screen in form mode — so it rides the BANNER, in the
        // colour the ONE map gives it ([`brep_render::assembly_status`]), never a
        // second vocabulary. The feature form uses the same slot for a run error.
        let status_label = assembly_status::status_label(&row.status);
        let [r, g, b] = assembly_status::status_color_rgb(&row.status);
        let spec = FormViewSpec {
            // The value-free title — see `ConstraintRow::title`.
            title: &row.title,
            subtitle: None,
            fields: &fields,
            banner: Some((status_label, egui::Color32::from_rgb(r, g, b))),
            // A constraint produces no named outputs — nothing to trail.
            trailing: None,
            // Q12: the constraint list is drawn by the SAME `panels::tree`
            // renderer as the feature history (a root node with connector
            // guides), so the history panel's wording is literally accurate here
            // and is kept VERBATIM — one button, one label, everywhere.
            exit_label: "Return to tree",
            // The owner's call: assembly constraints have NO rollback, so an exit
            // carries no roll and this panel has no roll branch at all.
            rollback: false,
            // The panel shows ONE form at a time, but its hit map holds the
            // tree's `acon:*` keys too AND is scanned alongside the history
            // panel's by the headed verifier — so the form's keys stay
            // namespaced.
            hits_prefix: "acon:",
        };
        let out = form_view(ui, &spec, &mut params, Some(&mut self.hits));

        // WHICH constraint the form is showing, as a presence-only zero-size rect
        // beside the header's real rect (`acon:form:feature`) — the history
        // panel's `form:feature:{id}` convention.
        let anchor = self
            .hits
            .get("acon:form:feature")
            .map(|rect| rect.min)
            .unwrap_or(egui::Pos2::ZERO);
        self.hits.insert(
            format!("acon:form:constraint:{}", row.id),
            egui::Rect::from_min_size(anchor, egui::Vec2::ZERO),
        );

        // Precedence matches the pre-form code exactly: a reference activation is
        // staged first and a param commit overrides it in the ONE action slot.
        if let Some(activate) = out.ref_activate {
            *action = Some(Action::BeginRefSelect {
                id: row.id.clone(),
                path: activate.path,
                label: activate.label,
                filter: activate.filter,
                multiple: activate.multiple,
                seed: activate.seed,
            });
        }
        if out.changed {
            *action = Some(Action::UpdateParams(row.id.clone(), params));
        }
        // The exit rides its own slot so a focus-loss commit in the SAME frame
        // still lands (see `close` in `show`).
        if out.exit_clicked {
            *close = Some(row.id.clone());
        }
        // No constraint schema declares a `button` param (the catalogue is ids,
        // `reference_selection`s, numbers and booleans), so there is no schema
        // button to dispatch here; `roll_to_tip` is likewise always false because
        // `rollback: false` above says constraints do not roll.
        debug_assert!(
            out.button_clicked.is_none(),
            "no constraint schema declares a button param"
        );
        debug_assert!(!out.roll_to_tip, "constraints declare rollback: false");
    }

    /// The published widget hit-rects for the headed verifier.
    #[cfg(target_arch = "wasm32")]
    pub fn hits_json(&self) -> String {
        let map: serde_json::Map<String, Value> = self
            .hits
            .iter()
            .map(|(k, r)| {
                (
                    k.clone(),
                    serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]),
                )
            })
            .collect();
        Value::Object(map).to_string()
    }
}

/// The drag source index for a row id — recovered from the ordered `acon:row:`
/// hits laid out this frame. (The row order in `hits` is not indexed; walk the
/// rects by vertical position instead.)
fn index_of_hit(hits: &HashMap<String, egui::Rect>, id: &str) -> usize {
    let Some(own) = hits.get(&format!("acon:row:{id}")) else {
        return 0;
    };
    hits.iter()
        .filter(|(key, _)| key.starts_with("acon:row:"))
        .filter(|(_, rect)| rect.center().y < own.center().y)
        .count()
}

/// Fold the constraint state + statuses + overlay values into owned rows.
fn snapshot_rows(
    constraint_state: &Value,
    statuses: &Value,
    overlay: &Value,
    schemas: &[Value],
) -> Vec<ConstraintRow> {
    let status_of = |id: &str| -> String {
        statuses
            .as_array()
            .and_then(|rows| {
                rows.iter().find(|row| {
                    row.get("id").and_then(Value::as_str) == Some(id)
                })
            })
            .and_then(|row| row.get("status").and_then(Value::as_str))
            .unwrap_or("")
            .to_string()
    };
    let overlay_value = |id: &str| -> Option<f64> {
        overlay
            .as_array()
            .and_then(|rows| {
                rows.iter()
                    .find(|row| row.get("id").and_then(Value::as_str) == Some(id))
            })
            .and_then(|row| row.get("value").and_then(Value::as_f64))
    };
    let label_of = |type_id: &str| -> String {
        schemas
            .iter()
            .find(|schema| schema.get("type").and_then(Value::as_str) == Some(type_id))
            .and_then(|schema| schema.get("longName").and_then(Value::as_str))
            .map(|long| long.trim_start_matches(|c: char| !c.is_alphanumeric()).trim().to_string())
            .unwrap_or_else(|| type_id.to_string())
    };

    constraint_state
        .get("constraints")
        .and_then(Value::as_array)
        .map(|constraints| {
            constraints
                .iter()
                .map(|entry| {
                    let type_id = entry
                        .get("type")
                        .and_then(Value::as_str)
                        .unwrap_or("")
                        .to_string();
                    let params = entry
                        .get("inputParams")
                        .cloned()
                        .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
                    let id = params
                        .get("id")
                        .and_then(Value::as_str)
                        .unwrap_or("")
                        .to_string();
                    // Evaluated numeric suffix on distance/angle labels
                    // (expression-capable — the overlay carries the evaluated
                    // measure; fall back to the raw param for unresolved rows).
                    let suffix = match type_id.as_str() {
                        "distance" => overlay_value(&id)
                            .or_else(|| params.get("distance").and_then(Value::as_f64))
                            .map(|value| format!("  {value:.3}"))
                            .unwrap_or_default(),
                        "angle" => overlay_value(&id)
                            .or_else(|| params.get("angle").and_then(Value::as_f64))
                            .map(|value| format!("  {value:.1}\u{00B0}"))
                            .unwrap_or_default(),
                        _ => String::new(),
                    };
                    let title = format!("{} {id}", label_of(&type_id));
                    ConstraintRow {
                        label: format!("{title}{suffix}"),
                        title,
                        enabled: entry.get("enabled").and_then(Value::as_bool).unwrap_or(true),
                        open: entry.get("open").and_then(Value::as_bool).unwrap_or(false),
                        status: status_of(&id),
                        input_params: params,
                        id,
                        type_id,
                    }
                })
                .collect()
        })
        .unwrap_or_default()
}

/// The DOF readout: `dof/rank/redundant` + the over-/under-constrained wording
/// (spec §6 surfacing — the old app only surfaced duplicates).
fn dof_summary(dof: &Value) -> String {
    if dof.get("ok").and_then(Value::as_bool) == Some(false) {
        let error = dof.get("error").and_then(Value::as_str).unwrap_or("solve failed");
        return format!("Solve failed: {error}");
    }
    let mates = dof.get("mates").and_then(Value::as_u64).unwrap_or(0);
    let Some(free) = dof.get("dof").and_then(Value::as_u64) else {
        return if mates == 0 {
            "No constraints solved yet".to_string()
        } else {
            format!("{mates} mate(s)")
        };
    };
    let rank = dof.get("rank").and_then(Value::as_u64).unwrap_or(0);
    let redundant = dof.get("redundant").and_then(Value::as_u64).unwrap_or(0);
    let wording = match (free, redundant) {
        (0, 0) => "fully constrained".to_string(),
        (0, r) => format!("over-constrained ({r} redundant)"),
        (d, 0) => format!("under-constrained ({d} DOF free)"),
        (d, r) => format!("under-constrained ({d} DOF free, {r} redundant)"),
    };
    format!("DOF {free} \u{00B7} rank {rank} \u{00B7} redundant {redundant} \u{2014} {wording}")
}

/// Pre-seed a new constraint's `elements` from the CURRENT selection, filtered
/// by the type's schema `selectionFilter` and capped at its `maxSelections` —
/// the per-type selection context of the `+` dropdown AND the context bar's
/// constraint-from-selection offers (`context_bar::add_constraint_from_selection`).
pub(crate) fn seeded_elements(state: &mut EngineState, schemas: &[Value], type_id: &str) -> Value {
    let Some(schema) = schemas
        .iter()
        .find(|schema| schema.get("type").and_then(Value::as_str) == Some(type_id))
    else {
        return serde_json::json!({});
    };
    let elements_spec = schema
        .get("inputParamsSchema")
        .and_then(|params| params.get("elements"));
    let filter: Vec<String> = elements_spec
        .and_then(|spec| spec.get("selectionFilter"))
        .and_then(Value::as_array)
        .map(|kinds| {
            kinds
                .iter()
                .filter_map(|kind| kind.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();
    let cap = elements_spec
        .and_then(|spec| spec.get("maxSelections"))
        .and_then(Value::as_u64)
        .unwrap_or(2) as usize;

    let selection: Value = serde_json::from_str(&state.selection_json()).unwrap_or(Value::Null);
    let names = |key: &str| -> Vec<String> {
        selection[key]
            .as_array()
            .map(|items| {
                items
                    .iter()
                    .filter_map(|item| item.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default()
    };
    let mut seeded: Vec<String> = Vec::new();
    let mut push = |src: Vec<String>| {
        for name in src {
            if seeded.len() < cap && !seeded.contains(&name) {
                seeded.push(name);
            }
        }
    };
    for kind in &filter {
        match kind.as_str() {
            // A COMPONENT ref is the owning component of any selected member
            // solid; FACE/EDGE map straight from the named selection.
            "COMPONENT" => {
                let owners: Vec<String> = names("solids")
                    .into_iter()
                    .filter_map(|solid| {
                        state
                            .assembly_components()
                            .iter()
                            .find(|record| record.solids.contains(&solid))
                            .map(|record| record.id.clone())
                    })
                    .collect();
                push(owners);
            }
            "FACE" => push(names("faces")),
            "EDGE" => push(names("edges")),
            // VERTEX selections are position-keyed; the ref-select picker
            // builds their `@`-refs — nothing to pre-seed here.
            _ => {}
        }
    }
    serde_json::json!({ "elements": seeded })
}

/// Mirror an engine JSON string to `window.<name>` (wasm/verification only).
#[cfg(target_arch = "wasm32")]
fn publish(name: &str, json: &str) {
    if let Some(win) = web_sys::window() {
        let _ = js_sys::Reflect::set(
            &win,
            &wasm_bindgen::JsValue::from_str(name),
            &wasm_bindgen::JsValue::from_str(json),
        );
    }
}

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

    fn part_document() -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": "Part",
                    "sizeX": 2.0, "sizeY": 3.0, "sizeZ": 4.0,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    fn two_instance_state() -> EngineState {
        brep_render::brep_kernel::clear_history_cache();
        let mut state = EngineState::new();
        state
            .insert_component(ComponentInsert::New {
                name: "bracket",
                source_key: "bracket",
                source_signature: "sig-1",
                document_json: &part_document(),
            })
            .unwrap();
        state
            .insert_component(ComponentInsert::Existing { part_name: "bracket" })
            .unwrap();
        state
    }

    fn run_frame(
        ctx: &egui::Context,
        panel: &mut AssemblyConstraintsPanel,
        state: &mut EngineState,
        model_store: &dyn ModelStore,
        updates: &mut UpdateComponents,
        events: Vec<egui::Event>,
    ) {
        let raw = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::pos2(0.0, 0.0),
                egui::vec2(800.0, 600.0),
            )),
            events,
            ..Default::default()
        };
        let _ = ctx.run_ui(raw, |ui| {
            panel.show(ui, state, model_store, updates)
        });
    }

    fn click_at(
        ctx: &egui::Context,
        panel: &mut AssemblyConstraintsPanel,
        state: &mut EngineState,
        model_store: &dyn ModelStore,
        updates: &mut UpdateComponents,
        pos: egui::Pos2,
    ) {
        run_frame(
            ctx,
            panel,
            state,
            model_store,
            updates,
            vec![
                egui::Event::PointerMoved(pos),
                egui::Event::PointerButton {
                    pos,
                    button: egui::PointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        run_frame(
            ctx,
            panel,
            state,
            model_store,
            updates,
            vec![egui::Event::PointerButton {
                pos,
                button: egui::PointerButton::Primary,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
        );
    }

    /// Add a `fixed` constraint through the `+` dropdown, exactly as a user
    /// does. The kernel mints the id AND marks the new constraint `open`
    /// (`assembly/exports.rs` — `open: true` on add), so the panel lands in FORM
    /// mode; returns the panel to the tree.
    fn add_fixed_through_the_panel(
        ctx: &egui::Context,
        panel: &mut AssemblyConstraintsPanel,
        state: &mut EngineState,
        store: &dyn ModelStore,
        updates: &mut UpdateComponents,
    ) {
        run_frame(ctx, panel, state, store, updates, vec![]);
        let add = *panel.hits.get("acon:add").expect("add combo rect");
        click_at(ctx, panel, state, store, updates, add.center());
        run_frame(ctx, panel, state, store, updates, vec![]);
        let item = *panel
            .hits
            .get("acon:add:fixed")
            .expect("fixed item rect while open");
        click_at(ctx, panel, state, store, updates, item.center());
        // The add opened the new constraint's FORM — leave it.
        run_frame(ctx, panel, state, store, updates, vec![]);
        let back = *panel
            .hits
            .get("acon:form:return")
            .expect("the add landed in form mode");
        click_at(ctx, panel, state, store, updates, back.center());
        run_frame(ctx, panel, state, store, updates, vec![]);
    }

    /// ROW LIFECYCLE through real egui clicks: `+` dropdown → pick a type → the
    /// kernel mints the id; the enable checkbox toggles; delete removes.
    #[test]
    fn add_toggle_delete_through_the_panel() {
        let ctx = egui::Context::default();
        let mut state = two_instance_state();
        let mut panel = AssemblyConstraintsPanel::new();
        let store = crate::store::MemModelStore::new();
        let mut updates = UpdateComponents::new();

        add_fixed_through_the_panel(&ctx, &mut panel, &mut state, &store, &mut updates);

        // The kernel minted FIXD1 and the row is live.
        let statuses = state.assembly_statuses_value();
        assert_eq!(statuses[0]["id"], "FIXD1", "id minted through the panel add");

        // Toggle enable off via the row checkbox.
        let enable = *panel.hits.get("acon:enable:FIXD1").expect("enable rect");
        click_at(&ctx, &mut panel, &mut state, &store, &mut updates, enable.center());
        let statuses = state.assembly_statuses_value();
        assert_eq!(statuses[0]["enabled"], false);
        assert_eq!(statuses[0]["status"], "disabled");

        // Delete the row.
        run_frame(&ctx, &mut panel, &mut state, &store, &mut updates, vec![]);
        let del = *panel.hits.get("acon:del:FIXD1").expect("delete rect");
        click_at(&ctx, &mut panel, &mut state, &store, &mut updates, del.center());
        let statuses = state.assembly_statuses_value();
        assert_eq!(statuses.as_array().map(Vec::len), Some(0), "row deleted");
    }

    /// THE MODE SWITCH, both ways. A constraint whose `open` flag is set takes
    /// over the WHOLE panel with the shared form (the tree, the solver header and
    /// the add dropdown are gone); the ONE bottom button clears the flag and the
    /// tree comes back. Both directions are asserted on the KERNEL's `open`
    /// flag, not on panel state — that is where the mode lives.
    #[test]
    fn opening_a_constraint_takes_over_the_panel_and_returning_restores_the_tree() {
        let ctx = egui::Context::default();
        let mut state = two_instance_state();
        let mut panel = AssemblyConstraintsPanel::new();
        let store = crate::store::MemModelStore::new();
        let mut updates = UpdateComponents::new();
        add_fixed_through_the_panel(&ctx, &mut panel, &mut state, &store, &mut updates);

        // Tree mode: rows and chrome, no form.
        assert!(panel.hits.contains_key("acon:row:FIXD1"), "the tree row");
        assert!(panel.hits.contains_key("acon:solve"), "the solver header");
        assert!(panel.hits.contains_key("acon:add"), "the add dropdown");
        assert!(!panel.hits.contains_key("acon:form:return"), "no form yet");

        // The row's EDIT button opens the form.
        let edit = *panel.hits.get("acon:edit:FIXD1").expect("edit rect");
        click_at(&ctx, &mut panel, &mut state, &store, &mut updates, edit.center());
        run_frame(&ctx, &mut panel, &mut state, &store, &mut updates, vec![]);
        assert_eq!(
            state.assembly_state_value()["constraints"][0]["open"],
            serde_json::json!(true),
            "the edit button set the kernel's open flag"
        );
        assert!(
            panel.hits.contains_key("acon:form:constraint:FIXD1"),
            "the form says WHICH constraint it is showing: {:?}",
            panel.hits.keys().collect::<Vec<_>>()
        );
        for gone in ["acon:row:FIXD1", "acon:solve", "acon:add", "acon:del:FIXD1"] {
            assert!(!panel.hits.contains_key(gone), "{gone} is gone in form mode");
        }
        for present in ["acon:form:feature", "acon:form:return", "acon:field:elements"] {
            assert!(
                panel.hits.contains_key(present),
                "{present}: {:?}",
                panel.hits.keys().collect::<Vec<_>>()
            );
        }

        // …and the ONE bottom button returns to the tree.
        let back = *panel.hits.get("acon:form:return").expect("return rect");
        click_at(&ctx, &mut panel, &mut state, &store, &mut updates, back.center());
        run_frame(&ctx, &mut panel, &mut state, &store, &mut updates, vec![]);
        assert_eq!(
            state.assembly_state_value()["constraints"][0]["open"],
            serde_json::json!(false),
            "the exit cleared the kernel's open flag"
        );
        assert!(panel.hits.contains_key("acon:row:FIXD1"), "the tree is back");
        assert!(!panel.hits.contains_key("acon:form:return"), "the form is gone");
    }

    /// A plain click on the ROW LABEL opens the form too — the affordance the
    /// expand-collapse used to be, unchanged in what it asks the engine for.
    #[test]
    fn a_row_label_click_opens_the_form() {
        let ctx = egui::Context::default();
        let mut state = two_instance_state();
        let mut panel = AssemblyConstraintsPanel::new();
        let store = crate::store::MemModelStore::new();
        let mut updates = UpdateComponents::new();
        add_fixed_through_the_panel(&ctx, &mut panel, &mut state, &store, &mut updates);

        let row = *panel.hits.get("acon:row:FIXD1").expect("row label rect");
        click_at(&ctx, &mut panel, &mut state, &store, &mut updates, row.center());
        run_frame(&ctx, &mut panel, &mut state, &store, &mut updates, vec![]);
        assert!(panel.hits.contains_key("acon:form:constraint:FIXD1"));
    }

    /// A press that egui reclassified as a DRAG but ended back on its OWN row is
    /// the label click egui threw away (it lingered past 0.8 s or wobbled past
    /// 6 pt) — the history tree routes that to "open the row", and so does this
    /// one. Before the form mode it fell into the reorder arm and did nothing.
    #[test]
    fn a_drifted_press_on_a_row_opens_the_form() {
        let ctx = egui::Context::default();
        let mut state = two_instance_state();
        let mut panel = AssemblyConstraintsPanel::new();
        let store = crate::store::MemModelStore::new();
        let mut updates = UpdateComponents::new();
        add_fixed_through_the_panel(&ctx, &mut panel, &mut state, &store, &mut updates);
        assert_eq!(
            state.assembly_state_value()["constraints"][0]["open"],
            serde_json::json!(false),
            "the tree is showing"
        );

        let row = *panel.hits.get("acon:row:FIXD1").expect("row rect");
        let at = row.center();
        let drifted = at + egui::vec2(0.0, 12.0);
        run_frame(
            &ctx,
            &mut panel,
            &mut state,
            &store,
            &mut updates,
            vec![
                egui::Event::PointerMoved(at),
                egui::Event::PointerButton {
                    pos: at,
                    button: egui::PointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        // Past egui's `max_click_dist` — the press is now a DRAG, so the label
        // will never report `clicked()`.
        run_frame(
            &ctx,
            &mut panel,
            &mut state,
            &store,
            &mut updates,
            vec![egui::Event::PointerMoved(drifted)],
        );
        run_frame(
            &ctx,
            &mut panel,
            &mut state,
            &store,
            &mut updates,
            vec![egui::Event::PointerButton {
                pos: drifted,
                button: egui::PointerButton::Primary,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
        );
        run_frame(&ctx, &mut panel, &mut state, &store, &mut updates, vec![]);
        assert_eq!(
            state.assembly_state_value()["constraints"][0]["open"],
            serde_json::json!(true),
            "the drifted press opened the form rather than vanishing"
        );
        assert!(panel.hits.contains_key("acon:form:constraint:FIXD1"));
    }

    /// LIVE COMMIT through the shared form's reference widget: removing an
    /// element chip writes straight through `assembly_update_constraint` — no
    /// Cancel, no buffer, no confirm. The chips are visible WITHOUT expanding
    /// anything, which is why `reference_node` is gone.
    #[test]
    fn removing_an_element_chip_commits_live() {
        let ctx = egui::Context::default();
        let mut state = two_instance_state();
        state
            .assembly_add_constraint(
                "distance",
                &serde_json::json!({ "elements": ["ACOMP1", "ACOMP2"] }).to_string(),
            )
            .unwrap();
        let mut panel = AssemblyConstraintsPanel::new();
        let store = crate::store::MemModelStore::new();
        let mut updates = UpdateComponents::new();

        // The add left the constraint open, so the panel is already in the form.
        run_frame(&ctx, &mut panel, &mut state, &store, &mut updates, vec![]);
        let params = &state.assembly_state_value()["constraints"][0]["inputParams"];
        assert_eq!(
            params["elements"],
            serde_json::json!(["ACOMP1", "ACOMP2"]),
            "seeded"
        );

        let x = *panel.hits.get("acon:field:elements#x0").unwrap_or_else(|| {
            panic!(
                "chip remove rect: {:?}",
                panel.hits.keys().collect::<Vec<_>>()
            )
        });
        click_at(&ctx, &mut panel, &mut state, &store, &mut updates, x.center());

        let params = &state.assembly_state_value()["constraints"][0]["inputParams"];
        assert_eq!(
            params["elements"],
            serde_json::json!(["ACOMP2"]),
            "the chip removal committed straight to the kernel"
        );
    }

    /// The form's TITLE must not carry the evaluated measure: it is the scope key
    /// for the fields' egui widget ids, so a title that changes as the solver
    /// re-evaluates would re-key a focused `Scalar` mid-edit and eat the
    /// keystrokes. The ROW label keeps the value.
    #[test]
    fn the_form_title_is_free_of_the_evaluated_value() {
        let mut state = two_instance_state();
        state
            .assembly_add_constraint(
                "distance",
                &serde_json::json!({ "elements": [], "distance": 12.5 }).to_string(),
            )
            .unwrap();
        let statuses = state.assembly_statuses_value();
        let overlay = state.assembly_overlay_value();
        let constraint_state = state.assembly_state_value();
        let catalogue = brep_render::brep_kernel::constraint_schema_catalogue();
        let schemas: Vec<Value> = catalogue.as_array().cloned().unwrap();
        let rows = snapshot_rows(&constraint_state, &statuses, &overlay, &schemas);

        let row = &rows[0];
        assert_eq!(row.title, "Distance DIST1", "the stable form title");
        assert!(
            row.label.starts_with(&row.title) && row.label.len() > row.title.len(),
            "the ROW label still appends the measure: {}",
            row.label
        );
    }

    /// BADGE + RUN through the header button: the count reflects the checker,
    /// a click refreshes every outdated entry (both instances rebuild with the
    /// store's edit), and the recheck lands back on 0.
    #[test]
    fn update_components_button_counts_and_runs() {
        use crate::panels::assembly_edit::document_signature;
        use crate::store::MemModelStore;

        brep_render::brep_kernel::clear_history_cache();
        let ctx = egui::Context::default();
        let store = MemModelStore::new();
        let content = part_document();
        store.put("bracket", &content);
        let mut state = EngineState::new();
        state
            .insert_component(ComponentInsert::New {
                name: "bracket",
                source_key: "bracket",
                source_signature: &document_signature(&content),
                document_json: &content,
            })
            .unwrap();
        state
            .insert_component(ComponentInsert::Existing { part_name: "bracket" })
            .unwrap();
        let mut panel = AssemblyConstraintsPanel::new();
        let mut updates = UpdateComponents::new();

        // Up-to-date: count 0 (the button renders disabled — a click on its
        // rect must be a no-op).
        updates.ensure_current(&mut state, &store, 0);
        run_frame(&ctx, &mut panel, &mut state, &store, &mut updates, vec![]);
        let update = *panel.hits.get("acon:update").expect("update rect");
        click_at(&ctx, &mut panel, &mut state, &store, &mut updates, update.center());
        let doc: Value = serde_json::from_str(&state.history_request_json()).unwrap();
        assert_eq!(
            doc["partsLibrary"]["bracket"]["sourceSignature"],
            document_signature(&content),
            "disabled button never refreshes"
        );

        // The part's source changes (a save elsewhere): the checker counts it
        // and a click runs the batch — both instances rebuild with the edit.
        let mut edited: Value = serde_json::from_str(&content).unwrap();
        edited["features"][0]["inputParams"]["sizeX"] = serde_json::json!(7.0);
        let edited = edited.to_string();
        store.put("bracket", &edited);
        updates.ensure_current(&mut state, &store, 1);
        assert_eq!(updates.outdated_count(), 1, "the changed source is counted");
        run_frame(&ctx, &mut panel, &mut state, &store, &mut updates, vec![]);
        let update = *panel.hits.get("acon:update").expect("update rect");
        click_at(&ctx, &mut panel, &mut state, &store, &mut updates, update.center());

        for solid in ["ACOMP1:Part", "ACOMP2:Part"] {
            let bbox = &state.scene.solid(solid).expect(solid).bbox;
            assert!(
                (bbox.max[0] - bbox.min[0] - 7.0).abs() < 1e-6,
                "{solid} rebuilt with the refreshed part"
            );
        }
        updates.ensure_current(&mut state, &store, 1);
        assert_eq!(updates.outdated_count(), 0, "badge clears after the run");
    }

    /// The `+` dropdown pre-seeds `elements` from the current selection,
    /// respecting the type's schema filter (a selected member solid seeds a
    /// COMPONENT ref for `fixed`; a face-only filter takes face names).
    #[test]
    fn add_seeds_elements_from_selection_context() {
        let mut state = two_instance_state();
        let catalogue = brep_render::brep_kernel::constraint_schema_catalogue();
        let schemas: Vec<Value> = catalogue.as_array().cloned().unwrap();

        // Select ACOMP2's member solid → `fixed` (COMPONENT filter, 1 element)
        // seeds the OWNING COMPONENT id.
        state.select_component("ACOMP2");
        let seed = seeded_elements(&mut state, &schemas, "fixed");
        assert_eq!(seed["elements"], serde_json::json!(["ACOMP2"]));

        // A FACE selection seeds a face-accepting type (tangent: FACE only).
        state.select_by_name("face", "ACOMP1:Part_PZ");
        let seed = seeded_elements(&mut state, &schemas, "tangent");
        assert_eq!(seed["elements"], serde_json::json!(["ACOMP1:Part_PZ"]));
        // …and never over-fills past maxSelections.
        let seed = seeded_elements(&mut state, &schemas, "distance");
        assert!(seed["elements"].as_array().unwrap().len() <= 2);
    }

    /// Status label + color per row come from the ONE map (`assembly_status`).
    #[test]
    fn row_status_uses_the_one_map() {
        let mut state = two_instance_state();
        state
            .assembly_add_constraint(
                "fixed",
                &serde_json::json!({ "elements": ["ACOMP2"] }).to_string(),
            )
            .unwrap();
        let statuses = state.assembly_statuses_value();
        let overlay = state.assembly_overlay_value();
        let constraint_state = state.assembly_state_value();
        let catalogue = brep_render::brep_kernel::constraint_schema_catalogue();
        let schemas: Vec<Value> = catalogue.as_array().cloned().unwrap();
        let rows = snapshot_rows(&constraint_state, &statuses, &overlay, &schemas);
        assert_eq!(rows.len(), 1);
        let status = &rows[0].status;
        // Whatever the solve produced, the label + color resolve through the
        // shared map (no per-panel vocabulary).
        assert!(!assembly_status::status_label(status).is_empty());
        let _ = assembly_status::status_color_rgb(status);
        assert!(rows[0].label.contains("FIXD1"), "label carries the id: {}", rows[0].label);
    }

    /// Reorder routes through `assembly_move_constraint` (kernel order flips).
    #[test]
    fn reorder_moves_the_constraint() {
        let mut state = two_instance_state();
        let first = state
            .assembly_add_constraint(
                "fixed",
                &serde_json::json!({ "elements": ["ACOMP2"] }).to_string(),
            )
            .unwrap();
        let second = state.assembly_add_constraint("parallel", "{}").unwrap();
        state.assembly_move_constraint(&second, 0).unwrap();
        let statuses = state.assembly_statuses_value();
        assert_eq!(statuses[0]["id"], second.as_str());
        assert_eq!(statuses[1]["id"], first.as_str());
    }

    /// The DOF readout wording: under-/over-/fully constrained + failure.
    #[test]
    fn dof_summary_wording() {
        let under = serde_json::json!({ "ok": true, "mates": 1, "dof": 3, "rank": 3, "redundant": 0 });
        assert!(dof_summary(&under).contains("under-constrained (3 DOF free)"));
        let full = serde_json::json!({ "ok": true, "mates": 6, "dof": 0, "rank": 6, "redundant": 0 });
        assert!(dof_summary(&full).contains("fully constrained"));
        let over = serde_json::json!({ "ok": true, "mates": 7, "dof": 0, "rank": 6, "redundant": 1 });
        assert!(dof_summary(&over).contains("over-constrained (1 redundant)"));
        let failed = serde_json::json!({ "ok": false, "error": "conflict" });
        assert!(dof_summary(&failed).contains("Solve failed: conflict"));
        let empty = serde_json::json!({ "ok": true, "mates": 0 });
        assert!(dof_summary(&empty).contains("No constraints"));
    }
}