uzor-desktop 1.5.1

uzor-desktop: winit-based desktop runtime for uzor apps. Implements AppBuilder::run() for native desktop targets.
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
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
//! `Manager` — L4's window-and-event watchdog (formerly `WindowManager`).
//!
//! Owns shared `App` state plus a `HashMap<winit::WindowId, PerWindow>` of
//! per-window state (window/provider/render_state/layout/input).
//! Implements winit's `ApplicationHandler` itself, so [`crate::AppRun::run`]
//! constructs a `Manager` and hands it straight to the event loop.

#[cfg(not(target_arch = "wasm32"))]
use winit::event_loop::{ActiveEventLoop, ControlFlow};

use std::collections::HashMap;

use uzor::core::types::Rect;
use uzor::docking::panels::DockPanel;
use uzor::layout::{LayoutManager, WindowHost};
use uzor::framework::multi_window::WindowSpec;
use uzor_render_hub::{
    RenderBackend, RenderHub, RenderSurfaceFactory, SurfaceSize, WindowRenderState,
    submit_frame, SubmitParams, Compose3DJob, SubmitOutcome,
};
use uzor::layout::window::{WindowDecorations, WindowProvider};

#[cfg(not(target_arch = "wasm32"))]
use uzor_window_desktop::WinitWindowProvider;
#[cfg(not(target_arch = "wasm32"))]
use uzor_window_desktop::event_mapper::EventMapper;
#[cfg(not(target_arch = "wasm32"))]
use winit::event::WindowEvent;
#[cfg(not(target_arch = "wasm32"))]
use winit::window::Window;

use uzor::framework::app::{App, AppConfig, CursorCaptureMode};
use uzor::framework::builder::{AnyFactory, BuildError, BuiltApp, TraySpec};
use uzor::framework::multi_window::{WindowCtx, WindowKey};
use uzor::framework::render_control::RenderControl;

use uzor::framework::frame_profiler::EmaF64;

use crate::scene3d_app::Scene3DFrameSubmission;

// ── HubControl ────────────────────────────────────────────────────────────────

/// Thin adapter that implements `RenderControl` by delegating to `&mut RenderHub`.
struct HubControl<'a> {
    hub: &'a mut RenderHub,
    fps_ema:           f32,
    last_frame_time_ms: f32,
    frame_count:       u64,
}

impl<'a> RenderControl for HubControl<'a> {
    fn active_backend(&self) -> uzor::platform::types::RenderBackend {
        self.hub.active()
    }
    fn available_backends(&self) -> Vec<uzor::platform::types::RenderBackend> {
        self.hub.available_backends()
    }
    fn set_backend(&mut self, b: uzor::platform::types::RenderBackend) {
        let _ = self.hub.set_active(b); // silent no-op if not in pool
    }
    fn fps_limit(&self) -> u32 {
        self.hub.settings().fps_limit
    }
    fn set_fps_limit(&mut self, fps: u32) {
        self.hub.set_fps_limit(fps);
    }
    fn msaa_samples(&self) -> u8 {
        self.hub.settings().msaa_samples
    }
    fn set_msaa_samples(&mut self, n: u8) {
        self.hub.set_msaa(n);
    }
    fn vsync(&self) -> bool {
        self.hub.settings().vsync
    }
    fn set_vsync(&mut self, on: bool) {
        self.hub.set_vsync(on);
    }
    fn measured_fps(&self) -> f32       { self.fps_ema }
    fn last_frame_time_ms(&self) -> f32 { self.last_frame_time_ms }
    fn frame_count(&self) -> u64        { self.frame_count }
}

// ── ManagerError ──────────────────────────────────────────────────────────────

/// Errors emitted by [`Manager`].
#[derive(Debug)]
pub enum ManagerError {
    Build(BuildError),
    Window(String),
    Backend(String),
}

impl std::fmt::Display for ManagerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ManagerError::Build(e)   => write!(f, "build error: {e}"),
            ManagerError::Window(s)  => write!(f, "window provider error: {s}"),
            ManagerError::Backend(s) => write!(f, "backend error: {s}"),
        }
    }
}

impl std::error::Error for ManagerError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ManagerError::Build(e) => Some(e),
            _ => None,
        }
    }
}

// ── PerWindow ─────────────────────────────────────────────────────────────────

/// Per-window state owned by the manager.
///
/// LM owns the logical state (provider, chrome, dock-tree, modals,
/// pointer state).  This struct holds only what stays on the platform
/// side: the raw winit handle (for `request_redraw` and surface
/// re-creation) and the GPU render state (because `WindowRenderState`
/// is wgpu-bound and LM stays platform-agnostic).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) struct PerWindow<P: DockPanel> {
    pub key:             WindowKey,
    pub spec:            WindowSpec,
    pub window:          std::sync::Arc<Window>,
    pub render_state:    WindowRenderState,
    /// Last known cursor position in logical pixels.
    pub last_mouse_pos:  (f64, f64),
    /// Stateful winit → platform event mapper for the app-facing event
    /// stream (feeds `slot.provider.push_platform_event`). Tracks this
    /// window's own cursor position and scale factor so `PointerDown`/`Up`
    /// carry real coordinates and every pointer/touch/scroll coordinate is
    /// normalized to logical pixels — independent of `last_mouse_pos` above,
    /// which drives the LM chrome/dock-separator layer.
    pub event_mapper:    EventMapper,
    pub last_frame:      std::time::Instant,
    pub initialised:     bool,
    pub close_requested: bool,
    /// Baseline repaint cadence for this window (resolved from
    /// `WindowSpec::tick_rate` or `AppConfig::default_tick_rate`).
    pub tick_rate:       uzor::render::TickRate,

    /// Per-region paint schedule state keyed by `RenderRegion::id`.
    /// Populated each frame from `App::regions()`. Empty when the app
    /// uses the legacy single-region (event-driven) path.
    pub region_states: std::collections::HashMap<&'static str, uzor::render::RegionScheduleState>,

    /// Per-region cached `vello::Scene`s. On a region's "due" frame we
    /// clear and rebuild the scene; on a non-due frame we reuse the
    /// cached geometry. Composite step appends all of them into the
    /// main `render_state.scene` before GPU submit so a single draw
    /// call covers the full window.
    pub region_scenes: std::collections::HashMap<&'static str, vello::Scene>,

    /// Active dock-separator drag, if any. Set when the user clicks on a
    /// `dock-sep-N` hit-zone, cleared on mouse-up. Stores the cursor
    /// origin and the separator index so per-frame mouse-moves can call
    /// `panels_mut().drag_separator(idx, delta, w, h)`.
    pub dock_separator_drag: Option<DockSeparatorDrag>,

    /// Whether the LAST frame rendered for this window went through the
    /// 3D compose path (Wave 2, W3D arc plan §1.7) — `true` only for the
    /// one tick after `Manager::scene3d_hook` returned `Some`. Gates
    /// `capture_window_png`'s screenshot-source choice: `render_state
    /// .capture_3d()` stays armed (non-`None`) FOREVER once a window has
    /// ever shown a 3D frame (`set_capture_3d` is never disarmed on a
    /// dimension flip back to 2D — see `tick_window_inner`'s divergence
    /// log), so `capture_3d().is_some()` alone can't tell "was 3D just
    /// drawn" from "3D was drawn at some point in the past, then the app
    /// switched back to 2D." This flag is the actual per-frame truth.
    pub last_frame_was_3d: bool,

    /// Applied OS cursor state. Kept per window so the runtime only calls
    /// winit when the application changes its capture request.
    pub cursor_capture_active: bool,

    pub _phantom: std::marker::PhantomData<P>,
}

/// In-flight dock-separator drag state owned by the manager.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Copy)]
pub(crate) struct DockSeparatorDrag {
    pub sep_idx: usize,
    pub last_x:  f64,
    pub last_y:  f64,
}

// ── PerWindowHost ─────────────────────────────────────────────────────────────

/// Transient `WindowHost` adapter for one `PerWindow`.
///
/// Wraps the winit `Arc<Window>` and the `close_requested` flag so that
/// `LayoutManager::handle_chrome_press` can call host operations without
/// touching winit directly.
#[cfg(not(target_arch = "wasm32"))]
struct PerWindowHost<'a> {
    window:          &'a std::sync::Arc<Window>,
    close_requested: &'a mut bool,
    pending_spawns:  &'a mut Vec<WindowSpec>,
    /// Signals that close_app was requested — caller closes all windows.
    close_app: bool,
}

#[cfg(not(target_arch = "wasm32"))]
impl<'a> WindowHost for PerWindowHost<'a> {
    fn drag_window(&mut self) {
        let _ = self.window.drag_window();
    }

    fn drag_resize_window(&mut self, dir: uzor::platform::types::ResizeDirection) {
        use uzor::platform::types::ResizeDirection as D;
        use winit::window::ResizeDirection as W;
        let wd = match dir {
            D::North     => W::North,
            D::South     => W::South,
            D::East      => W::East,
            D::West      => W::West,
            D::NorthEast => W::NorthEast,
            D::NorthWest => W::NorthWest,
            D::SouthEast => W::SouthEast,
            D::SouthWest => W::SouthWest,
        };
        let _ = self.window.drag_resize_window(wd);
    }

    fn set_minimized(&mut self, on: bool) {
        self.window.set_minimized(on);
    }

    fn set_maximized(&mut self, on: bool) {
        self.window.set_maximized(on);
    }

    fn is_maximized(&self) -> bool {
        self.window.is_maximized()
    }

    fn close_window(&mut self) {
        *self.close_requested = true;
    }

    fn close_app(&mut self) {
        self.close_app = true;
    }

    fn request_spawn_window(&mut self, spec: WindowSpec) {
        self.pending_spawns.push(spec);
    }

    fn request_redraw(&mut self) {
        self.window.request_redraw();
    }
}

// ── Manager ───────────────────────────────────────────────────────────────────

/// L4 window manager — thin winit→LayoutManager event pump.
///
/// Owns the App, the wgpu render hub, and a winit→WindowKey routing map.
/// The single `LayoutManager<P>` lives here too — all window-level state
/// (rect, provider, dock-tree, drag, init flag) is its responsibility,
/// addressed by `WindowKey`.  Render state stays in the per-window slot
/// because it's GPU-tied.
pub struct Manager<A: App<P>, P: DockPanel> {
    pub(crate) app:     A,
    pub(crate) config:  AppConfig,
    pub(crate) backend: RenderBackend,
    pub(crate) hub:     Option<RenderHub>,
    pub(crate) factory: Option<Box<dyn RenderSurfaceFactory>>,
    pub(crate) start:   std::time::Instant,

    /// The one and only LayoutManager. Holds dock tree, separators,
    /// overlays, edges, AND the registered windows (`layout.attach_window`).
    pub(crate) layout: LayoutManager<P>,

    /// 3D dispatch hook (W3D arc plan §1.7, Wave 2) — `None` for every
    /// ordinary `.run()`-started app (zero behavior change);
    /// `crate::builder_run::AppRun3D::run_with_3d` sets it to the
    /// monomorphized owned/retained dispatcher before `Manager::run`. A
    /// bare `fn` pointer (not a boxed closure) so this field can live on
    /// `Manager<A, P>` — which is generic over `A: App<P>` ONLY — without
    /// requiring every instantiation to also satisfy the narrower
    /// `Scene3DApp<P>` bound; only `AppRun3D::run_with_3d`'s own impl
    /// block carries that bound, at the one call site that produces the
    /// function pointer.
    pub(crate) scene3d_hook: Option<fn(&mut A, u32, u32) -> Option<Scene3DFrameSubmission>>,

    /// Per-window state, keyed by `winit::WindowId` for fast event routing.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) windows: HashMap<winit::window::WindowId, PerWindow<P>>,
    /// Window specs queued by the builder + by `App::take_pending_spawn`.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) pending_spawns: Vec<WindowSpec>,
    /// Window keys queued for destruction.
    #[cfg(not(target_arch = "wasm32"))]
    #[allow(dead_code)]
    pub(crate) pending_closes: Vec<WindowKey>,
    /// Optional tray spec — applied once when the first window is created.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) tray_spec: Option<TraySpec>,
    /// Live tray handle kept alive for the manager's lifetime.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) tray: Option<crate::tray::TrayHandle>,

    // ── Agent API plumbing ──
    /// Snapshot + command-channel pair.  `None` until
    /// `enable_agent_api(port)` is called.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) agent_bus: Option<crate::agent::AgentBus>,
    /// Owned axum-server handle.  Dropped at shutdown.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) agent_handle: Option<uzor_agent_api::AgentApiHandle>,

    // ── Frame metrics (EMA, mlc pattern) ──
    pub(crate) fps_ema:           f32,
    /// The actual smoothing tracker behind [`Self::fps_ema`] — see
    /// `frame_profiler::EmaF64`'s own doc comment for why this crate
    /// no longer hand-rolls the `previous * 0.9 + sample * 0.1` formula
    /// inline a second time (deduplicated against the generic named-stage
    /// profiler's identical idiom). `fps_ema` itself stays a plain `f32`
    /// field — every existing reader of it (`RenderControl::measured_fps`,
    /// `HubControl`) is unchanged.
    pub(crate) fps_ema_tracker:   EmaF64,
    pub(crate) last_frame_time_ms: f32,
    pub(crate) frame_count:       u64,
    pub(crate) last_frame_instant: std::time::Instant,
    _phantom: std::marker::PhantomData<P>,
}

impl<A: App<P>, P: DockPanel + Default + 'static> Manager<A, P> {
    pub fn new(
        app: A,
        config: AppConfig,
        backend: RenderBackend,
        hub: Option<RenderHub>,
    ) -> Self {
        Self {
            app,
            config,
            backend,
            hub,
            factory: None,
            start: std::time::Instant::now(),
            layout: LayoutManager::<P>::new(),
            scene3d_hook: None,
            #[cfg(not(target_arch = "wasm32"))]
            windows: HashMap::new(),
            #[cfg(not(target_arch = "wasm32"))]
            pending_spawns: Vec::new(),
            #[cfg(not(target_arch = "wasm32"))]
            pending_closes: Vec::new(),
            #[cfg(not(target_arch = "wasm32"))]
            tray_spec: None,
            #[cfg(not(target_arch = "wasm32"))]
            tray: None,
            #[cfg(not(target_arch = "wasm32"))]
            agent_bus: None,
            #[cfg(not(target_arch = "wasm32"))]
            agent_handle: None,
            fps_ema: 60.0,
            fps_ema_tracker: EmaF64::seeded(60.0),
            last_frame_time_ms: 16.0,
            frame_count: 0,
            last_frame_instant: std::time::Instant::now(),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Construct a `Manager` from a pre-built [`BuiltApp`].
    ///
    /// This is the primary entry point used by [`crate::AppRun::run`].
    ///
    /// **Autodetect** is the default:
    /// - Neither backend nor factory set → resolve a [`RenderFamily`] (see
    ///   below) and call `RenderHub::autodetect(family)`, which probes the
    ///   GPU and selects the best available backend + factory for that family.
    /// - Backend set, factory not set → `RenderHub::fixed(backend)` + factory
    ///   from the hub's pool. An explicit backend always skips family
    ///   resolution entirely (owner decision 2026-07-24 precedence: explicit
    ///   backend beats env override beats builder family beats default).
    /// - Both set → use the caller-supplied backend + factory; wrap backend in
    ///   `RenderHub::fixed` for metrics bookkeeping.
    ///
    /// **`RenderFamily` resolution** (only reached when `built.backend` is
    /// `None`): `uzor_render_hub::resolve_render_family_from_process_env`
    /// applied to `built.render_family` — `UZOR_RENDER_FAMILY` env var (if
    /// set and valid) beats the app builder's own `.render_family(...)`
    /// setting, which beats [`RenderFamily::default`] (`Vello`). Neither
    /// render family is ever auto-promoted over the other — see
    /// `uzor_render_hub::detect`'s own module doc for the full doctrine.
    pub fn from_built(built: BuiltApp<A, P>) -> Self {
        // ── Phase 1: resolve hub, backend, factory ────────────────────────────
        let hub = match (built.backend, built.factory.is_some()) {
            (None, false) => {
                let family = uzor_render_hub::resolve_render_family_from_process_env(built.render_family);
                RenderHub::autodetect(family)
            }
            (Some(b), _) => RenderHub::fixed(b),
            (None, true) => {
                eprintln!(
                    "[uzor-desktop] from_built: factory supplied without backend — \
                     running autodetect; factory may mismatch active backend"
                );
                let family = uzor_render_hub::resolve_render_family_from_process_env(built.render_family);
                RenderHub::autodetect(family)
            }
        };

        let active_backend = hub.active();

        // ── Phase 2: resolve factory ──────────────────────────────────────────
        let factory: Option<Box<dyn RenderSurfaceFactory>> = if let Some(any_factory) = built.factory {
            // Caller explicitly supplied a factory — downcast it.
            downcast_any_factory(any_factory)
        } else {
            // Let the hub produce a fresh factory for the active backend.
            hub.factory_for(active_backend)
        };

        // ── Phase 3: build manager ────────────────────────────────────────────
        let mut mgr = Self::new(built.app, built.config, active_backend, Some(hub));

        // Propagate AppConfig perf settings (msaa, fps_limit, vsync) into
        // the hub. Before this, `AppBuilder::msaa(0)` was a silent no-op:
        // the value stored on AppConfig but never reached the hub, which
        // stayed at its default `msaa_samples=8`. Symptom: any app that
        // explicitly opted out of MSAA still crashed on the first frame
        // when vello Renderer was compiled with area-only AA.
        if let Some(hub) = mgr.hub.as_mut() {
            hub.set_msaa(mgr.config.msaa_samples);
            hub.set_fps_limit(mgr.config.fps_limit);
            hub.set_vsync(mgr.config.vsync);
        }

        if let Some(f) = factory {
            mgr.factory = Some(f);
        }

        if let Some(tray) = built.tray {
            #[cfg(not(target_arch = "wasm32"))]
            mgr.set_tray_spec(tray);
        }
        #[cfg(not(target_arch = "wasm32"))]
        for spec in built.windows {
            mgr.queue_window_spec(spec);
        }
        mgr
    }

    pub fn set_surface_factory(&mut self, factory: Box<dyn RenderSurfaceFactory>) {
        self.factory = Some(factory);
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn set_tray_spec(&mut self, spec: TraySpec) {
        self.tray_spec = Some(spec);
    }

    pub fn backend(&self) -> RenderBackend { self.backend }
    pub fn app_config(&self) -> &AppConfig { &self.config }
    pub fn hub(&self) -> Option<&RenderHub> { self.hub.as_ref() }
    pub fn hub_mut(&mut self) -> Option<&mut RenderHub> { self.hub.as_mut() }

    /// Enable the local agent-API HTTP server on `127.0.0.1:port`.
    ///
    /// Spawns a tokio runtime in a dedicated thread and binds axum.
    /// The server stays alive for the manager's lifetime; dropping the
    /// manager closes it.  Errors only on bind failure (port taken).
    #[cfg(not(target_arch = "wasm32"))]
    pub fn enable_agent_api(&mut self, port: u16) -> std::io::Result<()> {
        let bus = crate::agent::AgentBus::new();
        let control = bus.control();
        let handle = uzor_agent_api::spawn_server(
            control as std::sync::Arc<dyn uzor::layout::agent::AgentControl>,
            port,
        )?;
        self.agent_bus = Some(bus);
        self.agent_handle = Some(handle);
        Ok(())
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn enable_agent_api_with_proxy(
        &mut self,
        port: u16,
        proxy: winit::event_loop::EventLoopProxy<()>,
    ) -> std::io::Result<()> {
        let bus = crate::agent::AgentBus::new();
        bus.set_waker(move || proxy.send_event(()).is_ok());
        let control = bus.control();
        let handle = uzor_agent_api::spawn_server(
            control as std::sync::Arc<dyn uzor::layout::agent::AgentControl>,
            port,
        )?;
        self.agent_bus = Some(bus);
        self.agent_handle = Some(handle);
        Ok(())
    }

    /// Drain queued agent commands and apply them.  Called from
    /// `about_to_wait` so all writes land on the winit thread and on
    /// the same tick they were submitted.
    #[cfg(not(target_arch = "wasm32"))]
    fn drain_agent_commands(&mut self) {
        let mut batch = Vec::new();
        if let Some(bus) = self.agent_bus.as_mut() {
            while let Ok(item) = bus.cmd_rx.try_recv() {
                batch.push(item);
            }
        }
        for (cmd, reply) in batch {
            let result = self.apply_agent_command(cmd);
            let _ = reply.send(result);
        }
        // Pull tick_rate from LM branch into PerWindow so the
        // scheduler in `about_to_wait` honours `SetTickRate`
        // updates that landed this tick.
        let updates: Vec<(winit::window::WindowId, uzor::render::TickRate)> = self.windows
            .iter()
            .filter_map(|(id, pw)| {
                self.layout.window(&pw.key).map(|s| (*id, s.tick_rate))
            })
            .collect();
        for (id, rate) in updates {
            if let Some(pw) = self.windows.get_mut(&id) {
                pw.tick_rate = rate;
            }
        }
    }

    /// Apply one agent command and return a reply.
    ///
    /// First tries [`uzor::layout::agent::LmAgent::try_apply`]; if that
    /// returns `None`, the command needs platform handling (real OS
    /// window spawn / close, true synthetic input that also requests
    /// a window redraw).
    #[cfg(not(target_arch = "wasm32"))]
    fn apply_agent_command(
        &mut self,
        cmd: uzor::layout::agent::Command,
    ) -> uzor::layout::agent::CommandReply {
        use uzor::layout::agent::{Command, CommandReply, LmAgent};

        if let Some(reply) = LmAgent::<P>::try_apply(&mut self.layout, &cmd) {
            // A semantic LM op was handled — kick a redraw on the
            // affected window so the change paints next frame.
            if let Some(window_key) = command_window_key(&cmd) {
                let key = uzor::framework::multi_window::WindowKey::new(window_key);
                if let Some(id) = self.window_id_for(&key) {
                    if let Some(pw) = self.windows.get(&id) {
                        pw.window.request_redraw();
                    }
                }
            }
            return reply;
        }

        // WM-side commands (synthetic input that needs redraw, OS
        // window lifecycle).  We compute the reply, then log a
        // matching `AgentCommand` entry so the agent log mirrors what
        // the LM-side side already records via `LmAgent::log_command`.
        let reply = match cmd.clone() {
            Command::InjectHover { window, x, y } => {
                let key = uzor::framework::multi_window::WindowKey::new(window);
                if !self.layout.window_keys().any(|k| k == &key) {
                    return CommandReply::err("unknown window");
                }
                self.layout.set_current_window(key.clone());
                self.layout.on_pointer_move(x, y);
                if let Some(id) = self.window_id_for(&key) {
                    if let Some(pw) = self.windows.get(&id) { pw.window.request_redraw(); }
                }
                CommandReply::ok()
            }
            Command::InjectClick { window, x, y, button: _ } => {
                let key = uzor::framework::multi_window::WindowKey::new(window);
                if !self.layout.window_keys().any(|k| k == &key) {
                    return CommandReply::err("unknown window");
                }
                self.layout.set_current_window(key.clone());
                // Push synthetic PointerDown platform event so app.on_event
                // resets drag_moved to 0.0.  Without this, a stale drag_moved
                // value from a prior real pointer drag silently blocks the
                // `was_clicked && drag_moved < TAP_SLOP` guard in the app.
                if let Some(slot) = self.layout.window_mut(&key) {
                    slot.provider.push_platform_event(
                        uzor::platform::PlatformEvent::PointerDown {
                            x,
                            y,
                            button: uzor::input::state::MouseButton::Left,
                        },
                    );
                }
                self.layout.on_pointer_move(x, y);
                self.layout.on_pointer_down(x, y);
                // Route synthetic (agent-driven) clicks through the same App
                // dispatch hooks as real clicks so chrome controls / tabs etc.
                // respond to agent-api input too.
                match self.layout.on_pointer_up(x, y) {
                    uzor::layout::PointerUpOutcome::DismissedOverlay(h) => {
                        self.app.on_dismiss(&mut self.layout, h);
                    }
                    uzor::layout::PointerUpOutcome::Click(_id, ev) => {
                        self.app.dispatch_event(&mut self.layout, ev);
                    }
                    uzor::layout::PointerUpOutcome::Unhandled => {}
                }
                if let Some(id) = self.window_id_for(&key) {
                    if let Some(pw) = self.windows.get(&id) { pw.window.request_redraw(); }
                }
                CommandReply::ok()
            }
            Command::InjectScroll { window, dx, dy } => {
                let key = uzor::framework::multi_window::WindowKey::new(window);
                if !self.layout.window_keys().any(|k| k == &key) {
                    return CommandReply::err("unknown window");
                }
                self.layout.set_current_window(key.clone());
                self.layout.on_scroll(dx, dy);
                if let Some(id) = self.window_id_for(&key) {
                    if let Some(pw) = self.windows.get(&id) { pw.window.request_redraw(); }
                }
                CommandReply::ok()
            }
            Command::InjectDrag { window, x1, y1, x2, y2, steps } => {
                let key = uzor::framework::multi_window::WindowKey::new(window);
                if !self.layout.window_keys().any(|k| k == &key) {
                    return CommandReply::err("unknown window");
                }
                self.layout.set_current_window(key.clone());
                // Push synthetic PointerDown so app.on_event resets drag_moved.
                if let Some(slot) = self.layout.window_mut(&key) {
                    slot.provider.push_platform_event(
                        uzor::platform::PlatformEvent::PointerDown {
                            x: x1,
                            y: y1,
                            button: uzor::input::state::MouseButton::Left,
                        },
                    );
                }
                self.layout.on_pointer_move(x1, y1);
                self.layout.on_pointer_down(x1, y1);
                // Interpolated moves from (x1,y1) → (x2,y2).
                let steps = steps.max(1);
                for i in 1..=steps {
                    let t = i as f64 / steps as f64;
                    let mx = x1 + (x2 - x1) * t;
                    let my = y1 + (y2 - y1) * t;
                    self.layout.on_pointer_move(mx, my);
                }
                self.layout.on_pointer_up(x2, y2);
                if let Some(id) = self.window_id_for(&key) {
                    if let Some(pw) = self.windows.get(&id) { pw.window.request_redraw(); }
                }
                CommandReply::ok()
            }
            Command::SpawnWindow { key, title, width, height, background, decorations } => {
                let mut spec = uzor::framework::multi_window::WindowSpec::new(
                    uzor::framework::multi_window::WindowKey::new(key),
                    &title,
                )
                .size(width, height);
                if let Some(bg) = background { spec = spec.background(bg); }
                if let Some(dec) = decorations { spec = spec.decorations(dec); }
                self.pending_spawns.push(spec);
                CommandReply::ok()
            }
            Command::CloseWindow { key } => {
                let target = uzor::framework::multi_window::WindowKey::new(key);
                if let Some(id) = self.window_id_for(&target) {
                    if let Some(pw) = self.windows.get_mut(&id) { pw.close_requested = true; }
                    CommandReply::ok()
                } else {
                    CommandReply::err("unknown window")
                }
            }
            // Anything else is one of the LM-routable commands handled
            // above by `try_apply`, so we shouldn't reach here.
            _ => CommandReply::err("internal: unhandled command"),
        };

        uzor::layout::agent::LmAgent::<P>::log_command(&mut self.layout, &cmd, &reply);
        reply
    }

    /// Rebuild the snapshot the HTTP server's `GET` endpoints read.
    #[cfg(not(target_arch = "wasm32"))]
    fn rebuild_agent_snapshot(&mut self) {
        let Some(bus) = self.agent_bus.as_ref() else { return };
        let snap = crate::agent::build_snapshot(
            &self.layout,
            self.fps_ema,
            self.frame_count,
            self.start.elapsed().as_secs_f64() * 1000.0,
        );
        if let Ok(mut w) = bus.snapshot.write() { *w = snap; }
        let widgets = crate::agent::build_widget_list(&self.layout);
        if let Ok(mut w) = bus.widgets.write() { *w = widgets; }
        // Publish agent-log mirror.  Cheap: ring buffer is bounded.
        let log_entries = self.layout.agent_log().snapshot();
        if let Ok(mut w) = bus.log.write() { *w = log_entries; }
        // Publish blackbox registry mirror.  Each entry is just an
        // `Arc` clone — cheap, no lock contention with the surface.
        let bb_clone: std::collections::HashMap<_, _> = self.layout.blackbox_slots()
            .into_iter()
            .filter_map(|slot| {
                self.layout.find_blackbox_agent(&slot).map(|s| (slot, s))
            })
            .collect();
        if let Ok(mut w) = bus.blackboxes.write() { *w = bb_clone; }
    }

    /// Drain queued screenshot requests and produce PNG bytes from
    /// the last-rendered frame of the named window.
    ///
    /// GPU pipeline: ensure `target_texture` has `COPY_SRC` usage,
    /// run `crate::utils::capture_screenshot` to read pixels back,
    /// then `encode_png`.  Returns `None` for software-presented
    /// windows or unknown keys.
    #[cfg(not(target_arch = "wasm32"))]
    fn drain_agent_screenshots(&mut self) {
        let mut batch: Vec<crate::agent::ScreenshotRequest> = Vec::new();
        if let Some(bus) = self.agent_bus.as_ref() {
            while let Ok(req) = bus.shot_rx.try_recv() {
                batch.push(req);
            }
        }
        for req in batch {
            let png = self.capture_window_png(&req.window);
            let _ = req.reply.send(png);
        }
    }

    /// Synchronous PNG capture for the named window.  Patches the
    /// vello target texture with `COPY_SRC` on first call, then reads
    /// it back through a staging buffer.
    #[cfg(not(target_arch = "wasm32"))]
    fn capture_window_png(&mut self, window: &str) -> Option<Vec<u8>> {
        use crate::utils::screenshot::{
            add_copy_src_to_target_texture, capture_screenshot, capture_screenshot_texture, encode_png,
        };
        let key = uzor::framework::multi_window::WindowKey::new(window);
        let id = self.window_id_for(&key)?;
        let pw = self.windows.get_mut(&id)?;

        // Wave 2 (W3D arc plan §0 gap #2 / §1.6/§1.7): when the LAST
        // frame rendered for this window went through the 3D compose
        // path, `target_texture` (the ordinary 2D vello path below) is
        // stale or blank for it — `submit_urx_composed` wrote the real
        // pixels into `render_state.capture_3d()`'s mirror instead.
        // `pw.last_frame_was_3d` (not just `capture_3d().is_some()`) is
        // the correct gate — see that field's own doc comment for why.
        if pw.last_frame_was_3d {
            if let Some(cap) = pw.render_state.capture_3d() {
                let format = cap.format;
                let (device, queue, _) = pw.render_state.gpu_handles()?;
                let (mut pixels, w, h) = capture_screenshot_texture(device, queue, &cap.texture, None)?;
                // The mirror is in the swapchain's native format, often
                // Bgra8 (`UrxCapture3D`'s own doc comment) — PNG needs
                // RGBA channel order.
                if matches!(format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb) {
                    for px in pixels.chunks_exact_mut(4) {
                        px.swap(0, 2);
                    }
                }
                return encode_png(&pixels, w, h);
            }
        }

        // Patch the target texture lazily — once it has COPY_SRC the
        // flag persists across resizes (until vello replaces the
        // surface itself, in which case we re-patch).
        {
            let (device, _queue, surface) = pw.render_state.gpu_handles_mut()?;
            let needs_patch = !surface
                .target_texture
                .usage()
                .contains(wgpu::TextureUsages::COPY_SRC);
            if needs_patch {
                add_copy_src_to_target_texture(surface, device);
                // Force one more frame so the freshly-replaced
                // texture is filled.  Without this the buffer would
                // contain undefined pixels.
                pw.window.request_redraw();
                return None;
            }
        }
        let (device, queue, surface) = pw.render_state.gpu_handles()?;
        let (pixels, w, h) = capture_screenshot(device, queue, surface, None)?;
        encode_png(&pixels, w, h)
    }

    fn fps_limit(&self) -> u32 {
        self.hub.as_ref()
            .map(|h| h.settings().fps_limit)
            .unwrap_or(self.config.fps_limit)
    }

    fn msaa_samples(&self) -> u8 {
        self.hub.as_ref()
            .map(|h| h.settings().msaa_samples)
            .unwrap_or(self.config.msaa_samples)
    }

    /// Queue an initial window spec (called by the builder before `run`).
    #[cfg(not(target_arch = "wasm32"))]
    pub fn queue_window_spec(&mut self, spec: WindowSpec) {
        self.pending_spawns.push(spec);
    }

    /// Run the manager — takes ownership and drives the winit event loop
    /// until all windows close.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn run(mut self) -> Result<(), ManagerError> {
        use winit::event_loop::EventLoop;
        // Drain any spawn requests the App pushed in its constructor before
        // the event loop runs (rare, but cheap to do).
        while let Some(s) = self.app.take_pending_spawn() {
            self.pending_spawns.push(s);
        }

        let event_loop = EventLoop::new()
            .map_err(|e| ManagerError::Window(e.to_string()))?;
        event_loop.set_control_flow(ControlFlow::Poll);

        // Activate the agent control plane only after an EventLoopProxy exists.
        // The HTTP server needs that proxy to wake dirty-only windows before a
        // synchronous command waits for the manager's reply.
        if let Some(port) = self.config.agent_api_port {
            if let Err(e) = self.enable_agent_api_with_proxy(port, event_loop.create_proxy()) {
                eprintln!("[uzor-desktop] agent-api bind on :{port} failed: {e}");
            }
        }

        event_loop.run_app(&mut self)
            .map_err(|e| ManagerError::Window(e.to_string()))?;

        Ok(())
    }

    // ── Window lifecycle ──────────────────────────────────────────────────────

    #[cfg(not(target_arch = "wasm32"))]
    fn create_window_from_spec(
        &mut self,
        event_loop: &ActiveEventLoop,
        spec: WindowSpec,
    ) -> Result<(), ManagerError> {
        let mut attrs = Window::default_attributes()
            .with_title(&spec.title)
            .with_inner_size(winit::dpi::LogicalSize::new(spec.size.0, spec.size.1))
            .with_decorations(spec.decorations)
            .with_visible(false);

        if let Some(ref rgba) = spec.icon.clone().or_else(|| self.config.icon.clone()) {
            if let Ok(ic) = winit::window::Icon::from_rgba(
                rgba.pixels.clone(), rgba.width, rgba.height,
            ) {
                attrs = attrs.with_window_icon(Some(ic));
            }
        }
        if let Some((mw, mh)) = spec.min_size {
            attrs = attrs.with_min_inner_size(winit::dpi::LogicalSize::new(mw, mh));
        }

        // macOS: a decorationless window is draggable by its background by
        // default, so EVERY left-press starts a native window-drag — AppKit then
        // consumes the mouse-up, so on_pointer_up never fires and NO click ever
        // resolves (only right-click, which doesn't drag, gets a Released). The
        // window still gets dragged explicitly via `chrome:drag` →
        // `Window::drag_window()` on the header, so disabling background drag
        // costs nothing and restores all clicks.
        #[cfg(target_os = "macos")]
        {
            use winit::platform::macos::WindowAttributesExtMacOS;
            attrs = attrs.with_movable_by_window_background(false);
        }

        let window = std::sync::Arc::new(
            event_loop.create_window(attrs)
                .map_err(|e| ManagerError::Window(e.to_string()))?
        );

        let mut provider = WinitWindowProvider::new(std::sync::Arc::clone(&window));
        let raw_handle = provider.raw_window_handle()
            .ok_or_else(|| ManagerError::Window("no raw handle available".into()))?;
        let rect = provider.window_rect();
        let dpr  = provider.scale_factor();
        let size = SurfaceSize {
            width:  (rect.width  * dpr).max(1.0) as u32,
            height: (rect.height * dpr).max(1.0) as u32,
        };
        // Each window gets a fresh factory for the hub's CURRENT active
        // backend. Reusing self.factory ties every spawned window to the
        // backend that was active when from_built ran, which breaks
        // backends switched at runtime via render_control.set_backend.
        // mlc-aligned policy: every window gets a wgpu swapchain.  Even
        // CPU backends (TinySkia, VelloCpu) render into a pixmap and
        // then upload it as a texture for blit + present through the
        // GPU.  This used to fork into a softbuffer-backed
        // `SurfaceMode::Software` path for CPU, which works for the
        // first window but loses pixels on subsequent spawns
        // (windows came up black).  The unified GPU swapchain path
        // also makes the screenshot endpoint usable on every backend.
        let active = self.hub.as_ref().map(|h| h.active()).unwrap_or(self.backend);
        let factory: Box<dyn RenderSurfaceFactory> = if let Some(hub) = self.hub.as_ref() {
            hub.factory_for(active)
                .ok_or_else(|| ManagerError::Backend(
                    format!("hub has no factory for backend {:?}", active)
                ))?
        } else {
            return Err(ManagerError::Backend("no hub initialised".into()));
        };

        let mut render_state = factory
            .create_render_state(&raw_handle, active, size)
            .map_err(|e| ManagerError::Backend(format!("create_render_state({:?}): {}", active, e)))?;

        window.set_visible(true);

        // Push the initial size into the render state so software presenters
        // and CPU pixmaps are sized for the very first frame — winit only
        // sends a `Resized` event later, after the first paint.
        render_state.resize_surface(size.width, size.height);

        // Apply OS window decorations (corner rounding, border colour, shadow).
        // Spec values win over AppConfig defaults. Non-Windows targets no-op silently.
        {
            let style = if spec.corner_style != uzor::platform::types::CornerStyle::Default {
                spec.corner_style
            } else {
                self.config.corner_style
            };
            if style != uzor::platform::types::CornerStyle::Default {
                provider.set_corner_style(style);
            }

            let color = spec.border_color.or(self.config.border_color);
            if color.is_some() {
                provider.set_border_color(color);
            }

            let shadow = spec.shadow.or(self.config.shadow);
            if let Some(s) = shadow {
                provider.set_shadow(s);
            }
        }

        let id = window.id();
        let tick_rate = spec.tick_rate.unwrap_or(self.config.default_tick_rate);
        let pw = PerWindow::<P> {
            key:             spec.key.clone(),
            spec:            spec.clone(),
            window:          std::sync::Arc::clone(&window),
            render_state,
            last_mouse_pos:  (0.0, 0.0),
            event_mapper:    EventMapper::new(dpr),
            last_frame:      std::time::Instant::now(),
            initialised:     false,
            close_requested: false,
            tick_rate,
            region_states:   std::collections::HashMap::new(),
            region_scenes:   std::collections::HashMap::new(),
            dock_separator_drag: None,
            last_frame_was_3d: false,
            cursor_capture_active: false,
            _phantom:        std::marker::PhantomData,
        };
        self.windows.insert(id, pw);

        // Hand the provider over to LM — from now on LM owns the trait
        // object and routes everything (resize, redraw, drag, decorations,
        // platform-event queue) through the trait.
        self.layout.attach_window(spec.key.clone(), Box::new(provider));
        if let Some(slot) = self.layout.window_mut(&spec.key) {
            slot.tick_rate = tick_rate;
        }

        // Kick off the first paint: winit only sends Resized/RedrawRequested
        // events to *future* state changes; without an explicit request the
        // freshly-spawned second window never ticks until the user moves the
        // mouse over it.
        if let Some(pw) = self.windows.get(&id) {
            pw.window.request_redraw();
        }

        // Apply tray spec on first window creation only.
        if self.tray.is_none() {
            if let Some(spec) = self.tray_spec.take() {
                let mut tb = crate::tray::TrayBuilder::new();
                if let Some(ref icon) = self.config.icon {
                    tb = tb.icon(icon.clone());
                }
                if let Some(t) = spec.tooltip { tb = tb.tooltip(t); }
                for (id, label, enabled) in spec.items {
                    tb = if enabled { tb.menu_item(id, label) }
                         else        { tb.menu_item_disabled(id, label) };
                }
                match tb.build() {
                    Ok(handle) => self.tray = Some(handle),
                    Err(e) => eprintln!("[uzor-desktop] tray init failed: {e}"),
                }
            }
        }

        Ok(())
    }

    /// Look up a window's `winit::WindowId` by app-supplied `WindowKey`.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn window_id_for(&self, key: &WindowKey) -> Option<winit::window::WindowId> {
        self.windows.iter().find_map(|(id, pw)| (pw.key == *key).then_some(*id))
    }

    // ── Per-window event handling ─────────────────────────────────────────────

    /// Process one raw winit event for the given window.
    /// Only talks to `LayoutManager` via its L3 surface — no direct coord/bridge access.
    #[cfg(not(target_arch = "wasm32"))]
    fn handle_window_winit_event(&mut self, id: winit::window::WindowId, event: &WindowEvent) {
        let now_ms = self.start.elapsed().as_secs_f64() * 1000.0;

        // Route LM to this window before any per-window state mutations.
        let key = match self.windows.get(&id) {
            Some(pw) => pw.key.clone(),
            None => return,
        };
        self.layout.set_current_window(key.clone());

        use winit::event::{ElementState, MouseButton as WMouseButton};

        match event {
            // ── Cursor moved ─────────────────────────────────────────────────
            WindowEvent::CursorMoved { position, .. } => {
                let Some(pw) = self.windows.get_mut(&id) else { return };
                let dpr = self.layout.window(&key)
                    .map(|s| s.provider.scale_factor())
                    .unwrap_or(1.0);
                let lx = position.x / dpr;
                let ly = position.y / dpr;
                pw.last_mouse_pos = (lx, ly);
                self.layout.on_pointer_move(lx, ly);

                // Drive an in-flight dock-separator drag.  panels_mut()
                // applies the per-pixel delta to the underlying split
                // ratio — the next frame's solve picks up the new sizes.
                if let Some(drag) = pw.dock_separator_drag.as_mut() {
                    use uzor::docking::panels::SeparatorOrientation as SO;
                    let orient = self.layout.panels()
                        .separators()
                        .get(drag.sep_idx)
                        .map(|s| s.orientation);
                    if let Some(orient) = orient {
                        let win = self.layout.last_window().unwrap_or(uzor::types::Rect::new(0.0, 0.0, 1.0, 1.0));
                        let delta = match orient {
                            SO::Vertical   => (lx - drag.last_x) as f32,
                            SO::Horizontal => (ly - drag.last_y) as f32,
                        };
                        self.layout.panels_mut().drag_separator(
                            drag.sep_idx,
                            delta,
                            win.width  as f32,
                            win.height as f32,
                        );
                    }
                    drag.last_x = lx;
                    drag.last_y = ly;
                }

            }

            // ── Mouse button pressed ─────────────────────────────────────────
            WindowEvent::MouseInput {
                state: ElementState::Pressed,
                button: WMouseButton::Left,
                ..
            } => {
                let Some(pw) = self.windows.get_mut(&id) else { return };
                let (mx, my) = pw.last_mouse_pos;
                self.layout.on_pointer_down(mx, my);

                // Dock-separator drag start.  on_pointer_down already
                // wrote `last_pressed` via process_drag_press; check it
                // for the `dock-sep-N` id pattern.
                if let Some(pressed) = self.layout.last_pressed_widget() {
                    let pressed_str = pressed.as_str().to_string();
                    if let Some(suffix) = pressed_str.strip_prefix("dock-sep-") {
                        if let Ok(idx) = suffix.parse::<usize>() {
                            pw.dock_separator_drag = Some(DockSeparatorDrag {
                                sep_idx: idx,
                                last_x:  mx,
                                last_y:  my,
                            });
                            return;
                        }
                    }

                    // Panel-edge drag start.  Each `lm::panel` composite
                    // registers up to 4 edge handles named
                    // `<panel_id>:edge_{top,bottom,left,right}`.  The LM
                    // resolves a (host_id, edge) pair onto an existing dock
                    // separator and we reuse the same per-frame
                    // `drag_separator(...)` math — sibling panels move
                    // together for free because the separator is shared.
                    let pid = pressed_str.as_str();
                    let parsed = if pid.ends_with(":edge_top") {
                        Some((&pid[..pid.len() - ":edge_top".len()], uzor::layout::ResizeEdge::N))
                    } else if pid.ends_with(":edge_bottom") {
                        Some((&pid[..pid.len() - ":edge_bottom".len()], uzor::layout::ResizeEdge::S))
                    } else if pid.ends_with(":edge_left") {
                        Some((&pid[..pid.len() - ":edge_left".len()], uzor::layout::ResizeEdge::W))
                    } else if pid.ends_with(":edge_right") {
                        Some((&pid[..pid.len() - ":edge_right".len()], uzor::layout::ResizeEdge::E))
                    } else {
                        None
                    };
                    if let Some((host_id, edge)) = parsed {
                        if let Some(sep_idx) = self.layout.resize_handle_to_separator(host_id, edge) {
                            pw.dock_separator_drag = Some(DockSeparatorDrag {
                                sep_idx,
                                last_x:  mx,
                                last_y:  my,
                            });
                            return;
                        }
                    }
                }

                // Try chrome / bezel resize via L3. If consumed — done.
                // For NewWindow we need App, so we handle that case here.
                // Build a transient host that delegates to winit.
                let mut host = PerWindowHost {
                    window:          &pw.window,
                    close_requested: &mut pw.close_requested,
                    pending_spawns:  &mut self.pending_spawns,
                    close_app:       false,
                };
                let consumed = self.layout.handle_chrome_press(mx, my, &mut host, now_ms);

                // If NewWindow was signalled (handle_chrome_press returns false for it),
                // let the App resolve it.
                // Note: handle_chrome_press returns false for NewWindow so we check
                // whether the chrome hit was NewWindow by re-testing here.
                // Simpler: unconditionally ask the App if nothing else consumed.
                if host.close_app {
                    for p in self.windows.values_mut() {
                        p.close_requested = true;
                    }
                    return;
                }
                if consumed {
                    return;
                }

                // Not consumed by chrome — check if it's a NewWindow hit.
                // We do this by calling chrome_hit_test again only if chrome is present.
                let pw2 = match self.windows.get_mut(&id) { Some(p) => p, None => return };
                if let Some(chrome_rect) = self.layout.rect_for_chrome() {
                    use uzor::ui::widgets::composite::chrome::{
                        chrome_hit_test, handle_chrome_action, ChromeAction,
                        ChromeRenderKind, ChromeSettings, ChromeView,
                    };
                    let cfg = self.layout.chrome_state().layout_config;
                    let view = ChromeView {
                        tabs: &[],
                        active_tab_id: None,
                        show_new_tab_btn: cfg.show_new_tab_btn,
                        show_menu_btn: cfg.show_menu_btn,
                        show_new_window_btn: cfg.show_new_window_btn,
                        show_close_window_btn: cfg.show_close_window_btn,
                        is_maximized: pw2.window.is_maximized(),
                        menu_left: cfg.menu_left,
                        show_maximize: cfg.show_maximize,
                        cursor_x: mx,
                        cursor_y: my,
                        time_ms: now_ms,
                    };
                    let settings = ChromeSettings::default();
                    let kind = ChromeRenderKind::Default;
                    let hit = chrome_hit_test(
                        self.layout.chrome_state(), &view, &settings, &kind,
                        chrome_rect, (mx, my),
                    );
                    let action = handle_chrome_action(hit);
                    if matches!(action, ChromeAction::NewWindow) {
                        let src = pw2.key.clone();
                        if let Some(spec) = self.app.on_chrome_new_window(&src) {
                            self.pending_spawns.push(spec);
                        }
                        return;
                    }
                }

                // Not a chrome press, not a drag target. macOS drags the whole
                // window on this very press (winit's view returns
                // mouseDownCanMoveWindow=YES and nothing we tried — isMovable,
                // movableByWindowBackground, isa-swapping the view — disables it)
                // and AppKit consumes the Left mouse-up, so the Released arm below
                // never fires for body clicks. Resolve the click here, on press.
                // Other platforms get a real mouse-up; this is macOS-only.
                #[cfg(target_os = "macos")]
                {
                    match self.layout.on_pointer_up(mx, my) {
                        uzor::layout::PointerUpOutcome::DismissedOverlay(h) => {
                            self.app.on_dismiss(&mut self.layout, h);
                        }
                        uzor::layout::PointerUpOutcome::Click(_id, ev) => {
                            self.app.dispatch_event(&mut self.layout, ev);
                        }
                        uzor::layout::PointerUpOutcome::Unhandled => {}
                    }
                }
            }

            // ── Mouse button released ────────────────────────────────────────
            WindowEvent::MouseInput {
                state: ElementState::Released,
                button: WMouseButton::Left,
                ..
            } => {
                let Some(pw) = self.windows.get_mut(&id) else { return };
                let (mx, my) = pw.last_mouse_pos;
                pw.dock_separator_drag = None;
                // L3 records the click in last_click; no pw.input write needed.
                // Route the resolved click to the App dispatch hooks (chrome
                // controls, tabs, dropdown / toolbar / context-menu items).
                // Previously the outcome was discarded, so on_chrome_control and
                // the other typed hooks were dead for AppBuilder apps.
                match self.layout.on_pointer_up(mx, my) {
                    uzor::layout::PointerUpOutcome::DismissedOverlay(h) => {
                        self.app.on_dismiss(&mut self.layout, h);
                    }
                    uzor::layout::PointerUpOutcome::Click(_id, ev) => {
                        self.app.dispatch_event(&mut self.layout, ev);
                    }
                    uzor::layout::PointerUpOutcome::Unhandled => {}
                }
                // App hooks on DispatchEvent / DismissedOverlay are called by
                // App::ui each frame via consume_event — no immediate callback here.
            }

            // ── All other events — no direct coord / bridge access ───────────
            _ => {}
        }
    }

    /// Tick one window — FPS-cap-guarded paint pass.
    #[cfg(not(target_arch = "wasm32"))]
    fn tick_window(
        &mut self,
        id: winit::window::WindowId,
        event_loop: &ActiveEventLoop,
    ) -> Result<(), ManagerError> {
        let fps_limit = self.fps_limit();
        if fps_limit > 0 {
            if let Some(pw) = self.windows.get(&id) {
                let target_dt = std::time::Duration::from_secs_f64(1.0 / fps_limit as f64);
                if pw.last_frame.elapsed() < target_dt {
                    event_loop.set_control_flow(ControlFlow::WaitUntil(
                        pw.last_frame + target_dt,
                    ));
                    return Ok(());
                }
            }
        }
        let result = self.tick_window_inner(id);
        self.sync_cursor_capture(id);
        result
    }

    /// Reconciles the OS cursor-grab state with what [`App::cursor_capture_mode`]
    /// currently requests — plus an engine-level safety net the app
    /// cannot opt out of: `requested` is only ever trusted while this
    /// window actually has OS focus (`pw.window.has_focus()`). An
    /// unfocused window (e.g. Alt-Tabbed away) always forces
    /// `requested = false` here regardless of the app's own answer, so
    /// capture is force-released the very next tick after focus is lost
    /// — no new event plumbing needed (this only ever polls the window's
    /// own focus state, it does not need `PlatformEvent::WindowFocused`
    /// relayed to it). Re-capture then happens naturally on a later tick
    /// once focus returns AND the app still requests `LockedHidden`.
    /// Every uzor app that requests `LockedHidden` gets this guarantee
    /// for free instead of having to reimplement its own focus-tracking
    /// release dance (see `nemo/docs/uzor-engines/research_foxhound_lift_candidates.md`
    /// §4 — `foxhound-app-shell-native`'s own `ViewportCursorState` did
    /// exactly this app-side, by omission rather than by design).
    #[cfg(not(target_arch = "wasm32"))]
    fn sync_cursor_capture(&mut self, id: winit::window::WindowId) {
        use winit::window::CursorGrabMode;

        let app_requested = self.app.cursor_capture_mode() == CursorCaptureMode::LockedHidden;
        let Some(pw) = self.windows.get_mut(&id) else { return };
        let requested = app_requested && pw.window.has_focus();
        if requested == pw.cursor_capture_active {
            return;
        }

        if requested {
            let captured = pw.window.set_cursor_grab(CursorGrabMode::Locked)
                .or_else(|_| pw.window.set_cursor_grab(CursorGrabMode::Confined))
                .is_ok();
            if captured {
                pw.window.set_cursor_visible(false);
                pw.cursor_capture_active = true;
            }
        } else {
            let _ = pw.window.set_cursor_grab(CursorGrabMode::None);
            pw.window.set_cursor_visible(true);
            pw.cursor_capture_active = false;
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn tick_window_inner(&mut self, id: winit::window::WindowId) -> Result<(), ManagerError> {
        let _frame_profile = uzor::diagnostics::FrameProfileGuard::enter();
        let now_secs = self.start.elapsed().as_secs_f64();
        let now_ms   = now_secs * 1000.0;
        let msaa     = self.msaa_samples();

        // Route LM to this window for the duration of the tick.
        let active_backend = self.hub.as_ref().map(|h| h.active()).unwrap_or(self.backend);
        uzor::diagnostics::stage(
            "desktop",
            "tick_begin",
            format_args!("window_id={id:?} backend={}", active_backend.as_str()),
        );
        if let Some(pw) = self.windows.get_mut(&id) {
            // Sync per-window active backend with the global hub
            // setting and lazily build the matching renderer / CPU
            // context if the user just switched backends.
            if pw.render_state.backend() != active_backend {
                pw.render_state.set_active(active_backend);
            } else {
                pw.render_state.ensure_backend_slot(active_backend);
            }
            self.layout.set_current_window(pw.key.clone());
        } else {
            return Ok(());
        }

        // ── Frame metrics (EMA, mlc pattern: α = 0.1) ──
        let now_inst = std::time::Instant::now();
        let dt = now_inst.duration_since(self.last_frame_instant);
        self.last_frame_instant = now_inst;
        let dt_ms = dt.as_secs_f64() * 1000.0;
        if dt_ms > 0.1 && dt_ms < 1000.0 {
            let instant_fps = 1000.0 / dt_ms;
            self.fps_ema = self.fps_ema_tracker.update(instant_fps, 0.1) as f32;
            self.last_frame_time_ms = dt_ms as f32;
        }
        self.frame_count = self.frame_count.wrapping_add(1);

        // Init hook — runs once per window before its first frame.
        if let Some(pw) = self.windows.get_mut(&id) {
            if !pw.initialised {
                let key = pw.key.clone();
                self.app.init(&key, &mut self.layout);
                pw.initialised = true;
                if let Some(slot) = self.layout.window_mut(&key) {
                    slot.initialised = true;
                }
                self.layout.agent_log_push(
                    "lm.window.first_tick",
                    serde_json::json!({ "window": key.as_str() }),
                );
            }
        }
        // Bump LM-side tick counter so /state/tree reflects ticks.
        if let Some(pw) = self.windows.get(&id) {
            let key = pw.key.clone();
            if let Some(slot) = self.layout.window_mut(&key) {
                slot.tick_count = slot.tick_count.wrapping_add(1);
            }
        }

        let outcome = {
            let pw = match self.windows.get_mut(&id) {
                Some(p) => p,
                None    => return Ok(()),
            };

            let key = pw.key.clone();
            let events = self.layout.window_mut(&key)
                .map(|s| s.provider.poll_events())
                .unwrap_or_default();
            for ev in events {
                let _ = self.app.on_event(&ev);
            }

            let rect = self.layout.window(&key)
                .map(|s| s.provider.window_rect())
                .unwrap_or_default();
            self.layout.solve(rect);
            let viewport = self.layout.rect_for_dock_area().unwrap_or(rect);
            // Clear last frame's widget nodes BEFORE the app re-registers
            // them.  Without this the retained tree grows unbounded (one
            // dup per tick × per widget) — snapshot ends up with stale
            // labels at the front and current ones at the back.
            self.layout.begin_frame_widgets();
            // begin_frame clears one-shot input flags and refreshes widget registrations
            // WITHOUT overwriting the pointer state that on_pointer_* already set.
            self.layout.begin_frame(now_ms, viewport);
            self.layout.set_frame_time_ms(now_ms);

            let bg_color = argb_to_alpha_color(pw.spec.background);
            pw.render_state.begin_frame();

            let regions = self.app.regions();
            let now_inst = std::time::Instant::now();
            // Register declared regions before selecting the 2D/3D paint
            // branch. A 3D frame skips the 2D region loops below, but its
            // declared regions must still participate in cadence scheduling;
            // otherwise `region_states` stays empty and the legacy no-region
            // fallback requests an immediate redraw forever.
            register_region_schedule_states(&regions, &mut pw.region_states);

            // Wave 2 (W3D arc plan §1.7): a `run_with_3d`-armed app can
            // take over this window's swapchain-writing path for the
            // frame. `scene3d_hook` is `None` for every ordinary
            // `.run()` app (zero behavior change below); a `Some(hook)`
            // app still falls through to the untouched 2D path whenever
            // `hook` returns `None` (2D dimension currently active).
            let surf_wh = pw.render_state.gpu_handles().map(|(_, _, surface)| (surface.config.width, surface.config.height));
            let scene3d_frame = match (self.scene3d_hook, surf_wh) {
                (Some(hook), Some((w, h))) if w > 0 && h > 0 => hook(&mut self.app, w, h),
                _ => None,
            };
            // See `PerWindow::last_frame_was_3d`'s own doc comment for
            // why `capture_window_png` needs this per-frame flag rather
            // than trusting `render_state.capture_3d().is_some()` alone.
            pw.last_frame_was_3d = scene3d_frame.is_some();

            // Pick path:
            // - VelloGpu: per-region scene + composite (mlc pattern).
            // - CPU rasterisers (VelloCpu, TinySkia) and others:
            //   render every region into the SAME context in
            //   declaration order — pixmap accumulates, no scene
            //   compositing.  Without this dock leaves and other
            //   region-only widgets stay invisible on CPU backends.
            //
            // Skipped entirely on a 3D-active frame (`scene3d_frame` is
            // `Some`, forced divergence from the plan's literal "build
            // the 2D scene exactly as today" — `submit_urx_composed`'s
            // own 2D pass reads `state.urx_ctx`, a channel this Manager
            // never populates (confirmed: no `set_active_urx` call
            // anywhere in this crate), so there is no 2D content for it
            // to merge with `app.ui()`'s vello `render_state.scene` — a
            // DIFFERENT render channel `submit_urx_composed` never
            // touches. Painting 2D content nobody will see this frame
            // would just be wasted work; a 3D-active window shows the
            // composed 3D viewport full-window instead.
            let active_backend = pw.render_state.backend();
            let app_build_t0 = std::time::Instant::now();
            uzor::diagnostics::stage(
                "desktop",
                "app_build_begin",
                format_args!(
                    "backend={} regions={} scene3d={}",
                    active_backend.as_str(),
                    regions.len(),
                    scene3d_frame.is_some(),
                ),
            );
            let supports_scene_compose = matches!(
                active_backend, uzor::platform::types::RenderBackend::VelloGpu,
            );
            let use_regions_compose = scene3d_frame.is_none() && !regions.is_empty() && supports_scene_compose;
            let use_regions_inline  = scene3d_frame.is_none() && !regions.is_empty() && !supports_scene_compose;

            if scene3d_frame.is_none() {
                let key = &pw.key;
                let layout = &mut self.layout;
                let render_state = &mut pw.render_state;
                let region_states = &mut pw.region_states;
                let region_scenes = &mut pw.region_scenes;
                let app = &mut self.app;
                let fps_ema = self.fps_ema;
                let last_frame_time_ms = self.last_frame_time_ms;
                let frame_count = self.frame_count;
                let hub = self.hub.as_mut().expect("hub initialised");
                let mut hub_ctrl = HubControl { hub, fps_ema, last_frame_time_ms, frame_count };

                if use_regions_compose {
                    // GPU path: per-region scene + composite.
                    for region in &regions {
                        let state = region_states
                            .entry(region.id)
                            .or_insert_with(uzor::render::RegionScheduleState::default);
                        if !state.due(region, now_inst) { continue; }
                        let scene = region_scenes
                            .entry(region.id)
                            .or_insert_with(vello::Scene::new);
                        scene.reset();
                        render_state.with_scene_render_context(scene, |render_ctx| {
                            let mut ctx = WindowCtx::<P> {
                                key,
                                layout,
                                render: render_ctx,
                                rect,
                                render_control: &mut hub_ctrl,
                            };
                            app.draw_region(region.id, &mut ctx);
                        });
                        state.last_painted = Some(now_inst);
                    }
                    for region in &regions {
                        if let Some(rs) = region_scenes.get(region.id) {
                            render_state.append_region_scene(rs);
                        }
                    }
                } else if use_regions_inline {
                    // Inline backends retain one complete shared frame rather
                    // than independent region scenes. If no region is due,
                    // leave that frame untouched and submit it again. Once any
                    // region is due, rebuild every region in declaration order
                    // so the retained frame never mixes old and new partial
                    // composition.
                    if regions_need_full_inline_repaint(&regions, region_states, now_inst) {
                        render_state.with_render_context(|render_ctx| {
                            let mut ctx = WindowCtx::<P> {
                                key,
                                layout,
                                render: render_ctx,
                                rect,
                                render_control: &mut hub_ctrl,
                            };
                            for region in &regions {
                                app.draw_region(region.id, &mut ctx);
                            }
                        });
                        for region in &regions {
                            let state = region_states
                                .entry(region.id)
                                .or_insert_with(uzor::render::RegionScheduleState::default);
                            state.last_painted = Some(now_inst);
                        }
                    }
                } else {
                    render_state.with_render_context(|render_ctx| {
                        let mut ctx = WindowCtx::<P> {
                            key,
                            layout,
                            render: render_ctx,
                            rect,
                            render_control: &mut hub_ctrl,
                        };
                        app.ui(&mut ctx);
                    });
                }
            }
            uzor::diagnostics::stage(
                "desktop",
                "app_build_end",
                format_args!(
                    "backend={} duration_us={}",
                    active_backend.as_str(),
                    app_build_t0.elapsed().as_micros(),
                ),
            );
            let _responses = self.layout.ctx_mut().end_frame();
            // Clear one-shot input flags AFTER app.ui consumed them.
            self.layout.end_frame_inputs();

            let submit_t0 = std::time::Instant::now();
            uzor::diagnostics::stage(
                "desktop",
                "submit_begin",
                format_args!(
                    "backend={} scene3d={}",
                    active_backend.as_str(),
                    scene3d_frame.is_some(),
                ),
            );
            let outcome = if let Some(mut frame) = scene3d_frame {
                let (surf_w, surf_h) = surf_wh.expect("scene3d_frame is Some only when surf_wh was already Some");
                pw.render_state.set_capture_3d(true);
                let job = Compose3DJob { camera: frame.camera(), dst_x: 0, dst_y: 0, dst_w: surf_w, dst_h: surf_h };
                let overlay = frame.take_overlay();
                let cached_overlay = frame.take_cached_overlay();
                // Wave 4 (W3D arc plan §1.3 label-overlay gap): forward the
                // app's optional 2D overlay closure into the new post-3D
                // Phase 4.5 — see `uzor-render-hub::compose`'s own doc
                // comment for exactly where it lands in the composed frame.
                // Taken by VALUE (not `&mut`) — `submit_urx_composed` only
                // ever needs it for this one call and never hands it back,
                // so an owned `Box` sidesteps threading a borrowed
                // `&mut dyn FnMut(...)` reference's lifetime through a
                // generic function boundary entirely.
                match uzor_render_hub::submit_urx_composed_with_scene(
                    &mut pw.render_state,
                    frame.scene(),
                    bg_color.components,
                    std::slice::from_ref(&job),
                    overlay,
                    cached_overlay,
                ) {
                    Ok(composed) => SubmitOutcome { metrics: Default::default(), surface_lost: composed.surface_lost },
                    Err(e) => {
                        eprintln!("[uzor-desktop] submit_urx_composed failed: {e:?}");
                        SubmitOutcome { metrics: Default::default(), surface_lost: false }
                    }
                }
            } else {
                submit_frame(
                    &mut pw.render_state,
                    SubmitParams { base_color: bg_color, msaa_samples: msaa },
                )
            };
            uzor::diagnostics::stage(
                "desktop",
                "submit_end",
                format_args!(
                    "backend={} duration_us={} render_to_texture_us={} present_us={} surface_lost={}",
                    active_backend.as_str(),
                    submit_t0.elapsed().as_micros(),
                    outcome.metrics.render_to_texture_us,
                    outcome.metrics.present_us,
                    outcome.surface_lost,
                ),
            );

            let now_inst = std::time::Instant::now();
            pw.last_frame = now_inst;

            // Legacy event-driven path: when the app declares no regions,
            // fall back to the always-redraw loop (mouse/event driven).
            if pw.region_states.is_empty() {
                pw.window.request_redraw();
            }

            outcome
        };

        if outcome.surface_lost {
            return Err(ManagerError::Backend(
                "wgpu surface/device became unrecoverable".into(),
            ));
        }
        if let Some(ref mut h) = self.hub {
            h.update_metrics(outcome.metrics);
        }
        Ok(())
    }
}

// ── ApplicationHandler ────────────────────────────────────────────────────────

#[cfg(not(target_arch = "wasm32"))]
impl<A, P> winit::application::ApplicationHandler for Manager<A, P>
where
    A: App<P>,
    P: DockPanel + Default + 'static,
{
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        // First resume: drain whatever the builder queued.
        let queued = std::mem::take(&mut self.pending_spawns);
        for spec in queued {
            if let Err(e) = self.create_window_from_spec(event_loop, spec) {
                eprintln!("[uzor-desktop] window create failed: {e}");
                event_loop.exit();
                return;
            }
        }

        if self.windows.is_empty() {
            eprintln!("[uzor-desktop] no windows queued — exiting");
            event_loop.exit();
        }
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        id: winit::window::WindowId,
        event: WindowEvent,
    ) {
        match event {
            WindowEvent::CloseRequested => {
                if let Some(pw) = self.windows.get_mut(&id) {
                    pw.close_requested = true;
                }
            }
            WindowEvent::Resized(size) => {
                if size.width > 0 && size.height > 0 {
                    if let Some(pw) = self.windows.get_mut(&id) {
                        pw.render_state.resize_surface(size.width, size.height);
                        invalidate_region_schedule_states(&mut pw.region_states);
                    }
                }
                if let Some(pw) = self.windows.get(&id) {
                    pw.window.request_redraw();
                }
            }
            WindowEvent::RedrawRequested => {
                if let Err(e) = self.tick_window(id, event_loop) {
                    eprintln!("[uzor-desktop] tick error: {e}");
                    event_loop.exit();
                }
            }
            ref ev => {
                self.handle_window_winit_event(id, ev);
                let key = self.windows.get(&id).map(|pw| pw.key.clone());
                if let Some(key) = key {
                    // Route through THIS window's own mapper — stamps
                    // PointerDown/Up with the real last-Moved position and
                    // normalizes every pointer/touch/scroll coordinate to
                    // logical pixels using the window's real scale factor
                    // (was: free fn hardcoding scale 1.0 and the mapper
                    // stamping button events with (0.0, 0.0)).
                    let platform_ev = self.windows.get_mut(&id)
                        .and_then(|pw| pw.event_mapper.map_window_event(ev));
                    let redraw_window = self.windows
                        .get(&id)
                        .map(|pw| std::sync::Arc::clone(&pw.window));
                    if let (Some(slot), Some(redraw_window)) =
                        (self.layout.window_mut(&key), redraw_window)
                    {
                        dispatch_mapped_platform_event(
                            platform_ev,
                            |platform_ev| {
                                slot.provider.push_platform_event(platform_ev);
                            },
                            || redraw_window.request_redraw(),
                        );
                    }
                    // macOS consumes the Left mouse-up while it drags the window,
                    // so the app never receives PointerUp and `pointer_down` sticks
                    // true (planet spins on any move). Synthesize the up right after
                    // the down so the app sees a complete click and clears its drag
                    // state. (The window still moves — that's fine and expected.)
                    #[cfg(target_os = "macos")]
                    if matches!(
                        ev,
                        WindowEvent::MouseInput {
                            state: winit::event::ElementState::Pressed,
                            button: winit::event::MouseButton::Left,
                            ..
                        }
                    ) {
                        let (x, y) = self.windows.get(&id)
                            .map(|pw| pw.last_mouse_pos)
                            .unwrap_or((0.0, 0.0));
                        if let Some(slot) = self.layout.window_mut(&key) {
                            slot.provider.push_platform_event(
                                uzor::platform::PlatformEvent::PointerUp {
                                    x,
                                    y,
                                    button: uzor::input::state::MouseButton::Left,
                                },
                            );
                        }
                    }
                }
            }
        }
    }

    fn device_event(
        &mut self,
        _event_loop: &ActiveEventLoop,
        _device_id: winit::event::DeviceId,
        event: winit::event::DeviceEvent,
    ) {
        let winit::event::DeviceEvent::MouseMotion { delta: (dx, dy) } = event else { return };
        if !self.windows.values().any(|window| window.cursor_capture_active) {
            return;
        }
        if self.app.on_event(&uzor::platform::PlatformEvent::PointerDelta { dx, dy }) {
            for window in self.windows.values().filter(|window| window.cursor_capture_active) {
                window.window.request_redraw();
            }
        }
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        // 1. Collect close requests.
        let mut to_close: Vec<winit::window::WindowId> = self.windows.iter()
            .filter_map(|(id, pw)| pw.close_requested.then_some(*id))
            .collect();
        while let Some(key) = self.app.take_window_to_close() {
            if let Some(id) = self.window_id_for(&key) {
                to_close.push(id);
            }
        }
        for id in to_close {
            if let Some(pw) = self.windows.remove(&id) {
                pw.window.set_visible(false);
            }
        }

        // 2. Exit when no windows left.
        if self.windows.is_empty() {
            self.app.shutdown();
            event_loop.exit();
            return;
        }

        // 2.5. Drain agent-API write commands and apply them on this
        //      thread before any spawn / paint work picks up the new
        //      state.  Each command resolves a oneshot the HTTP handler
        //      is awaiting.
        self.drain_agent_commands();
        self.drain_agent_screenshots();

        // 3. Drain spawn requests.
        while let Some(s) = self.app.take_pending_spawn() {
            self.pending_spawns.push(s);
        }
        let queued = std::mem::take(&mut self.pending_spawns);
        for spec in queued {
            if let Err(e) = self.create_window_from_spec(event_loop, spec) {
                eprintln!("[uzor-desktop] window spawn failed: {e}");
            }
        }

        // 3.5. Rebuild the agent snapshot after spawn/close so HTTP
        //      readers see the current window list and per-branch state.
        self.rebuild_agent_snapshot();

        // 4. Paint scheduler.
        //    a) Per-region cadence (mlc pattern) — drives intra-window
        //       sub-region rebuilds when the app declares them.
        //    b) Per-window baseline `TickRate` — guarantees every
        //       window keeps painting at its declared heartbeat even
        //       when no winit events fire.  Without this the agent API
        //       can mutate state but the user never sees it because
        //       `was_clicked` etc only fire while the window paints.
        let regions = self.app.regions();
        let now = std::time::Instant::now();
        let mut next_due: Option<std::time::Instant> = None;

        for pw in self.windows.values_mut() {
            let mut any_due_now = false;

            // (a) intra-window region cadence.
            for region in &regions {
                let state = pw.region_states
                    .entry(region.id)
                    .or_insert_with(uzor::render::RegionScheduleState::default);
                if state.due(region, now) {
                    any_due_now = true;
                } else if let Some(nd) = state.next_due(region, now) {
                    next_due = Some(match next_due {
                        None => nd,
                        Some(cur) => cur.min(nd),
                    });
                }
            }

            // (b) per-window baseline tick.
            match pw.tick_rate {
                uzor::render::TickRate::Dirty => {}
                uzor::render::TickRate::Uncapped => {
                    any_due_now = true;
                }
                uzor::render::TickRate::Capped(fps) if fps > 0 => {
                    let target = std::time::Duration::from_secs_f64(1.0 / fps as f64);
                    let elapsed = now.saturating_duration_since(pw.last_frame);
                    if elapsed >= target {
                        any_due_now = true;
                    } else {
                        let nd = pw.last_frame + target;
                        next_due = Some(match next_due {
                            None => nd,
                            Some(cur) => cur.min(nd),
                        });
                    }
                }
                uzor::render::TickRate::Capped(_) => {} // fps == 0 acts like Dirty
            }

            if any_due_now {
                pw.window.request_redraw();
            }
        }

        // Decide control-flow: if anyone is uncapped or already due,
        // poll continuously; otherwise sleep until the soonest next-due.
        let any_uncapped = self.windows.values().any(|p|
            matches!(p.tick_rate, uzor::render::TickRate::Uncapped)

        );
        event_loop.set_control_flow(scheduled_control_flow(
            any_uncapped,
            next_due,
            now,
        ));
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

#[cfg(not(target_arch = "wasm32"))]
fn dispatch_mapped_platform_event<E>(
    event: Option<E>,
    push: impl FnOnce(E),
    request_redraw: impl FnOnce(),
) -> bool {
    let Some(event) = event else {
        return false;
    };
    push(event);
    request_redraw();
    true
}

#[cfg(not(target_arch = "wasm32"))]
fn scheduled_control_flow(
    any_uncapped: bool,
    next_due: Option<std::time::Instant>,
    now: std::time::Instant,
) -> ControlFlow {
    if any_uncapped {
        ControlFlow::Poll
    } else if let Some(deadline) = next_due {
        if deadline > now {
            ControlFlow::WaitUntil(deadline)
        } else {
            ControlFlow::Poll
        }
    } else {
        ControlFlow::Wait
    }
}

fn register_region_schedule_states(
    regions: &[uzor::render::RenderRegion],
    region_states: &mut HashMap<&'static str, uzor::render::RegionScheduleState>,
) {
    for region in regions {
        region_states
            .entry(region.id)
            .or_insert_with(uzor::render::RegionScheduleState::default);
    }
}

/// Inline backends retain one full composed frame, so one due region requires
/// rebuilding all declared regions. Missing scheduler state is treated as due
/// to keep a newly declared region from disappearing behind an old frame.
fn regions_need_full_inline_repaint(
    regions: &[uzor::render::RenderRegion],
    region_states: &HashMap<&'static str, uzor::render::RegionScheduleState>,
    now: std::time::Instant,
) -> bool {
    regions.iter().any(|region| {
        region_states
            .get(region.id)
            .map_or(true, |state| state.due(region, now))
    })
}

/// A resize changes layout-space coordinates even when application data did
/// not change. Clearing the paint timestamps makes every declared region due
/// once, so retained scenes are rebuilt for the new viewport.
fn invalidate_region_schedule_states(
    region_states: &mut HashMap<&'static str, uzor::render::RegionScheduleState>,
) {
    for state in region_states.values_mut() {
        state.last_painted = None;
    }
}

/// Downcast an opaque `Box<dyn AnyFactory>` to `Box<dyn RenderSurfaceFactory>`.
///
/// Tries each known concrete factory type in turn.  Returns `None` and prints a
/// warning if the concrete type is unrecognised.
fn downcast_any_factory(any_factory: Box<dyn AnyFactory>) -> Option<Box<dyn RenderSurfaceFactory>> {
    let any_box = any_factory.into_any();
    macro_rules! try_downcast {
        ($box:expr, $($T:ty),+) => {{
            let mut b = $box;
            $(
                b = match b.downcast::<$T>() {
                    Ok(f) => return Some(f as Box<dyn RenderSurfaceFactory>),
                    Err(b) => b,
                };
            )+
            eprintln!(
                "[uzor-desktop] from_built: unknown factory type — \
                 use Manager::set_surface_factory() directly"
            );
            None
        }};
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        try_downcast!(
            any_box,
            uzor_render_hub::VelloGpuSurfaceFactory,
            uzor_render_hub::VelloHybridSurfaceFactory,
            uzor_render_hub::WgpuInstancedSurfaceFactory,
            uzor_render_hub::TinySkiaSurfaceFactory,
            uzor_render_hub::VelloCpuSurfaceFactory,
            uzor_render_hub::Canvas2dSurfaceFactory
        )
    }
    #[cfg(target_arch = "wasm32")]
    {
        try_downcast!(any_box, uzor_render_hub::Canvas2dSurfaceFactory)
    }
}

/// Extract the affected window key from a command, if it carries one.
/// Used by the manager to request a redraw on the right OS window
/// after applying an LM-routable agent command.
#[cfg(not(target_arch = "wasm32"))]
fn command_window_key(cmd: &uzor::layout::agent::Command) -> Option<String> {
    use uzor::layout::agent::Command as C;
    match cmd {
        C::InjectHover  { window, .. }
        | C::InjectClick  { window, .. }
        | C::InjectScroll { window, .. }
        | C::InjectDrag   { window, .. }
        | C::ClickWidget  { window, .. }
        | C::HoverWidget  { window, .. }
        | C::OpenModal    { window, .. }
        | C::CloseModal   { window, .. }
        | C::OpenPopup    { window, .. }
        | C::ClosePopup   { window, .. }
        | C::OpenDropdown { window, .. }
        | C::CloseDropdown { window, .. }
        | C::ToggleSidebar { window, .. } => Some(window.clone()),
        C::SpawnWindow { key, .. } | C::CloseWindow { key } => Some(key.clone()),
        C::BlackboxClickWidget { window, .. } => Some(window.clone()),
        C::LogPush { window, .. } => window.clone(),
        C::SetTickRate { window, .. } => Some(window.clone()),
        C::ResizePanelEdge { window, .. }
        | C::DragDockSeparator { window, .. }
        | C::SetPanelRect { window, .. } => Some(window.clone()),
        C::SetSyncMode { .. } | C::ApplyStylePreset { .. } => None,
    }
}

fn argb_to_alpha_color(argb: u32) -> vello::peniko::color::AlphaColor<vello::peniko::color::Srgb> {
    let a = ((argb >> 24) & 0xFF) as f32 / 255.0;
    let r = ((argb >> 16) & 0xFF) as f32 / 255.0;
    let g = ((argb >>  8) & 0xFF) as f32 / 255.0;
    let b = ( argb        & 0xFF) as f32 / 255.0;
    vello::peniko::color::AlphaColor::new([r, g, b, a])
}

#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
fn _suppress_unused(_: &dyn WindowProvider, _: &Rect) {}

#[cfg(test)]
mod tests {
    use super::{
        dispatch_mapped_platform_event, register_region_schedule_states,
        invalidate_region_schedule_states, regions_need_full_inline_repaint,
        scheduled_control_flow,
    };
    use std::cell::Cell;
    use std::collections::HashMap;
    use std::time::Instant;
    use uzor::core::types::Rect;
    use uzor::input::{KeyCode, ModifierKeys, PlatformEvent};
    use uzor::render::{RegionScheduleState, RenderRegion};
    use winit::event_loop::ControlFlow;

    #[test]
    fn declared_regions_register_before_paint_branch_without_affecting_legacy_empty_path() {
        let mut states: HashMap<&'static str, RegionScheduleState> = HashMap::new();

        register_region_schedule_states(&[], &mut states);
        assert!(states.is_empty(), "legacy no-region path must remain empty");

        let regions = [
            RenderRegion::capped("graph", Rect::default(), 60),
            RenderRegion::dirty_driven("inspector", Rect::default()),
        ];
        register_region_schedule_states(&regions, &mut states);

        assert_eq!(states.len(), 2);
        assert!(states.contains_key("graph"));
        assert!(states.contains_key("inspector"));
    }

    #[test]
    fn clean_dirty_only_region_waits_for_an_explicit_wake() {
        let now = Instant::now();
        let mut region = RenderRegion::dirty_driven("flow", Rect::default());
        region.dirty = false;
        let state = RegionScheduleState {
            last_painted: Some(now),
        };

        assert!(!state.due(&region, now));
        assert_eq!(state.next_due(&region, now), None);
        assert!(matches!(
            scheduled_control_flow(false, state.next_due(&region, now), now),
            ControlFlow::Wait,
        ));
    }

    #[test]
    fn inline_region_gate_rebuilds_all_only_when_any_region_is_due() {
        let now = Instant::now();
        let mut graph = RenderRegion::dirty_driven("graph", Rect::default());
        graph.dirty = false;
        let mut inspector = RenderRegion::dirty_driven("inspector", Rect::default());
        inspector.dirty = false;
        let regions = [graph, inspector];
        let mut states: HashMap<&'static str, RegionScheduleState> = HashMap::new();
        states.insert("graph", RegionScheduleState { last_painted: Some(now) });
        states.insert("inspector", RegionScheduleState { last_painted: Some(now) });

        assert!(!regions_need_full_inline_repaint(&regions, &states, now));

        let mut due_regions = regions.clone();
        due_regions[1].dirty = true;
        assert!(regions_need_full_inline_repaint(&due_regions, &states, now));

        states.remove("inspector");
        assert!(
            regions_need_full_inline_repaint(&regions, &states, now),
            "a newly declared region must force one complete rebuild",
        );
    }

    #[test]
    fn resize_invalidation_makes_all_known_regions_due() {
        let now = Instant::now();
        let mut states: HashMap<&'static str, RegionScheduleState> = HashMap::new();
        states.insert("graph", RegionScheduleState { last_painted: Some(now) });
        states.insert("inspector", RegionScheduleState { last_painted: Some(now) });

        invalidate_region_schedule_states(&mut states);

        assert!(states.values().all(|state| state.last_painted.is_none()));
    }

    #[test]
    fn mapped_keyboard_event_is_pushed_and_requests_exactly_one_redraw() {
        let pushes = Cell::new(0);
        let redraws = Cell::new(0);
        let event = PlatformEvent::KeyDown {
            key: KeyCode::A,
            modifiers: ModifierKeys::none(),
        };

        assert!(dispatch_mapped_platform_event(
            Some(event),
            |_| pushes.set(pushes.get() + 1),
            || redraws.set(redraws.get() + 1),
        ));
        assert_eq!(pushes.get(), 1);
        assert_eq!(redraws.get(), 1);
    }
}