BREP_app 0.4.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
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
//! `BrepApp` — the THIN shell of the engine-native UI.
//!
//! One eframe [`App`] that hosts the EXISTING `brep-render` engine and lays out
//! the panels. The heavy lifting lives in focused modules; this file only owns
//! the shell:
//!
//! * [`Documents`] (`crate::document`) holds the OPEN MODELS — one
//!   [`EngineState`] per document plus its identity, exactly one active. Panels
//!   borrow the active engine through `self.docs.engine_mut()`, which borrows
//!   only that FIELD and so still composes with the disjoint panel borrows
//!   beside it. [`EngineState`] (`brep-render`) is still the single
//!   windowing-agnostic BRAIN per document (scene / camera / controls / settings
//!   / widgets + pointer/wheel/viewcube/pick); we do NOT fork it.
//! * [`crate::viewport::Viewport`] draws + drives the central 3D viewport (the
//!   offscreen texture, the `egui_wgpu` blit callback, input routing).
//! * [`crate::panels`] — one module per left-panel section, each a small state
//!   struct + a `show(&mut self, ui, state, …)` method. Adding a panel = add
//!   `panels/<name>.rs`, one field here, one `self.<name>.show(…)` call in
//!   [`eframe::App::ui`] below (see `README.md` → "Adding a panel").
//!
//! Native (`run_native`) and wasm (`WebRunner`) run this SAME code.

use crate::document::{Documents, EngineFactory};
use crate::panels::assembly_constraints::AssemblyConstraintsPanel;
use crate::panels::bug_report::BugReportPanel;
use crate::panels::wire_harness::WireHarnessPanel;
use crate::panels::component_actions::ComponentActionRequest;
use crate::panels::context_bar::ContextBarPanel;
use crate::panels::mode_bar::ModeBar;
use crate::panels::expressions::ExpressionsPanel;
use crate::panels::file::{FileAction, FileDialog};
use crate::panels::history::HistoryPanel;
use crate::panels::info_windows::InfoWindows;
use crate::panels::scene::ScenePanel;
use crate::panels::selection::SelectionPanel;
use crate::panels::sketch::SketchPanel;
use crate::panels::part_properties::PartPropertiesPanel;
use crate::panels::settings::SettingsPanel;
use crate::panels::toasts::Toasts;
use crate::panels::toolbar::ToolbarPanel;
use crate::panels::workbench_toolbar::WorkbenchToolbarPanel;
use crate::panels::update_components::UpdateComponents;
use crate::panels::bom::BomPanel;
use crate::panels::dock::{DockContext, DockState, PaneKind};
use crate::panels::document_tabs;
use crate::store::{default_model_store, ModelStore, SESSION_KEY, SETTINGS_KEY};
use crate::viewport::Viewport;
use brep_render::engine_state::EngineState;
use brep_render::style::ThemeMode;
use eframe::egui;

pub struct BrepApp {
    /// Every OPEN MODEL and which one is active. Each document owns a full
    /// `EngineState` (the shared viewer brain `desktop.rs` / the wasm shell
    /// wrap) plus its file identity; panels borrow the active one.
    pub(crate) docs: Documents,
    /// The central 3D viewport: engine render core + offscreen texture + blit +
    /// input routing.
    pub(crate) viewport: Viewport,
    /// The single persistence seam for settings, layout, and model documents
    /// (native filesystem / wasm IndexedDB + download/upload).
    model_store: Box<dyn ModelStore>,

    // --- one small state value per panel --------------------------------------
    /// Top toolbar: undo/redo, wireframe toggle, zoom-to-fit + standard views,
    /// and the File-actions seam (owned by the concurrent file panel).
    toolbar: ToolbarPanel,
    /// New / Open / Save / Save As of the model document (the `.BREP.json`
    /// recipe) — a reusable modal file dialog opened from the toolbar.
    file: FileDialog,
    stl_import: Option<crate::panels::stl_import::StlImportPreview>,
    /// The "Submit Bug" flow: on the toolbar bug button it screenshots the app
    /// (UI + 3D model) BEFORE its own dialog opens, then collects a description
    /// (+ optional email) and POSTs the model + screenshot to the public reports
    /// endpoint. Native + wasm, one path.
    bug_report: BugReportPanel,
    /// The Info window: the licences and this session's diagnostics, toggled
    /// from the toolbar's info button.
    info: crate::panels::info::InfoPanel,
    /// What this session is running on — captured ONCE, from the adapter eframe
    /// actually gave us (never re-probed), and read by BOTH the Info window and
    /// the problem report so the two cannot disagree. See
    /// [`crate::diagnostics`].
    diagnostics: crate::diagnostics::Diagnostics,
    /// Workbench actions toolbar: the second top strip under the primary
    /// toolbar — one button per feature the active workbench offers, plus the
    /// constraint types where the Constraints panel is shown. Gated by the
    /// `showWorkbenchToolbar` setting and hidden in the special modes. A click
    /// flows out as the type to add; the shell adds it through the SAME paths
    /// the palette / context bar use.
    workbench_toolbar: WorkbenchToolbarPanel,
    /// Display-settings + per-solid color panel (Phase 1): a FLOATING window
    /// (movable + resizable, toggled from the toolbar gear button), no longer a
    /// left-panel section.
    settings: SettingsPanel,
    /// The active document's OWN BOM attributes (Part Number, Material, Mass,
    /// …) as a floating window, toggled from the toolbar's Properties button.
    /// Document-level, not selection-level: entity inspection is the context
    /// bar's `info_windows`.
    part_properties: PartPropertiesPanel,
    /// History feature-tree + schema-driven feature dialog panel (Phase 2).
    /// NOTE: the editable history is NOT owned here — it lives in the engine core
    /// (`EngineState.history`), the single source of truth; this panel only reads
    /// it back to draw and calls the engine's `history_*` methods to mutate.
    history: HistoryPanel,
    /// Scene tree ("Scene Manager"): the display scene as a file-tree — per-solid
    /// visibility + Faces/Edges/Vertices with two-way selection sync. Reads the
    /// engine scene/emphasis; owns only transient expand + hit state.
    scene: ScenePanel,
    /// Assembly Structure tree (claimed by the Assembly workbench): a VIEW over
    /// the scene's component records — per-instance fixed/visibility/status
    /// adornments, actions routed to the owning ACOMP feature.
    /// The BOM panel (claimed by the Assembly workbench): the parts list on
    /// the shared column-tree widget, with the editable part/occurrence
    /// attribute columns the Settings "Assemblies" section configures.
    bom: BomPanel,
    /// Assembly Constraints panel (claimed by the Assembly workbench): the
    /// schema-driven constraint collection widget + Solve/auto-solve/DOF header.
    assembly_constraints: AssemblyConstraintsPanel,
    /// The wire-harness connection list (a Wire harness workbench pane): add /
    /// edit / remove wires, read their routed length + status, hover to
    /// highlight. Document data lives in the engine; this holds the widget's
    /// transient state.
    wire_harness: WireHarnessPanel,
    /// The PMI view tree + annotation forms (the PMI workbench's pane).
    pmi: crate::panels::pmi::PmiPanel,
    /// Update-components checker (build-spec §8.6): compares each parts-library
    /// entry's `sourceSignature` against the model store's current content.
    /// Kept current once per frame (cheap generation key: applied run + store
    /// save); the constraints header reads the count + runs the batch refresh,
    /// the structure tree reads per-part badges.
    update_components: UpdateComponents,
    /// Expressions / parameters panel: the variable sheet (engine-owned history
    /// `expressions`) feature params reference. Owns only its editor buffer.
    expressions: ExpressionsPanel,
    /// Info windows: MULTIPLE pinned per-entity inspector windows opened from the
    /// selection-driven context bar's Info action. Each floating (movable +
    /// resizable) window is PINNED to one object name at open time — a Metadata
    /// (editable attribute) tab + a read-only Info (measurements + provenance) tab —
    /// and keeps showing that entity regardless of later selection changes. Replaces
    /// the old single Properties window.
    info_windows: InfoWindows,
    /// Interference results window (assemblies build-spec §9): opened by the
    /// Assembly workbench's `∩` toolbar button, which runs the engine's
    /// pairwise-intersect check; a floating window like the Info windows with a
    /// row per interfering pair (click = select both components), a green
    /// all-clear pass line, and a Re-run button.
    interference: crate::panels::interference::InterferenceWindow,
    /// Auto Constraints window (Assembly workbench): opened by the `⚿` toolbar
    /// button, it lists the constraint types the kernel's inference lane can
    /// read out of the components' current placement, with what a scan found
    /// for each, and creates the whole accepted set as one undo step.
    auto_constraints: crate::panels::auto_constraints::AutoConstraintsWindow,
    /// step.parts online model library browser (Assembly workbench): a ctx-level
    /// window (opened by the library toolbar button) that searches the public
    /// step.parts v1 API, shows results with thumbnails, and imports a chosen
    /// STEP model as a new part document + adds it to the assembly as an ACOMP.
    step_parts: crate::panels::step_parts::StepPartsPanel,
    /// Selection panel: the pickable-kinds filter (which entity kinds a viewport
    /// click may select — honored by the engine's `select_top_at`). The filter +
    /// selection live in `EngineState`; this panel only reads/writes them.
    selection: SelectionPanel,
    /// Context action toolbar: the selection-driven action bar (Clear / Hide /
    /// Edit-owning-feature + the feature-from-selection actions whose primary
    /// reference accepts the selected kind). Shown only while something is
    /// selected; drives the engine directly and returns a feature id for the shell
    /// to expand in the history tree.
    context_bar: ContextBarPanel,
    /// Sketch (S0): a seeded, read-only sketch preview — pushes a solved rectangle
    /// + circle to the `set_overlay` channel colored by solver mobility, and shows
    /// the DOF status readout. The engine-native sketcher's foundation surface.
    sketch: SketchPanel,
    /// Special-mode EXIT controls (Finish/Cancel), always pinned to the top-right
    /// corner — reference-selection, sketch mode, and any future special mode.
    mode_bar: ModeBar,
    /// Transient toast overlay: drains the engine's queued notices each frame
    /// (e.g. a sketch solve that failed after an edit) and shows each briefly.
    pub(crate) toasts: Toasts,
    /// Dockable / tabbed side-panel layout (egui_tiles): the shared, persisted
    /// tree that hosts every side-panel section AND the 3D viewport as tiles the
    /// user can split, tab, resize, and drag-rearrange. Owns the layout; borrows
    /// each panel + the engine per frame through [`DockContext`]. Drawn in normal
    /// modeling mode; sketch / ref-select mode bypasses it (viewport drawn direct).
    dock: DockState,

    /// Whether the ONE-SHOT first-model framing has fired. The seed run is async
    /// under a background runner (native thread / wasm worker), so the boot
    /// `zoom_to_fit` can run before the first solids exist → an unframed first
    /// model. Once the seed run has landed (`has_solids() && !run_pending()`), the
    /// `ui` loop frames it once and sets this. Under the synchronous Inline runner
    /// (tests) the scene is already populated, so this fires on the very first frame.
    first_run_framed: bool,

    /// A model fetch kicked off at boot from a `?loadModel=<url>` query param
    /// (wasm only — the cadDev admin "Launch model in CAD app" opens the app with
    /// a report's model URL). When the fetch lands it REPLACES the seed model.
    /// `None` on native and once applied.
    pending_boot_load: Option<std::sync::mpsc::Receiver<Result<String, String>>>,

    /// The document handle the shared panels were last reset for. Compared to
    /// `docs.active_id()` at the top of every frame: ONE check catches a switch
    /// from any source (a tab click, a close, New, Open, Edit Part) instead of a
    /// hook per call site, and it runs BEFORE any panel draws this frame.
    active_document: u64,

    /// The DOCUMENT TAB STRIP's per-tab hit-rects from the last dock frame,
    /// published for the headed verifier. The strip is drawn inside the dock's
    /// viewport pane, so its rects have to ride back out through the outcome.
    document_tab_hits: Vec<(String, egui::Rect)>,

    /// The last session blob written through the store — the change detector for
    /// the open-document list, so persisting cannot be forgotten at a mutation
    /// site (there is no "session dirty" flag to set).
    session_saved: String,

    /// The debounced autosave of every dirty document (`crate::recovery`), and
    /// the boot-time **Recover unsaved work?** prompt its blob feeds. The
    /// autosave is held while the prompt is open: the clean seed tab would
    /// otherwise remove the very blob being offered.
    autosave: crate::recovery::Autosave,
    recovery: crate::recovery::RecoveryPanel,

    /// The UI zoom scale CURRENTLY applied to the egui context. Tracks
    /// `settings.ui_scale` but is only synced to it while the pointer is up, so
    /// dragging the Settings "UI scale" slider doesn't rescale the whole UI under
    /// the cursor mid-drag — the settled value is committed on release. See the
    /// zoom-apply block in `ui`.
    applied_ui_scale: f32,
    /// The automation channel (hosts submit commands; the frame drains them at
    /// three fixed points — see `automation::queue`).
    #[cfg(feature = "automation")]
    pub(crate) automation: std::sync::Arc<crate::automation::queue::AutomationQueue>,
}

impl BrepApp {
    /// The automation queue a host submits commands to.
    #[cfg(feature = "automation")]
    pub fn automation(&self) -> &std::sync::Arc<crate::automation::queue::AutomationQueue> {
        &self.automation
    }

    /// The 3D viewport rect of the last frame, in egui points.
    pub fn view_rect(&self) -> Option<egui::Rect> {
        self.viewport.last_rect()
    }

    /// The active document's engine.
    pub fn docs_engine(&self) -> &EngineState {
        self.docs.engine()
    }

    pub fn new(cc: &eframe::CreationContext<'_>) -> Result<Self, String> {
        Self::new_with(cc, crate::automation::AppOptions::default())
    }

    /// Build the app with host-supplied options: an isolated store (a host
    /// MUST pass one, spec §8) and whether to start on the seed model.
    pub fn new_with(cc: &eframe::CreationContext<'_>, opts: crate::automation::AppOptions) -> Result<Self, String> {
        let crate::automation::AppOptions { store: opt_store, seed } = opts;
        let render_state = cc
            .wgpu_render_state
            .as_ref()
            .ok_or_else(|| "eframe was not created with a wgpu render state".to_string())?;

        // The viewport owns the render core + blit pipeline, built from eframe's
        // SHARED device/queue/format.
        let viewport = Viewport::new(render_state);

        // The session's diagnostics, taken from that same render state: the
        // adapter about to draw every frame is the one a report must name. The
        // WebGPU-vs-WebGL2 decision has already been made by the time we get
        // here (eframe drops `BROWSER_WEBGPU` from the backend set when the
        // browser offers no WebGPU adapter), so this READS the outcome — asking
        // again later would be a second question with its own answer.
        let diagnostics = crate::diagnostics::Diagnostics::from_render_state(render_state);

        // --- storage seam: load the persisted settings ------------------------
        let model_store = opt_store.unwrap_or_else(default_model_store);
        // wasm: hand the store the egui context so an async file-upload load
        // callback can wake the reactive frame loop (see `store::set_repaint_ctx`).
        #[cfg(target_arch = "wasm32")]
        crate::store::set_repaint_ctx(cc.egui_ctx.clone());
        let saved_settings = model_store.read(SETTINGS_KEY);

        // --- how a document's engine is built --------------------------------
        // Every tab gets its OWN engine, and therefore its own history runner —
        // a runner owns the resident kernel state of the document it executes,
        // so one shared between documents would apply a background run against
        // the wrong registry. See `crate::document`.
        let engine_factory: EngineFactory = Box::new(move || {
            let mut state = EngineState::new();
            // Native: run the whole history — and per-object measurement queries — on a
            // persistent background thread so the UI never freezes during a run or a
            // selection (M2b). Installed BEFORE anything loads so it builds through it.
            #[cfg(not(target_arch = "wasm32"))]
            state.set_runner(Box::new(brep_render::runner::ThreadRunner::new()));
            // wasm: the browser-thread analogue — a dedicated web worker (M3b) so the
            // single-threaded wasm UI stays responsive during a run. Same seam. Tests
            // (which never hit this wasm path) keep the default synchronous InlineRunner.
            #[cfg(target_arch = "wasm32")]
            state.set_runner(Box::new(crate::worker::WorkerRunner::new()));
            state.set_viewcube_enabled(true);
            // Partial-override apply: unknown/absent keys keep their defaults.
            if let Some(saved) = &saved_settings {
                let _ = state.apply_settings_json(saved);
            }
            state
        });

        // Start with the seed model on every launch. Reopening the previous
        // session can immediately rerun a problematic document and prevent the
        // user from recovering by restarting the app. Saved models are opened
        // explicitly through the file dialog instead.
        let mut docs = Documents::new(engine_factory);
        let _ = docs.engine_mut().set_history_json(if seed { seed_history_json() } else { crate::document::EMPTY_DOCUMENT.to_string() }.as_str());
        docs.engine_mut().zoom_to_fit();
        docs.active_mut().mark_clean();
        let session_saved = docs.session_json();

        // The autosave blob from a session that ended with unsaved work: offer
        // it back (a prompt, never an automatic restore — see `crate::recovery`).
        let mut recovery = crate::recovery::RecoveryPanel::new();
        recovery.arm(crate::recovery::read_entries(model_store.as_ref()));

        // The settings panel seeds its working JSON from the (post-load) engine
        // settings so the widgets reflect the persisted state on first paint.
        let settings = SettingsPanel::new();
        let part_properties = PartPropertiesPanel::new();

        // New / Open / Save / Save As. Holds no document identity — that lives
        // on each `Document`.
        let file = FileDialog::new();

        // Boot at the saved UI scale.
        let applied_ui_scale = docs.engine().settings.ui_scale;
        let active_document = docs.active_id();

        // The dock layout (loads the persisted tree, or the default). Built before
        // `model_store` is moved into `Self`.
        let dock = DockState::new(model_store.as_ref());

        // Boot-load: if the page URL carries `?loadModel=<url>` (wasm only), start
        // fetching that model NOW; the seed still loads this frame and the fetched
        // model REPLACES it when it lands (drained in `ui`). See the drain block.
        #[cfg(target_arch = "wasm32")]
        let pending_boot_load = web_sys::window()
            .and_then(|w| w.location().search().ok())
            .and_then(|search| web_sys::UrlSearchParams::new_with_str(&search).ok())
            .and_then(|params| params.get("loadModel"))
            .filter(|url| !url.is_empty())
            .map(|url| crate::http::fetch_text(&cc.egui_ctx, url));
        #[cfg(not(target_arch = "wasm32"))]
        let pending_boot_load: Option<std::sync::mpsc::Receiver<Result<String, String>>> = None;

        Ok(Self {
            docs,
            viewport,
            toolbar: ToolbarPanel::new(),
            workbench_toolbar: WorkbenchToolbarPanel::new(),
            model_store,
            file,
            stl_import: None,
            bug_report: BugReportPanel::new(),
            info: crate::panels::info::InfoPanel::new(),
            diagnostics,
            settings,
            part_properties,
            history: HistoryPanel::new(),
            scene: ScenePanel::new(),
            bom: BomPanel::new(),
            assembly_constraints: AssemblyConstraintsPanel::new(),
            wire_harness: WireHarnessPanel::new(),
            pmi: crate::panels::pmi::PmiPanel::new(),
            update_components: UpdateComponents::new(),
            expressions: ExpressionsPanel::new(),
            info_windows: InfoWindows::new(),
            interference: crate::panels::interference::InterferenceWindow::new(),
            auto_constraints: crate::panels::auto_constraints::AutoConstraintsWindow::new(),
            step_parts: crate::panels::step_parts::StepPartsPanel::new(),
            selection: SelectionPanel::new(),
            context_bar: ContextBarPanel::new(),
            sketch: SketchPanel::new(),
            mode_bar: ModeBar::new(),
            toasts: Toasts::new(),
            dock,
            first_run_framed: false,
            pending_boot_load,
            active_document,
            document_tab_hits: Vec::new(),
            session_saved,
            autosave: crate::recovery::Autosave::new(),
            recovery,
            applied_ui_scale,
            #[cfg(feature = "automation")]
            automation: {
                let q = crate::automation::queue::AutomationQueue::new();
                q.attach(&cc.egui_ctx);
                q
            },
        })
    }

    /// Global keyboard shortcuts (egui input): **Ctrl/Cmd+Z** undo,
    /// **Ctrl/Cmd+Shift+Z** or **Ctrl/Cmd+Y** redo, **Esc** clears the selection.
    ///
    /// `Modifiers::COMMAND` is Ctrl on Windows/Linux and ⌘ on macOS, so one map
    /// covers both. Skipped entirely while an egui TEXT edit is focused so typing
    /// (and text-field Ctrl+Z / Esc-to-defocus) is never hijacked. Redo is
    /// consumed BEFORE undo because egui's `consume_key` matches modifiers
    /// logically (a plain `COMMAND+Z` pattern would also swallow `COMMAND+Shift+Z`).
    fn handle_shortcuts(&mut self, ctx: &egui::Context) {
        if ctx.text_edit_focused() {
            return;
        }
        use egui::{Key, Modifiers};
        let (redo, undo, esc) = ctx.input_mut(|i| {
            let redo = i.consume_key(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z)
                || i.consume_key(Modifiers::COMMAND, Key::Y);
            let undo = i.consume_key(Modifiers::COMMAND, Key::Z);
            let esc = i.consume_key(Modifiers::NONE, Key::Escape);
            (redo, undo, esc)
        });
        // While editing a sketch, Ctrl+Z / Ctrl+Shift+Z drive the PER-SESSION sketch
        // history (S6a), not the model-level undo — this global router consumes the
        // keys first (before the viewport), so it must intercept here. Esc drops the
        // active draw/trim/pick tool back to Select/drag (clearing any in-progress
        // placement): this is the ONLY reliable capture point, since `consume_key`
        // above already swallowed the Escape before the viewport can see it.
        if self.docs.engine().sketch_mode() {
            if redo {
                self.docs.engine_mut().sketch_redo();
            }
            if undo {
                self.docs.engine_mut().sketch_undo();
            }
            if esc {
                self.docs.engine_mut().sketch_set_tool(Some("select"));
            }
            return;
        }
        if redo {
            self.docs.engine_mut().redo();
        }
        if undo {
            self.docs.engine_mut().undo();
        }
        if esc {
            // An open pick-list popup owns the first Escape: close it WITHOUT
            // clearing the selection (a popup-built multi-selection must survive
            // dismissing the list); the next Escape clears as before.
            if !self.viewport.close_candidate_popup() {
                self.docs.engine_mut().clear_selection();
            }
        }
    }

    /// EDIT PART (assemblies §8.5): open the component's SOURCE document in its
    /// own tab — or focus the tab already holding it. Editing a component IS
    /// opening its part now; the assembly picks the change up through the
    /// outdated badge / Update Components once the part is saved, so there is no
    /// session to finish and nothing to stash.
    ///
    /// A part with no store document under its `sourceKey` (an embedded-only
    /// part — a headless STEP import, or one whose write failed) has no file to
    /// open, and says so rather than doing nothing.
    fn edit_part(&mut self, component_id: &str) {
        let source =
            crate::panels::component_actions::part_source_key(self.docs.engine(), component_id);
        match source {
            Some(key) if self.model_store.read(&key).is_some() => {
                self.file
                    .open_document(&mut self.docs, self.model_store.as_ref(), &key);
            }
            Some(key) => self.docs.engine_mut().push_notice(format!(
                "This part's source document '{key}' is no longer in storage — nothing to open"
            )),
            None => self.docs.engine_mut().push_notice(
                "This part is embedded in the assembly — it has no source document to open"
                    .to_string(),
            ),
        }
    }

    /// Draw an isolated preview while the destination document remains untouched.
    fn show_stl_preview(&mut self, ui: &mut egui::Ui) -> bool {
        use crate::panels::stl_import::PreviewAction;
        let Some(preview) = self.stl_import.as_mut() else {
            return false;
        };
        let action = if preview.destination != self.docs.active_id() {
            PreviewAction::Cancel
        } else {
            preview.show(ui, &mut self.viewport)
        };
        if crate::automation::registry::enabled() {
            crate::automation::registry::publish("__brepImportPreview", "STL/OBJ import preview state (tolerances, counts, accept readiness); null when no preview is open", &preview.state_json());
            crate::automation::registry::publish("__brepImportPreviewHit", "import preview dialog widget rects", &preview.hits_json());
            crate::automation::registry::publish("__brepCamera", "camera state: kind, eye, target, up, near/far, projection block, worldPerPixel", &preview.engine.camera_state_json());
            crate::automation::registry::publish("__brepPpp", "pixels per point of the surface", &format!("{}", ui.ctx().pixels_per_point()));
            crate::automation::registry::publish("__brepHistory", "history listing {step, features:[{index,type,id}]}", &self.docs.engine().history_listing_json());
            crate::automation::registry::publish("__brepDocuments", "open document tabs {active, tabs:[{title,name,dirty}]}", &document_tabs::state_json(&self.docs));
        }
        let close = match action {
            PreviewAction::Accept => {
                match preview.accept_into(self.docs.active_id(), self.docs.engine_mut()) {
                    Ok(()) => true,
                    Err(error) => {
                        self.docs.engine_mut().push_notice(error);
                        false
                    }
                }
            }
            PreviewAction::Cancel => true,
            PreviewAction::None => false,
        };
        if close {
            self.stl_import = None;
            self.viewport.forget_document();
            ui.ctx().request_repaint();
        }
        true
    }

    /// Reset everything the shared panels and the viewport hold ABOUT ONE
    /// DOCUMENT, run at the top of the first frame that sees a different active
    /// document.
    ///
    /// Panel state is deliberately NOT per-document (one History panel, one
    /// Scene tree, …): a second copy per tab would double every panel's state
    /// for a benefit — remembering which feature form was open in a background
    /// tab — nobody asked for. The price is that the transient state has to be
    /// dropped on a switch, because every bit of it (expansion sets, hit maps,
    /// an open feature form, a pinned Info window's object name) refers to the
    /// document that just went away.
    fn reset_document_scoped_state(&mut self) {
        self.history = HistoryPanel::new();
        self.scene = ScenePanel::new();
        self.bom = BomPanel::new();
        self.assembly_constraints = AssemblyConstraintsPanel::new();
        self.wire_harness = WireHarnessPanel::new();
        self.pmi = crate::panels::pmi::PmiPanel::new();
        self.expressions = ExpressionsPanel::new();
        // Pinned to object NAMES of the old document ("Box" exists in most of
        // them), so these would silently retarget rather than go blank.
        self.info_windows = InfoWindows::new();
        self.interference = crate::panels::interference::InterferenceWindow::new();
        self.auto_constraints = crate::panels::auto_constraints::AutoConstraintsWindow::new();
        // The outdated-parts cache keys on `(applied_generation, save_generation)`,
        // and two documents' generations are unrelated — a switch can land on the
        // same key with an entirely different parts library.
        self.update_components.invalidate();
        self.viewport.forget_document();
    }

    /// A signature of the CURRENT rendered model (rolled-to step) — solid count,
    /// per-solid triangle count + bbox, and total triangles. Published to JS so
    /// the headed verifier can prove each roll / edit produced different geometry
    /// (names alone don't: a SUBTRACT reuses the target's name).
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    fn model_signature_json(&self) -> String {
        let solids: Vec<serde_json::Value> = self
            .docs
            .engine()
            .scene
            .solids()
            .iter()
            .map(|s| {
                serde_json::json!({
                    "name": s.name,
                    "tris": s.mesh.indices.len() / 3,
                    "min": s.bbox.min,
                    "max": s.bbox.max,
                })
            })
            .collect();
        let total_tris: usize = self
            .docs
            .engine()
            .scene
            .solids()
            .iter()
            .map(|s| s.mesh.indices.len() / 3)
            .sum();
        serde_json::json!({
            "step": self.docs.engine().history_rollback(),
            "solidCount": solids.len(),
            "totalTris": total_tris,
            "solids": solids,
        })
        .to_string()
    }

    /// Open or close the floating Settings window — the toolbar gear's flag,
    /// reachable from the automation layer (`settings_window`).
    pub fn set_settings_window_open(&mut self, open: bool) {
        self.settings.open = open;
    }

    /// Open or close the floating Part Properties window — the toolbar tag
    /// button's flag, reachable from the automation layer
    /// (`part_properties_window`).
    pub fn set_part_properties_window_open(&mut self, open: bool) {
        self.part_properties.open = open;
    }

    /// Open or close the floating Info window — the toolbar info button's flag,
    /// reachable from the automation layer (`info_window`).
    pub fn set_info_window_open(&mut self, open: bool) {
        self.info.open = open;
    }

    /// What this session is running on. The app's ONE record of it: the Info
    /// window draws it, a problem report carries it, the `diagnostics` command
    /// returns it and the MCP banner names its adapter — all from here.
    pub fn diagnostics(&self) -> &crate::diagnostics::Diagnostics {
        &self.diagnostics
    }

    /// Begin the in-app problem report: the same call the Submit Bug button
    /// makes, and for the same reason it makes it THIS frame — `request`
    /// captures the current frame before its own dialog exists.
    pub fn begin_bug_report(&mut self, ctx: &egui::Context) {
        self.bug_report.request(ctx, self.docs.engine(), &self.diagnostics);
    }

    /// Bring a dock pane to the front (`show_pane`).
    pub fn show_pane(&mut self, kind: PaneKind) {
        self.dock.show_pane(kind);
    }

    /// The parts-library staleness check and its refresh — the Constraints
    /// header's "Update components (N)" button, reachable as the
    /// `component_update` command. Returns `(outdated, missing, refreshed)`;
    /// `run` is skipped when nothing is outdated.
    pub fn update_components(&mut self, run: bool) -> Result<(usize, Vec<String>, usize), String> {
        let store = self.model_store.as_ref();
        self.update_components.ensure_current(self.docs.engine_mut(), store, self.file.save_generation());
        let outdated = self.update_components.outdated_count();
        let missing = self.update_components.missing().to_vec();
        let refreshed = if run { self.update_components.run(self.docs.engine_mut(), store)? } else { 0 };
        Ok((outdated, missing, refreshed))
    }

    /// Run what a WORKBENCH TOOLBAR button does, by its `WorkbenchButton::id`.
    ///
    /// Split out of `ui` so a toolbar click and the `workbench_button` command
    /// run the SAME arms: the workbench registry declares a button, this
    /// dispatches it, and the automation surface owns no second copy of the
    /// list. Returns whether the id was known.
    pub fn dispatch_workbench_button(&mut self, id: &str) -> bool {
        match id {
            // Sheet Metal's flat pattern: open the export modal in its DXF /
            // SVG mode; the engine reports "no sheet-metal body in the part"
            // as a toast on export.
            "sheetmetal.flat_pattern" => {
                self.file.dispatch(FileAction::ExportFlatPattern, &mut self.docs, self.model_store.as_ref());
            }
            // Assembly's Add Component: open the insert-component modal (the
            // same flow as the ACOMP palette pick).
            "assembly.add_component" => {
                self.file.dispatch(FileAction::InsertComponent, &mut self.docs, self.model_store.as_ref());
            }
            // Assembly's interference check: run the engine's pairwise
            // intersect sweep NOW and open the results window.
            "assembly.interference" => {
                self.interference.open_and_run(self.docs.engine_mut());
            }
            // Assembly's Auto Constraints: open the inference window and scan
            // the current placement NOW, so it opens showing real counts.
            "assembly.auto_constrain" => {
                self.auto_constraints.open_and_scan(self.docs.engine_mut());
            }
            // Assembly's step.parts library: open the online-library browser
            // (search → thumbnails → import a STEP part → add as an ACOMP).
            "assembly.step_parts_library" => {
                self.step_parts.open();
            }
            // PMI's Capture view: snapshot the camera + visibility into a new
            // active view and surface the PMI pane so its row is seen.
            crate::workbench::pmi::CAPTURE_BUTTON_ID => {
                self.docs.engine_mut().pmi_capture_view(None);
                self.dock.show_pane(PaneKind::Pmi);
            }
            _ => return false,
        }
        true
    }

}

impl eframe::App for BrepApp {
    /// Phase 1 of the automation frame (§4.4): queued input commands become
    /// egui events; a screenshot that landed completes its reply. Called by
    /// every eframe runner before `ui`; the headless host calls it itself.
    #[cfg(feature = "automation")]
    fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
        let view = self.viewport.last_rect();
        self.automation.drain_input(raw_input, ctx.cumulative_frame_nr(), ctx.pixels_per_point(), view);
    }


    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        // --- global keyboard shortcuts (undo/redo/clear-selection) ------------
        // Handled before any panel draws so a Ctrl+Z etc. this frame takes effect
        // this frame. `ctx` is a cheap Arc clone (avoids borrowing `ui` across the
        // `&mut self` call).
        let ctx = ui.ctx().clone();

        // Phase 2 of the automation frame (§4.4): mutations run before any
        // panel draws, so this frame shows their effect.
        #[cfg(feature = "automation")]
        {
            let queue = self.automation.clone();
            let frame = ctx.cumulative_frame_nr();
            queue.drain_app(
                crate::automation::command::Phase::Mutate,
                &mut crate::automation::command::Ctx { app: self, egui: &ctx },
                frame,
            );
        }

        // --- a different document is active than the panels were drawn for ----
        // Checked FIRST, before anything draws: the switch itself happened late
        // in some earlier frame (a tab click, a close, an Open), and every
        // shared panel is still holding the previous document's transient state.
        if self.active_document != self.docs.active_id() {
            self.active_document = self.docs.active_id();
            self.reset_document_scoped_state();
        }

        // --- the workbench decides whether placed parts show their ports -------
        // A workbench that shows the Wire Harness panel (Wire harness, All)
        // draws the ports components carry; the others — Modeling included,
        // though it offers the Port feature — keep the assembly clean. A no-op
        // when nothing changed.
        {
            let engine = self.docs.engine_mut();
            let show = crate::workbench::panel_visible(
                &engine.settings.workbench,
                crate::workbench::wire_harness::PANEL_ID,
            );
            engine.set_component_ports_visible(show);
            // The PMI workbench IS the PMI editing mode: a workbench that shows
            // the PMI panel (PMI, All) enters it — the modeling camera /
            // visibility / wireframe are remembered — and one that hides it
            // leaves it, deactivating the view and restoring them.
            let pmi_shown = crate::workbench::panel_visible(
                &engine.settings.workbench,
                crate::workbench::pmi::PANEL_ID,
            );
            if pmi_shown && !engine.pmi_workbench_entered() {
                engine.pmi_enter_workbench();
            } else if !pmi_shown && engine.pmi_workbench_entered() {
                engine.pmi_leave_workbench();
            }
        }

        // --- GUI chrome theme -------------------------------------------------
        // Apply the user's theme preference to the egui chrome every frame
        // (idempotent: `set_theme` just stores the preference). Auto follows the
        // OS/system theme (prefers-color-scheme on web); egui falls back to dark
        // when no OS signal is available. This controls panels/windows/toolbar/
        // text only — the 3D viewport `background` is a separate setting.
        ctx.set_theme(match self.docs.engine().settings.theme {
            ThemeMode::Auto => egui::ThemePreference::System,
            ThemeMode::Light => egui::ThemePreference::Light,
            ThemeMode::Dark => egui::ThemePreference::Dark,
        });

        // --- global UI size scale --------------------------------------------
        // Apply the user's "UI scale" to the whole egui chrome every frame. This
        // is idempotent when unchanged (`set_zoom_factor` only repaints on an
        // actual change) and composes with the native device pixel ratio
        // (pixels_per_point = zoom_factor * native_pixels_per_point).
        //
        // Defer live UI rescale while the user drags the Settings "UI scale" slider:
        // the slider value updates continuously, but only commit it to the actual egui
        // zoom once the pointer is released, so the whole UI doesn't rescale under the
        // cursor mid-drag.
        let pointer_down = ctx.input(|i| i.pointer.any_down());
        if !pointer_down {
            self.applied_ui_scale = self.docs.engine().settings.ui_scale;
        }
        ctx.set_zoom_factor(self.applied_ui_scale);

        // --- history-runner pump ---------------------------------------------
        // Apply any completed background history run BEFORE panels read the scene.
        // For the synchronous InlineRunner this is a no-op (`rerun_history` already
        // pumped its own submit), so nothing changes today; it is the seam a future
        // native-thread / wasm-worker runner lands its reply through. While a run is
        // still in flight, keep the frame loop alive so its reply gets pumped — for
        // Inline `run_pending()` is always false, so this never fires.
        //
        // EVERY open document is pumped, not just the active one: a run belongs
        // to the engine that submitted it (each document owns its own runner —
        // see `crate::document`), so a run still in flight when the user switches
        // tabs must land in ITS document rather than be dropped or, worse,
        // applied to whatever is on screen. An idle document's pump is a couple
        // of empty `try_recv`s.
        let mut work_in_flight = false;
        for doc in self.docs.iter_mut() {
            doc.engine.pump();
            work_in_flight |= doc.engine.run_pending()
                || doc.engine.queries_pending()
                || doc.engine.mesh_imports_pending()
                || doc.engine.step_probes_pending();
        }
        if work_in_flight {
            ctx.request_repaint();
        }
        if self.show_stl_preview(ui) {
            return;
        }
        if crate::automation::registry::enabled() {
            crate::automation::registry::publish("__brepImportPreview", "STL/OBJ import preview state (tolerances, counts, accept readiness); null when no preview is open", "null");
        }

        // The tab strip's dirty dots, refreshed once per frame (cheap — see
        // `Document::refresh_dirty_marker`).
        self.docs.refresh_dirty_markers();

        // --- boot-load (?loadModel=): apply the fetched model once it lands ----
        // Replaces the seed with the URL-specified document (armed in `new`). The
        // ehttp callback wakes the frame loop, so a plain per-frame drain suffices.
        // `load_model_and_fit` arms deferred framing; the pump above reframes it
        // next frame. `mark_clean` opens it as a non-dirty document.
        if self.pending_boot_load.is_some() {
            let received = self
                .pending_boot_load
                .as_ref()
                .and_then(|rx| rx.try_recv().ok());
            if let Some(result) = received {
                self.pending_boot_load = None;
                match result {
                    Ok(json) => {
                        // REPLACES the seed in place rather than adding a tab:
                        // the cadDev "Launch model in CAD app" link means "show
                        // me this model", and a boot with the demo cube sitting
                        // in tab 1 beside it would be noise. It lands on the
                        // document that is already active, whatever the session
                        // restored.
                        let _ = self.docs.engine_mut().load_model_and_fit(&json);
                        self.docs.active_mut().mark_clean();
                    }
                    Err(e) => self
                        .docs
                        .engine_mut()
                        .push_notice(format!("Could not load model from URL: {e}")),
                }
            }
        }

        // --- update-components badge freshness ---------------------------------
        // Keep the outdated-parts checker current BEFORE any assembly panel draws
        // (the structure tree renders per-node badges ahead of the constraints
        // header). Cheap: a real recompute happens only when an applied run or a
        // successful store save moved the generation key.
        self.update_components.ensure_current(
            self.docs.engine_mut(),
            self.model_store.as_ref(),
            self.file.save_generation(),
        );

        // --- async-safe first-model framing -----------------------------------
        // The seed run is async under a background runner (native thread / wasm
        // worker), so the boot `zoom_to_fit` may have run before any solid existed.
        // Frame the model ONCE, the first frame the seed run has fully landed (solids
        // present AND no run still in flight). Under the synchronous Inline runner
        // (tests) both hold on the very first frame, so this is identical to today.
        if !self.first_run_framed
            && !self.docs.engine().run_pending()
            && self.docs.engine().has_solids()
        {
            self.docs.engine_mut().zoom_to_fit();
            self.first_run_framed = true;
        }

        self.handle_shortcuts(&ctx);

        // --- top toolbar: primary actions, drawn FIRST so its top strip is
        // reserved above the left panel + central viewport. A clicked File button
        // returns an action the file dialog acts on (open its modal / save / new).
        let toolbar_outcome = self.toolbar.show(
            ui,
            self.docs.engine_mut(),
            self.model_store.as_ref(),
            &mut self.settings.open,
            &mut self.part_properties.open,
            &mut self.info.open,
        );
        if let Some(action) = toolbar_outcome.file {
            self.file
                .dispatch(action, &mut self.docs, self.model_store.as_ref());
        }
        // Submit Bug: begin the screenshot-capture + report flow. `request`
        // grabs the current frame (before its dialog exists) and the model, so
        // it must run THIS frame while the shot is still dialog-free.
        if toolbar_outcome.bug_report {
            self.bug_report.request(&ctx, self.docs.engine(), &self.diagnostics);
        }
        // A workbench toolbar button click surfaces its id here; the dispatch
        // itself is a METHOD so the `workbench_button` command runs the very
        // same arms (a button an agent can only reach by clicking is a button
        // an agent cannot reach when something covers it).
        if let Some(id) = toolbar_outcome.workbench_button {
            self.dispatch_workbench_button(id);
        }

        // --- workbench actions toolbar: a second strip directly UNDER the
        // primary toolbar (egui stacks top panels in call order) listing the
        // active workbench's creatable features + the constraint types. Off via
        // the Settings checkbox, and never in sketch / reference-selection mode
        // (the panel decides — see `WorkbenchToolbarPanel::visible`). A feature
        // click adds exactly what the palette pick would, so ACOMP still routes
        // to the component selector; a constraint click is the context bar's
        // constraint offer, seeded from the current selection.
        let actions = self.workbench_toolbar.show(ui, self.docs.engine());
        if let Some(type_code) = actions.feature {
            self.history
                .add_feature_of_type(self.docs.engine_mut(), &type_code);
            if self.history.take_insert_component_request() {
                self.file.dispatch(
                    FileAction::InsertComponent,
                    &mut self.docs,
                    self.model_store.as_ref(),
                );
            } else {
                // Surface History so the new feature's form is actually visible.
                self.dock.show_pane(PaneKind::History);
            }
        }
        if let Some(type_id) = actions.constraint {
            // The strip offers every type regardless of the selection (unlike the
            // context bar's gated offers), so a refusal has to be SAID: a toast,
            // never a silent no-op. A document with no components has no assembly
            // session to add to (the kernel's own message names the session, not
            // the cause) — say what is actually missing.
            let engine = self.docs.engine_mut();
            if !engine.history_has_assembly() {
                engine.push_notice(
                    "Add constraint: the document has no components — insert a component first"
                        .to_string(),
                );
            } else {
                match crate::panels::context_bar::add_constraint_from_selection(engine, &type_id) {
                    Ok(_) => self.dock.show_pane(PaneKind::AssemblyConstraints),
                    Err(error) => engine.push_notice(format!("Add constraint: {error}")),
                }
            }
        }

        // --- sketch mode: a slim top bar (the draw tools) drawn just below the
        // toolbar while editing a sketch. The normal side panel is hidden (below)
        // so the 3D viewport is the full-width sketching surface.
        if self.docs.engine().sketch_mode() {
            self.sketch.show_mode_bar(ui, self.docs.engine_mut());
        }

        // --- bottom STATUS BAR: a persistent, full-width strip whose CONTENT is
        // chosen by context each frame. Drawn AFTER the top bars but BEFORE the
        // left panel(s) so it reserves the FULL bottom width and the left column
        // stops above it (egui resolves reserved space by call order). It is a
        // HOST: the branch below picks what to draw. A NEW context is added by
        // extending this branch (e.g. `else if engine.some_mode() { … }`) and
        // routing through the owning panel's `show_status_bar` for DRY styling.
        egui::containers::panel::Panel::bottom("brep-status-bar")
            .resizable(false)
            .min_size(30.0)
            .show(ui, |ui| {
                ui.add_space(2.0);
                if self.docs.engine().sketch_mode() {
                    // Sketch context: the status row (title / DOF / N selected /
                    // undo-redo / Lock). The selection-filter row is NOT drawn
                    // now, so drop its stale hit-rects (the verifier must never
                    // click a phantom rect for an off-screen widget).
                    self.selection.clear_hits();
                    self.sketch.show_status_bar(ui, self.docs.engine_mut());
                } else {
                    // Modeling context: the selection filter (pickable kinds).
                    self.selection.show_status_bar(ui, self.docs.engine_mut());
                }
                ui.add_space(2.0);
            });

        // --- central region: the dock tree, OR (special modes) the bare 3D view
        // ---------------------------------------------------------------------
        // Normal modeling mode: ONE egui_tiles tree fills the whole remaining
        // area between the top toolbar and the bottom status bar. Every side-panel
        // section AND the 3D viewport are tiles the user can split / tab / resize /
        // drag-rearrange, and the layout persists. Which side panes are visible is
        // filtered per-workbench inside the dock (`workbench::panel_visible`).
        //
        // Sketch mode and reference-selection are "special modes" that take over
        // the shell: they BYPASS the tree and draw the viewport directly, so the
        // modeling side panes don't appear (sketch's own entity-list panel + the
        // top-right mode card own those flows). Drawing the viewport HERE — before
        // the top-right overlay below — keeps `viewport.last_rect()` current-frame
        // so the overlay anchors to the live 3D-view rect with no lag.
        let sketch = self.docs.engine().sketch_mode();
        let ref_select = self.docs.engine().ref_select_active();

        if sketch {
            // Sketch entity lists (Curves / Points / Constraints) + solver
            // settings — a dedicated left panel, drawn BEFORE the viewport so it
            // reserves the left and the viewport fills the rest.
            egui::containers::panel::Panel::left("sketch-entities")
                .resizable(true)
                .default_size(300.0)
                .size_range(200.0..=560.0)
                .show(ui, |ui| {
                    self.sketch.show_entity_lists(ui, self.docs.engine_mut());
                });
        }

        self.history.sync_palette_display(self.model_store.as_ref());
        if sketch || ref_select {
            // Special mode: the viewport fills the remaining central area; no
            // dock, no modeling side panes — and therefore no DOCUMENT TAB
            // STRIP either, which is the guard that keeps a live sketch /
            // reference-pick session from having its document swapped out from
            // under it.
            self.viewport.show(ui, self.docs.engine_mut());
        } else {
            // Normal mode: the dock owns the whole central area (the viewport is a
            // pane). Cross-panel requests the panels can't act on while their
            // borrows are held bubble OUT via the returned outcome — the SAME
            // requests the old left-panel closure produced.
            let outcome = self.dock.ui(
                ui,
                DockContext {
                    docs: &mut self.docs,
                    viewport: &mut self.viewport,
                    history: &mut self.history,
                    bom: &mut self.bom,
                    assembly_constraints: &mut self.assembly_constraints,
                    wire_harness: &mut self.wire_harness,
                    pmi: &mut self.pmi,
                    scene: &mut self.scene,
                    expressions: &mut self.expressions,
                    update_components: &mut self.update_components,
                    model_store: self.model_store.as_ref(),
                },
            );

            // The ACOMP palette pick must open the COMPONENT SELECTOR, never a
            // bare feature dialog — the file dialog is shell-owned.
            if outcome.insert_component_requested {
                self.file.dispatch(
                    FileAction::InsertComponent,
                    &mut self.docs,
                    self.model_store.as_ref(),
                );
            }
            // The DOCUMENT TAB STRIP inside the viewport tile. Activation is
            // immediate; a close routes through the file dialog because a dirty
            // document has to be confirmed first, and that prompt lives there.
            if let Some(index) = outcome.document_tabs.activate {
                self.docs.activate(index);
            }
            if let Some(index) = outcome.document_tabs.close {
                self.file.request_close(&mut self.docs, index);
            }
            self.document_tab_hits = outcome.document_tabs.hits;
            // A structure-tree Edit — or a BOM row's action button, which
            // reports through the same outcome field so there is one arm and
            // not two — expands its feature in the history tree.
            if let Some(focus) = outcome.feature_focus {
                self.history.focus_feature(focus);
                // Surface History so the expanded feature is actually visible.
                self.dock.show_pane(PaneKind::History);
            }
            // Structure-tree interaction hooks route through the SAME dispatcher
            // as the context bar (one truth per action); document-level flows
            // (edit-in-place / open-part) come back as requests the shell runs.
            // A BOM row menu's document-level flow: its engine-mutating half
            // already ran inside the panel, through the same dispatcher.
            match outcome.component_request {
                Some(ComponentActionRequest::OpenPart { component_id }) => {
                    self.edit_part(&component_id);
                }
                None => {}
            }
        }

        self.history.sync_palette_display(self.model_store.as_ref());

        // --- file dialog: a ctx-level modal (like the command palette), drawn
        // after the panels so its backdrop dims the whole shell. Idempotent when
        // closed; also polls for a completed async import each frame.
        self.file
            .show(&ctx, &mut self.docs, self.model_store.as_ref());

        // --- crash recovery: the boot prompt, then the debounced autosave -----
        // Drawn with the same ctx-level modal treatment as the file dialog. The
        // autosave ticks only once the prompt has resolved (or never existed).
        if self.recovery.is_open() {
            if let Some(resolution) =
                self.recovery.show(&ctx, &mut self.docs, self.model_store.as_ref())
            {
                self.autosave.note_cleared();
                if let crate::recovery::Resolution::Restored(count) = resolution {
                    self.docs.engine_mut().push_notice(format!(
                        "Restored {count} unsaved document{}",
                        if count == 1 { "" } else { "s" }
                    ));
                }
            }
        } else {
            self.recovery.clear_hits();
            let now = ctx.input(|i| i.time);
            if let Some(due) = self.autosave.tick(&self.docs, self.model_store.as_ref(), now) {
                // The frame loop idles between inputs; wake it when the write is due.
                ctx.request_repaint_after(std::time::Duration::from_secs_f64(due.max(0.05)));
            }
        }

        if let Some((name, bytes)) = self.file.take_stl_import() {
            self.stl_import = Some(crate::panels::stl_import::StlImportPreview::new(
                self.docs.active_id(), name, bytes, self.docs.spawn_engine(),
            ));
            self.viewport.forget_document();
            ctx.request_repaint();
        }

        // --- Submit Bug: the screenshot-capture state machine + report modal.
        // Drawn at ctx level like the file dialog; idempotent while idle. Draws
        // NOTHING during capture, so the screenshot it requested never contains
        // this dialog.
        self.bug_report.show(&ctx, self.docs.engine_mut());

        // --- Info: the licences + this session's diagnostics, a floating window
        // toggled from the toolbar's info button. Idempotent when closed.
        self.info.show(&ctx, &self.diagnostics);

        // --- Settings: a floating (movable + resizable) window, toggled from the
        // toolbar gear button, drawn at ctx level like Properties so it floats
        // over the shell. Idempotent when closed. Replaces the old sidebar section.
        self.settings
            .show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());

        // --- Part Properties: the active document's own BOM attribute record,
        // in a floating window beside Settings. The title is passed in because
        // the panel takes only the engine, and a user with several tabs open
        // must be able to see WHICH part they are annotating.
        let part_title = self.docs.active().title();
        let part_document = self.docs.active().id();
        self.part_properties
            .show(&ctx, self.docs.engine_mut(), &part_title, part_document);

        // --- top-right overlay column: the special-mode EXIT card (Finish/Cancel
        // for reference-selection / sketch mode) stacked ABOVE the selection-driven
        // CONTEXT ACTION rail. Both cards live in ONE ctx-level Area anchored
        // top-right so they never overlap, and the context rail uses the SAME
        // renderer whether it is showing modeling actions or sketch actions
        // (`panels::action_rail`). A modeling create/edit action returns a feature
        // id to expand in the history tree.
        {
            let mut focus: Option<String> = None;
            let mut info_targets: Vec<String> = Vec::new();
            let mut component_request: Option<ComponentActionRequest> = None;
            let mut pmi_added = false;
            // Anchor the overlay to the RIGHT edge of the 3D VIEW (the viewport
            // tile), not the window — so it stays glued to the viewport wherever
            // docking frames it. The viewport was drawn earlier THIS frame, so its
            // rect is current. Before the first draw (`None`) fall back to the
            // window's top-right.
            let mut overlay = egui::Area::new(egui::Id::new("brep-top-right-overlay"))
                .order(egui::Order::Foreground);
            overlay = match self.viewport.last_rect() {
                Some(rect) => overlay
                    .fixed_pos(rect.right_top() + egui::vec2(-12.0, 8.0))
                    .pivot(egui::Align2::RIGHT_TOP),
                None => overlay.anchor(egui::Align2::RIGHT_TOP, egui::vec2(-12.0, 56.0)),
            };
            overlay
                .show(&ctx, |ui| {
                    // 1. Exit controls for whatever special mode is active.
                    self.mode_bar.card(ui, self.docs.engine_mut());
                    // 2. Context actions: sketch actions in sketch mode, else the
                    // modeling selection actions. Same rail, mode-appropriate items.
                    if self.docs.engine().sketch_mode() {
                        self.sketch.context_card(ui, self.docs.engine_mut());
                    } else {
                        let outcome = self.context_bar.card(ui, self.docs.engine_mut());
                        focus = outcome.focus;
                        info_targets = outcome.info_targets;
                        component_request = outcome.component;
                        pmi_added = outcome.pmi_added;
                    }
                });
            // An annotation added from the selection opened its form in the
            // PMI pane: surface the pane so the form is actually seen.
            if pmi_added {
                self.dock.show_pane(PaneKind::Pmi);
            }
            if let Some(focus) = focus {
                self.history.focus_feature(focus);
                // Adding a feature from the context bar can happen while another
                // side tab is active — bring History forward so the new row shows.
                self.dock.show_pane(PaneKind::History);
            }
            // The Info action returns one target per selected entity — open (or, on
            // dedup, keep) a pinned Info window for each. Drawn below.
            if !info_targets.is_empty() {
                self.info_windows.open_for(&info_targets);
            }
            // Component document-level flows (the engine-mutating component
            // actions already ran inside the bar).
            match component_request {
                Some(ComponentActionRequest::OpenPart { component_id }) => {
                    self.edit_part(&component_id);
                }
                None => {}
            }
        }

        // --- Info windows: the pinned per-entity inspector windows, drawn at ctx
        // level like the file dialog so they float over the shell. Each is pinned to
        // its open-time object name (selection changes never retarget them); closed
        // windows (their `×`) are pruned here. Drawn AFTER the context bar so a
        // window opened THIS frame paints this frame.
        self.info_windows.show(&ctx, self.docs.engine_mut());

        // --- interference results window: same floating idiom, owned report;
        // its Re-run button re-drives the engine check.
        self.interference.show(&ctx, self.docs.engine_mut());

        // --- auto-constraints window: the inference scan + its Create button.
        self.auto_constraints.show(&ctx, self.docs.engine_mut());
        self.step_parts
            .show(&ctx, self.docs.engine_mut(), self.model_store.as_ref());

        // --- transient toasts: drain the engine's queued notices (e.g. a sketch
        // solve that failed after an edit) and show each briefly. Drawn last so
        // the cards float over the whole shell.
        let now = ctx.input(|i| i.time);
        let notices = self.docs.engine_mut().take_notices();
        self.toasts.extend(notices, now);
        // Same lane for STORAGE failures the store could only discover after its
        // synchronous `write` returned `Ok` (the browser backend writes behind an
        // in-memory mirror). A save that did not persist must never be silent.
        self.toasts
            .extend(self.model_store.take_persistence_errors(), now);
        self.toasts.extend(self.autosave.take_errors(), now);
        self.toasts.show(&ctx);

        // --- persist the open-document session --------------------------------
        // Compared against what was last WRITTEN rather than flagged at each
        // mutation site: New / Open / close / activate / Save As (a rename) all
        // move it, and a change detector cannot forget one of them. The blob is
        // a short name list, so the per-frame compare is free.
        let session = self.docs.session_json();
        if session != self.session_saved {
            let _ = self.model_store.write(SESSION_KEY, &session);
            self.session_saved = session;
        }

        // The state registry (`automation::registry`): the live app + engine
        // state, published by name with a one-line doc so a host can read it
        // (and, on wasm, mirrored to `window.__brep*` for the verify scripts).
        // Purely additive; no render effect. Published AFTER the panels draw so
        // the hit-rects are for THIS frame's layout. Off unless a host enabled it.
        if crate::automation::registry::enabled() {
            let ppp = ui.ctx().pixels_per_point();
            crate::automation::registry::publish("__brepCamera", "camera state: kind, eye, target, up, near/far, projection block, worldPerPixel", &self.docs.engine().camera_state_json());
            crate::automation::registry::publish("__brepSettings", "render and UI settings", &self.docs.engine().settings_json());
            crate::automation::registry::publish("__brepSolidColors", "per-solid colour overrides", &self.docs.engine().solid_color_overrides_json());
            crate::automation::registry::publish("__brepHistory", "history listing {step, features:[{index,type,id}]}", &self.docs.engine().history_listing_json());
            crate::automation::registry::publish("__brepGizmo", "transform gizmo state", &self.docs.engine().gizmo_state_json());
            crate::automation::registry::publish("__brepFile", "file dialog state (mode, entries, current name)",
                &self.file.file_state_json(&self.docs, self.model_store.as_ref()),
            );
            crate::automation::registry::publish("__brepFileHit", "file dialog widget rects", &self.file.hits_json());
            crate::automation::registry::publish("__brepModel", "model signature: solid count, triangle count, per-solid bounds (change detection)", &self.model_signature_json());
            crate::automation::registry::publish("__brepReport", "last run report {featureErrors, unresolved, displayErrors, featureTimings, featureOutputs}", &self.docs.engine().history_report_json());
            // The in-flight run: whether one is pending, the feature the runner
            // says it is executing, and the feature a cancelled run was stuck on.
            crate::automation::registry::publish("__brepRun", "in-flight run {pending, progress:{generation,index,total,featureId,featureType}|null, cancelled}",
                &serde_json::json!({
                    "pending": self.docs.engine().run_pending(),
                    "progress": self.docs.engine().run_progress().map(|p| serde_json::json!({
                        "generation": p.generation,
                        "index": p.index,
                        "total": p.total,
                        "featureId": p.feature_id,
                        "featureType": p.feature_type,
                    })),
                    "cancelled": self.docs.engine().cancelled_run(),
                })
                .to_string(),
            );
            crate::automation::registry::publish("__brepHit", "history panel widget rects: step:i edit:i del:i box:i add:menu palette:type form:* field:* panel:clip", &self.history.hits_json());
            crate::automation::registry::publish("__brepExprHit", "expressions panel widget rects", &self.expressions.hits_json());
            crate::automation::registry::publish("__brepExpr", "expressions script, its variables and the configurator",
                &serde_json::json!({
                    "expressions": self.docs.engine().expressions_json(),
                    "variables": serde_json::from_str::<serde_json::Value>(
                        &self.docs.engine().expression_variables_json()
                    )
                    .unwrap_or(serde_json::Value::Null),
                    "configurator": serde_json::from_str::<serde_json::Value>(
                        &self.docs.engine().configurator_json()
                    )
                    .unwrap_or(serde_json::Value::Null),
                })
                .to_string(),
            );
            crate::automation::registry::publish("__brepToolbar", "primary toolbar rects: file:* undo redo fit projection wireframe properties settings help info bug workbench workbench:id", &self.toolbar.hits_json());
            // The workbench actions strip's button rects (`wbtb:feature:<type>` /
            // `wbtb:constraint:<type>`); an empty map while the strip is hidden.
            crate::automation::registry::publish("__brepWorkbenchToolbar", "workbench actions strip rects: wbtb:* feature:type constraint:type (empty while hidden)", &self.workbench_toolbar.hits_json());
            // The queued toast texts — the only trace of a refusal the app shows
            // as a transient card (e.g. a constraint the strip could not add).
            crate::automation::registry::publish("__brepNotices", "queued toast texts", &self.toasts.texts_json());
            crate::automation::registry::publish("__brepBug", "bug report panel state", &self.bug_report.state_json());
            crate::automation::registry::publish("__brepDiagnostics", "what this session is running on: renderer, adapter, texture ceiling, version, platform", &self.diagnostics.json().to_string());
            crate::automation::registry::publish("__brepBugHit", "bug report panel widget rects", &self.bug_report.hits_json());
            // The wire harness: the document's connections + the last run's
            // routing report (engine truth), and the panel's widget rects.
            crate::automation::registry::publish("__brepWireHarness", "wire harness connections and the last routing report", &self.docs.engine().wire_harness_state_json());
            crate::automation::registry::publish("__brepWireHarnessHit", "wire harness panel widget rects", &self.wire_harness.hits_json());
            // The PMI block + report + active view / open annotation, and the
            // PMI panel's rects (`pmi:capture`, `pmi:add`, `pmi:add:<type>`,
            // `pmi:row:<id>`, `pmi:cell:<id>:<column>`, `pmi:menu:<id>`, the
            // form's `pmi:` keys).
            crate::automation::registry::publish("__brepPmi", "PMI block, report, active view and open annotation", &self.docs.engine().pmi_state_json());
            crate::automation::registry::publish("__brepPmiHit", "PMI panel widget rects (pmi:*)", &self.pmi.hits_json());
            // The workbench logical state (resolved current id + available ids) so
            // the verifier can drive the dropdown and confirm the active workbench.
            // Hit-rects for the dropdown ride in `__brepToolbar` (self.toolbar.hits).
            crate::automation::registry::publish("__brepWorkbench", "active workbench id and the available ids",
                &crate::workbench::workbench_state_json(&self.docs.engine().settings.workbench),
            );
            crate::automation::registry::publish("__brepSelection", "selection {solids, faces, edges, datums, vertices}", &self.docs.engine().selection_json());
            crate::automation::registry::publish("__brepInfoWindows", "open info windows (mass properties, topology, metadata)",
                &self.info_windows.published_json(self.docs.engine_mut()),
            );
            crate::automation::registry::publish("__brepInfoWindowsHit", "info window widget rects", &self.info_windows.hits_json());
            crate::automation::registry::publish("__brepInterference", "interference check state", &self.interference.state_json());
            crate::automation::registry::publish("__brepInterferenceHit", "interference panel widget rects", &self.interference.hits_json());
            crate::automation::registry::publish("__brepAutoConstraints", "auto-constraint inference state", &self.auto_constraints.state_json());
            crate::automation::registry::publish("__brepAutoConstraintsHit", "auto-constraints widget rects", &self.auto_constraints.hits_json());
            crate::automation::registry::publish("__brepStepParts", "STEP parts library panel state", &self.step_parts.state_json());
            crate::automation::registry::publish("__brepStepPartsHit", "STEP parts library widget rects", &self.step_parts.hits_json());
            crate::automation::registry::publish("__brepSelectionFilter", "which entity kinds a viewport click may pick", &self.docs.engine().selection_filter_json());
            crate::automation::registry::publish("__brepSelectionHit", "selection bar widget rects (filter:kind, clear, hide)", &self.selection.hits_json());
            crate::automation::registry::publish("__brepContext", "context action bar state (offers for the selection)", &self.context_bar.state_json());
            crate::automation::registry::publish("__brepContextHit", "context action bar widget rects", &self.context_bar.hits_json());
            crate::automation::registry::publish("__brepModeBarHit", "mode bar widget rects (refsel:*, Sketch:*)", &self.mode_bar.hits_json());
            // The DOCUMENT TABS: the open models, which one is active, and the
            // strip's per-tab hit-rects, so an e2e script can switch and close
            // documents the way a user does.
            crate::automation::registry::publish("__brepDocuments", "open document tabs {active, tabs:[{title,name,dirty}]}", &document_tabs::state_json(&self.docs));
            crate::automation::registry::publish(
                "__brepDocumentsHit",
                "document tab strip widget rects",
                &crate::automation::hit_rects::hits_json(
                    self.document_tab_hits.iter().map(|(key, rect)| (key, rect)),
                ),
            );
            // The boot-time recovery prompt: its entries and its two buttons.
            crate::automation::registry::publish("__brepRecovery", "boot-time recovery prompt entries", &self.recovery.state_json());
            crate::automation::registry::publish("__brepRecoveryHit", "recovery prompt widget rects", &self.recovery.hits_json());
            crate::automation::registry::publish("__brepComponentMove", "assembly component move state", &self.docs.engine().component_move_json());
            crate::automation::registry::publish("__brepSketch", "sketch mode state (session, tool, selection, constraints)", &self.sketch.published_json(self.docs.engine()));
            crate::automation::registry::publish("__brepWireframe", "wireframe toggle", &format!("{}", self.docs.engine().settings.wireframe));
            crate::automation::registry::publish("__brepRefSelect", "reference-selection picker {active, prompt, names}",
                &serde_json::json!({
                    "active": self.docs.engine().ref_select_active(),
                    "prompt": self.docs.engine().ref_select_prompt(),
                    "names": self.docs.engine().ref_select_names(),
                })
                .to_string(),
            );
            // Viewport origin + projected probe points (viewport-local logical
            // px) so the verifier can click precise spots ON the Box and ON the
            // Pin during ref-select mode. Index 0 is a Box top-corner clear of the
            // pin; indices 1..4 are points on the Pin's cylindrical stub that
            // protrudes above the Box top (y=20), on the camera-facing sides — the
            // verifier tries them until one picks "Pin".
            crate::automation::registry::publish("__brepView", "the 3D viewport rect {x,y,w,h} in egui points", &self.viewport.viewport_rect_json());
            // Dock layout snapshot (per-pane visible / rendered) so the verifier
            // can see which side panels are on-screen and, once a user tabs panels
            // together, activate the right tab before asserting on its widgets.
            // `active=false` in sketch / ref-select (the dock is bypassed).
            crate::automation::registry::publish("__brepDock", "dock layout: per-pane visible/rendered", &self.dock.state_json(!sketch && !ref_select));
            crate::automation::registry::publish("__brepProbe", "projected seed-model probe points (viewport-local px) for the verifier",
                &self
                    .docs
                    .engine()
                    .world_to_screen_json(
                        "[[2.0,20.0,2.0],[14.243,22.5,14.243],[16.0,22.5,10.0],\
                          [10.0,22.5,16.0],[10.0,25.0,10.0]]",
                    )
                    .unwrap_or_else(|_| "[]".to_string()),
            );
            crate::automation::registry::publish("__brepPpp", "pixels per point of the surface", &format!("{ppp}"));
            crate::automation::registry::publish("__brepStep", "the rolled-to feature index", &format!("{}", self.docs.engine().history_rollback()));
            crate::automation::registry::publish("__brepParams", "inputParams of the rolled-to feature",
                &self.docs.engine().feature_params_json(self.docs.engine().history_rollback()),
            );
        }

        // Phase 3 of the automation frame (§4.4): reads answer from THIS frame's
        // registry and layout.
        #[cfg(feature = "automation")]
        {
            let queue = self.automation.clone();
            let frame = ctx.cumulative_frame_nr();
            queue.drain_app(
                crate::automation::command::Phase::Read,
                &mut crate::automation::command::Ctx { app: self, egui: &ctx },
                frame,
            );
        }

        // NOTE: the 3D viewport is no longer drawn here — it is a dock tile drawn
        // earlier this frame (normal mode) or drawn directly in the sketch /
        // ref-select branch above. Drawing it before the top-right overlay is what
        // keeps that overlay anchored to the live viewport rect.
    }
}


/// Mirror an engine JSON string to `window.<name>` (wasm/verification only).

/// The seed model handed to the engine at startup: a 3-feature history so the
/// tree / roll / edit are real —
///   0. `P.CU` "Box"  — a 20 mm cube at the origin (spans `[0,20]³`).
///   1. `P.CY` "Pin"  — a r=6, h=30 cylinder (axis +Y) positioned to pierce the
///      cube through its centre in XZ (x=10, z=10) from below (y=-5) to above.
///   2. `B`    "Cut"  — SUBTRACT: `targetSolid = Box`, tools `[Pin]` → the cube
///      with a cylindrical through-hole (the ref-select field is visible for the
///      next slice). Roll-to-step shows: cube → cube+cylinder → subtracted cube.
///
/// This is just the INITIAL document — once handed to `EngineState`, the engine
/// OWNS the mutable history; the app keeps no copy.
pub(crate) fn seed_history_json() -> String {
    serde_json::json!({
        "expressions": "",
        "configurator": {},
        "features": [
            {
                "type": "P.CU",
                "inputParams": {
                    "id": "Box",
                    "sizeX": 20.0, "sizeY": 20.0, "sizeZ": 20.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", "mergeCoplanarFaces": true }
                },
                "persistentData": {}
            },
            {
                "type": "P.CY",
                "inputParams": {
                    "id": "Pin",
                    "radius": 6.0, "height": 30.0,
                    "transform": {
                        "position": [10.0, -5.0, 10.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE", "mergeCoplanarFaces": true }
                },
                "persistentData": {}
            },
            {
                "type": "B",
                "inputParams": {
                    "id": "Cut",
                    "targetSolid": "Box",
                    "boolean": { "operation": "SUBTRACT", "targets": ["Pin"], "mergeCoplanarFaces": true }
                },
                "persistentData": {}
            }
        ]
    })
    .to_string()
}