plushie 0.7.1

Desktop GUI framework for Rust
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
//! Wire mode runner: subprocess renderer via stdin/stdout.
//!
//! Spawns the plushie renderer binary as a child process and
//! communicates over the plushie wire protocol. The app's view
//! tree is diffed and sent as patches. Events arrive from the
//! renderer and are converted to SDK Event types.
//!
//! SDK-local commands (Async, Cancel, SendAfter) are handled
//! in-process using a background tokio runtime. Async task
//! results and delayed events are delivered through an internal
//! channel and processed alongside renderer events.

#[cfg(feature = "wire")]
use plushie_core::outgoing_message::OutgoingMessage;
#[cfg(feature = "wire")]
use serde_json::Value;
#[cfg(feature = "wire")]
use std::collections::HashMap;
#[cfg(feature = "wire")]
use std::io;

#[cfg(feature = "wire")]
use super::bridge::Bridge;
#[cfg(feature = "wire")]
use super::effect_tracker::{self, EffectTracker};
#[cfg(feature = "wire")]
use super::event_bridge::SinkEvent;
#[cfg(feature = "wire")]
use crate::App;
#[cfg(feature = "wire")]
use crate::command::Command;
#[cfg(feature = "wire")]
use crate::event::{EffectEvent, EffectResult, Event};
#[cfg(feature = "wire")]
use crate::runtime::tree_diff;
#[cfg(feature = "wire")]
use crate::settings::ExitReason;

#[cfg(feature = "wire")]
fn hello_protocol_version(hello: &Value) -> Option<u32> {
    hello
        .get("protocol_version")
        .or_else(|| hello.get("protocol"))
        .and_then(plushie_core::protocol::json_protocol_version)
}

#[cfg(feature = "wire")]
fn hello_string_field<'a>(hello: &'a Value, field: &str) -> &'a str {
    hello
        .get(field)
        .and_then(|value| value.as_str())
        .unwrap_or("unknown")
}

#[cfg(feature = "wire")]
fn hello_optional_string_field<'a>(hello: &'a Value, field: &str) -> &'a str {
    hello
        .get(field)
        .and_then(|value| value.as_str())
        .unwrap_or("None")
}

#[cfg(feature = "wire")]
fn renderer_hello_log_message(hello: &Value) -> String {
    let protocol = hello_protocol_version(hello)
        .map(|version| version.to_string())
        .unwrap_or_else(|| "unknown".to_string());

    format!(
        "renderer hello: name={} protocol={} codec={} mode={} backend={} transport={}",
        hello_string_field(hello, "name"),
        protocol,
        hello_string_field(hello, "codec"),
        hello_string_field(hello, "mode"),
        hello_string_field(hello, "backend"),
        hello_optional_string_field(hello, "transport")
    )
}

#[cfg(feature = "wire")]
fn log_renderer_hello(hello: &Value) {
    log::info!("{}", renderer_hello_log_message(hello));
}

/// Run the app in wire mode.
///
/// Spawns the renderer binary at `binary_path` and communicates
/// over stdin/stdout using the plushie wire protocol.
///
/// Auto-restart is governed by [`App::restart_policy`]. On every
/// unexpected renderer exit the app's [`App::handle_renderer_exit`]
/// hook is called with the matching [`ExitReason`]; if the policy
/// allows, the runner then respawns the subprocess and resends
/// Settings + tree snapshot + subscription state. After
/// `max_restarts` exhaustion the hook fires once more with
/// [`ExitReason::MaxRestartsReached`] and the function returns
/// [`crate::Error::RendererExit`].
///
/// Uses a private 2-worker tokio runtime for SDK-local async work
/// (`Command::Async`, `Command::Stream`, `Command::SendAfter`,
/// effect-timeout scheduling). Apps that already have a tokio
/// runtime should prefer [`run_wire_with_runtime`] to avoid a
/// second runtime living alongside theirs.
///
/// # Errors
///
/// Returns [`crate::Error::Spawn`] when the renderer binary cannot
/// be spawned, [`crate::Error::ProtocolVersionMismatch`] on a
/// handshake version mismatch, [`crate::Error::WireEncode`] or
/// [`crate::Error::WireDecode`] on framing failures, and
/// [`crate::Error::RendererExit`] after the restart policy is
/// exhausted.
#[cfg(feature = "wire")]
pub fn run_wire<A: App>(binary_path: &str) -> crate::Result {
    run_wire_inner::<A>(binary_path, None)
}

/// Run the app in wire mode using a caller-provided tokio runtime.
///
/// Equivalent to [`run_wire`] except SDK-local async tasks are
/// spawned on the supplied [`tokio::runtime::Handle`]. Integration
/// point for apps that already drive their own tokio runtime and
/// want to avoid a second one being created implicitly.
///
/// The handle is only used to spawn tasks; the runtime itself is
/// owned by the caller and must outlive the returned [`crate::Result`].
///
/// # Errors
///
/// Same error conditions as [`run_wire`].
#[cfg(feature = "wire")]
pub fn run_wire_with_runtime<A: App>(
    binary_path: &str,
    runtime: tokio::runtime::Handle,
) -> crate::Result {
    run_wire_inner::<A>(binary_path, Some(runtime))
}

/// Run the app over an already-connected renderer socket.
///
/// Resolves the socket via `opts`, opens a [`SocketAdapter`], hands
/// it to [`Bridge::connect`], and drives a single session (no
/// restart loop; socket mode can't respawn a remote renderer).
///
/// Merges `opts.token` into the Settings message so the renderer's
/// listen-mode token check accepts the connection.
///
/// # Errors
///
/// Same error surface as [`run_wire`] plus:
///
/// - [`crate::Error::InvalidSettings`] when no socket is supplied
///   (neither `opts.socket` nor `PLUSHIE_SOCKET`).
/// - [`crate::Error::Io`] when the connect fails.
#[cfg(feature = "wire")]
pub fn run_connect<A: App>(opts: crate::ConnectOpts) -> crate::Result {
    run_connect_inner::<A>(opts, None)
}

/// [`run_connect`] on a caller-provided tokio runtime.
///
/// # Errors
///
/// Same as [`run_connect`].
#[cfg(feature = "wire")]
pub fn run_connect_with_runtime<A: App>(
    opts: crate::ConnectOpts,
    runtime: tokio::runtime::Handle,
) -> crate::Result {
    run_connect_inner::<A>(opts, Some(runtime))
}

#[cfg(feature = "wire")]
fn run_connect_inner<A: App>(
    opts: crate::ConnectOpts,
    runtime: Option<tokio::runtime::Handle>,
) -> crate::Result {
    let socket_str = opts
        .socket
        .clone()
        .or_else(|| std::env::var("PLUSHIE_SOCKET").ok())
        .ok_or_else(|| {
            crate::Error::InvalidSettings(
                "no socket address supplied: pass `ConnectOpts.socket`, set \
                 PLUSHIE_SOCKET, or use `--plushie-socket <path>`"
                    .to_string(),
            )
        })?;

    let adapter = super::socket::SocketAdapter::connect(&socket_str)?;
    log::info!(
        "plushie::run_connect: connected to renderer at {:?} (token: {})",
        adapter.addr,
        if opts.token.is_some() {
            "present"
        } else {
            "none"
        }
    );
    let bridge = Bridge::connect(adapter.stream)?;

    let mut settings = build_settings::<A>();
    if let Some(tok) = opts.token.as_deref() {
        settings["token"] = Value::String(tok.to_string());
    }

    run_session_single::<A>(bridge, settings, runtime)
}

/// Run one full session against a pre-built bridge.
///
/// Shared by `run_connect_inner`: handshake, snapshot send,
/// subscription sync, main loop. No restart logic; on exit, the
/// normal shutdown / effect-flush / error-propagation path runs and
/// the function returns.
#[cfg(feature = "wire")]
fn run_session_single<A: App>(
    mut bridge: Bridge,
    settings: Value,
    runtime: Option<tokio::runtime::Handle>,
) -> crate::Result {
    let (mut model, init_cmd) = A::init();

    let mut sub_manager = crate::runtime::subscriptions::SubscriptionManager::new();
    let mut effect_tracker = EffectTracker::new();
    let mut async_mgr = AsyncTaskManager::new(runtime);
    let mut view_errors = crate::runtime::view_errors::ViewErrors::default();
    let mut window_sync = crate::runtime::windows::WindowSync::new();

    let seed = plushie_core::protocol::TreeNode {
        id: String::new(),
        type_name: "container".to_string(),
        props: plushie_core::protocol::Props::from(plushie_core::protocol::PropMap::new()),
        children: vec![],
    };
    let mut current_tree = match crate::runtime::view_errors::run_guarded_view_wire::<A>(
        &mut view_errors,
        &model,
        &seed,
    ) {
        crate::runtime::view_errors::ViewOutcome::Ok(tree, _) => tree,
        crate::runtime::view_errors::ViewOutcome::Panicked { last_good, .. } => last_good,
    };

    bridge.send_settings(&settings)?;

    let hello = bridge.receive()?;
    log_renderer_hello(&hello);

    let expected = plushie_core::protocol::PROTOCOL_VERSION;
    let remote_protocol = hello_protocol_version(&hello);
    if remote_protocol != Some(expected) {
        log::error!(
            "protocol version mismatch: SDK expects {expected}, renderer advertised {remote_protocol:?}"
        );
        drop(bridge);
        return Err(crate::Error::ProtocolVersionMismatch {
            expected,
            got: remote_protocol,
        });
    }

    if let Some(remote) = hello.get("version").and_then(|v| v.as_str())
        && remote != crate::RENDERER_VERSION
    {
        log::warn!(
            "renderer version skew: SDK built against {expected}, \
             renderer reports {got}",
            expected = crate::RENDERER_VERSION,
            got = remote,
        );
    }

    if let Some(codec_str) = hello.get("codec").and_then(|v| v.as_str()) {
        let codec = match codec_str {
            "msgpack" => super::bridge::Codec::MsgPack,
            "json" => super::bridge::Codec::Json,
            other => {
                log::warn!("renderer advertised unknown codec `{other}`; keeping JSON");
                super::bridge::Codec::Json
            }
        };
        bridge.set_codec(codec);
    }

    bridge.start_reader()?;

    let snapshot_value = serde_json::to_value(&current_tree)
        .map_err(|e| crate::Error::WireEncode(format!("snapshot: {e}")))?;
    bridge.send_snapshot(&snapshot_value)?;

    for op in window_sync.sync(&current_tree, &settings) {
        dispatch_window_sync_op(&mut bridge, &op)?;
    }

    if let Err(e) = execute_wire_command(&mut bridge, init_cmd, &mut effect_tracker, &mut async_mgr)
    {
        log::error!("initial command execution failed: {e}");
    }

    let new_subs = A::subscribe(&model);
    validate_subscription_windows(&new_subs, &current_tree);
    apply_wire_sub_ops(&mut bridge, &mut async_mgr, sub_manager.sync(new_subs))?;

    let policy = A::restart_policy();
    let reason = run_session::<A>(
        &mut bridge,
        &mut model,
        &mut current_tree,
        &mut effect_tracker,
        &mut async_mgr,
        &mut sub_manager,
        &mut view_errors,
        &mut window_sync,
        &settings,
        policy.heartbeat_interval,
        // Connect mode: the renderer lives in a separate process we
        // didn't spawn. A hot-reload swap signal has no meaningful
        // action here, so the session loop drains and ignores it.
        false,
    );

    log::warn!("plushie wire: renderer exited ({})", reason.label());
    A::handle_renderer_exit(&mut model, reason.clone());

    if matches!(reason, ExitReason::Shutdown) {
        flush_effects_on_shutdown::<A>(&mut model, &mut effect_tracker);
        return Ok(());
    }

    flush_effects_on_shutdown::<A>(&mut model, &mut effect_tracker);
    Err(crate::Error::RendererExit(reason))
}

#[cfg(feature = "wire")]
fn run_wire_inner<A: App>(
    binary_path: &str,
    runtime: Option<tokio::runtime::Handle>,
) -> crate::Result {
    let settings = build_settings::<A>();
    let policy = A::restart_policy();

    // Initialize the app once. The model persists across restarts.
    let (mut model, init_cmd) = A::init();

    let mut sub_manager = crate::runtime::subscriptions::SubscriptionManager::new();
    let mut effect_tracker = EffectTracker::new();
    let mut async_mgr = AsyncTaskManager::new(runtime);
    let mut view_errors = crate::runtime::view_errors::ViewErrors::default();
    let mut window_sync = crate::runtime::windows::WindowSync::new();

    // Initial view; shared across restarts as the "current tree". If
    // the first view call panics there is no last-good tree to fall
    // back to, so we use an empty container as a seed.
    let seed = plushie_core::protocol::TreeNode {
        id: String::new(),
        type_name: "container".to_string(),
        props: plushie_core::protocol::Props::from(plushie_core::protocol::PropMap::new()),
        children: vec![],
    };
    let mut current_tree = match crate::runtime::view_errors::run_guarded_view_wire::<A>(
        &mut view_errors,
        &model,
        &seed,
    ) {
        crate::runtime::view_errors::ViewOutcome::Ok(tree, _) => tree,
        crate::runtime::view_errors::ViewOutcome::Panicked { last_good, .. } => last_good,
    };

    let mut restart_count: u32 = 0;
    let mut pending_init: Option<Command> = Some(init_cmd);

    // Binary path can be swapped between iterations when a dev-mode
    // hot-reload finishes and rediscovery picks a fresh custom build.
    // Seed it with the caller's value; RendererSwap branches rewrite
    // `binary_owned` and the next iteration uses it.
    #[cfg_attr(not(feature = "dev"), allow(unused_mut, unused_assignments))]
    let mut binary_owned: Option<String> = None;

    loop {
        let active_binary: &str = binary_owned.as_deref().unwrap_or(binary_path);

        // Bring up (or respawn) the renderer and establish the
        // reader thread. On respawn we resend settings + snapshot +
        // subscription state so the renderer catches up.
        let mut bridge = Bridge::spawn(active_binary)
            .map_err(|e| crate::Error::spawn(active_binary.to_string(), e))?;

        bridge.send_settings(&settings)?;

        // Synchronous hello read (reader thread not started yet).
        let hello = bridge.receive()?;
        log_renderer_hello(&hello);

        // Protocol-version gate. A mismatch between the SDK's
        // PROTOCOL_VERSION and whatever the renderer advertises is
        // fatal: wire shapes are tied to the version, and proceeding
        // would lead to misparsed messages further down. Reap the
        // child before returning so we don't leave a zombie.
        let expected = plushie_core::protocol::PROTOCOL_VERSION;
        let remote_protocol = hello_protocol_version(&hello);
        if remote_protocol != Some(expected) {
            log::error!(
                "protocol version mismatch: SDK expects {expected}, renderer advertised {remote_protocol:?}"
            );
            drop(bridge);
            return Err(crate::Error::ProtocolVersionMismatch {
                expected,
                got: remote_protocol,
            });
        }

        // CARGO_PKG_VERSION skew is advisory: wire-protocol compatibility
        // is PROTOCOL_VERSION, not CARGO_PKG_VERSION. Divergence often
        // signals a stale installed renderer binary though, so the hint
        // names the exact install command.
        if let Some(remote) = hello.get("version").and_then(|v| v.as_str())
            && remote != crate::RENDERER_VERSION
        {
            log::warn!(
                "renderer version skew: SDK built against {expected}, \
                 renderer reports {got}; run `cargo install plushie-renderer --version {expected}` \
                 if this is unexpected",
                expected = crate::RENDERER_VERSION,
                got = remote,
            );
        }

        // Keep the bridge aligned with the renderer's codec confirmation.
        // The renderer already knows the codec before emitting hello.
        if let Some(codec_str) = hello.get("codec").and_then(|v| v.as_str()) {
            let codec = match codec_str {
                "msgpack" => super::bridge::Codec::MsgPack,
                "json" => super::bridge::Codec::Json,
                other => {
                    log::warn!("renderer advertised unknown codec `{other}`; keeping JSON");
                    super::bridge::Codec::Json
                }
            };
            bridge.set_codec(codec);
        }

        bridge.start_reader()?;

        // Send snapshot so the renderer has the current tree.
        let snapshot_value = serde_json::to_value(&current_tree)
            .map_err(|e| crate::Error::WireEncode(format!("snapshot: {e}")))?;
        bridge.send_snapshot(&snapshot_value)?;

        // On restart, abort every SDK-side task tied to the previous
        // renderer session. Without this, recurring timers, async
        // results, send_after deliveries, and effect-timeout tasks
        // accumulate across restarts and fire delayed events into
        // the new session. The matching renderer-side state (tree,
        // subscriptions, in-flight effects) is replayed below; the
        // task replay path runs through the normal subscription diff
        // and re-issues StartTimer ops, so clearing the timer table
        // here is safe.
        if restart_count > 0 {
            async_mgr.cancel_all_running();
            async_mgr.clear_all_timers();
            async_mgr.clear_all_effect_timeouts();
            async_mgr.clear_all_send_after();
        }

        // Synchronize window lifecycle with the renderer. On restart,
        // reset the tracker so every current window is resent as an
        // `open` op; otherwise replay from whatever the tracker held
        // before. The base settings object is the same JSON the SDK
        // sent via send_settings, so per-window prop merges reuse it
        // directly.
        if restart_count > 0 {
            window_sync = crate::runtime::windows::WindowSync::new();
        }
        for op in window_sync.sync(&current_tree, &settings) {
            dispatch_window_sync_op(&mut bridge, &op)?;
        }

        // Execute the initial command once (only on the first spawn).
        // Subscriptions and in-flight commands are replayed below.
        if let Some(cmd) = pending_init.take()
            && let Err(e) =
                execute_wire_command(&mut bridge, cmd, &mut effect_tracker, &mut async_mgr)
        {
            log::error!("initial command execution failed: {e}");
        }

        // Subscription sync. On restart this replays the full set.
        let new_subs = A::subscribe(&model);
        // Force a full resync by clearing the manager state so every
        // current subscription is re-emitted as a Subscribe op.
        if restart_count > 0 {
            sub_manager = crate::runtime::subscriptions::SubscriptionManager::new();
        }
        validate_subscription_windows(&new_subs, &current_tree);
        apply_wire_sub_ops(&mut bridge, &mut async_mgr, sub_manager.sync(new_subs))?;

        // After a restart, flush all in-flight effects with
        // RendererRestarted so the app can react (image re-upload,
        // etc.). On first spawn this is a no-op.
        if restart_count > 0 {
            for (tag, _kind) in effect_tracker.flush_all() {
                let event = Event::Effect(EffectEvent {
                    tag,
                    result: EffectResult::RendererRestarted,
                });
                // Guarded so a panic in the app's restart-handling
                // branch doesn't kill the main thread before the new
                // renderer is fully wired up.
                let _ = crate::runtime::view_errors::run_guarded_update::<A>(
                    &mut view_errors,
                    &mut model,
                    event,
                );
            }
        }

        // Run the main event loop until the renderer exits. The
        // inner function returns the classified ExitReason on break.
        let reason = run_session::<A>(
            &mut bridge,
            &mut model,
            &mut current_tree,
            &mut effect_tracker,
            &mut async_mgr,
            &mut sub_manager,
            &mut view_errors,
            &mut window_sync,
            &settings,
            policy.heartbeat_interval,
            // Spawn mode: we own the renderer subprocess and can
            // respawn it, so dev-mode swap signals are actionable.
            true,
        );

        log::warn!(
            "plushie wire: renderer exited ({}); restart count = {}",
            reason.label(),
            restart_count
        );

        // Always call the app's exit hook; this lets apps save state
        // or log before the (potentially final) restart attempt.
        A::handle_renderer_exit(&mut model, reason.clone());

        // Shutdown: do not restart. Drain any in-flight effects with
        // EffectResult::Shutdown so the app can release associated
        // resources (progress bars, loading flags) instead of
        // waiting forever on a response that will never come.
        if matches!(reason, ExitReason::Shutdown) {
            flush_effects_on_shutdown::<A>(&mut model, &mut effect_tracker);
            return Ok(());
        }

        // Dev-mode hot-reload: skip backoff, reset restart count
        // (a clean swap shouldn't eat into the crash budget),
        // rediscover the binary so the fresh build is picked up,
        // then loop around. The Bridge drop at the bottom of this
        // iteration tears down the old subprocess; the next
        // iteration spawns its replacement.
        if matches!(reason, ExitReason::RendererSwap) {
            restart_count = 0;
            #[cfg(feature = "dev")]
            {
                match crate::runner::wire_discovery::discover_renderer() {
                    Ok(fresh) => {
                        log::info!("plushie wire: swap-discovered renderer at {fresh}");
                        binary_owned = Some(fresh);
                    }
                    Err(e) => {
                        log::warn!(
                            "plushie wire: swap-rediscovery failed ({e}); \
                             reusing current binary path"
                        );
                    }
                }
            }
            drop(bridge);
            continue;
        }

        // Restart policy: if we're out of attempts, fire a final
        // hook call and return the typed error.
        if restart_count >= policy.max_restarts {
            let final_reason = ExitReason::MaxRestartsReached {
                last_reason: Box::new(reason.clone()),
            };
            A::handle_renderer_exit(&mut model, final_reason.clone());
            // Max-restarts is a terminal state; flush pending effects
            // as Shutdown too so the app sees the same drained state
            // as on a clean shutdown.
            flush_effects_on_shutdown::<A>(&mut model, &mut effect_tracker);
            return Err(crate::Error::RendererExit(final_reason));
        }

        // Exponential backoff before respawning.
        let delay = policy
            .restart_delay
            .saturating_mul(2u32.saturating_pow(restart_count));
        log::info!(
            "plushie wire: restarting renderer in {}ms (attempt {}/{})",
            delay.as_millis(),
            restart_count + 1,
            policy.max_restarts
        );
        std::thread::sleep(delay);
        restart_count += 1;

        // Bridge is dropped here; its Drop kills + reaps the old
        // child. We rebuild cleanly next iteration.
        drop(bridge);
    }
}

/// Drain pending effects with [`EffectResult::Shutdown`].
///
/// Called on runner teardown (clean shutdown or max-restarts
/// exhaustion) so the app observes a terminal event for each
/// in-flight effect rather than a silent drop.
#[cfg(feature = "wire")]
fn flush_effects_on_shutdown<A: App>(model: &mut A::Model, effect_tracker: &mut EffectTracker) {
    let pending = effect_tracker.pending_count();
    if pending == 0 {
        return;
    }
    log::info!("wire shutdown: flushing {pending} in-flight effect(s) as Shutdown");
    // Ephemeral error tracking: shutdown is terminal, so a fresh
    // counter is fine. The guard still logs any panic instead of
    // crashing the process during teardown.
    let mut shutdown_errors = crate::runtime::view_errors::ViewErrors::default();
    for (tag, _kind) in effect_tracker.flush_all() {
        let event = Event::Effect(EffectEvent {
            tag,
            result: EffectResult::Shutdown,
        });
        // Fire-and-forget: commands returned from update() are
        // discarded on teardown since the wire is already closing.
        let _ = crate::runtime::view_errors::run_guarded_update::<A>(
            &mut shutdown_errors,
            model,
            event,
        );
    }
}

/// Run one session against an already-spawned renderer. Returns the
/// classified [`ExitReason`] when the session ends (renderer
/// disconnect, crash, heartbeat timeout, or explicit shutdown).
///
/// `manages_renderer_lifecycle` controls whether the dev-mode swap
/// signal is honored. Spawn-mode callers (`run_wire_inner`) own the
/// renderer subprocess and can respawn it, so they pass `true` and
/// get back `ExitReason::RendererSwap`. Connect-mode callers
/// (`run_session_single`) are attached to an external renderer they
/// did not spawn; they pass `false` and the signal is drained and
/// ignored so a hot-reload rebuild in a parallel dev session does
/// not tear down the connected session.
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "wire")]
fn run_session<A: App>(
    bridge: &mut Bridge,
    model: &mut A::Model,
    current_tree: &mut plushie_core::protocol::TreeNode,
    effect_tracker: &mut EffectTracker,
    async_mgr: &mut AsyncTaskManager,
    sub_manager: &mut crate::runtime::subscriptions::SubscriptionManager,
    view_errors: &mut crate::runtime::view_errors::ViewErrors,
    window_sync: &mut crate::runtime::windows::WindowSync,
    base_settings: &Value,
    heartbeat_interval: Option<std::time::Duration>,
    manages_renderer_lifecycle: bool,
) -> ExitReason {
    // Dev-mode needs to wake up periodically to check for swap
    // signals even when the heartbeat is disabled or set to a long
    // interval. The poll window picks the shorter of the two.
    #[cfg(feature = "dev")]
    let poll_interval = heartbeat_interval
        .unwrap_or(std::time::Duration::from_millis(250))
        .min(std::time::Duration::from_millis(250));
    #[cfg(not(feature = "dev"))]
    let poll_interval_opt = heartbeat_interval;
    #[cfg(feature = "dev")]
    let mut since_last_msg = std::time::Instant::now();

    loop {
        // Dev-mode swap signal takes priority when this session owns
        // the renderer subprocess: a successful rebuild means the
        // current binary is stale, so we return RendererSwap and let
        // the outer loop respawn without counting against the restart
        // policy. In connect mode we drain the queue but discard the
        // signal so a parallel dev session's rebuild doesn't tear
        // down the connected session. Compiled out when the `dev`
        // feature is absent.
        #[cfg(feature = "dev")]
        {
            if handle_dev_control_signals() && manages_renderer_lifecycle {
                return ExitReason::RendererSwap;
            }
        }
        #[cfg(not(feature = "dev"))]
        let _ = manages_renderer_lifecycle;

        #[cfg(feature = "dev")]
        let incoming = bridge.recv_timeout(Some(poll_interval));
        #[cfg(not(feature = "dev"))]
        let incoming = bridge.recv_timeout(poll_interval_opt);

        // Map a short dev-mode poll Timeout into either "keep going"
        // (heartbeat hasn't elapsed yet, or is disabled) or a real
        // HeartbeatTimeout.
        #[cfg(feature = "dev")]
        let incoming = match (&incoming, heartbeat_interval) {
            (super::bridge::Incoming::Timeout, Some(hb)) => {
                if since_last_msg.elapsed() >= hb {
                    incoming
                } else {
                    continue;
                }
            }
            (super::bridge::Incoming::Timeout, None) => continue,
            _ => {
                since_last_msg = std::time::Instant::now();
                incoming
            }
        };

        match incoming {
            super::bridge::Incoming::Message(raw) => {
                let events = wire_to_sdk_events(&raw, effect_tracker, async_mgr);
                for event in events {
                    if let Err(e) = process_event::<A>(
                        model,
                        event,
                        bridge,
                        current_tree,
                        effect_tracker,
                        async_mgr,
                        sub_manager,
                        view_errors,
                        window_sync,
                        base_settings,
                    ) {
                        log::error!("command execution failed: {e}");
                    }
                }
            }
            super::bridge::Incoming::Error(e) => {
                log::error!("renderer connection lost: {e}");
                return classify_exit(bridge, &e);
            }
            super::bridge::Incoming::Timeout => {
                log::warn!(
                    "plushie wire: no message in {:?}, triggering restart",
                    heartbeat_interval
                );
                return ExitReason::HeartbeatTimeout;
            }
        }

        // Drain async results, delayed events, and effect timeouts
        // that arrived while we were waiting on the bridge.
        for sink_event in async_mgr.drain() {
            let event = match sink_event {
                SinkEvent::EffectTimeout { wire_id } => {
                    // Resolve to the user tag via the tracker; emit
                    // Timeout. Skip if already resolved by a
                    // response that raced the deadline.
                    match effect_tracker.resolve(&wire_id) {
                        Some((tag, kind)) => {
                            log::debug!(
                                "wire effect timeout resolved: wire_id={wire_id} tag={tag} kind={kind}"
                            );
                            Some(Event::Effect(EffectEvent {
                                tag,
                                result: EffectResult::Timeout,
                            }))
                        }
                        None => {
                            log::debug!(
                                "wire effect timeout fired after resolution: wire_id={wire_id}"
                            );
                            None
                        }
                    }
                }
                other => super::event_bridge::sink_event_to_sdk(other),
            };
            if let Some(event) = event
                && let Err(e) = process_event::<A>(
                    model,
                    event,
                    bridge,
                    current_tree,
                    effect_tracker,
                    async_mgr,
                    sub_manager,
                    view_errors,
                    window_sync,
                    base_settings,
                )
            {
                log::error!("async event processing failed: {e}");
            }
        }
    }
}

/// Process a single SDK event through the full MVU cycle:
/// update -> view -> normalize -> diff -> patch -> sub sync.
///
/// Wraps `A::view()` in the view-errors guard so a panic falls
/// back to the last-good tree and increments the consecutive
/// counter (frozen-UI overlay at threshold).
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "wire")]
fn process_event<A: App>(
    model: &mut A::Model,
    event: Event,
    bridge: &mut Bridge,
    current_tree: &mut plushie_core::protocol::TreeNode,
    effect_tracker: &mut EffectTracker,
    async_mgr: &mut AsyncTaskManager,
    sub_manager: &mut crate::runtime::subscriptions::SubscriptionManager,
    view_errors: &mut crate::runtime::view_errors::ViewErrors,
    window_sync: &mut crate::runtime::windows::WindowSync,
    base_settings: &Value,
) -> crate::Result {
    // Dev-mode overlay interception: if the event belongs to the
    // rebuilding-overlay ID namespace, handle it internally and skip
    // the app's update. Compiled out when the `dev` feature is off.
    #[cfg(feature = "dev")]
    {
        if crate::dev::intercept_event(&event) {
            return Ok(());
        }
    }
    let cmd = match crate::runtime::view_errors::run_guarded_update::<A>(view_errors, model, event)
    {
        crate::runtime::view_errors::UpdateOutcome::Ok(cmd) => cmd,
        crate::runtime::view_errors::UpdateOutcome::Panicked { cmd, .. } => cmd,
    };
    execute_wire_command(bridge, cmd, effect_tracker, async_mgr)?;

    // Re-render and diff under panic guard.
    let outcome =
        crate::runtime::view_errors::run_guarded_view_wire::<A>(view_errors, model, current_tree);
    let new_tree = match outcome {
        crate::runtime::view_errors::ViewOutcome::Ok(tree, warnings) => {
            for warning in &warnings {
                log::warn!("view normalization: {warning}");
            }
            tree
        }
        crate::runtime::view_errors::ViewOutcome::Panicked { last_good, .. } => last_good,
    };

    // Window lifecycle sync runs *before* tree diff so an
    // open_window op precedes any patch that references the new
    // window's subtree. Close ops trail for the same reason: the
    // renderer still needs the window alive while applying the
    // remove patches inside it. Update ops are order-insensitive.
    for op in window_sync.sync(&new_tree, base_settings) {
        dispatch_window_sync_op(bridge, &op)?;
    }

    let patches = tree_diff::diff_tree(current_tree, &new_tree);
    if !patches.is_empty() {
        let ops: Vec<Value> = patches
            .iter()
            .filter_map(|op| serde_json::to_value(op).ok())
            .collect();
        bridge.send_patch(&ops)?;
    }

    *current_tree = new_tree;

    // Sync subscriptions.
    let new_subs = A::subscribe(model);
    validate_subscription_windows(&new_subs, current_tree);
    apply_wire_sub_ops(bridge, async_mgr, sub_manager.sync(new_subs))?;

    Ok(())
}

/// Emit an `unknown_window` diagnostic for any subscription whose
/// `window_id` does not appear in the current tree.
///
/// The renderer accepts the subscription either way and just never
/// delivers events for a dangling window, which is a silent failure
/// mode. This diagnostic surfaces the typo / stale wiring loudly.
#[cfg(feature = "wire")]
fn validate_subscription_windows(
    subs: &[crate::subscription::Subscription],
    tree: &plushie_core::protocol::TreeNode,
) {
    let windows = crate::runtime::windows::detect_windows(tree);
    for sub in subs {
        if let Some(wid) = sub.window_id()
            && !windows.contains(wid)
        {
            plushie_core::diagnostics::warn(plushie_core::Diagnostic::UnknownWindow {
                window_id: wid.to_string(),
                subscription_tag: sub.kind().to_string(),
            });
        }
    }
}

/// Translate a [`WindowSyncOp`] into the bridge's window-op wire
/// message.
#[cfg(feature = "wire")]
fn dispatch_window_sync_op(
    bridge: &mut Bridge,
    op: &crate::runtime::windows::WindowSyncOp,
) -> crate::Result {
    use crate::runtime::windows::WindowSyncOp;
    match op {
        WindowSyncOp::Open {
            window_id,
            settings,
        } => bridge.send_window_op("open", window_id, settings),
        WindowSyncOp::Close { window_id } => {
            bridge.send_window_op("close", window_id, &Value::Null)
        }
        WindowSyncOp::Update {
            window_id,
            settings,
        } => bridge.send_window_op("update", window_id, settings),
    }
}

/// Classify a bridge receive error into a typed [`ExitReason`].
///
/// `UnexpectedEof` indicates the renderer closed stdout cleanly but
/// without sending a proper shutdown marker; everything else is
/// treated as a crash. Reaps the child (non-blocking) to capture the
/// exit code for `Crash`.
/// Drain the dev-mode control-signal queue. Returns true when a
/// [`crate::dev::ControlSignal::SwapRenderer`] is pending so the
/// session loop can return a [`ExitReason::RendererSwap`]. Any other
/// signal variants are logged and discarded (reserved for future
/// use).
#[cfg(all(feature = "wire", feature = "dev"))]
fn handle_dev_control_signals() -> bool {
    let signals = crate::dev::drain_control_signals();
    let mut swap = false;
    for signal in signals {
        match signal {
            crate::dev::ControlSignal::SwapRenderer => {
                log::info!("plushie wire: dev-mode swap requested; restarting renderer");
                swap = true;
            }
        }
    }
    swap
}

#[cfg(feature = "wire")]
fn classify_exit(bridge: &mut Bridge, err: &io::Error) -> ExitReason {
    match err.kind() {
        io::ErrorKind::UnexpectedEof => ExitReason::ConnectionLost,
        _ => {
            let code = bridge.try_reap();
            ExitReason::Crash {
                message: err.to_string(),
                code,
            }
        }
    }
}

/// Typed representation of a single renderer -> SDK message.
///
/// Mirrors the outgoing shapes in plushie-core's OutgoingEvent /
/// response families. Unknown messages decode into
/// [`IncomingRendererMessage::Unknown`] so a SDK/renderer version
/// skew produces a diagnostic rather than a silent drop.
#[cfg(feature = "wire")]
#[derive(Debug)]
enum IncomingRendererMessage {
    Event {
        family: String,
        id: String,
        value: Option<Value>,
        tag: Option<String>,
        modifiers: Option<plushie_core::protocol::KeyModifiers>,
        captured: Option<bool>,
    },
    EffectResponse {
        id: String,
        status: &'static str,
        result: Option<Value>,
        error: Option<String>,
    },
    QueryResponse {
        kind: String,
        tag: String,
        data: Value,
    },
    InteractStep {
        #[allow(dead_code)]
        id: String,
        events: Vec<Value>,
    },
    InteractResponse {
        #[allow(dead_code)]
        id: String,
        events: Vec<Value>,
    },
    /// Message type the SDK doesn't recognise. Preserves the type
    /// string and raw payload so diagnostics can surface version
    /// skew cleanly.
    Unknown {
        msg_type: String,
        #[allow(dead_code)] // Retained for log-only diagnostic use.
        raw: Value,
    },
}

/// Decode a top-level wire message into a typed variant.
#[cfg(feature = "wire")]
fn decode_incoming(msg: &Value) -> Option<IncomingRendererMessage> {
    let msg_type = msg.get("type").and_then(|v| v.as_str())?;
    let decoded = match msg_type {
        "event" => {
            let family = msg.get("family").and_then(|v| v.as_str())?.to_string();
            let id = msg
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string();
            IncomingRendererMessage::Event {
                family,
                id,
                value: msg.get("value").cloned(),
                tag: msg
                    .get("tag")
                    .and_then(|v| v.as_str())
                    .map(ToString::to_string),
                modifiers: msg
                    .get("modifiers")
                    .and_then(|v| serde_json::from_value(v.clone()).ok()),
                captured: msg.get("captured").and_then(|v| v.as_bool()),
            }
        }
        "effect_response" => {
            let id = msg.get("id").and_then(|v| v.as_str())?.to_string();
            let status = match msg.get("status").and_then(|v| v.as_str()) {
                Some("ok") => "ok",
                Some("cancelled") => "cancelled",
                Some("unsupported") => "unsupported",
                _ => "error",
            };
            IncomingRendererMessage::EffectResponse {
                id,
                status,
                result: msg.get("result").cloned(),
                error: msg.get("error").and_then(|v| v.as_str()).map(String::from),
            }
        }
        "query_response" | "op_query_response" => {
            let kind = msg
                .get("kind")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let tag = msg
                .get("tag")
                .or_else(|| msg.get("id"))
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string();
            let data = msg
                .get("result")
                .or_else(|| msg.get("data"))
                .cloned()
                .unwrap_or(Value::Null);
            IncomingRendererMessage::QueryResponse { kind, tag, data }
        }
        "interact_step" => {
            let id = msg
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let events = msg
                .get("events")
                .and_then(|v| v.as_array())
                .cloned()
                .unwrap_or_default();
            IncomingRendererMessage::InteractStep { id, events }
        }
        "interact_response" => {
            let id = msg
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let events = msg
                .get("events")
                .and_then(|v| v.as_array())
                .cloned()
                .unwrap_or_default();
            IncomingRendererMessage::InteractResponse { id, events }
        }
        other => IncomingRendererMessage::Unknown {
            msg_type: other.to_string(),
            raw: msg.clone(),
        },
    };
    Some(decoded)
}

/// Convert a wire protocol JSON message to SDK Events.
///
/// Decodes into [`IncomingRendererMessage`] first so unknown
/// message types are preserved as `Unknown` and surface through the
/// diagnostic channel instead of being silently dropped.
#[cfg(feature = "wire")]
fn wire_to_sdk_events(
    msg: &Value,
    effect_tracker: &mut EffectTracker,
    async_mgr: &mut AsyncTaskManager,
) -> Vec<Event> {
    use super::event_bridge::{SinkEvent, sink_event_to_sdk};
    use plushie_core::protocol::{EffectResponse, OutgoingEvent};

    let Some(decoded) = decode_incoming(msg) else {
        // No `type` field at all: not our message shape. We are on the
        // SDK side here (reading renderer output), so the diagnostic
        // channel hook on the renderer does not apply; log as error
        // with the raw payload for diagnosis.
        plushie_core::diagnostics::error(plushie_core::Diagnostic::UnknownMessageType {
            msg_type: String::new(),
        });
        log::error!("raw unknown-type message: {msg}");
        return vec![];
    };

    let sink_event = match decoded {
        IncomingRendererMessage::InteractStep { id: _, events }
        | IncomingRendererMessage::InteractResponse { id: _, events } => {
            // Interact responses contain multiple events that each
            // need a full MVU cycle. Recursively convert each one.
            return events
                .iter()
                .flat_map(|e| wire_to_sdk_events(e, effect_tracker, async_mgr))
                .collect();
        }
        IncomingRendererMessage::Unknown { msg_type, raw: _ } => {
            plushie_core::diagnostics::error(plushie_core::Diagnostic::UnknownMessageType {
                msg_type,
            });
            return vec![];
        }
        IncomingRendererMessage::Event {
            family,
            id,
            value,
            tag,
            modifiers,
            captured,
        } => {
            let mut event = OutgoingEvent::generic(family, id, value);
            event.tag = tag;
            event.modifiers = modifiers;
            event.captured = captured;
            SinkEvent::Event(event)
        }
        IncomingRendererMessage::EffectResponse {
            id: wire_id,
            status,
            result,
            error,
        } => {
            // Cancel the tokio-scheduled deadline task now that a
            // real response has arrived. Cheap if the task already
            // completed (rare).
            async_mgr.cancel_effect_timeout(&wire_id);
            // Resolve via the tracker for typed result parsing.
            if let Some((tag, kind)) = effect_tracker.resolve(&wire_id) {
                log::debug!(
                    "wire effect response resolved: wire_id={wire_id} tag={tag} kind={kind} status={status}"
                );
                let error_as_value = error.as_ref().map(|e| Value::String(e.clone()));
                let value = result.as_ref().or(error_as_value.as_ref());
                let result = EffectResult::parse(&kind, status, value);
                return vec![Event::Effect(EffectEvent { tag, result })];
            }

            log::debug!(
                "wire effect response without tracked request: wire_id={wire_id} status={status}"
            );
            let response = EffectResponse {
                message_type: "effect_response",
                session: String::new(),
                id: wire_id,
                status,
                result,
                error,
            };
            SinkEvent::EffectResponse(response)
        }
        IncomingRendererMessage::QueryResponse { kind, tag, data } => {
            SinkEvent::QueryResponse { kind, tag, data }
        }
    };

    sink_event_to_sdk(sink_event).into_iter().collect()
}

// ---------------------------------------------------------------------------
// Async task manager: handles Command::Async, Cancel, and SendAfter
// ---------------------------------------------------------------------------

/// Manages SDK-local async tasks and delayed events for wire mode.
///
/// Spawns a background tokio runtime for async work. Results and
/// delayed events are sent through a bounded mpsc channel that the
/// main event loop polls between renderer messages. The 1024 slot
/// capacity matches the backpressure pattern used by the headless
/// multiplex writer.
/// Tokio runtime backing: either a caller-supplied handle or a
/// privately owned 2-worker runtime.
#[cfg(feature = "wire")]
enum RuntimeBacking {
    Handle(tokio::runtime::Handle),
    Owned(tokio::runtime::Runtime),
}

#[cfg(feature = "wire")]
impl RuntimeBacking {
    fn handle(&self) -> tokio::runtime::Handle {
        match self {
            Self::Handle(h) => h.clone(),
            Self::Owned(rt) => rt.handle().clone(),
        }
    }
}

#[cfg(feature = "wire")]
struct AsyncTaskManager {
    runtime: RuntimeBacking,
    tx: std::sync::mpsc::SyncSender<SinkEvent>,
    rx: std::sync::mpsc::Receiver<SinkEvent>,
    running: HashMap<String, tokio::task::JoinHandle<()>>,
    /// Pending effect timeout tasks keyed by tracker wire ID.
    ///
    /// Aborted when a response arrives so the deadline task does
    /// not fire for a completed effect.
    effect_timeouts: HashMap<String, tokio::task::JoinHandle<()>>,
    /// Recurring-timer tasks keyed by subscription tag.
    ///
    /// Each tagged `Subscription::every` spawns a tokio interval
    /// task that pushes a `SinkEvent::DelayedEvent` carrying a
    /// timer-tick event on each fire. Aborted on `stop_timer` or
    /// AsyncTaskManager drop.
    timers: HashMap<String, tokio::task::JoinHandle<()>>,
    /// In-flight `Command::SendAfter` delivery tasks. Tracked so a
    /// renderer restart can abort them before they fire delayed
    /// events from a pre-restart context after the renderer is
    /// already gone.
    send_after_handles: Vec<tokio::task::JoinHandle<()>>,
}

#[cfg(feature = "wire")]
impl AsyncTaskManager {
    /// Bounded capacity for async-result delivery. Matches the
    /// headless multiplex writer pattern; generous for typical
    /// workloads while preventing runaway growth.
    const CHANNEL_CAPACITY: usize = 1024;

    fn new(external: Option<tokio::runtime::Handle>) -> Self {
        let runtime = match external {
            Some(handle) => RuntimeBacking::Handle(handle),
            None => {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .worker_threads(2)
                    .enable_all()
                    .build()
                    .expect("failed to create tokio runtime for wire async");
                RuntimeBacking::Owned(rt)
            }
        };
        let (tx, rx) = std::sync::mpsc::sync_channel(Self::CHANNEL_CAPACITY);
        Self {
            runtime,
            tx,
            rx,
            running: HashMap::new(),
            effect_timeouts: HashMap::new(),
            timers: HashMap::new(),
            send_after_handles: Vec::new(),
        }
    }

    /// Spawn a tokio sleep task that posts an [`SinkEvent::EffectTimeout`]
    /// once the deadline elapses.
    ///
    /// The task is keyed by the tracker's wire ID so a response can
    /// cancel it via [`Self::cancel_effect_timeout`]. The timeout
    /// fires regardless of whether the wire reader is currently
    /// blocked, closing the "deadline only checked on next incoming
    /// message" gap in the old polling design.
    fn schedule_effect_timeout(&mut self, wire_id: String, duration: std::time::Duration) {
        // Replace any prior timeout task for this wire ID.
        if let Some(handle) = self.effect_timeouts.remove(&wire_id) {
            log::debug!("wire effect timeout task cancelled: wire_id={wire_id}");
            handle.abort();
        }
        log::debug!("wire effect timeout task scheduled: wire_id={wire_id} duration={duration:?}");
        let tx = self.tx.clone();
        let wire_id_for_task = wire_id.clone();
        let handle = self.runtime.handle().spawn(async move {
            tokio::time::sleep(duration).await;
            log::debug!("wire effect timeout task fired: wire_id={wire_id_for_task}");
            let _ = tx.send(SinkEvent::EffectTimeout {
                wire_id: wire_id_for_task,
            });
        });
        self.effect_timeouts.insert(wire_id, handle);
    }

    /// Cancel a pending effect-timeout task by wire ID.
    ///
    /// Called when a response arrives before the deadline so the
    /// scheduled SinkEvent::EffectTimeout is never emitted.
    fn cancel_effect_timeout(&mut self, wire_id: &str) {
        if let Some(handle) = self.effect_timeouts.remove(wire_id) {
            log::debug!("wire effect timeout task cancelled: wire_id={wire_id}");
            handle.abort();
        }
    }

    /// Start a recurring SDK-side timer for [`Subscription::every`].
    ///
    /// Spawns a tokio interval task on the runtime that pushes a
    /// `SinkEvent::DelayedEvent(Event::Timer(...))` on each tick. The
    /// main event loop picks those up via [`Self::drain`] and routes
    /// them through the same path as async results.
    ///
    /// Replaces any existing timer with the same tag (matches the
    /// direct mode behaviour where `active_timers.insert` replaces).
    fn start_timer(&mut self, tag: String, interval: std::time::Duration) {
        if let Some(handle) = self.timers.remove(&tag) {
            handle.abort();
        }
        let tx = self.tx.clone();
        let tag_for_task = tag.clone();
        let handle = self.runtime.handle().spawn(async move {
            let mut ticker = tokio::time::interval(interval);
            // Skip the immediate tick (tokio::interval fires once at
            // start); users expect the first fire to land after
            // `interval` has elapsed, matching iced's `time::every`.
            ticker.tick().await;
            loop {
                ticker.tick().await;
                let timestamp = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis() as u64;
                let event = Event::Timer(crate::event::TimerEvent {
                    tag: tag_for_task.clone(),
                    timestamp,
                });
                if tx.send(SinkEvent::DelayedEvent(event)).is_err() {
                    // Main loop tore down; stop ticking.
                    break;
                }
            }
        });
        self.timers.insert(tag, handle);
    }

    /// Stop a recurring timer by tag.
    fn stop_timer(&mut self, tag: &str) {
        if let Some(handle) = self.timers.remove(tag) {
            handle.abort();
        }
    }

    fn spawn_async(&mut self, tag: String, task_fn: crate::command::AsyncTaskFn) {
        // Cancel any existing task with the same tag.
        if let Some(handle) = self.running.remove(&tag) {
            handle.abort();
        }

        let tx = self.tx.clone();
        let tag_clone = tag.clone();
        let handle = self.runtime.handle().spawn(async move {
            let future = (task_fn)();
            // Guard against user-future panics so the app sees an
            // AsyncEvent(Err(..)) instead of silently hanging.
            let result = super::run_task_with_panic_guard(&tag_clone, future).await;
            let _ = tx.send(SinkEvent::AsyncResult {
                tag: tag_clone,
                result,
            });
        });
        self.running.insert(tag, handle);
    }

    fn spawn_stream(&mut self, tag: String, task_fn: crate::command::StreamTaskFn) {
        if let Some(handle) = self.running.remove(&tag) {
            handle.abort();
        }

        let tx_stream = self.tx.clone();
        let tx_final = self.tx.clone();
        let tag_for_sink = tag.clone();
        let tag_for_result = tag.clone();

        let emitter = crate::command::StreamEmitter::buffered(&tag);
        emitter.attach_sink(Box::new(move |t, value| {
            let _ = tx_stream.send(SinkEvent::StreamValue { tag: t, value });
            let _ = &tag_for_sink;
        }));

        let handle = self.runtime.handle().spawn(async move {
            let future = (task_fn)(emitter);
            let result = super::run_task_with_panic_guard(&tag_for_result, future).await;
            let _ = tx_final.send(SinkEvent::AsyncResult {
                tag: tag_for_result,
                result,
            });
        });
        self.running.insert(tag, handle);
    }

    fn cancel(&mut self, tag: &str) {
        if let Some(handle) = self.running.remove(tag) {
            handle.abort();
        }
    }

    /// Synchronously push a SinkEvent onto the delivery channel. Used
    /// for synthetic events (e.g. one-per-tag cancellation) that need
    /// to interleave with async results drained by the main loop.
    ///
    /// A full channel drops the event silently: the runtime is
    /// already wedged, there is no recovery path worth taking.
    fn deliver_sink_event(&self, event: SinkEvent) {
        let _ = self.tx.send(event);
    }

    fn send_after(&mut self, delay: std::time::Duration, event: crate::event::Event) {
        let tx = self.tx.clone();
        let handle = self.runtime.handle().spawn(async move {
            // tokio::time::sleep doesn't panic in practice, but we
            // route through the panic guard for consistency with the
            // other spawn paths. SendAfter carries a delivery-only
            // future, so the result slot is unused.
            use futures::FutureExt;
            let fut = async move { tokio::time::sleep(delay).await };
            let _ = std::panic::AssertUnwindSafe(fut).catch_unwind().await;
            let _ = tx.send(SinkEvent::DelayedEvent(event));
        });
        // Drop already-completed handles opportunistically so the Vec
        // stays roughly proportional to in-flight delays rather than
        // total send_after calls over the session lifetime.
        self.send_after_handles
            .retain(|h: &tokio::task::JoinHandle<()>| !h.is_finished());
        self.send_after_handles.push(handle);
    }

    /// Abort and forget every in-flight async/stream task. Used on
    /// renderer restart so long-running futures from a pre-restart
    /// context do not deliver their results into the new session.
    fn cancel_all_running(&mut self) {
        for (_, handle) in self.running.drain() {
            handle.abort();
        }
    }

    /// Abort all recurring timer tasks and clear the table. The new
    /// session re-issues StartTimer ops via the subscription diff.
    fn clear_all_timers(&mut self) {
        for (_, handle) in self.timers.drain() {
            handle.abort();
        }
    }

    /// Abort all pending effect-timeout tasks. The effect tracker is
    /// flushed separately by the caller.
    fn clear_all_effect_timeouts(&mut self) {
        for (_, handle) in self.effect_timeouts.drain() {
            handle.abort();
        }
    }

    /// Abort all pending `send_after` delivery tasks so a delayed
    /// event from a pre-restart context cannot land after the new
    /// session has already received its `RendererRestarted` events.
    fn clear_all_send_after(&mut self) {
        for handle in self.send_after_handles.drain(..) {
            handle.abort();
        }
    }

    /// Drain all pending async results and delayed events.
    ///
    /// Also cleans up completed task handles from the running map
    /// to prevent unbounded growth.
    fn drain(&mut self) -> Vec<SinkEvent> {
        let mut events = Vec::new();
        while let Ok(event) = self.rx.try_recv() {
            // Remove completed task handles to free memory.
            match &event {
                SinkEvent::AsyncResult { tag, .. } => {
                    self.running.remove(tag);
                }
                SinkEvent::EffectTimeout { wire_id } => {
                    self.effect_timeouts.remove(wire_id);
                }
                _ => {}
            }
            events.push(event);
        }
        events
    }
}

/// Execute a Command by sending messages through the bridge.
///
/// Renderer operations are sent over the wire. SDK-local commands
/// (Async, Cancel, SendAfter) are handled by the AsyncTaskManager.
#[cfg(feature = "wire")]
fn execute_wire_command(
    bridge: &mut Bridge,
    cmd: Command,
    effect_tracker: &mut EffectTracker,
    async_mgr: &mut AsyncTaskManager,
) -> crate::Result {
    match cmd {
        Command::None => {}
        Command::Exit => {
            // Best-effort: tell the renderer we're shutting down so
            // it can close cleanly instead of seeing stdin drop as
            // the bridge is torn down. The main loop observes the
            // subsequent pipe closure and classifies it as
            // `ExitReason::Shutdown` via the shutdown flag below,
            // which flushes pending effects and delivers an exit
            // hook before the runner returns. See `run_wire_inner`
            // and `classify_exit` for the full lifecycle.
            bridge.send_widget_op("exit", &Value::Null)?;
        }
        Command::Batch(cmds) => {
            for c in cmds {
                execute_wire_command(bridge, c, effect_tracker, async_mgr)?;
            }
        }
        Command::Renderer(ref op) => {
            execute_wire_renderer_op(bridge, op, effect_tracker, async_mgr)?;
        }
        Command::Async { tag, task } => {
            async_mgr.spawn_async(tag, task);
        }
        Command::Stream { tag, task } => {
            async_mgr.spawn_stream(tag, task);
        }
        Command::Cancel { tag } => {
            async_mgr.cancel(&tag);
        }
        Command::SendAfter { delay, event } => {
            async_mgr.send_after(delay, *event);
        }
    }
    Ok(())
}

/// Serialize a RendererOp to wire messages and send via the bridge.
#[cfg(feature = "wire")]
fn execute_wire_renderer_op(
    bridge: &mut Bridge,
    op: &plushie_core::ops::RendererOp,
    effect_tracker: &mut EffectTracker,
    async_mgr: &mut AsyncTaskManager,
) -> crate::Result {
    use plushie_core::ops::{ImageOp, RendererOp};
    use serde_json::json;

    match op {
        RendererOp::Command { id, family, value } => bridge.send_command(id, family, value),
        RendererOp::Commands(commands) => bridge.send_commands(commands.clone()),
        RendererOp::FocusNext => bridge.send_widget_op("focus_next", &json!({})),
        RendererOp::FocusPrevious => bridge.send_widget_op("focus_previous", &json!({})),
        RendererOp::FocusNextWithin { scope } => {
            bridge.send_widget_op("focus_next_within", &json!({"scope": scope}))
        }
        RendererOp::FocusPreviousWithin { scope } => {
            bridge.send_widget_op("focus_previous_within", &json!({"scope": scope}))
        }
        RendererOp::Window(op) => execute_wire_window_op(bridge, op),
        RendererOp::WindowQuery(query) => {
            let (op_name, window_id, payload) = query.to_wire();
            bridge.send_window_op(op_name, &window_id, &payload)
        }
        RendererOp::SystemOp(op) => {
            let (op_name, payload) = op.to_wire();
            bridge.send(&OutgoingMessage::SystemOp {
                session: String::new(),
                op: op_name.to_string(),
                payload,
            })
        }
        RendererOp::SystemQuery(query) => {
            let (op_name, payload) = query.to_wire();
            bridge.send(&OutgoingMessage::SystemQuery {
                session: String::new(),
                op: op_name.to_string(),
                payload,
            })
        }
        RendererOp::Effect {
            tag,
            request,
            timeout,
        } => {
            let kind = request.kind();
            let effective_timeout =
                timeout.unwrap_or_else(|| effect_tracker::default_timeout(kind));
            let (wire_id, replaced) =
                effect_tracker.track_with_replacement(tag, kind, effective_timeout);
            if let Some((prior_tag, _prior_kind)) = replaced {
                // Surface the one-per-tag replacement as a synthetic
                // Cancelled event, routed through the same channel the
                // async manager drains so it interleaves correctly
                // with other delayed events.
                async_mgr.deliver_sink_event(SinkEvent::DelayedEvent(Event::Effect(EffectEvent {
                    tag: prior_tag,
                    result: EffectResult::Cancelled,
                })));
            }
            // Schedule a tokio-driven timeout so the deadline fires
            // even when the bridge reader is blocked waiting for
            // renderer input. Cancelled in the resolve path when a
            // response arrives in time.
            async_mgr.schedule_effect_timeout(wire_id.clone(), effective_timeout);
            let (_, payload) = plushie_core::ops::effect_request_to_wire(request);
            bridge.send_effect(&wire_id, kind, &payload)
        }
        RendererOp::Image(image_op) => {
            // Wire op names match the renderer's typed `IncomingMessage::ImageOp`
            // dispatch, which routes `create_image` / `update_image` /
            // `delete_image` to the image registry and `list` / `clear`
            // to the registry-level handlers.
            let (op, payload) = match image_op {
                ImageOp::Create { handle, data } => (
                    "create_image",
                    json!({"handle": handle, "data": base64_encode(data)}),
                ),
                ImageOp::CreateRaw {
                    handle,
                    width,
                    height,
                    pixels,
                } => (
                    "create_image",
                    json!({"handle": handle, "pixels": base64_encode(pixels),
                           "width": width, "height": height}),
                ),
                ImageOp::Update { handle, data } => (
                    "update_image",
                    json!({"handle": handle, "data": base64_encode(data)}),
                ),
                ImageOp::UpdateRaw {
                    handle,
                    width,
                    height,
                    pixels,
                } => (
                    "update_image",
                    json!({"handle": handle, "pixels": base64_encode(pixels),
                           "width": width, "height": height}),
                ),
                ImageOp::Delete(handle) => ("delete_image", json!({"handle": handle})),
                ImageOp::List { tag } => ("list", json!({"tag": tag})),
                ImageOp::Clear => ("clear", json!({})),
                _ => {
                    log::warn!("wire mode: unhandled ImageOp variant; op skipped");
                    return Ok(());
                }
            };
            bridge.send(&OutgoingMessage::ImageOp {
                session: String::new(),
                op: op.to_string(),
                payload,
            })
        }
        RendererOp::Announce { text, politeness } => bridge.send_widget_op(
            "announce",
            &json!({
                "text": text,
                "politeness": match politeness {
                    plushie_core::types::Live::Polite => "polite",
                    plushie_core::types::Live::Assertive => "assertive",
                },
            }),
        ),
        RendererOp::LoadFont { family, bytes } => bridge.send_load_font(family, bytes),
        RendererOp::Subscribe {
            kind,
            tag,
            max_rate,
            window_id,
        } => bridge.send_subscribe(kind, tag, *max_rate, window_id.as_deref()),
        RendererOp::Unsubscribe { kind, tag } => bridge.send_unsubscribe(kind, tag),
        RendererOp::TreeHash { tag } => bridge.send_widget_op("tree_hash", &json!({"tag": tag})),
        RendererOp::FindFocused { tag } => {
            bridge.send_widget_op("find_focused", &json!({"tag": tag}))
        }
        RendererOp::AdvanceFrame { timestamp } => bridge.send(&OutgoingMessage::AdvanceFrame {
            session: String::new(),
            timestamp: *timestamp,
        }),
        // RendererOp is #[non_exhaustive]; any variant added after this
        // match was written is an unknown op in wire mode and is
        // skipped with a warning rather than silently dropped.
        _ => {
            log::warn!("wire mode: unhandled RendererOp variant; op skipped");
            Ok(())
        }
    }
}

/// Execute a window operation via the bridge.
///
/// Uses [`plushie_core::ops::WindowOp::to_wire`] so the enum itself owns
/// the wire serialisation; wire mode just forwards the string triple.
#[cfg(feature = "wire")]
fn execute_wire_window_op(bridge: &mut Bridge, op: &plushie_core::ops::WindowOp) -> crate::Result {
    let (op_str, window_id, payload) = op.to_wire();
    bridge.send_window_op(op_str, &window_id, &payload)
}

/// Base64-encode binary data for JSON wire transport.
#[cfg(feature = "wire")]
fn base64_encode(data: &[u8]) -> String {
    use base64::Engine;
    base64::engine::general_purpose::STANDARD.encode(data)
}

/// Build settings JSON from the App trait for the wire protocol.
///
/// Defers to [`plushie_core::settings::Settings::to_wire_json`] for
/// the body shape and tacks on the `protocol_version` envelope field.
fn build_settings<A: App>() -> Value {
    let mut json = A::settings().to_wire_json();
    if let Value::Object(ref mut map) = json {
        map.insert(
            "protocol_version".to_string(),
            serde_json::json!(plushie_core::protocol::PROTOCOL_VERSION),
        );
    }
    json
}

/// Apply subscription operations by sending wire messages.
///
/// Subscribe / Unsubscribe go over the wire to the renderer.
/// StartTimer / StopTimer are SDK-side only and flow into the
/// AsyncTaskManager's runtime for recurring delivery; each tick
/// pushes a `SinkEvent::DelayedEvent` that the main loop drains
/// alongside async results.
#[cfg(feature = "wire")]
fn apply_wire_sub_ops(
    bridge: &mut Bridge,
    async_mgr: &mut AsyncTaskManager,
    ops: Vec<crate::runtime::subscriptions::SubOp>,
) -> crate::Result {
    use crate::runtime::subscriptions::SubOp;
    for op in ops {
        match op {
            SubOp::Subscribe {
                kind,
                tag,
                max_rate,
                window_id,
            } => {
                bridge.send_subscribe(&kind, &tag, max_rate, window_id.as_deref())?;
            }
            SubOp::Unsubscribe { kind, tag } => {
                bridge.send_unsubscribe(&kind, &tag)?;
            }
            SubOp::StartTimer { tag, interval } => {
                async_mgr.start_timer(tag, interval);
            }
            SubOp::StopTimer { tag } => {
                async_mgr.stop_timer(&tag);
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod async_mgr_restart_cleanup_tests {
    //! AsyncTaskManager state is rebuilt on every renderer restart.
    //! These tests exercise the cleanup helpers that the restart path
    //! calls, asserting the SDK-side task tables are empty after the
    //! cleanup so a delayed event from a pre-restart context cannot
    //! leak into the new session.

    use super::*;
    use std::time::Duration;

    fn fresh_mgr() -> AsyncTaskManager {
        AsyncTaskManager::new(None)
    }

    #[test]
    fn cleanup_helpers_clear_all_async_mgr_tables() {
        let mut mgr = fresh_mgr();

        mgr.start_timer("tick".into(), Duration::from_secs(60));
        mgr.start_timer("hover".into(), Duration::from_secs(60));
        mgr.schedule_effect_timeout("wire-1".into(), Duration::from_secs(60));
        mgr.send_after(
            Duration::from_secs(60),
            crate::event::Event::Timer(crate::event::TimerEvent {
                tag: "delayed".into(),
                timestamp: 0,
            }),
        );
        mgr.spawn_async(
            "task-a".into(),
            Box::new(|| Box::pin(async { Ok(serde_json::Value::Null) })),
        );

        assert_eq!(mgr.timers.len(), 2);
        assert_eq!(mgr.effect_timeouts.len(), 1);
        assert_eq!(mgr.send_after_handles.len(), 1);
        assert_eq!(mgr.running.len(), 1);

        mgr.cancel_all_running();
        mgr.clear_all_timers();
        mgr.clear_all_effect_timeouts();
        mgr.clear_all_send_after();

        assert!(mgr.timers.is_empty(), "timers should be cleared");
        assert!(
            mgr.effect_timeouts.is_empty(),
            "effect_timeouts should be cleared"
        );
        assert!(
            mgr.send_after_handles.is_empty(),
            "send_after handles should be cleared"
        );
        assert!(mgr.running.is_empty(), "running tasks should be cleared");
    }
}

#[cfg(test)]
mod build_settings_tests {
    //! Coverage for the Settings handshake payload produced by
    //! [`build_settings`]. Focuses on `required_widgets` pass-through
    //! so the wire message is shaped right before the renderer even
    //! parses it.

    use super::*;
    use crate::App;
    use crate::Event;
    use crate::Subscription;
    use crate::settings::Settings;
    use crate::widget::WidgetRegistrar;

    /// Minimal App with an overridable `Settings` return. Each test
    /// wires a different `settings()` body via a distinct App impl
    /// because `settings()` is an associated function with no self.
    struct AppWithRequired;
    impl App for AppWithRequired {
        type Model = ();
        fn init() -> (Self::Model, crate::Command) {
            ((), crate::Command::none())
        }
        fn update(_model: &mut Self::Model, _event: Event) -> crate::Command {
            crate::Command::none()
        }
        fn view(_model: &Self::Model, _widgets: &mut WidgetRegistrar) -> crate::ViewList {
            crate::ui::window("main").into()
        }
        fn subscribe(_model: &Self::Model) -> Vec<Subscription> {
            vec![]
        }
        fn settings() -> Settings {
            Settings {
                required_widgets: vec!["gauge".into(), "custom_chart".into()],
                ..Settings::default()
            }
        }
    }

    struct AppWithoutRequired;
    impl App for AppWithoutRequired {
        type Model = ();
        fn init() -> (Self::Model, crate::Command) {
            ((), crate::Command::none())
        }
        fn update(_model: &mut Self::Model, _event: Event) -> crate::Command {
            crate::Command::none()
        }
        fn view(_model: &Self::Model, _widgets: &mut WidgetRegistrar) -> crate::ViewList {
            crate::ui::window("main").into()
        }
        fn subscribe(_model: &Self::Model) -> Vec<Subscription> {
            vec![]
        }
        // settings() uses the default, which leaves required_widgets empty.
    }

    #[test]
    fn required_widgets_populated_lands_on_wire() {
        let json = build_settings::<AppWithRequired>();
        let arr = json
            .get("required_widgets")
            .and_then(|v| v.as_array())
            .expect("required_widgets should be present when the App supplies names");
        let names: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
        assert_eq!(names, vec!["gauge", "custom_chart"]);
    }

    #[test]
    fn required_widgets_empty_is_omitted() {
        let json = build_settings::<AppWithoutRequired>();
        assert!(
            json.get("required_widgets").is_none(),
            "empty required_widgets should not appear on the wire; got: {json}"
        );
    }
}

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

    #[test]
    fn protocol_version_wins_over_legacy_protocol() {
        let expected = plushie_core::protocol::PROTOCOL_VERSION;
        let hello = serde_json::json!({
            "protocol_version": expected,
            "protocol": expected + 1,
        });

        assert_eq!(hello_protocol_version(&hello), Some(expected));
    }

    #[test]
    fn legacy_protocol_is_fallback() {
        let expected = plushie_core::protocol::PROTOCOL_VERSION;
        let hello = serde_json::json!({
            "protocol": expected,
        });

        assert_eq!(hello_protocol_version(&hello), Some(expected));
    }

    #[test]
    fn out_of_range_protocol_is_rejected() {
        let hello = serde_json::json!({
            "protocol_version": u64::from(u32::MAX) + 1,
        });

        assert_eq!(hello_protocol_version(&hello), None);
    }

    #[test]
    fn non_integer_protocol_is_rejected() {
        let hello = serde_json::json!({
            "protocol_version": 1.5,
        });

        assert_eq!(hello_protocol_version(&hello), None);
    }

    #[test]
    fn u32_max_protocol_is_accepted() {
        let hello = serde_json::json!({
            "protocol_version": u32::MAX,
        });

        assert_eq!(hello_protocol_version(&hello), Some(u32::MAX));
    }

    #[test]
    fn hello_log_message_includes_handshake_details() {
        let hello = serde_json::json!({
            "name": "plushie-renderer",
            "protocol_version": 7,
            "protocol": 8,
            "codec": "msgpack",
            "mode": "headless",
            "backend": "tiny-skia",
            "transport": "stdio",
        });

        assert_eq!(
            renderer_hello_log_message(&hello),
            "renderer hello: name=plushie-renderer protocol=7 codec=msgpack mode=headless backend=tiny-skia transport=stdio"
        );
    }

    #[test]
    fn hello_log_message_uses_fallbacks_for_missing_details() {
        let hello = serde_json::json!({});

        assert_eq!(
            renderer_hello_log_message(&hello),
            "renderer hello: name=unknown protocol=unknown codec=unknown mode=unknown backend=unknown transport=None"
        );
    }
}

#[cfg(all(test, feature = "wire"))]
mod wire_contract_tests {
    use super::*;

    #[test]
    fn decode_incoming_recognizes_interact_step() {
        let raw = serde_json::json!({
            "type": "interact_step",
            "session": "s1",
            "id": "i1",
            "events": [
                {
                    "type": "event",
                    "session": "s1",
                    "family": "click",
                    "id": "btn1",
                }
            ],
        });

        match decode_incoming(&raw).expect("message should decode") {
            IncomingRendererMessage::InteractStep { id, events } => {
                assert_eq!(id, "i1");
                assert_eq!(events.len(), 1);
                assert_eq!(events[0]["family"], "click");
            }
            other => panic!("expected interact_step, got {other:?}"),
        }
    }

    #[test]
    fn wire_to_sdk_events_unwraps_interact_step_events() {
        let raw = serde_json::json!({
            "type": "interact_step",
            "session": "s1",
            "id": "i1",
            "events": [
                {
                    "type": "event",
                    "session": "s1",
                    "family": "click",
                    "id": "btn1",
                }
            ],
        });

        let mut effect_tracker = EffectTracker::new();
        let mut async_mgr = AsyncTaskManager::new(None);
        let events = wire_to_sdk_events(&raw, &mut effect_tracker, &mut async_mgr);

        assert_eq!(events.len(), 1);
        match &events[0] {
            Event::Widget(widget) => {
                assert_eq!(widget.event_type, plushie_core::EventType::Click);
                assert_eq!(widget.scoped_id.id, "btn1");
            }
            other => panic!("expected widget event, got {other:?}"),
        }
    }
}