frust-ui 0.5.2

Frust: a Rust-native, mobile-first declarative UI framework; the facade crate application code depends on.
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
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
//! Back-press ⇄ navigator glue (predictive-back + facade auto-wiring): the
//! facade is the only crate seeing both `frust-widgets`'
//! [`NavigatorController`] and `frust-reactive`'s back-press source, mirroring
//! [`router_glue`](crate::router_glue) — `frust-widgets` stays reactive-free,
//! `frust-reactive` navigator-free.
//!
//! # The Android back contract
//!
//! Shell delivers a hardware/gesture back press → framework attempts an async
//! back → framework maintains a "handles back" boolean the shell reads, so a
//! *root-level* press falls through to the platform (activity finish). This
//! module is the framework half: a press is consumed exactly once and routed
//! through [`NavigatorController::request_back`] — which applies the top page's
//! `BackPolicy` (`Pop` pops, `DismissAnimated` fires the overlay's dismiss
//! signal, `Veto` swallows it) — never a bare [`pop`](NavigatorController::pop).
//! "Handles back" reads [`back_interest`](NavigatorController::back_interest),
//! not [`can_pop`](NavigatorController::can_pop), so a dismissable/veto overlay
//! at the *root* claims the press ahead-of-time (predictive-back parity) instead
//! of exiting the app.
//!
//! # Two entry points, one consumption source
//!
//! [`auto_wire`], called from the facade's [`navigator`](crate::navigator)
//! wrapper every rebuild (back handling with ZERO back-specific app code), and
//! the explicit [`BackHandler`]/[`attach_back_handler`], constructed in
//! `Component::init` and driven by [`track`](BackHandler::track) from every
//! `Component::build` (Huddle's shape). Both funnel through one process-wide
//! (UI-thread-affine) [`SHARED`] marker, so a press is consumed **exactly
//! once**: whichever entry point runs first in a rebuild consumes it, the other
//! sees the same already-consumed count and no-ops — never a double-pop.
//!
//! # R44-back: arbitration across more than one navigator
//!
//! An app with a root [`overlay_host`](crate::overlay_host) wires **two**
//! navigators — the host and the navigator inside it — and both want the press.
//! `frust-reactive`'s live-provider slot stays single-registrant (see
//! `frust_reactive::back`); this module owns that registration and multiplexes:
//!
//! > **R44-back — a root overlay host outranks every plain navigator; among
//! > [`Role::Navigator`] peers the innermost (last-wired) ranks first, LIFO —
//! > mirroring Android's `OnBackPressedDispatcher`; a back press goes to the
//! > first registrant reporting
//! > [`back_interest()`](NavigatorController::back_interest)` == true`.**
//!
//! [`SharedBack::registrants`] is that ordered list, sorted by ([`Role`], wire
//! sequence): build order among hosts, *reversed* among navigators so the
//! innermost wins. **Rank comes from the call site, not wire timing** —
//! [`auto_wire_overlay_host`] registers [`Role::Host`], every other entry point
//! [`Role::Navigator`] — because both *when* and *how often* a controller wires
//! genuinely vary: a [`BackHandler`] built in `Component::init` wires before any
//! view exists, and Huddle's documented pattern wires one controller **twice in
//! one build pass** (`state.back.track()` beside
//! `frust::navigator(&controller, …)`), so neither first-wire order nor "one
//! wire per pass" is a premise anything here may rest on. `handles_back`/the
//! live provider answer `any(interest)`, and a consumed press goes to the
//! *first* registrant with interest — so one registrant (or a host with no
//! overlays, `compute_back_interest` `false` at depth 1) behaves exactly as if
//! arbitration did not exist.
//!
//! ## Releasing a navigator that went away
//!
//! A navigator that goes away (a screen with its own nested navigator, popped)
//! must stop claiming presses and release its controller clone. Two rules, in
//! priority order:
//!
//! 1. **Mounted is live.** [`NavigatorController::is_mounted`] is exact (the
//!    navigator's `View::build`/`teardown` write it), so a *mounted* registrant
//!    is in the retained tree by definition and is never pruned, however the
//!    wire sequence looks — the load-bearing half: a root overlay host is
//!    mounted from its own `build`, which runs before its page builder and hence
//!    before the inner navigator wires at all.
//! 2. **The one-cycle rule, for registrants never mounted.** A wire from an
//!    already-registered controller ends a window; an unmounted registrant that
//!    did not wire within it is dropped — the one case rule 1 cannot see (a
//!    `BackHandler` whose navigator view never made it into the tree).
//!
//! **Rule 2 must not be trusted for a mounted navigator**: it infers a build
//! cycle from a repeat wire, and the double-wire-per-pass pattern above breaks
//! that inference (the second wire of one pass looks exactly like the first of
//! the next). Before rule 1, that inference pruned the root overlay host
//! mid-pass and re-created the root-modal double-claim bug.
//!
//! ## Reachability is upstream of arbitration, by design (R23)
//!
//! Ranking decides who wins *among the claimants*, never who may claim. A
//! navigator input cannot reach — one nested inside a page the outer navigator
//! has covered — reports `back_interest() == false` at the source:
//! `frust-widgets` gates it on the hosting page being in the host navigator's
//! `input_routed_pages()` (rule **R23**: navigator reach follows input routing,
//! exactly; see `frust_widgets::NavigatorController::back_interest`). So nothing
//! here filters on visibility and there is **no second notion of reachability**
//! to keep in sync with the widget's — load-bearing for innermost-first ranking,
//! since an off-screen innermost navigator would otherwise outrank the one the
//! user is actually looking at and swallow every press. Reach says *whether* a
//! navigator is in the running, rank *which* of those gets it.
//!
//! # Timing: the live provider closes the stale window
//!
//! Wiring runs during a rebuild's *build* pass, **before** the navigator's
//! `apply_ops` publishes the new stack depth, so the polled [`set_handles_back`]
//! flag lags a stack change by one frame — and a frame gate skipping the settle
//! frame lets that stale value persist. So the wiring also registers a live
//! provider ([`set_can_pop_provider`]) reading `controller.back_interest()`,
//! which `frust_reactive::handles_back` prefers to the flag: it reads CURRENT
//! interest at press time, after `apply_ops` published it. UI-thread-affine (it
//! reads an `Rc`-backed controller through [`SHARED`]); `frust_reactive::back`'s
//! module docs carry the source-side contract.

use std::cell::RefCell;
use std::rc::Rc;

use frust_reactive::{CanPopRegistration, back_presses, set_can_pop_provider, set_handles_back};
use frust_widgets::{NavigatorController, NavigatorId};
use reactive_graph::traits::{Get, GetUntracked};

thread_local! {
    /// The process-wide (UI-thread-affine) back-press wiring shared by BOTH the
    /// automatic [`navigator`](crate::navigator) path and the explicit
    /// [`BackHandler`]. A single shared marker is the "single consumption
    /// source" that makes an auto-wired `navigator()` and a manual
    /// `BackHandler` on the same controller consume a press EXACTLY once — no
    /// double-pop — and a single ordered registrant list is what arbitrates a
    /// press across a root overlay host and the navigator inside it (R44-back;
    /// see the module docs).
    ///
    /// UI-thread-affine because every [`Registrant`] holds an `Rc`-backed
    /// `NavigatorController` (`!Send`), exactly like frust-reactive's live
    /// provider slot it feeds.
    static SHARED: RefCell<SharedBack> = const { RefCell::new(SharedBack::new()) };
}

/// What a registrant *is*, which is what R44-back ranks it by — taken from the
/// facade entry point that wired it, never inferred from wire timing.
///
/// `Ord` is the arbitration order: [`Host`](Self::Host) sorts first.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
enum Role {
    /// A root [`overlay_host`](crate::overlay_host). Its overlays are drawn over
    /// every piece of chrome, including any inner navigator, so an open one owns
    /// the back press outright — R44-back's host-outranks-navigator half.
    Host,
    /// Any other wired navigator: [`navigator`](crate::navigator)'s auto-wiring
    /// or an explicit [`BackHandler`].
    Navigator,
}

/// One wired navigator in [`SharedBack::registrants`] — the unit R44-back
/// arbitrates over. The closures hold a controller clone, so a registrant keeps
/// its navigator's op queue alive until it is pruned.
struct Registrant {
    /// Which controller this entry stands for, so a re-wire refreshes it in
    /// place instead of appending a duplicate.
    id: NavigatorId,
    /// This entry's arbitration rank (see [`Role`]). Sticky-upgrades to
    /// [`Role::Host`]: a controller wired *once* as an overlay host is one, even
    /// on a re-wire that names it through a different entry point.
    role: Role,
    /// The wire sequence number of this entry's FIRST wire — the tiebreak within
    /// a role, so two navigators of equal rank keep build order.
    birth: u64,
    /// The wire sequence number of this entry's most recent refresh; the
    /// one-cycle prune compares against it (see [`refresh_interest`]).
    seq: u64,
    /// `controller.is_mounted()` — is this navigator in the retained tree right
    /// now? A `true` here vetoes the one-cycle prune (see the module docs'
    /// release rules).
    mounted: Box<dyn Fn() -> bool>,
    /// `controller.back_interest()` — does this navigator claim the next press?
    /// Already `false` for a navigator whose hosting page input cannot reach
    /// (the R23 gate in `frust-widgets`; see the module docs), which is why
    /// nothing here filters on visibility.
    interest: Box<dyn Fn() -> bool>,
    /// `controller.request_back()` — deliver the press to this navigator,
    /// honoring its top page's `BackPolicy`. An `Rc` rather than a `Box` so
    /// [`route_back`] can clone it out and call it with **no** [`SHARED`] borrow
    /// outstanding.
    request_back: Rc<dyn Fn()>,
}

impl Registrant {
    /// The sort key R44-back orders the arbitration list by: rank first
    /// ([`Role`], `Host` sorts ahead of every `Navigator`), then within
    /// `Role::Navigator` **innermost-first** (highest `birth` — a nested
    /// navigator always wires after the navigator hosting it, so the highest
    /// `birth` among `Navigator` peers is the innermost one); `Role::Host`
    /// peers keep first-wire order (`birth` ascending), unchanged.
    ///
    /// Innermost-first is what lets a nested navigator take the press at all:
    /// ordering every rank by first wire (`birth` ascending) would leave an
    /// outer navigator at depth > 1 — exactly the case where a pushed page hosts
    /// a nested navigator — permanently outranking the nested navigator inside
    /// it, so back would pop the outer stack (discarding the whole page the
    /// nested navigator lives on) instead of reaching in. `Role::Host` peers
    /// keep first-wire order: R44-back only ever requires Host to rank above
    /// every Navigator, never a particular order among multiple hosts.
    fn key(&self) -> (Role, u64) {
        match self.role {
            Role::Host => (self.role, self.birth),
            // `u64::MAX - birth`: ascending sort on this puts the HIGHEST
            // birth (innermost, wired last) first among `Navigator` peers —
            // LIFO, mirroring Android's `OnBackPressedDispatcher`.
            Role::Navigator => (self.role, u64::MAX - self.birth),
        }
    }
}

/// The shared back state behind [`SHARED`] (see its docs).
struct SharedBack {
    /// The last back-press count consumed by *any* entry point; `None` until
    /// the first observation. A press up to this count has already been routed
    /// through `request_back`, so a second entry point (or a re-run rebuild)
    /// observing the same count does not re-fire (the `RouterDeepLinks`
    /// consumed-marker pattern, shared across both back entry points).
    consumed: Option<u64>,
    /// Every wired navigator, sorted by [`Registrant::key`] — [`Role::Host`]
    /// first (build order among hosts, unchanged), then [`Role::Navigator`]
    /// peers innermost-first (LIFO: last-wired sorts first, the reverse of
    /// build order) — the R44-back arbitration list. Kept sorted on every
    /// wire, so a registrant's position never depends on how often its
    /// controller wires per pass; an unmounted registrant that misses a
    /// build cycle is pruned (see [`refresh_interest`]). The live provider
    /// (below) reads through this list, so a press is decided against the
    /// CURRENT navigators' interest.
    registrants: Vec<Registrant>,
    /// Monotonic wire counter stamped into [`Registrant::birth`]/
    /// [`Registrant::seq`]; ordering and the one-cycle prune are both expressed
    /// against it.
    seq: u64,
    /// The live can-pop provider registration, made once on the first wire and
    /// kept for the process lifetime. Its closure reads
    /// [`registrants`](Self::registrants) live, so `handles_back()` answers
    /// against the current navigators with no one-frame lag (see the module
    /// docs' timing note). `None` until the first wire registers it.
    provider: Option<CanPopRegistration>,
}

impl SharedBack {
    const fn new() -> Self {
        Self {
            consumed: None,
            registrants: Vec::new(),
            seq: 0,
            provider: None,
        }
    }
}

/// Whether **any** wired navigator claims the next back press — the value both
/// the live provider and the polled `handles_back` flag publish.
///
/// Only ever called with no outstanding [`SHARED`] borrow: an `interest` probe
/// reads an `Rc<Cell<bool>>` on its controller and never re-enters this module.
fn any_interest() -> bool {
    SHARED.with(|shared| shared.borrow().registrants.iter().any(|r| (r.interest)()))
}

/// Register (or refresh) `controller` in the R44-back arbitration list at
/// `role`'s rank and republish the polled `handles_back` fallback flag,
/// registering the live provider once. Called on every wire from both entry
/// points ([`auto_wire`]/[`auto_wire_overlay_host`] and
/// [`BackHandler::new`]/[`track`](BackHandler::track)).
///
/// Ordering and pruning are the whole mechanism — see the module docs' R44-back
/// section. In short: the entry is (re-)inserted at its ([`Role`], first-wire)
/// sort position, so neither *when* nor *how often* a controller wires can move
/// it; and a repeat wire drops every **unmounted** registrant that did not wire
/// since this controller's previous wire, a mounted one being in the tree by
/// definition.
///
/// # Panics
///
/// The first call registers the live provider via [`set_can_pop_provider`],
/// which panics off the UI thread — always the case here (a rebuild / a
/// `Component::init` runs on the UI thread).
fn refresh_interest<State: 'static>(controller: &NavigatorController<State>, role: Role) {
    let id = controller.id();
    let mounted_probe = controller.clone();
    let interest_probe = controller.clone();
    let request_probe = controller.clone();
    SHARED.with(|shared| {
        let mut shared = shared.borrow_mut();
        shared.seq += 1;
        let seq = shared.seq;
        // Carry the existing entry's identity forward (rank sticky-upgrades to
        // `Host`, first-wire order is preserved), and prune against its previous
        // wire while it is still in the list.
        let (role, birth) = match shared.registrants.iter().position(|r| r.id == id) {
            Some(index) => {
                let previous = shared.registrants[index].seq;
                let carried = (
                    // `Host` sorts first, so `min` IS the sticky upgrade: a
                    // controller ever wired as an overlay host stays one.
                    shared.registrants[index].role.min(role),
                    shared.registrants[index].birth,
                );
                // A repeat wire closes a window. Any registrant that neither
                // wired within it nor is currently mounted is no longer in the
                // tree — drop it rather than let it keep claiming presses. The
                // mounted probe is a `Cell` read on the registrant's controller
                // and never re-enters this module, so calling it under the
                // `SHARED` borrow is safe (same contract as `any_interest`).
                shared
                    .registrants
                    .retain(|r| r.id == id || r.seq >= previous || (r.mounted)());
                carried
            }
            // First wire: this seq is the entry's permanent tiebreak.
            None => (role, seq),
        };
        let entry = Registrant {
            id,
            role,
            birth,
            seq,
            mounted: Box::new(move || mounted_probe.is_mounted()),
            interest: Box::new(move || interest_probe.back_interest()),
            request_back: Rc::new(move || request_probe.request_back()),
        };
        // Re-insert at the sort position, never "wherever it already was": that
        // is what keeps arbitration order a function of what a registrant IS
        // (its role and first wire) rather than of the wire sequence.
        shared.registrants.retain(|r| r.id != id);
        let at = shared
            .registrants
            .iter()
            .position(|r| r.key() > entry.key())
            .unwrap_or(shared.registrants.len());
        shared.registrants.insert(at, entry);
        if shared.provider.is_none() {
            // Register the stable live provider ONCE. It reads whatever
            // registrants are currently wired from `SHARED`, so a new
            // controller joining the list needs no re-registration.
            shared.provider = Some(set_can_pop_provider(Box::new(any_interest)));
        }
    });
    // Refresh the polled fallback flag (the live provider is authoritative; this
    // only keeps the no-provider fallback roughly in sync — see the module docs).
    set_handles_back(any_interest());
}

/// Deliver a consumed back press under **R44-back**: to the first registrant in
/// arbitration order (hosts first, then plain navigators innermost-first) that
/// claims it via `back_interest()`.
///
/// No visibility/reachability filter here on purpose: `back_interest()` is
/// already gated on the claimant's hosting page being input-routed (see the
/// module docs' R23 note), so a navigator the user cannot reach is never in this
/// list's answer to begin with.
///
/// `fallback` is the controller whose wire consumed the press, used only when
/// *no* registrant claims one — which preserves the pre-arbitration behaviour
/// exactly (a press was always delivered to the wiring controller). Delivery
/// there is a no-op by construction: `back_interest()` is false only at depth 1
/// with a `BackPolicy::Pop` top page, and `request_back` on that stack pops
/// nothing.
fn route_back<State: 'static>(fallback: &NavigatorController<State>) {
    // The claimant's `request_back` is CLONED OUT of the list (that is what the
    // `Rc<dyn Fn()>` is for) and called with NO `SHARED` borrow outstanding.
    // `request_back` only enqueues an op or bumps a dismiss signal today, but it
    // is the one call here that reaches app-reachable machinery, and a re-entry
    // into this module would panic on the already-borrowed `RefCell` — so the
    // borrow ends before the call rather than that staying load-bearing. (The
    // `interest` probe above is a plain `Cell` read, as `any_interest` notes.)
    let claimant = SHARED.with(|shared| {
        let shared = shared.borrow();
        shared
            .registrants
            .iter()
            .find(|r| (r.interest)())
            .map(|r| Rc::clone(&r.request_back))
    });
    match claimant {
        Some(request_back) => request_back(),
        None => fallback.request_back(),
    }
}

/// Consume any new back press against the shared marker, routing it through
/// [`NavigatorController::request_back`] (applies the top page's `BackPolicy`)
/// on the navigator [`route_back`] arbitrates to. The tracked read of the
/// back-press counter subscribes THIS rebuild, so a later `push_back_press`
/// wakes it (State & Reactivity: the track-per-rebuild contract).
///
/// The shared marker is the single consumption source (see the module docs): if
/// both entry points run in the same rebuild on the same controller, the first
/// fires `request_back` and the second no-ops on the already-consumed count.
///
/// `controller` is the *wiring* controller, not necessarily the recipient —
/// under R44-back the press goes to the first registrant claiming it, and
/// `controller` is only the fallback when none does.
fn consume_back<State: 'static>(controller: &NavigatorController<State>) {
    // Tracked read — subscribes the rebuild to the back-press counter.
    let count = back_presses().count.get();
    let fire = SHARED.with(|shared| {
        let mut shared = shared.borrow_mut();
        match shared.consumed {
            // A fresh process/marker: seed to the current count WITHOUT firing,
            // so a press delivered before any handler existed does not trigger a
            // spurious back on the first wire.
            None => {
                shared.consumed = Some(count);
                false
            }
            // Already caught up — a re-run rebuild or the second entry point.
            Some(prev) if prev == count => false,
            // A new press (a burst collapses to one `request_back`: catch up to
            // the current depth, don't replay each event — the back semantics).
            Some(_) => {
                shared.consumed = Some(count);
                true
            }
        }
    });
    if fire {
        route_back(controller);
    }
}

/// Seed the shared consumption marker to the current back-press count if it is
/// not seeded yet, so a press delivered before a [`BackHandler`] existed does
/// not trigger a spurious `request_back` on the first [`track`](BackHandler::track).
/// Idempotent (only-if-unseeded), so it composes with a `navigator()` that
/// already seeded the marker on an earlier rebuild.
fn seed_consumed() {
    let count = back_presses().count.get_untracked();
    SHARED.with(|shared| {
        let mut shared = shared.borrow_mut();
        if shared.consumed.is_none() {
            shared.consumed = Some(count);
        }
    });
}

/// Auto-wire back handling for `controller`: the entry point the
/// facade's [`navigator`](crate::navigator) wrapper calls on every rebuild.
/// Consumes a new back press (routing it through `request_back`) and refreshes
/// the `handles_back` interest — so an app using `frust::navigator` gets the
/// full Android back contract (overlay dismiss → pop → app exit) with ZERO
/// back-specific app code, and with no double-pop against a manual
/// [`BackHandler`] on the same controller (see the module docs).
///
/// # Panics
///
/// Runs during a rebuild's build pass; the first call registers the live
/// provider, which panics off the UI thread (always the UI thread here).
pub(crate) fn auto_wire<State: 'static>(controller: &NavigatorController<State>) {
    consume_back(controller);
    refresh_interest(controller, Role::Navigator);
}

/// [`auto_wire`] for a root [`overlay_host`](crate::overlay_host): identical,
/// except the registrant takes [`Role::Host`] — the rank that puts an open
/// root overlay ahead of the inner navigator whatever the wire sequence looks
/// like (R44-back; see the module docs).
///
/// # Panics
///
/// As [`auto_wire`].
pub(crate) fn auto_wire_overlay_host<State: 'static>(controller: &NavigatorController<State>) {
    consume_back(controller);
    refresh_interest(controller, Role::Host);
}

/// A [`NavigatorController`] wired to the process-wide back-press source (see
/// the module docs) — the **explicit** back-wiring surface predating the
/// automatic [`navigator`](crate::navigator) auto-wiring.
///
/// App code using `frust::navigator` no longer needs this: back handling is
/// automatic. It stays fully supported for apps that want an explicit handle
/// (Huddle constructs one), and now shares the same single consumption source
/// and `request_back`/`back_interest` routing as the automatic path — so
/// constructing a `BackHandler` *and* calling `frust::navigator` on the same
/// controller still consumes each press exactly once.
///
/// Construct once with [`attach_back_handler`] (or [`BackHandler::new`]) —
/// typically from `Component::init`, storing the result in `Component::State` —
/// then call [`track`](Self::track) from every `Component::build`.
pub struct BackHandler<State: 'static> {
    controller: NavigatorController<State>,
}

impl<State: 'static> BackHandler<State> {
    /// Wire `controller` to the back-press source. Seeds the shared consumption
    /// marker to the current back-press count (so a press delivered before this
    /// handler existed does not trigger a spurious back on the first
    /// [`track`](Self::track)), publishes the initial `handles_back` fallback
    /// flag, and registers the live `back_interest` provider (see the module
    /// docs' timing note).
    ///
    /// Call this once per controller (e.g. from `Component::init`) — from the UI
    /// thread, since the provider slot is UI-thread-affine (it reads the
    /// `Rc`-backed controller). A `Component::init` always runs on the UI thread.
    ///
    /// **Registration position does not depend on when you construct this**
    /// (see the module docs' R44-back section): a handler built in
    /// `Component::init` wires before any view exists, and a root
    /// [`overlay_host`](crate::overlay_host) still outranks the navigator it
    /// wraps — the host's rank comes from its own entry point, not from wire
    /// order. Where you call [`track`](Self::track) from is likewise free.
    pub fn new(controller: NavigatorController<State>) -> Self {
        seed_consumed();
        refresh_interest(&controller, Role::Navigator);
        Self { controller }
    }

    /// Consume a new back press (routing it through
    /// [`request_back`](NavigatorController::request_back)) and refresh the
    /// framework's `handles_back` interest from the current stack. Call from
    /// every `Component::build`.
    ///
    /// Shares the single consumption source with the automatic
    /// [`navigator`](crate::navigator) path (see the module docs): a rebuild
    /// re-run that observes the same already-consumed count neither re-fires nor
    /// double-counts, and a `frust::navigator` on the same controller in the
    /// same rebuild cannot double-pop.
    pub fn track(&self) {
        consume_back(&self.controller);
        refresh_interest(&self.controller, Role::Navigator);
    }

    /// The wired controller — hand it to
    /// [`navigator`](frust_widgets::navigator), or drive it directly.
    pub fn controller(&self) -> &NavigatorController<State> {
        &self.controller
    }
}

/// Convenience constructor equivalent to [`BackHandler::new`] — see its docs and
/// [`RouterDeepLinks`](crate::RouterDeepLinks)/[`router_with_deep_links`](crate::router_with_deep_links)
/// for the mirrored API shape.
///
/// Note that back handling is **automatic** for any app using
/// [`frust::navigator`](crate::navigator); this explicit surface is
/// only needed when an app wants a handle it drives directly (e.g. Huddle).
///
/// ```no_run
/// use frust::{
///     AnyView, BackHandler, Component, NavigatorController, any, attach_back_handler,
///     navigator, text,
/// };
///
/// #[derive(Default)]
/// struct App;
///
/// struct AppState {
///     back: BackHandler<AppState>,
/// }
///
/// impl Component for App {
///     type State = AppState;
///
///     fn init(&self) -> AppState {
///         let nav: NavigatorController<AppState> = NavigatorController::new();
///         AppState {
///             back: attach_back_handler(nav),
///         }
///     }
///
///     fn build(&self, state: &mut AppState) -> AnyView<AppState> {
///         // Called every rebuild: consumes a new back press (via `request_back`)
///         // and keeps the framework's handles-back interest in sync. The
///         // `frust::navigator` call auto-wires the SAME controller — one press
///         // still pops exactly once (shared consumption source).
///         state.back.track();
///         let controller = state.back.controller();
///         any(navigator(controller, || any(text("home"))))
///     }
/// }
///
/// frust::app!(App);
/// # fn main() {}
/// ```
pub fn attach_back_handler<State: 'static>(
    controller: NavigatorController<State>,
) -> BackHandler<State> {
    BackHandler::new(controller)
}

#[cfg(test)]
mod tests {
    use super::*;
    use frust_core::{AnyView, RenderRoot, any};
    use frust_reactive::{
        ReactiveRuntime, clear_can_pop_provider, handles_back, push_back_press, set_handles_back,
    };
    use frust_widgets::{
        BackPolicy, NavigatorController, NavigatorView, PushOptions, navigator as raw_navigator,
        overlay_host as raw_overlay_host,
    };
    use std::sync::{Arc, Mutex};

    /// Serializes every test in this module: they all touch `frust-reactive`'s
    /// process-wide back-press counter / `handles_back` flag / live-provider slot
    /// AND this module's `SHARED` marker, so concurrent runs would race the
    /// shared counter (one test's `push_back_press` advancing it under another's
    /// feet). `reset()` (below) additionally clears the per-thread state a reused
    /// harness thread would otherwise carry between tests.
    static TEST_LOCK: Mutex<()> = Mutex::new(());

    /// Reset the per-thread wiring so each test starts clean: force-clear
    /// frust-reactive's live provider, drop the shared marker/interest/provider,
    /// and reset the polled flag. Call at the top of every test (after taking
    /// [`TEST_LOCK`], under an initialized runtime).
    fn reset() {
        clear_can_pop_provider();
        set_handles_back(false);
        SHARED.with(|shared| *shared.borrow_mut() = SharedBack::new());
    }

    fn page() -> AnyView<()> {
        any(frust_widgets::text("x"))
    }

    /// The build closure type [`RenderRoot::rebuild`] drives, boxed so
    /// [`Harness`] can store it (mirroring `router_glue`'s `AppLogic`).
    type AppLogic = Box<dyn FnMut(&mut ()) -> NavigatorView<()>>;

    /// A `RenderRoot`/app closure driving a controller's `navigator`. The
    /// `wire` closure runs each rebuild BEFORE reconciliation to exercise a back
    /// entry point (the automatic `auto_wire`, an explicit `BackHandler::track`,
    /// or both) exactly as a `Component::build` would.
    struct Harness {
        controller: NavigatorController<()>,
        root: RenderRoot<(), NavigatorView<()>>,
        app: AppLogic,
        wire: Box<dyn FnMut()>,
    }

    impl Harness {
        /// A fresh-controller harness whose per-rebuild wiring runs `wire`
        /// (given a clone of that controller) — the seam each test uses to pick
        /// its back entry point.
        fn new(wire: impl FnMut(&NavigatorController<()>) + 'static) -> Self {
            Self::with_controller(NavigatorController::new(), wire)
        }

        /// As [`new`](Self::new) but drives an EXISTING `controller` — so a test
        /// can share one controller between a `BackHandler` and the navigator
        /// (the manual + auto criterion).
        fn with_controller(
            controller: NavigatorController<()>,
            mut wire: impl FnMut(&NavigatorController<()>) + 'static,
        ) -> Self {
            let app_controller = controller.clone();
            let app: AppLogic = Box::new(move |_: &mut ()| raw_navigator(&app_controller, page));
            let wire_controller = controller.clone();
            let wire: Box<dyn FnMut()> = Box::new(move || wire(&wire_controller));
            let mut harness = Harness {
                controller,
                root: RenderRoot::new(),
                app,
                wire,
            };
            harness.rebuild();
            harness
        }

        fn rebuild(&mut self) {
            // Wire under the build pass, exactly as a Component::build would,
            // then reconcile (which applies the navigator's queued ops).
            (self.wire)();
            self.root.rebuild(&mut self.app, &mut ());
        }

        fn depth(&self) -> usize {
            self.controller.depth()
        }
    }

    /// Criterion 1: an app using the AUTOMATIC `frust::navigator` auto-wiring
    /// (no `BackHandler` in app code) pops one page on a back press. Also
    /// covers criterion 2 (depth 1, no overlay → `handles_back()` false: the
    /// press falls through to the platform).
    #[test]
    fn auto_wire_pops_without_a_backhandler() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let mut h = Harness::new(auto_wire);

        // Criterion 2: at the root (depth 1, no overlay) the framework does NOT
        // handle back — a root-level press bubbles to the platform.
        assert_eq!(h.depth(), 1, "starts at the root page");
        assert!(!handles_back(), "depth 1 + no overlay: handles_back false");

        // Push to depth 2 (a normal opaque push → BackPolicy::Pop).
        h.controller.push(page);
        h.rebuild();
        assert_eq!(h.depth(), 2, "pushed to depth 2");
        assert!(
            handles_back(),
            "poppable stack: handles_back true, same rebuild"
        );

        // Criterion 1: one back press pops one page — with NO BackHandler.
        push_back_press();
        h.rebuild();
        assert_eq!(h.depth(), 1, "auto-wired back press pops one page");
        assert!(
            !handles_back(),
            "back at the root: handles_back false again"
        );
    }

    /// Criterion 3: a `Veto` overlay claims the back press (`handles_back()`
    /// true — predictive-back parity via `back_interest`), the press is
    /// consumed, and the stack is UNCHANGED — the routing-through-`request_back`
    /// (not a bare `pop`) contract. This is the meaningful facade-reachable
    /// form of "depth 1 + Veto overlay": the overlay sits over the root, and
    /// even though a raw `pop()` *would* remove it (the stack is poppable),
    /// `request_back` honors the Veto policy and pops nothing. (A Veto policy on
    /// the depth-1 *root* itself is not expressible through the public push API
    /// — the root is always `BackPolicy::Pop` — and is covered by a
    /// widget-level `compute_back_interest` test.)
    #[test]
    fn veto_overlay_claims_back_but_does_not_pop() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let mut h = Harness::new(auto_wire);

        // Push a transparent Veto overlay over the root.
        h.controller
            .push_with_options(page, PushOptions::transparent().back(BackPolicy::Veto));
        h.rebuild();

        // The overlay claims back ahead-of-time (facade reads `back_interest`).
        assert!(handles_back(), "a Veto overlay claims the back press");

        let before = h.depth();
        // A back press is consumed but Veto swallows it — the stack is unchanged.
        // A bare `pop()` here would have removed the overlay (regression guard
        // for the request_back-not-pop switch).
        push_back_press();
        h.rebuild();
        assert_eq!(
            h.depth(),
            before,
            "Veto consumes the press via request_back: stack unchanged (not popped)"
        );
        assert!(handles_back(), "still claiming back (overlay still on top)");
    }

    /// The EXPLICIT `BackHandler` path still works on its own (regression for
    /// the original surface, now routing through `request_back`): a press
    /// pops one page and `handles_back()` tracks the depth with no settle frame
    /// (the live provider closes the stale-window).
    #[test]
    fn explicit_backhandler_pops_and_tracks_handles_back() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let controller: NavigatorController<()> = NavigatorController::new();
        let back = BackHandler::new(controller.clone());
        // Only the explicit handler drives back here — on the SAME controller the
        // harness's navigator uses (a raw navigator view, no auto-wiring).
        let mut h = Harness::with_controller(controller, move |_c| back.track());

        assert_eq!(h.depth(), 1, "starts at the root");
        assert!(
            !handles_back(),
            "root-level back bubbles: handles_back false"
        );

        h.controller.push(page);
        h.rebuild();
        assert_eq!(h.depth(), 2, "push published to depth immediately");
        assert!(
            handles_back(),
            "poppable stack reports handles_back true on the SAME rebuild, no settle frame"
        );

        push_back_press();
        h.rebuild();
        assert_eq!(h.depth(), 1, "one back press pops one page");
        assert!(
            !handles_back(),
            "root again: handles_back false immediately"
        );

        // A back press at the root is a safe no-op (consumed, pops nothing).
        push_back_press();
        h.rebuild();
        assert_eq!(h.depth(), 1, "pop-at-root is a no-op");

        // After a force-clear the polled fallback flag answers (depth-1 false).
        clear_can_pop_provider();
        assert!(
            !handles_back(),
            "after clear, handles_back reads the polled fallback"
        );
    }

    /// Criterion 4 (regression): a manual `BackHandler` AND the automatic
    /// `navigator()` auto-wiring on the SAME controller consume one press
    /// exactly once — no double-pop. Both run every rebuild (as Huddle does:
    /// `state.back.track()` then `frust::navigator(&controller, ...)`).
    #[test]
    fn manual_backhandler_plus_auto_wire_pops_once() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        // Construct the manual handler first (as an app would, in init).
        let controller: NavigatorController<()> = NavigatorController::new();
        let back = BackHandler::new(controller.clone());

        // The harness's navigator AND both back entry points drive the SAME
        // controller. Each rebuild runs BOTH entry points in Huddle's order: the
        // manual `track()` then the auto-wiring (`c` is the harness controller).
        let mut h = Harness::with_controller(controller, move |c| {
            back.track();
            auto_wire(c);
        });

        // Push to depth 3 so a single-vs-double pop is unambiguous.
        h.controller.push(page);
        h.rebuild();
        h.controller.push(page);
        h.rebuild();
        assert_eq!(h.depth(), 3, "pushed to depth 3");

        // ONE back press: with a shared consumption source this pops exactly one
        // page (depth 2). A double-consumption bug would pop two (depth 1).
        push_back_press();
        h.rebuild();
        assert_eq!(
            h.depth(),
            2,
            "manual + auto share one consumption source: one press pops once"
        );

        // A rebuild with no new press does not re-pop (dedupe).
        h.rebuild();
        assert_eq!(h.depth(), 2, "no new press -> no extra pop");
    }

    // -----------------------------------------------------------------------
    // R44-back — arbitration across a root overlay host and an inner navigator.
    // -----------------------------------------------------------------------

    /// A root `overlay_host` wrapping an inner `navigator`, each auto-wired
    /// where its view is constructed: the host from the app's build pass, the
    /// inner navigator from the host's root-page builder — which runs inside
    /// the host's own reconcile, i.e. strictly later. That *is* the build order
    /// R44-back arbitrates on, so the harness reproduces the real ordering
    /// rather than hand-declaring it.
    struct HostHarness {
        host: NavigatorController<()>,
        inner: NavigatorController<()>,
        root: RenderRoot<(), NavigatorView<()>>,
        app: AppLogic,
    }

    impl HostHarness {
        fn new() -> Self {
            let host: NavigatorController<()> = NavigatorController::new();
            let inner: NavigatorController<()> = NavigatorController::new();
            let app: AppLogic = {
                let host = host.clone();
                let inner = inner.clone();
                Box::new(move |_: &mut ()| {
                    // Outermost: exactly what `frust::overlay_host` does.
                    auto_wire_overlay_host(&host);
                    let inner = inner.clone();
                    raw_overlay_host(&host, move || {
                        // Innermost: exactly what `frust::navigator` does.
                        auto_wire(&inner);
                        any(raw_navigator(&inner, page))
                    })
                })
            };
            let mut harness = Self {
                host,
                inner,
                root: RenderRoot::new(),
                app,
            };
            harness.rebuild();
            harness
        }

        fn rebuild(&mut self) {
            self.root.rebuild(&mut self.app, &mut ());
        }
    }

    /// The R44-back arbitration list, in order — the whitebox view the ordering
    /// and pruning rules are pinned against.
    fn registrant_ids() -> Vec<frust_widgets::NavigatorId> {
        SHARED.with(|shared| shared.borrow().registrants.iter().map(|r| r.id).collect())
    }

    /// **R44-back**: with a root overlay open, the press goes to the HOST even
    /// though the inner navigator is poppable and wired *later*. Without the
    /// rank the last wire would win outright and this press would pop the inner
    /// navigator — a page vanishing under an open modal.
    #[test]
    fn a_root_overlay_takes_the_back_press_from_the_inner_navigator() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let mut h = HostHarness::new();
        // Registration order is build order: the host first, then the navigator
        // its root page builds.
        assert_eq!(
            registrant_ids(),
            vec![h.host.id(), h.inner.id()],
            "outermost first"
        );

        // Both stacks are poppable: the inner navigator has a page pushed, and
        // an overlay sits on the host.
        h.inner.push(page);
        h.rebuild();
        h.host
            .push_with_options(page, PushOptions::transparent().back(BackPolicy::Pop));
        h.rebuild();
        assert_eq!((h.host.depth(), h.inner.depth()), (2, 2));
        assert!(handles_back(), "some registrant claims the press");

        push_back_press();
        h.rebuild();
        assert_eq!(h.host.depth(), 1, "the press went to the root overlay host");
        assert_eq!(
            h.inner.depth(),
            2,
            "and NOT to the inner navigator (the root-modal back bug)"
        );
    }

    /// **The degenerate case, bit for bit.** A host with no overlays sits at
    /// depth 1 with the default `BackPolicy::Pop`, so `compute_back_interest`
    /// is false and it claims nothing — the press falls straight through to the
    /// inner navigator, exactly as before the host existed. This is the
    /// single-navigator (huddle) regression guard.
    #[test]
    fn a_host_with_no_overlay_defers_the_back_press_to_the_inner_navigator() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let mut h = HostHarness::new();
        assert!(
            !handles_back(),
            "two navigators, both at the root: back bubbles to the platform"
        );

        h.inner.push(page);
        h.rebuild();
        assert_eq!(h.host.depth(), 1, "the host stays empty");
        assert!(
            handles_back(),
            "the inner navigator's interest answers for the whole app"
        );

        push_back_press();
        h.rebuild();
        assert_eq!(h.inner.depth(), 1, "the press popped the inner navigator");
        assert_eq!(h.host.depth(), 1, "the empty host was untouched");
        assert!(!handles_back(), "back at the root of both: bubbles again");

        // A press with nothing to do stays a safe no-op (nobody claims it, so it
        // routes to the wiring controller, whose stack cannot pop).
        push_back_press();
        h.rebuild();
        assert_eq!((h.host.depth(), h.inner.depth()), (1, 1));
    }

    /// The predictive-back half of R44-back: an overlay on the host claims the
    /// press even when the inner navigator has nothing to pop. `handles_back`
    /// answers `any(interest)`, not "the last navigator wired" — under the
    /// latter the shell would be told nobody handles back and would *exit the
    /// app* with a root modal open.
    #[test]
    fn a_root_overlay_claims_back_even_with_the_inner_navigator_at_its_root() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let mut h = HostHarness::new();
        h.host
            .push_with_options(page, PushOptions::transparent().back(BackPolicy::Pop));
        h.rebuild();
        assert_eq!((h.host.depth(), h.inner.depth()), (2, 1));
        assert!(
            handles_back(),
            "the root overlay claims the press though the inner navigator cannot pop"
        );

        push_back_press();
        h.rebuild();
        assert_eq!(h.host.depth(), 1, "the press dismissed the root overlay");
        assert!(!handles_back(), "nothing left to claim it");
    }

    /// The one-cycle prune: a navigator that stops wiring (its screen torn down)
    /// is dropped from the arbitration list rather than claiming presses
    /// forever from a stack nothing renders. These controllers are never mounted
    /// (no widget builds them), so the mounted veto never applies and this is
    /// the pure one-cycle path.
    ///
    /// All three controllers here register as plain `Role::Navigator` peers —
    /// despite the `outer`/`inner`/`nested` names, nothing wires one *inside*
    /// another — so this test pins only the birth tiebreak among equal-rank
    /// registrants (innermost/last-wire first), not `Role::Host`-first ranking
    /// (that is
    /// `an_init_registered_backhandler_does_not_outrank_a_later_overlay_host`).
    /// The expected order below is therefore the REVERSE of build order, by
    /// design.
    #[test]
    fn a_navigator_that_stops_wiring_is_pruned_after_one_full_cycle() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let outer: NavigatorController<()> = NavigatorController::new();
        let inner: NavigatorController<()> = NavigatorController::new();
        let nested: NavigatorController<()> = NavigatorController::new();

        // Frame 1: three navigators wire, in build order.
        refresh_interest(&outer, Role::Navigator);
        refresh_interest(&inner, Role::Navigator);
        refresh_interest(&nested, Role::Navigator);
        assert_eq!(
            registrant_ids(),
            vec![nested.id(), inner.id(), outer.id()],
            "innermost/last-wired first: the reverse of build order"
        );

        // Frame 2: the nested navigator's screen is gone — it never wires again.
        refresh_interest(&outer, Role::Navigator);
        refresh_interest(&inner, Role::Navigator);
        assert_eq!(
            registrant_ids(),
            vec![nested.id(), inner.id(), outer.id()],
            "not yet: a full cycle has not elapsed without it"
        );

        // Frame 3: the outer wire now spans a whole cycle in which `nested`
        // never appeared.
        refresh_interest(&outer, Role::Navigator);
        assert_eq!(
            registrant_ids(),
            vec![inner.id(), outer.id()],
            "the departed navigator is pruned, and its controller clone released"
        );

        // Re-wiring an existing registrant never re-orders it.
        refresh_interest(&inner, Role::Navigator);
        refresh_interest(&outer, Role::Navigator);
        refresh_interest(&inner, Role::Navigator);
        assert_eq!(registrant_ids(), vec![inner.id(), outer.id()]);
    }

    // -----------------------------------------------------------------------
    // The two ways a "a repeat wire proves a build cycle" premise breaks — a
    // controller wiring TWICE per pass, and a `BackHandler` wiring from
    // `Component::init` before any view exists.
    // -----------------------------------------------------------------------

    /// The REAL Huddle shape under a root overlay host: the inner navigator is
    /// wired **twice in one build pass** — an explicit `BackHandler` built in
    /// `Component::init` and `track()`ed from the host's page builder, plus the
    /// automatic `navigator()` wiring right beside it
    /// (`examples/huddle/src/lib.rs` does exactly this pair).
    ///
    /// Without the mounted veto, the second wire's one-cycle prune reads the
    /// FIRST wire of the same pass as a cycle boundary and drops the host, which
    /// then re-appends *after* the inner navigator — permanently inverting
    /// arbitration and re-creating the root-modal back bug (a press with a root
    /// modal open popping the page underneath it).
    #[test]
    fn an_overlay_host_survives_an_inner_navigator_wiring_twice_per_pass() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let host: NavigatorController<()> = NavigatorController::new();
        let inner: NavigatorController<()> = NavigatorController::new();
        // `Component::init`: the explicit handler exists before any view does.
        let back = Rc::new(BackHandler::new(inner.clone()));

        let mut app: AppLogic = {
            let host = host.clone();
            let inner = inner.clone();
            Box::new(move |_: &mut ()| {
                // The app's build pass: `frust::overlay_host`.
                auto_wire_overlay_host(&host);
                let inner = inner.clone();
                let back = Rc::clone(&back);
                raw_overlay_host(&host, move || {
                    // The host's page builder — Huddle's own build body, moved
                    // inside the host: `state.back.track()` then
                    // `frust::navigator(&controller, …)`, one pass, one
                    // controller, TWO wires.
                    back.track();
                    auto_wire(&inner);
                    any(raw_navigator(&inner, page))
                })
            })
        };
        let mut root: RenderRoot<(), NavigatorView<()>> = RenderRoot::new();
        root.rebuild(&mut app, &mut ());

        assert_eq!(
            registrant_ids(),
            vec![host.id(), inner.id()],
            "the host outranks the inner navigator despite wiring once to its twice"
        );

        // An overlay over the whole app, and a poppable inner stack under it.
        inner.push(page);
        host.push_with_options(page, PushOptions::transparent().back(BackPolicy::Pop));
        // Two more passes: the ordering must survive repeated double-wiring.
        for _ in 0..2 {
            root.rebuild(&mut app, &mut ());
        }
        assert_eq!((host.depth(), inner.depth()), (2, 2));
        assert_eq!(
            registrant_ids(),
            vec![host.id(), inner.id()],
            "still outermost-first after repeated passes"
        );
        assert!(
            handles_back(),
            "the shell is told the app handles back (a root modal is open)"
        );

        push_back_press();
        root.rebuild(&mut app, &mut ());
        assert_eq!(host.depth(), 1, "the press dismissed the root overlay");
        assert_eq!(
            inner.depth(),
            2,
            "and NOT the page under it (the root-modal back bug)"
        );
    }

    /// The second ordering break: `BackHandler::new` wires from
    /// `Component::init`, which runs before ANY view is constructed — so a
    /// first-wire-order rule alone would give the inner navigator position 0
    /// from frame 1, and no amount of "track from inside the host's page
    /// builder" advice could fix a registration that already happened. Rank
    /// comes from the entry point instead, so the host still sorts first.
    #[test]
    fn an_init_registered_backhandler_does_not_outrank_a_later_overlay_host() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let host: NavigatorController<()> = NavigatorController::new();
        let inner: NavigatorController<()> = NavigatorController::new();

        // `Component::init` — the inner navigator's handler registers FIRST.
        let back = BackHandler::new(inner.clone());
        assert_eq!(registrant_ids(), vec![inner.id()], "init wired it alone");

        // The first `Component::build`: the host wires only now.
        auto_wire_overlay_host(&host);
        assert_eq!(
            registrant_ids(),
            vec![host.id(), inner.id()],
            "the host claims the outermost slot even though it wired second"
        );

        // And a repeat pass keeps it there.
        auto_wire_overlay_host(&host);
        back.track();
        assert_eq!(registrant_ids(), vec![host.id(), inner.id()]);
    }

    /// The mounted veto's other half: it only ever *delays* release. A
    /// navigator whose widget is torn down (its page rebuilt without it) reports
    /// unmounted, so the one-cycle rule drops it and releases the controller
    /// clone the registrant holds.
    ///
    /// `nested` genuinely lives inside `outer`'s own page here, so it wires
    /// after `outer` and — under innermost-first `Role::Navigator` order — sorts
    /// AHEAD of it; that ordering is incidental to this test's own point
    /// (mount-liveness pruning).
    #[test]
    fn a_torn_down_navigator_stops_vetoing_the_prune_and_is_released() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let outer: NavigatorController<()> = NavigatorController::new();
        let nested: NavigatorController<()> = NavigatorController::new();
        // The nested navigator lives inside the outer navigator's root page,
        // until this flag turns it off.
        let show_nested = Rc::new(std::cell::Cell::new(true));
        // The arbitration list as seen MID-PASS, at the moment the outer
        // navigator's page rebuilds — i.e. inside the window a spurious prune
        // opens, when the shell may read `handles_back` or a press may route.
        let mid_pass: Rc<RefCell<Vec<NavigatorId>>> = Rc::new(RefCell::new(Vec::new()));

        let mut app: AppLogic = {
            let outer = outer.clone();
            let nested = nested.clone();
            let show_nested = Rc::clone(&show_nested);
            let mid_pass = Rc::clone(&mid_pass);
            Box::new(move |_: &mut ()| {
                // The outer navigator wires TWICE per pass (Huddle's
                // `track()` + `navigator()` pair), so the one-cycle rule alone
                // would prune the nested navigator on every second wire — the
                // mounted veto is the only reason it survives below.
                auto_wire(&outer);
                auto_wire(&outer);
                let nested = nested.clone();
                let show_nested = Rc::clone(&show_nested);
                let mid_pass = Rc::clone(&mid_pass);
                raw_navigator(&outer, move || {
                    *mid_pass.borrow_mut() = registrant_ids();
                    if show_nested.get() {
                        auto_wire(&nested);
                        any(raw_navigator(&nested, page))
                    } else {
                        page()
                    }
                })
            })
        };
        let mut root: RenderRoot<(), NavigatorView<()>> = RenderRoot::new();
        root.rebuild(&mut app, &mut ());
        assert!(nested.is_mounted(), "the nested navigator is in the tree");
        assert_eq!(registrant_ids(), vec![nested.id(), outer.id()]);

        // While mounted it survives the outer navigator's double wire — the
        // exact sequence the one-cycle rule alone misreads as a build cycle.
        root.rebuild(&mut app, &mut ());
        root.rebuild(&mut app, &mut ());
        assert_eq!(
            registrant_ids(),
            vec![nested.id(), outer.id()],
            "a mounted navigator is in the tree by definition: never pruned"
        );
        assert_eq!(
            *mid_pass.borrow(),
            vec![nested.id(), outer.id()],
            "and it is never MISSING mid-pass either — the window in which a \
             spurious prune would mis-answer handles_back / mis-route a press"
        );

        // Its page rebuilds without it: the widget tears down.
        show_nested.set(false);
        root.rebuild(&mut app, &mut ());
        assert!(!nested.is_mounted(), "teardown dropped the liveness");

        // Now the one-cycle rule reaches it (the outer wire that spans a whole
        // cycle in which the nested navigator never appeared).
        root.rebuild(&mut app, &mut ());
        root.rebuild(&mut app, &mut ());
        assert_eq!(
            registrant_ids(),
            vec![outer.id()],
            "the departed navigator is released, not kept alive by the veto"
        );
    }

    // -----------------------------------------------------------------------
    // Innermost-first: a nested navigator must receive the back press.
    // -----------------------------------------------------------------------

    /// An outer navigator PUSHES a page that hosts a nested navigator (the outer
    /// navigator is at depth > 1 — exactly what makes `compute_back_interest`
    /// true for it too), and the nested navigator's own stack is also poppable.
    /// A back press must reach the INNERMOST (nested) navigator, popping its
    /// stack, and must leave the outer navigator's depth untouched — the reverse
    /// of what plain build-order (outermost-first) arbitration gives, where the
    /// outer navigator, wired first, claims the press and pops the whole page
    /// hosting the nested navigator instead of reaching into it.
    #[test]
    fn a_nested_navigator_inside_a_pushed_page_gets_the_back_press() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let outer: NavigatorController<()> = NavigatorController::new();
        let inner: NavigatorController<()> = NavigatorController::new();

        // The outer navigator's ROOT page is plain — no nested navigator
        // exists at depth 1, so `compute_back_interest` starts false for it
        // (matching the module docs: the bug only appears once the outer
        // navigator itself is poppable).
        let mut app: AppLogic = {
            let outer_c = outer.clone();
            Box::new(move |_: &mut ()| {
                auto_wire(&outer_c);
                raw_navigator(&outer_c, page)
            })
        };
        let mut root: RenderRoot<(), NavigatorView<()>> = RenderRoot::new();
        root.rebuild(&mut app, &mut ());
        assert_eq!(outer.depth(), 1, "outer starts at its own root");
        assert!(
            !handles_back(),
            "root-level, no nested navigator yet: back bubbles"
        );

        // Push a page onto the OUTER navigator that hosts the nested
        // navigator — outer is now at depth 2, so it claims back interest too:
        // the shape the ranking has to arbitrate.
        {
            let inner_for_push = inner.clone();
            outer.push(move || {
                auto_wire(&inner_for_push);
                any(raw_navigator(&inner_for_push, page))
            });
        }
        root.rebuild(&mut app, &mut ());
        assert_eq!(
            outer.depth(),
            2,
            "outer pushed to depth 2: the page hosting the nested navigator"
        );
        assert_eq!(
            inner.depth(),
            1,
            "the nested navigator starts at its own root"
        );

        // Push inside the nested navigator too, so BOTH stacks are poppable —
        // the exact ambiguity R44-back must arbitrate between two
        // `Role::Navigator` peers.
        inner.push(page);
        root.rebuild(&mut app, &mut ());
        assert_eq!((outer.depth(), inner.depth()), (2, 2));
        assert!(handles_back(), "some registrant claims the press");

        push_back_press();
        root.rebuild(&mut app, &mut ());
        assert_eq!(
            inner.depth(),
            1,
            "the back press popped the NESTED navigator's stack"
        );
        assert_eq!(
            outer.depth(),
            2,
            "and left the outer navigator's depth UNCHANGED — a bare \
             build-order (outermost-first) arbitration would instead have \
             popped the outer stack, discarding the whole page the nested \
             navigator lives on"
        );
    }

    // -----------------------------------------------------------------------
    // R23, the converse of innermost-first: a nested navigator whose hosting
    // page input can no longer reach must NOT take the press.
    // -----------------------------------------------------------------------

    /// An outer navigator whose ROOT page hosts a nested navigator, each
    /// auto-wired where its view is constructed (the outer from the app's build
    /// pass, the nested from the page builder the outer runs during its own
    /// reconcile) — the canonical tab/section-stack shape. `cull` sets the outer
    /// navigator's [`cull_covered_builds`], the switch that decides whether the
    /// covered page keeps re-running its builder at all.
    struct NestedHarness {
        outer: NavigatorController<()>,
        nested: NavigatorController<()>,
        root: RenderRoot<(), NavigatorView<()>>,
        app: AppLogic,
    }

    impl NestedHarness {
        fn new(cull: bool) -> Self {
            let outer: NavigatorController<()> = NavigatorController::new();
            let nested: NavigatorController<()> = NavigatorController::new();
            let app: AppLogic = {
                let outer = outer.clone();
                let nested = nested.clone();
                Box::new(move |_: &mut ()| {
                    // Exactly what `frust::navigator` does, outermost first.
                    auto_wire(&outer);
                    let nested = nested.clone();
                    raw_navigator(&outer, move || {
                        auto_wire(&nested);
                        any(raw_navigator(&nested, page))
                    })
                    .cull_covered_builds(cull)
                })
            };
            let mut harness = Self {
                outer,
                nested,
                root: RenderRoot::new(),
                app,
            };
            harness.rebuild();
            harness
        }

        fn rebuild(&mut self) {
            self.root.rebuild(&mut self.app, &mut ());
        }
    }

    /// The outer navigator pushes a page OVER the one hosting the nested
    /// navigator. Input can reach only the outer navigator's top page
    /// (`input_routed_pages`), so back must follow: the press pops the OUTER
    /// stack, and the nested (invisible) stack is untouched.
    ///
    /// Without the R23 reach gate at the source, `route_back`'s
    /// innermost-first `find(|r| interest())` would hand the press to the nested
    /// navigator — the covered page keeps reconciling (the default) or stays
    /// `is_mounted()` (under the cull) either way — popping a stack nobody can
    /// see while the back button appears to do nothing.
    ///
    /// Run under BOTH `cull_covered_builds` settings: they are exactly the two
    /// ways the covered page's builder does or does not keep running, and the
    /// answer must not depend on that.
    #[test]
    fn a_nested_navigator_on_a_covered_page_does_not_take_the_back_press() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));

        for cull in [false, true] {
            reset();
            let mut h = NestedHarness::new(cull);

            // The nested stack is poppable while its page is still current —
            // the innermost-first case, which must keep working (below too).
            h.nested.push(page);
            h.rebuild();
            assert_eq!((h.outer.depth(), h.nested.depth()), (1, 2));
            assert!(
                handles_back(),
                "the nested navigator claims the press while its page is current (cull={cull})"
            );

            // Now push a page over it on the OUTER navigator: the nested
            // navigator's page is covered and routed no input.
            h.outer.push(page);
            h.rebuild();
            assert_eq!((h.outer.depth(), h.nested.depth()), (2, 2));
            // A few idle frames: under `cull_covered_builds(true)` the covered
            // page stops rebuilding entirely here, so this is where a
            // wire-refreshed (rather than live) reachability flag would go stale.
            for _ in 0..3 {
                h.rebuild();
            }
            assert!(
                handles_back(),
                "the outer navigator claims it (cull={cull})"
            );

            push_back_press();
            h.rebuild();
            assert_eq!(
                h.outer.depth(),
                1,
                "the press popped the OUTER stack — the page the user is \
                 actually looking at came off (cull={cull})"
            );
            assert_eq!(
                h.nested.depth(),
                2,
                "and the covered navigator's invisible stack is UNCHANGED \
                 (cull={cull})"
            );

            // Revealed again, the nested navigator takes the next press — the
            // innermost-first behaviour, unregressed, in the same harness.
            push_back_press();
            h.rebuild();
            assert_eq!(
                (h.outer.depth(), h.nested.depth()),
                (1, 1),
                "back reaches the nested navigator again once its page is \
                 current (cull={cull})"
            );
        }
    }

    /// The reach gate is **input routing**, not painting: a *transparent*
    /// overlay pushed on the outer navigator leaves the page below it painted
    /// (`PageVisibility::Visible`) but routes it no input, so the nested
    /// navigator on that page must not take the press either. This is the same
    /// divergence R23 pins for semantics.
    #[test]
    fn a_nested_navigator_under_a_transparent_overlay_does_not_take_the_back_press() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let mut h = NestedHarness::new(false);
        h.nested.push(page);
        h.rebuild();
        h.outer
            .push_with_options(page, PushOptions::transparent().back(BackPolicy::Pop));
        h.rebuild();
        assert_eq!((h.outer.depth(), h.nested.depth()), (2, 2));

        push_back_press();
        h.rebuild();
        assert_eq!(h.outer.depth(), 1, "the overlay came off");
        assert_eq!(
            h.nested.depth(),
            2,
            "the painted-but-inert page's navigator kept its stack"
        );
    }

    // -----------------------------------------------------------------------
    // A design-claim stress test: wiring-order independence between two
    // `Role::Navigator` peers. `Registrant::key`'s own doc states the
    // premise plainly — "a nested navigator always wires after the navigator
    // hosting it, so the highest `birth` among `Navigator` peers is the
    // innermost one" — and the two tests above this section
    // (`an_overlay_host_survives_an_inner_navigator_wiring_twice_per_pass`,
    // `an_init_registered_backhandler_does_not_outrank_a_later_overlay_host`)
    // already prove that premise does NOT hold for wire order in general
    // (`Role::Host` is decoupled from it on purpose), but only for a `Host`
    // vs. a `Navigator`. Nothing pins the analogous case for two `Navigator`
    // peers — this section does. `refresh_interest`/`Role`/`registrant_ids`
    // are crate-private, so this composition cannot be built from an
    // integration test the way the rest of the shell matrix is.
    // -----------------------------------------------------------------------

    /// `inner` gets an explicit [`BackHandler`], built and FIRST wired before
    /// `outer` (its eventual host) has any view at all — the
    /// `Component::init` shape — and `track()`ed every rebuild from then on,
    /// so its earliest `birth` is never dropped by the one-cycle prune even
    /// while its own navigator widget doesn't exist yet (a bare, never-tracked
    /// pre-registration IS pruned before outer's page ever mounts inner for
    /// real, which self-heals the ordering — tried first, and not what this
    /// test pins). The REST of the composition is the honest structural
    /// nesting the shell matrix uses elsewhere: outer's plain root, then a
    /// page it pushes that hosts `inner`'s real navigator. With BOTH
    /// navigators poppable, the innermost-first rule says `inner` must win.
    ///
    /// **Observed vs. designed:** a `Role::Navigator` peer's sort key is
    /// `u64::MAX - birth`, and `birth` never changes after a registrant's
    /// FIRST wire (only `seq` refreshes) — so pinning `inner`'s birth ahead of
    /// `outer`'s gives `inner` the numerically LARGER key, and `route_back`'s
    /// first-match search finds `outer` first. `outer` wins, inverting the
    /// documented "structurally innermost wins" rule for this ordering. This
    /// is a real, reachable divergence between the documented rule (nesting
    /// depth) and its actual implementation (raw wire sequence), not a test
    /// bug — see the `#[ignore]` reason for the acceptance criterion this
    /// pins for future ranking work.
    #[test]
    #[ignore = "pins a design case that FAILS against current ranking: an inner \
                navigator whose explicit BackHandler wires (and keeps tracking) \
                before its outer host's first view exists (the Component::init \
                shape) loses the innermost-first tie-break to the outer \
                navigator instead of winning it — Registrant::key ranks \
                Role::Navigator peers by raw wire sequence (birth), not by \
                structural nesting depth. Expected to start passing once \
                ranking accounts for nesting depth rather than birth order \
                alone; rerun with `cargo test -p frust-ui --lib \
                wiring_order_does_not_flip -- --ignored` to observe the \
                current failure."]
    fn wiring_order_does_not_flip_the_innermost_navigator_when_it_is_still_poppable() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let outer: NavigatorController<()> = NavigatorController::new();
        let inner: NavigatorController<()> = NavigatorController::new();

        // `Component::init`: inner's explicit handler wires FIRST, before
        // outer's own view exists.
        let inner_back = BackHandler::new(inner.clone());
        assert_eq!(registrant_ids(), vec![inner.id()], "inner wired alone");

        let mut app: AppLogic = {
            let outer_c = outer.clone();
            Box::new(move |_: &mut ()| {
                // Tracked every pass, exactly like Huddle's own
                // `state.back.track()` — this is what keeps inner's early
                // birth from ever being pruned as stale.
                inner_back.track();
                auto_wire(&outer_c);
                raw_navigator(&outer_c, page)
            })
        };
        let mut root: RenderRoot<(), NavigatorView<()>> = RenderRoot::new();
        root.rebuild(&mut app, &mut ());
        assert_eq!(outer.depth(), 1, "outer starts at its own root");

        {
            let inner_for_push = inner.clone();
            outer.push(move || {
                auto_wire(&inner_for_push);
                any(raw_navigator(&inner_for_push, page))
            });
        }
        root.rebuild(&mut app, &mut ());
        assert_eq!(outer.depth(), 2, "outer pushed the page hosting inner");

        // The case-5 shape: BOTH navigators poppable.
        inner.push(page);
        root.rebuild(&mut app, &mut ());
        assert_eq!((outer.depth(), inner.depth()), (2, 2));

        push_back_press();
        root.rebuild(&mut app, &mut ());
        assert_eq!(
            inner.depth(),
            1,
            "the structurally-innermost navigator should win the tie \
             regardless of which one registered first"
        );
        assert_eq!(
            outer.depth(),
            2,
            "and the outer stack should stay untouched"
        );
    }

    /// The harmless half of the same stress test: at inner depth 1 (default
    /// `BackPolicy::Pop`, no interest either way), wire order cannot matter
    /// because ranking is never even consulted — `route_back` only compares
    /// registrants that both claim interest, and `inner` claims none here.
    /// Unlike its sibling above, this one is expected to (and does) pass
    /// against unchanged code.
    #[test]
    fn wiring_order_is_irrelevant_when_the_inner_navigator_has_no_interest() {
        let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _rt = ReactiveRuntime::init(Arc::new(|| {}));
        reset();

        let outer: NavigatorController<()> = NavigatorController::new();
        let inner: NavigatorController<()> = NavigatorController::new();

        let inner_back = BackHandler::new(inner.clone());

        let mut app: AppLogic = {
            let outer_c = outer.clone();
            Box::new(move |_: &mut ()| {
                inner_back.track();
                auto_wire(&outer_c);
                raw_navigator(&outer_c, page)
            })
        };
        let mut root: RenderRoot<(), NavigatorView<()>> = RenderRoot::new();
        root.rebuild(&mut app, &mut ());

        {
            let inner_for_push = inner.clone();
            outer.push(move || {
                auto_wire(&inner_for_push);
                any(raw_navigator(&inner_for_push, page))
            });
        }
        root.rebuild(&mut app, &mut ());
        assert_eq!(
            (outer.depth(), inner.depth()),
            (2, 1),
            "outer poppable, inner still at its own root"
        );

        push_back_press();
        root.rebuild(&mut app, &mut ());
        assert_eq!(outer.depth(), 1, "outer popped its own shell page");
    }
}