blitz-control-protocol 0.8.0

The Blitz agent-control and diagnostics surface: one vocabulary, one core, two transports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
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
//! The Blitz agent-control and diagnostics surface: one vocabulary, one core,
//! two transports.
//!
//! # The shape of this crate
//!
//! This module is the **vocabulary**: the request, response and event types,
//! and the MCP framing that carries them. It is what a client needs and all it
//! needs, it costs serde and endpoint-libs, and it is what you get with no
//! features enabled.
//!
//! [`document`] is the **core**, behind `engine`. It answers a request against
//! a `blitz-dom` document: the semantic tree, the capture surface, input
//! injection. It knows nothing about sockets.
//!
//! [`in_process`] and [`server`] are the **two transports** over that core. An
//! embedder holding the document calls the first one directly; a harness or an
//! agent outside the process reaches the second one over a Unix socket.
//! [`client`] is the connecting half of that socket, and it is a sibling of the
//! server rather than a layer on top of it, because a peer can be both: an
//! application driven by agents while it drives a browser it embeds is a client
//! and a server at once.
//!
//! [`lifecycle`] is the one answer neither transport nor core can give.
//! `Relaunch` and `Quit` are about the process, so the embedder that started it
//! registers what they mean; it is here rather than in a host because more than
//! one host serves the same request.
//!
//! There were three copies of this vocabulary before, in three repositories,
//! and two of them were transports rather than duplicates: an in-process
//! interface in the browser and a socket in the Tauri runtime, each with its
//! own spelling of the same commands. The transports are both still here. The
//! spelling is not.
//!
//! # Typed local debugging protocol carried by endpoint-libs framing.
//!
//! This is deliberately not WebDriver. It models the native renderer and app
//! lifecycle directly, supports observation by more than one client, and has
//! no authentication handshake. Agent control binds only to a local transport;
//! expensive diagnostics collection remains an explicit compile-time feature
//! *of the server*, `izumo/diagnostics`.
//!
//! # Why this is its own crate
//!
//! These are the server's own definitions, and a client that hand-rolls the
//! JSON gets them wrong in ways that do not look like encoding mistakes.
//! `AgentAction` is adjacently tagged, so `{"action":"click","nodeId":9}` is
//! malformed where `{"action":"click","params":{"nodeId":9}}` is correct, and
//! the difference used to present as a hung application. Sharing the types
//! makes that a compile error.
//!
//! Speaking the protocol must not cost a renderer. `izumo` pulls
//! in tauri, winit, wgpu and blitz, so a measurement tool that depended on it
//! for these types would build a browser engine to send a wheel event. Nothing
//! here needs any of that: it is serde plus endpoint-libs' framing.
//!
//! # No `diagnostics` feature, on purpose
//!
//! The types are inert data definitions and cost nothing to compile, whereas
//! gating them creates feature skew: cargo unifies features across a build, so
//! one workspace member asking for diagnostics types while the server crate is
//! built without them turned `DebugResponse` into a non-exhaustive match in
//! code nobody had touched. What stays gated in the server is *collection*,
//! which is where the expense actually is. A build that cannot serve
//! diagnostics says so by omitting the tool from `tools/list`; see
//! [`encode_tools_list_response`].

/// The socket transport, connecting half.
#[cfg(feature = "client")]
pub mod client;

/// Condensing a settled page into levels a caller can widen from.
///
/// Types and ranking only, no transport: a caller with a snapshot already has
/// everything this needs, and the cache is keyed on settle rather than fetch.
pub mod condense;
#[cfg(all(unix, any(feature = "server", feature = "client")))]
mod control_directory;
/// The core: reading, capturing and driving a document.
#[cfg(feature = "engine")]
pub mod document;
/// Secret-aware file output shared by every workspace crate.
#[allow(clippy::disallowed_methods)]
pub mod guarded_writer;
/// The in-process transport.
#[cfg(feature = "engine")]
pub mod in_process;

/// A script-capable backend for the control protocol.
///
/// Implementations provide a [`blitz_dom::Document`] for protocol observation and
/// implement the event delivery that the document alone cannot perform. Event
/// methods must preserve target-directed delivery, bubbling, cancellation and
/// native default actions. Pointer movement must preserve hover event ordering.
///
/// Observation calls [`blitz_dom::Document::poll_for_settle`] with timers
/// disabled and a bounded budget. Action settlement uses bounded calls to
/// [`blitz_dom::Document::poll`], preserving the backend's normal timer policy.
/// Backends must report whether each poll leaves immediate work runnable.
///
/// Hosts implement this contract on their document owner or an adapter that
/// delegates `Document` and event delivery to the selected script backend.
#[cfg(feature = "engine")]
pub trait ControlScriptBackend: blitz_dom::Document {
    /// Dispatch a DOM event through the backend's scripted event handling.
    fn dispatch_dom_event(&mut self, event: blitz_traits::events::DomEvent);

    /// Deliver pointer movement to a target node, preserving hover event order.
    fn handle_pointer_move_to_node(
        &mut self,
        event: blitz_traits::events::BlitzPointerEvent,
        node: blitz_dom::NodeId,
    );

    /// Deliver a UI event to its target node with native defaults and bubbling.
    fn handle_ui_event_to_node(
        &mut self,
        event: blitz_traits::events::UiEvent,
        node: blitz_dom::NodeId,
    );

    /// Return script runtime metrics when the backend can provide them.
    fn script_metrics(&self) -> Option<ScriptMetrics> {
        None
    }
}
/// Latest-value and one-shot handoffs built on nagoya, replacing tokio channels.
#[cfg(any(feature = "server", feature = "client"))]
pub mod latest;
/// The embedder's answer to a request about the process, not the document.
pub mod lifecycle;
pub mod target;
pub use target::*;
#[cfg(any(feature = "server", feature = "client"))]
pub mod journal;
/// Page-owned WebGPU diagnostic reports.
pub mod webgpu;
pub use webgpu::*;
/// The socket transport, listening half.
///
/// Unix only. The transport is a Unix domain socket with owner-only
/// permissions, which is the access control: there is no handshake and no
/// token, because the file mode already says who may connect.
#[cfg(all(feature = "server", unix))]
pub mod server;
#[cfg(all(feature = "server", unix))]
mod server_stream;

use std::collections::BTreeMap;

use endpoint_libs::libs::ws::mcp_wire::{INVALID_PARAMS, INVALID_REQUEST, parse};
pub use endpoint_libs::libs::ws::{
    MessageStream, WireMessage,
    mcp_wire::{
        JsonRpcError, JsonRpcId, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse,
        MCP_PROTOCOL_VERSION,
    },
    transport::{FramedError, Transport, TransportStream, framed_json_neutral},
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize, de::DeserializeOwned};

/// Version 2 names every field inside a command camelCase (`nodeId`,
/// `maxDepth`, `deltaX`). Version 1 field names are still accepted on input,
/// so a version 2 host serves version 1 clients; a version 2 client refuses a
/// version 1 descriptor instead of sending names that host cannot read.
pub const DEBUG_PROTOCOL_VERSION: u32 = 2;
/// Largest single frame either side may send or accept. Shared by every
/// host, client and relay, so a supervisor never forwards a frame its peer
/// would refuse.
pub const MAX_DEBUG_FRAME_BYTES: usize = 16 * 1024 * 1024;
pub const MCP_INITIALIZE: &str = "initialize";
pub const MCP_INITIALIZED_NOTIFICATION: &str = "notifications/initialized";
pub const MCP_TOOLS_LIST: &str = "tools/list";
pub const MCP_TOOLS_CALL: &str = "tools/call";
pub const AGENT_CONTROL_TOOL: &str = "blitz.agent.control";
pub const AGENT_EVENT_NOTIFICATION: &str = "notifications/blitz/agent";
pub const DIAGNOSTICS_TOOL: &str = "blitz.diagnostics";
pub const DIAGNOSTICS_EVENT_NOTIFICATION: &str = "notifications/blitz/diagnostics";

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DebugDescriptor {
    pub protocol_version: u32,
    pub pid: u32,
    pub instance_id: String,
    pub address: String,
    pub renderer: String,
    pub renderer_revision: String,
}

#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum IncomingRequest {
    Initialize {
        id: JsonRpcId,
    },
    Initialized,
    ToolsList {
        id: JsonRpcId,
    },
    Agent {
        id: JsonRpcId,
        request: AgentControlRequest,
    },
    Diagnostics {
        id: JsonRpcId,
        request: DiagnosticsRequest,
    },
    Targeted {
        id: JsonRpcId,
        request: TargetRequest,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
    tag = "command",
    content = "params",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
#[non_exhaustive]
pub enum AgentControlRequest {
    ListTargets,
    Inspect {
        root: Option<u64>,
        #[serde(alias = "max_depth")]
        max_depth: u32,
    },
    Act(AgentAction),
    /// Load a URL in the standing document.
    ///
    /// Relative values resolve against the page that is up. The host that
    /// owns the loader answers this; a document core cannot, any more than it
    /// can relaunch the process.
    Navigate {
        url: String,
    },
    /// Condense the settled page into one level, with an account of what the
    /// level dropped.
    ///
    /// The document core can answer this: it needs the tree that is already
    /// there and no loader, no compositor and no second renderer pass. See
    /// [`condense`], which is where the ranking lives.
    Condense {
        #[serde(default)]
        level: condense::Level,
        #[serde(default)]
        options: condense::CondenseOptions,
    },
    Relaunch,
    Quit,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
    tag = "command",
    content = "params",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
#[non_exhaustive]
pub enum DiagnosticsRequest {
    Observe {
        streams: Vec<DebugStream>,
    },
    Snapshot(SnapshotRequest),
    Metrics,
    WaitForIdle,
    /// The native window layers which sit outside the renderer's document.
    ///
    /// A renderer capture cannot see whether an opaque platform window or a
    /// tinted native glass view was placed behind its transparent root. This
    /// response makes that compositor boundary observable without pretending
    /// pixels from an unknown desktop prove which native layer produced them.
    WindowComposition,
    /// Render the current document to an RGBA8 image and return the pixels.
    ///
    /// The one question the rest of this protocol cannot answer. A snapshot
    /// reports the boxes and colours the engine *resolved*, which is not the
    /// same as what it drew: an element can hold a correct box, a correct
    /// computed colour and an accessible role while painting nothing at all.
    /// That gap is not hypothetical. An entire icon set rendered blank in a
    /// shipping application while every snapshot, every layout box and every
    /// accessibility node read exactly right, and no tool in this protocol
    /// could see it.
    ///
    /// Rendered offscreen rather than read back from the window surface. The
    /// protocol requires no swapchain, compositor, or display server; concrete
    /// host availability still depends on the renderer backend for that
    /// platform.
    Capture(CaptureRequest),
    /// Inspect page-owned devices, live resources, errors and submitted frames.
    ///
    /// Asking renews a ten-second lease for pass and draw bookkeeping.
    /// Hosts without a page WebGPU inspector return their unsupported
    /// diagnostics error; absence of support is not an empty report.
    WebGpuInspect,
    /// Copy one page-owned texture or canvas drawing buffer to RGBA8.
    ///
    /// `target` is `texture:<label>` or `canvas:#id`. The answer is
    /// [`DebugResponse::Captured`], the same image a document Capture returns.
    WebGpuCapture {
        target: String,
    },
    /// Read bytes from one labeled page-owned GPUBuffer.
    ///
    /// The target is buffer:<label>, with * matching any run of characters.
    /// Zero or multiple matches are errors naming the label or matching labels.
    /// Offset and length are bytes and must be multiples of four. An absent
    /// length reads to the end. Hosts return the previous completed write
    /// while a newer submit is pending, or error code pending when no
    /// completed write is available. They do not wait for that newer submit.
    WebGpuBuffer {
        target: String,
        offset: u64,
        length: Option<u64>,
    },
    /// Run a script in the page and return its completion value as JSON.
    ///
    /// The same evaluation a page console offers, so an agent driving a
    /// headless page can read state no tree or capture exposes, such as a
    /// media element's `currentTime`. Hosts that run no page script answer
    /// with their unsupported diagnostics error.
    Evaluate {
        script: String,
    },
}

/// What to draw, and how large.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CaptureRequest {
    /// The subtree to draw, or the whole document when absent.
    ///
    /// Capturing one node is the difference between a test that says "the
    /// window is not blank" and one that says "this button's icon is drawn",
    /// and the second is the one worth writing.
    pub node_id: Option<u64>,
    /// Pixel scale, so a small control can be inspected at a useful size.
    ///
    /// A 16px icon is a handful of pixels at 1x, and antialiasing dominates
    /// them; asking for it at 4x makes "is anything there" answerable without
    /// making the threshold a guess.
    pub scale: f32,
}

impl Default for CaptureRequest {
    fn default() -> Self {
        Self {
            node_id: None,
            scale: 1.0,
        }
    }
}

impl CaptureRequest {
    pub fn validate(&self) -> Result<(), &'static str> {
        if !self.scale.is_finite() || !(0.25..=8.0).contains(&self.scale) {
            return Err("capture scale must be finite and between 0.25 and 8");
        }
        Ok(())
    }
}

/// An RGBA8 image, as the renderer actually drew it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CapturedImage {
    pub width: u32,
    pub height: u32,
    /// Row-major RGBA8, four bytes per pixel, base64 over the wire.
    ///
    /// Base64 rather than raw bytes because the transport is line-delimited
    /// JSON, and a full window at 2x is a few megabytes: large enough to be
    /// worth encoding compactly, not large enough to justify a second channel.
    pub rgba_base64: String,
    /// The node this shows, when the request named one.
    pub node_id: Option<u64>,
}

#[cfg(feature = "capture")]
impl CapturedImage {
    /// Encode tightly packed straight RGBA8 as a document capture payload.
    pub fn from_rgba(width: u32, height: u32, rgba: &[u8]) -> Result<Self, DebugError> {
        let expected = u64::from(width)
            .saturating_mul(u64::from(height))
            .saturating_mul(4);
        if width == 0 || height == 0 || expected != rgba.len() as u64 {
            return Err(DebugError {
                code: "invalidArgument".to_owned(),
                message: format!(
                    "RGBA8 capture is {width}x{height} but holds {} bytes",
                    rgba.len()
                ),
            });
        }
        // Same frame ceiling as document capture: leave room for the JSON
        // envelope inside the transport's fixed frame limit.
        const FRAME_ENVELOPE_RESERVE: usize = 64 * 1024;
        const MAX_BASE64_BYTES: usize = MAX_DEBUG_FRAME_BYTES - FRAME_ENVELOPE_RESERVE;
        const MAX_RAW_BYTES: usize = (MAX_BASE64_BYTES / 4) * 3;
        if rgba.len() > MAX_RAW_BYTES {
            return Err(DebugError {
                code: "captureTooLarge".to_owned(),
                message: format!(
                    "{width}x{height} cannot fit in one diagnostic frame; capture a smaller texture"
                ),
            });
        }
        Ok(Self {
            width,
            height,
            rgba_base64: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, rgba),
            node_id: None,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "result", content = "value", rename_all = "camelCase")]
#[allow(clippy::large_enum_variant)] // wire shape is public; boxing would break consumers
#[non_exhaustive]
pub enum DebugResponse {
    Ack,
    Targets(Vec<TargetInfo>),
    Targeted(TargetReply),
    AgentSnapshot(AgentSnapshot),
    Snapshot(DebugSnapshot),
    Metrics(RendererMetrics),
    Idle(RevisionSet),
    WindowComposition(WindowComposition),
    Captured(CapturedImage),
    WebGpu(WebGpuReport),
    WebGpuBuffer(WebGpuBufferSnapshot),
    /// One condensation level over the settled page, level-shaped so a caller
    /// asking for keywords is not handed the page's full text.
    Condensation(condense::Condensation),
    /// The JSON completion value of an [`DiagnosticsRequest::Evaluate`].
    Evaluated(serde_json::Value),
    Error(DebugError),
}

/// Effective native composition selected for the application window.
///
/// `supported` is false for a headless host or a runtime which has no native
/// window integration. The remaining fields describe the path the runtime
/// actually installed, not merely values requested by application CSS.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct WindowComposition {
    pub supported: bool,
    pub surface_transparent: bool,
    pub glass_enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub glass_backend: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tint_rgba: Option<[u8; 4]>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub radius: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "event", content = "value", rename_all = "camelCase")]
#[allow(clippy::large_enum_variant)] // wire shape is public; boxing would break consumers
#[non_exhaustive]
pub enum DebugEvent {
    DiagnosticLoss {
        stream: DebugStream,
        lost: u64,
    },
    Snapshot(DebugSnapshot),
    Metrics(RendererMetrics),
    Console(ConsoleEntry),
    RuntimeError(RuntimeErrorEntry),
    /// A real window frame completed after style, layout and paint.
    ///
    /// The event carries only a monotonic revision. Consumers pull a snapshot
    /// or capture if they need one; pushing images or trees on every frame
    /// would turn observation into an unbounded second renderer workload.
    PaintCommitted {
        revision: u64,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "event", content = "value", rename_all = "camelCase")]
#[non_exhaustive]
pub enum AgentControlEvent {
    Ready(DebugDescriptor),
    TreeChanged { revision: u64 },
    Lifecycle(LifecycleEvent),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum DebugStream {
    Snapshots,
    Metrics,
    Console,
    RuntimeErrors,
    Paint,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct SnapshotRequest {
    pub include_dom: bool,
    pub include_layout: bool,
    pub include_computed_style: bool,
    /// Restrict DOM, layout, and computed-style collection to these nodes.
    /// Empty preserves the full-snapshot behavior used by inspection reports.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub node_ids: Vec<u64>,
}

/// A node's live border box, encoded on the wire as `[x, y, width, height]`.
///
/// Named fields keep consumers out of positional indexing while the custom
/// array conversion preserves compatibility with existing inspectors.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(from = "[f64; 4]", into = "[f64; 4]")]
pub struct LayoutBounds {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

impl From<[f64; 4]> for LayoutBounds {
    fn from([x, y, width, height]: [f64; 4]) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }
}

impl From<LayoutBounds> for [f64; 4] {
    fn from(bounds: LayoutBounds) -> Self {
        [bounds.x, bounds.y, bounds.width, bounds.height]
    }
}

/// A two-dimensional layout size, encoded as `[width, height]`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(from = "[f64; 2]", into = "[f64; 2]")]
pub struct LayoutSize {
    pub width: f64,
    pub height: f64,
}

impl From<[f64; 2]> for LayoutSize {
    fn from([width, height]: [f64; 2]) -> Self {
        Self { width, height }
    }
}

impl From<LayoutSize> for [f64; 2] {
    fn from(size: LayoutSize) -> Self {
        [size.width, size.height]
    }
}

/// A live scroll offset, encoded as `[x, y]`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(from = "[f64; 2]", into = "[f64; 2]")]
pub struct LayoutOffset {
    pub x: f64,
    pub y: f64,
}

impl From<[f64; 2]> for LayoutOffset {
    fn from([x, y]: [f64; 2]) -> Self {
        Self { x, y }
    }
}

impl From<LayoutOffset> for [f64; 2] {
    fn from(offset: LayoutOffset) -> Self {
        [offset.x, offset.y]
    }
}

/// Computed CSS edges, encoded in shorthand order `[top, right, bottom, left]`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(from = "[f64; 4]", into = "[f64; 4]")]
pub struct LayoutEdges {
    pub top: f64,
    pub right: f64,
    pub bottom: f64,
    pub left: f64,
}

impl From<[f64; 4]> for LayoutEdges {
    fn from([top, right, bottom, left]: [f64; 4]) -> Self {
        Self {
            top,
            right,
            bottom,
            left,
        }
    }
}

impl From<LayoutEdges> for [f64; 4] {
    fn from(edges: LayoutEdges) -> Self {
        [edges.top, edges.right, edges.bottom, edges.left]
    }
}

/// One node's renderer-computed geometry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct LayoutDiagnosticRow {
    pub node_id: u64,
    pub bounds: LayoutBounds,
    pub scroll_offset: LayoutOffset,
    pub client_size: LayoutSize,
    pub scroll_size: LayoutSize,
    pub scroll_range: LayoutSize,
    pub border: LayoutEdges,
    pub padding: LayoutEdges,
    pub content_size: LayoutSize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
    tag = "action",
    content = "params",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
#[non_exhaustive]
pub enum AgentAction {
    /// Give one semantic node keyboard focus without activating it.
    ///
    /// Keyboard setup must not be implemented as a click: focusing a submit,
    /// delete or fork button by clicking it performs the action before the key
    /// under test is ever delivered.
    Focus {
        #[serde(alias = "node_id")]
        node_id: u64,
    },
    /// Activate one semantic node without resolving it back through screen
    /// coordinates. The runtime dispatches pointer, mouse and click events in
    /// browser order directly to this target.
    Click {
        #[serde(alias = "node_id")]
        node_id: u64,
    },
    /// Two activations in one runtime call, inside the platform's double-click
    /// interval. Used for rows whose single click only selects or folds them.
    DoubleClick {
        #[serde(alias = "node_id")]
        node_id: u64,
    },
    /// Present one semantic node as hovered. The target is still named by id;
    /// the runtime owns any renderer-specific positioning needed to update CSS
    /// hover state.
    Hover {
        #[serde(alias = "node_id")]
        node_id: u64,
    },
    SetValue {
        #[serde(alias = "node_id")]
        node_id: u64,
        value: String,
    },
    ScrollIntoView {
        #[serde(alias = "node_id")]
        node_id: u64,
    },
    /// Scroll a specific node's nearest scroll container by a delta.
    ///
    /// Wheel events carry no coordinates and are delivered to whatever the
    /// document last saw hovered, which an injected pointer move does not
    /// reliably set. That made every scrollable panel in the application
    /// undrivable from outside, so a bug that only appears further down a long
    /// page could not be reproduced without a human at the keyboard.
    ScrollBy {
        #[serde(alias = "node_id")]
        node_id: u64,
        #[serde(alias = "delta_x")]
        delta_x: f64,
        #[serde(alias = "delta_y")]
        delta_y: f64,
    },
    Input(InputCommand),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
    tag = "input",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
#[non_exhaustive]
pub enum InputCommand {
    Key {
        phase: KeyPhase,
        key: String,
        code: String,
        modifiers: Modifiers,
    },
    Pointer {
        phase: PointerPhase,
        x: f64,
        y: f64,
        button: u16,
        modifiers: Modifiers,
    },
    Wheel {
        #[serde(alias = "delta_x")]
        delta_x: f64,
        #[serde(alias = "delta_y")]
        delta_y: f64,
        phase: WheelPhase,
        modifiers: Modifiers,
    },
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Modifiers {
    pub shift: bool,
    pub control: bool,
    pub alt: bool,
    pub meta: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum KeyPhase {
    Down,
    Up,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum PointerPhase {
    Move,
    Down,
    Up,
    Cancel,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum WheelPhase {
    Started,
    Moved,
    Ended,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RevisionSet {
    pub document: u64,
    /// Per-stage counters. A host fills one only when it can read that stage
    /// from the runtime (blitz-dom counts Stylo traversals and layout passes);
    /// a host that cannot leaves it at zero rather than copying `document`.
    pub style: u64,
    pub layout: u64,
    pub paint: u64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DebugSnapshot {
    pub revisions: RevisionSet,
    pub active_window: Option<String>,
    pub active_element: Option<u64>,
    pub dom: Option<serde_json::Value>,
    pub layout: Option<Vec<LayoutDiagnosticRow>>,
    /// Resolved colours per node, when `include_computed_style` was set.
    ///
    /// Only the properties that decide legibility. A full longhand dump for
    /// every node is megabytes of JSON nobody reads, and these are what a
    /// question about invisible text actually needs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub computed_style: Option<serde_json::Value>,
    pub metrics: RendererMetrics,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentSnapshot {
    pub revision: u64,
    pub active_window: Option<String>,
    pub focused_node: Option<u64>,
    /// The client-space viewport in CSS pixels.
    ///
    /// The root and `main` boxes may be as tall as the whole document, so
    /// their semantic bounds cannot tell an external pointer driver where the
    /// physical window ends.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub viewport: Option<[f64; 4]>,
    pub nodes: Vec<SemanticNode>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct SemanticNode {
    /// The stable DOM identity supplied by the application, when present.
    ///
    /// This is deliberately separate from `id`: `id` is Blitz's ephemeral
    /// node handle and may change whenever the element remounts. QA selectors
    /// need the authored HTML `id` so a test keeps targeting the same control.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dom_id: Option<String>,
    pub id: u64,
    pub parent: Option<u64>,
    pub role: String,
    pub name: String,
    pub value: Option<String>,
    pub enabled: bool,
    /// Whether the element participates in keyboard focus or native activation.
    ///
    /// Role alone cannot answer this for elements such as sortable column
    /// headers: a plain `<th>` and `<th tabindex="0">` share a role, while only
    /// the latter is an operable control.
    #[serde(default)]
    pub focusable: bool,
    /// Whether this box is anchored to the window viewport.
    ///
    /// Fixed descendants keep their DOM parent even though layout hoists them
    /// to the viewport. An external driver needs this bit so it does not clip
    /// a visible fixed control against a scrolled ancestor's content box.
    #[serde(default)]
    pub viewport_fixed: bool,
    pub visible: bool,
    pub selected: bool,
    pub bounds: Option<[f64; 4]>,
    /// The library slot this element is, when it is part of a component.
    ///
    /// Read from `data-slot`, which a component library emits to name its own
    /// parts. Addressing a control by the slot it *is* rather than by the text
    /// it happens to carry is what lets a harness tell a trigger from the thing
    /// it opens: those two routinely share an accessible name, so a check
    /// written against the name passes whether or not anything happened.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slot: Option<String>,
    /// ARIA and data attributes that target predicates may compare exactly.
    /// Other DOM attributes stay out of semantic snapshots.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub attributes: BTreeMap<String, String>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RendererMetrics {
    pub revisions: RevisionSet,
    /// Depth of a pending-work queue in front of the renderer.
    ///
    /// Blitz has no such queue: `View::redraw` resolves, paints and presents
    /// inline on the event-loop thread. The one queue that exists, `ScriptQueue`,
    /// lives inside the Tauri webview dispatcher and is not reachable from the
    /// runtime, so this stays `None` rather than reporting a constant zero that
    /// reads like a measured "nothing is backed up".
    pub queue_depth: Option<u64>,
    pub invalidations_coalesced: u64,
    /// The most recently presented frame, as measured by blitz-shell.
    ///
    /// `None` until the window has drawn at least once.
    pub frame: Option<FrameMetrics>,
    /// Mean, p95 and worst case across the last few hundred presented frames.
    pub frame_window: Option<FrameWindowMetrics>,
    /// Cost of collecting this diagnostic snapshot. This measures the observer,
    /// not the application, and is reported separately so the two are never
    /// confused again.
    pub snapshot: Option<SnapshotCost>,
    /// What script execution cost, per backend poll.
    ///
    /// The frame numbers above cover resolve, paint and present, which is the
    /// engine. Reactivity, event handlers, timers and microtasks are none of
    /// those, so an application could present a 4ms frame and still feel slow
    /// with nothing here to explain it. `None` until script has actually run.
    pub script: Option<ScriptMetrics>,
    pub resident_bytes: Option<u64>,
}

/// Script execution cost, in milliseconds, over the retained poll window.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ScriptMetrics {
    pub mean_ms: f64,
    pub p95_ms: f64,
    pub max_ms: f64,
    /// Polls that ran script, within the retained window.
    pub window_polls: u64,
    /// Every poll since launch, including the ones that found nothing to do.
    pub total_polls: u64,
    /// Polls that ran script since launch.
    pub productive_polls: u64,
    /// Total time spent in the script runtime since launch.
    pub spent_ms: f64,
    /// Where that time went, worst total first: event name or timer source,
    /// call count, total milliseconds, worst single call.
    pub breakdown: Vec<ScriptSource>,
}

/// One attributed source of script time.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ScriptSource {
    pub label: String,
    pub calls: u64,
    pub total_ms: f64,
    pub worst_ms: f64,
}

/// Timings of one real presented frame, in milliseconds.
///
/// Every `Option` here is a value blitz does not measure. They are left empty on
/// purpose: a plausible-looking zero is worse than an admitted gap, because it
/// makes a missing measurement look like a fast one.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FrameMetrics {
    /// Wall time from the input event that caused the frame to the frame reaching
    /// the screen. Blitz does not stamp input events with an arrival time and the
    /// renderer reports no present timestamp, so there are no two clocks to
    /// subtract.
    pub input_to_present_ms: Option<f64>,
    /// Style recalculation alone. Blitz runs style and layout inside a single
    /// `resolve` pass and times only the pass, so the combined cost is in
    /// `resolve_ms` instead.
    pub style_ms: Option<f64>,
    /// Layout alone. See `style_ms`.
    pub layout_ms: Option<f64>,
    /// Style plus layout, i.e. the `resolve` pass.
    pub resolve_ms: f64,
    /// Scene building: the `paint_scene` call that turns the resolved document
    /// into renderer commands.
    pub scene_ms: f64,
    /// GPU submit alone. The renderer reports encode, submit and present as one
    /// figure, which is in `renderer_ms`.
    pub submit_ms: Option<f64>,
    /// Present alone. See `submit_ms`.
    pub present_ms: Option<f64>,
    /// Everything the renderer did outside scene building: encode, submit and
    /// present.
    pub renderer_ms: f64,
    /// `resolve_ms + scene_ms + renderer_ms`. CPU time inside `redraw`, not
    /// input-to-photon latency.
    pub total_ms: f64,
    /// How long ago the frame started, measured when this response was built. A
    /// large value means the app has been idle and these numbers are stale.
    pub age_ms: f64,
}

/// Mean, 95th percentile and worst case for one timing series, in milliseconds.
///
/// The percentile and maximum matter more than the mean: a one-second average
/// hides the single slow frame that is the only one a user notices.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TimingStats {
    pub mean_ms: f64,
    pub p95_ms: f64,
    pub max_ms: f64,
}

/// Aggregate statistics over the recently presented frames.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FrameWindowMetrics {
    /// Frames presented since process start.
    pub frames_total: u64,
    /// Frames the statistics below were computed over.
    pub window_frames: u64,
    /// Style plus layout.
    pub resolve: TimingStats,
    /// Scene building.
    pub scene: TimingStats,
    /// Encode, submit and present.
    pub renderer: TimingStats,
    /// Per-frame `resolve + scene + renderer`.
    pub total: TimingStats,
    /// Gap between the starts of consecutive frames, idle gaps excluded.
    pub interval: TimingStats,
    /// Frames per second across active intervals only. Blitz idles at zero FPS by
    /// design, so counting idle time would make every measurement meaningless.
    pub active_fps: f64,
    /// Active intervals longer than 1.5 display refresh periods. Always zero when
    /// `display_refresh_hz` is unknown.
    pub missed_refreshes: u64,
    pub display_refresh_hz: Option<f64>,
}

/// What it cost to answer this diagnostics request.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct SnapshotCost {
    /// Time spent draining the script event loop before reading the document.
    pub poll_ms: f64,
    /// Time spent forcing a `resolve` so the reported layout is up to date.
    pub resolve_ms: f64,
    /// Total time spent building the response.
    pub total_ms: f64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConsoleEntry {
    pub sequence: u64,
    pub level: String,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RuntimeErrorEntry {
    pub sequence: u64,
    pub message: String,
    pub stack: String,
    pub revisions: RevisionSet,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "state", rename_all = "camelCase")]
#[non_exhaustive]
pub enum LifecycleEvent {
    Relaunching { replacement_instance_id: String },
    Ready { instance_id: String },
    Quitting,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DebugError {
    pub code: String,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
struct ToolCallParams {
    name: String,
    arguments: serde_json::Value,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
struct ToolCallResult {
    content: Vec<TextContent>,
    structured_content: serde_json::Value,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    is_error: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
struct TextContent {
    #[serde(rename = "type")]
    content_type: String,
    text: String,
}

#[derive(Debug)]
#[non_exhaustive]
pub enum DebugProtocolError {
    Json(serde_json::Error),
    Rpc(JsonRpcError),
    NonTextFrame,
    RequestIdRequired,
    UnexpectedMessage,
    UnexpectedMethod(String),
    UnexpectedTool(String),
    PayloadTooLarge(usize),
}

impl std::fmt::Display for DebugProtocolError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Json(error) => write!(formatter, "invalid debug frame: {error}"),
            Self::Rpc(error) => write!(
                formatter,
                "JSON-RPC error {}: {}",
                error.code, error.message
            ),
            Self::NonTextFrame => formatter.write_str("debug protocol requires a text frame"),
            Self::RequestIdRequired => formatter.write_str("tools/call requires a request id"),
            Self::UnexpectedMessage => formatter.write_str("unexpected JSON-RPC message"),
            Self::UnexpectedMethod(method) => write!(formatter, "unexpected method {method}"),
            Self::UnexpectedTool(tool) => write!(formatter, "unexpected tool {tool}"),
            Self::PayloadTooLarge(bytes) => write!(
                formatter,
                "debug response is {bytes} bytes, exceeding the {MAX_DEBUG_FRAME_BYTES}-byte frame limit"
            ),
        }
    }
}

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

impl From<serde_json::Error> for DebugProtocolError {
    fn from(error: serde_json::Error) -> Self {
        Self::Json(error)
    }
}

pub fn encode_agent_request(
    id: JsonRpcId,
    request: &AgentControlRequest,
) -> Result<WireMessage, DebugProtocolError> {
    encode_tool_request(id, AGENT_CONTROL_TOOL, request)
}

pub fn decode_incoming(message: WireMessage) -> Result<IncomingRequest, DebugProtocolError> {
    decode_incoming_value(decode_wire_value(message)?)
}

/// Decode an incoming request from a JSON value that the transport already parsed.
///
/// Server loops need the request id even when the typed payload is malformed. Keeping
/// the parsed value lets them recover that id and then consume the same allocation for
/// typed decoding instead of parsing the complete frame twice.
pub fn decode_incoming_value(
    value: serde_json::Value,
) -> Result<IncomingRequest, DebugProtocolError> {
    let JsonRpcMessage::Request(request) = decode_rpc_value(value)? else {
        return Err(DebugProtocolError::UnexpectedMessage);
    };
    match request.method.as_str() {
        MCP_INITIALIZE => Ok(IncomingRequest::Initialize {
            id: request.id.ok_or(DebugProtocolError::RequestIdRequired)?,
        }),
        MCP_INITIALIZED_NOTIFICATION if request.is_notification() => {
            Ok(IncomingRequest::Initialized)
        }
        MCP_TOOLS_LIST => Ok(IncomingRequest::ToolsList {
            id: request.id.ok_or(DebugProtocolError::RequestIdRequired)?,
        }),
        MCP_TOOLS_CALL => decode_incoming_tool_call(request),
        _ => Err(DebugProtocolError::UnexpectedMethod(request.method)),
    }
}

/// The MCP handshake, answered on behalf of whichever host is serving.
///
/// `server_name` used to be the literal `tauri-runtime-blitz` (now izumo), because that is
/// where this code lived. There are three hosts now, and none of them is this
/// crate: a window runtime, a headless browser, and an embedder driving a
/// browser in-process. Each says its own name.
pub fn encode_initialize_response(
    id: JsonRpcId,
    server_name: &str,
    server_version: &str,
) -> Result<WireMessage, DebugProtocolError> {
    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
        Some(id),
        serde_json::json!({
            "protocolVersion": MCP_PROTOCOL_VERSION,
            "capabilities": {"tools": {"listChanged": false}},
            "serverInfo": {"name": server_name, "version": server_version}
        }),
    )))
}

/// The tool list, which is the one place a build's *capability* shows.
///
/// `include_diagnostics` is the server's `diagnostics` feature. The protocol
/// types for diagnostics exist unconditionally, so a build that cannot collect
/// them has to say so here rather than by failing to define them. Advertising
/// a tool that answers every call with an error would be worse than omitting
/// it: a client would report the app as broken instead of as a plain build.
pub fn encode_tools_list_response(
    id: JsonRpcId,
    include_diagnostics: bool,
) -> Result<WireMessage, DebugProtocolError> {
    let mut tools = vec![serde_json::json!({
        "name": AGENT_CONTROL_TOOL,
        "description": "Inspect and operate the native Blitz semantic UI tree",
        "inputSchema": schema_for::<TargetEnvelope<AgentControlRequest>>()?
    })];
    if include_diagnostics {
        tools.push(serde_json::json!({
            "name": DIAGNOSTICS_TOOL,
            "description": "Observe Blitz DOM, layout, errors, and renderer metrics",
            "inputSchema": schema_for::<TargetEnvelope<DiagnosticsRequest>>()?
        }));
    }
    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
        Some(id),
        serde_json::json!({"tools": tools}),
    )))
}

fn schema_for<T: JsonSchema>() -> Result<serde_json::Value, DebugProtocolError> {
    serde_json::to_value(schemars::schema_for!(T)).map_err(DebugProtocolError::from)
}

pub fn encode_rpc_error(
    id: Option<JsonRpcId>,
    error: JsonRpcError,
) -> Result<WireMessage, DebugProtocolError> {
    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::error(id, error)))
}

pub fn decode_agent_request(
    message: WireMessage,
) -> Result<(JsonRpcId, AgentControlRequest), DebugProtocolError> {
    decode_tool_request(message, AGENT_CONTROL_TOOL)
}

pub fn encode_diagnostics_request(
    id: JsonRpcId,
    request: &DiagnosticsRequest,
) -> Result<WireMessage, DebugProtocolError> {
    encode_tool_request(id, DIAGNOSTICS_TOOL, request)
}

pub fn decode_diagnostics_request(
    message: WireMessage,
) -> Result<(JsonRpcId, DiagnosticsRequest), DebugProtocolError> {
    decode_tool_request(message, DIAGNOSTICS_TOOL)
}

pub fn encode_response(
    id: JsonRpcId,
    response: &DebugResponse,
) -> Result<WireMessage, DebugProtocolError> {
    #[derive(Serialize)]
    #[serde(untagged)]
    enum Payload<'a> {
        Targeted(&'a TargetReply),
        Plain(&'a DebugResponse),
    }
    #[derive(Serialize)]
    #[serde(rename_all = "camelCase")]
    struct BorrowedToolCallResult<'a> {
        content: [TextContent; 1],
        structured_content: Payload<'a>,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        is_error: bool,
    }

    #[derive(Serialize)]
    struct RpcResponse<'a> {
        jsonrpc: &'static str,
        id: JsonRpcId,
        result: BorrowedToolCallResult<'a>,
    }

    let message = WireMessage::text(serde_json::to_string(&RpcResponse {
        jsonrpc: "2.0",
        id,
        result: BorrowedToolCallResult {
            content: [TextContent {
                content_type: "text".into(),
                // structuredContent is the typed payload consumed by the local
                // client. Repeating a full DOM snapshot as text doubled the frame
                // and could cross endpoint-libs' 16 MiB safety limit, which closed
                // an otherwise healthy socket. Keep the required human-readable
                // MCP content concise and send the snapshot exactly once.
                text: response_summary(response),
            }],
            structured_content: match response {
                DebugResponse::Targeted(reply) => Payload::Targeted(reply),
                other => Payload::Plain(other),
            },
            is_error: matches!(response.unscoped(), DebugResponse::Error(_)),
        },
    })?);
    if matches!(&message, WireMessage::Text(text) if text.len() > MAX_DEBUG_FRAME_BYTES) {
        let WireMessage::Text(text) = &message else {
            unreachable!("text encoding checked above")
        };
        return Err(DebugProtocolError::PayloadTooLarge(text.len()));
    }
    Ok(message)
}

fn response_summary(response: &DebugResponse) -> String {
    match response {
        DebugResponse::Ack => "ok".into(),
        DebugResponse::Targets(targets) => format!("{} inspection targets", targets.len()),
        DebugResponse::Targeted(reply) => response_summary(&reply.response),
        DebugResponse::AgentSnapshot(snapshot) => {
            format!("semantic snapshot with {} nodes", snapshot.nodes.len())
        }
        DebugResponse::Snapshot(_) => "diagnostic snapshot".into(),
        DebugResponse::Metrics(_) => "renderer metrics".into(),
        DebugResponse::Idle(_) => "renderer idle".into(),
        DebugResponse::WindowComposition(_) => "native window composition".into(),
        DebugResponse::Captured(image) => {
            format!("captured {}x{} image", image.width, image.height)
        }
        DebugResponse::Condensation(condensation) => {
            format!("condensed page, {} level", condensation.level_name())
        }
        DebugResponse::WebGpu(_) => "WebGPU report".into(),
        DebugResponse::WebGpuBuffer(snapshot) => {
            format!(
                "WebGPU buffer {:?} at submit {}",
                snapshot.label, snapshot.submit
            )
        }
        DebugResponse::Evaluated(_) => "evaluated script".into(),
        DebugResponse::Error(error) => error.message.clone(),
    }
}

pub fn decode_response(
    message: WireMessage,
) -> Result<(JsonRpcId, DebugResponse), DebugProtocolError> {
    decode_response_value(decode_wire_value(message)?)
}

pub fn decode_response_value(
    value: serde_json::Value,
) -> Result<(JsonRpcId, DebugResponse), DebugProtocolError> {
    let JsonRpcMessage::Response(response) = decode_rpc_value(value)? else {
        return Err(DebugProtocolError::UnexpectedMessage);
    };
    let id = response.id.ok_or(DebugProtocolError::RequestIdRequired)?;
    if let Some(error) = response.error {
        return Err(DebugProtocolError::Rpc(error));
    }
    let result: ToolCallResult = serde_json::from_value(
        response
            .result
            .ok_or(DebugProtocolError::UnexpectedMessage)?,
    )?;
    let response = if result.structured_content.get("context").is_some() {
        DebugResponse::Targeted(serde_json::from_value(result.structured_content)?)
    } else {
        serde_json::from_value(result.structured_content)?
    };
    Ok((id, response))
}

pub fn encode_agent_event(event: &AgentControlEvent) -> Result<WireMessage, DebugProtocolError> {
    encode_notification(AGENT_EVENT_NOTIFICATION, event)
}

pub fn decode_agent_event(message: WireMessage) -> Result<AgentControlEvent, DebugProtocolError> {
    decode_notification(message, AGENT_EVENT_NOTIFICATION)
}

pub fn encode_diagnostics_event(event: &DebugEvent) -> Result<WireMessage, DebugProtocolError> {
    encode_notification(DIAGNOSTICS_EVENT_NOTIFICATION, event)
}

pub fn encode_target_event(event: &DiagnosticRecord) -> Result<WireMessage, DebugProtocolError> {
    let frame = encode_notification(DIAGNOSTICS_EVENT_NOTIFICATION, event)?;
    match &frame {
        WireMessage::Text(text) if text.len() > MAX_DEBUG_FRAME_BYTES => {
            Err(DebugProtocolError::PayloadTooLarge(text.len()))
        }
        _ => Ok(frame),
    }
}

pub fn encode_diagnostic_overflow(
    first: u64,
    last: u64,
) -> Result<WireMessage, DebugProtocolError> {
    encode_notification(
        DIAGNOSTICS_EVENT_NOTIFICATION,
        &serde_json::json!({
            "event": "diagnosticOverflow",
            "value": {"code": "diagnosticOverflow", "firstSequence": first, "lastSequence": last}
        }),
    )
}

pub fn decode_diagnostics_event(message: WireMessage) -> Result<DebugEvent, DebugProtocolError> {
    decode_notification(message, DIAGNOSTICS_EVENT_NOTIFICATION)
}

pub fn decode_diagnostics_event_value(
    value: serde_json::Value,
) -> Result<DebugEvent, DebugProtocolError> {
    decode_notification_value(value, DIAGNOSTICS_EVENT_NOTIFICATION)
}

fn encode_tool_request<T: Serialize>(
    id: JsonRpcId,
    tool: &str,
    request: &T,
) -> Result<WireMessage, DebugProtocolError> {
    let params = ToolCallParams {
        name: tool.into(),
        arguments: serde_json::to_value(request)?,
    };
    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
        id,
        MCP_TOOLS_CALL,
        serde_json::to_value(params)?,
    )))
}

fn decode_tool_request<T: DeserializeOwned>(
    message: WireMessage,
    expected_tool: &str,
) -> Result<(JsonRpcId, T), DebugProtocolError> {
    let JsonRpcMessage::Request(request) = decode_rpc(message)? else {
        return Err(DebugProtocolError::UnexpectedMessage);
    };
    if request.method != MCP_TOOLS_CALL {
        return Err(DebugProtocolError::UnexpectedMethod(request.method));
    }
    let id = request.id.ok_or(DebugProtocolError::RequestIdRequired)?;
    let params: ToolCallParams = serde_json::from_value(request.params.ok_or_else(|| {
        DebugProtocolError::Rpc(JsonRpcError::new(
            INVALID_PARAMS,
            "missing tools/call params",
        ))
    })?)?;
    if params.name != expected_tool {
        return Err(DebugProtocolError::UnexpectedTool(params.name));
    }
    Ok((id, serde_json::from_value(params.arguments)?))
}

fn decode_incoming_tool_call(
    request: JsonRpcRequest,
) -> Result<IncomingRequest, DebugProtocolError> {
    let id = request.id.ok_or(DebugProtocolError::RequestIdRequired)?;
    let params: ToolCallParams = serde_json::from_value(request.params.ok_or_else(|| {
        DebugProtocolError::Rpc(JsonRpcError::new(
            INVALID_PARAMS,
            "missing tools/call params",
        ))
    })?)?;
    let targeted = [
        "target",
        "expectedGeneration",
        "expectedDocumentId",
        "allTargets",
        "afterSequence",
    ]
    .iter()
    .any(|key| params.arguments.get(*key).is_some());
    match params.name.as_str() {
        AGENT_CONTROL_TOOL => {
            let envelope: TargetEnvelope<AgentControlRequest> =
                serde_json::from_value(params.arguments)?;
            if targeted || matches!(envelope.request, AgentControlRequest::ListTargets) {
                Ok(IncomingRequest::Targeted {
                    id,
                    request: TargetRequest {
                        options: envelope.options,
                        command: TargetCommand::Agent(envelope.request),
                    },
                })
            } else {
                Ok(IncomingRequest::Agent {
                    id,
                    request: envelope.request,
                })
            }
        }
        DIAGNOSTICS_TOOL => {
            let envelope: TargetEnvelope<DiagnosticsRequest> =
                serde_json::from_value(params.arguments)?;
            if targeted {
                Ok(IncomingRequest::Targeted {
                    id,
                    request: TargetRequest {
                        options: envelope.options,
                        command: TargetCommand::Diagnostics(envelope.request),
                    },
                })
            } else {
                Ok(IncomingRequest::Diagnostics {
                    id,
                    request: envelope.request,
                })
            }
        }
        _ => Err(DebugProtocolError::UnexpectedTool(params.name)),
    }
}

fn encode_notification<T: Serialize>(
    method: &str,
    value: &T,
) -> Result<WireMessage, DebugProtocolError> {
    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::notification(
        method,
        serde_json::to_value(value)?,
    )))
}

fn decode_notification<T: DeserializeOwned>(
    message: WireMessage,
    expected_method: &str,
) -> Result<T, DebugProtocolError> {
    decode_notification_value(decode_wire_value(message)?, expected_method)
}

fn decode_notification_value<T: DeserializeOwned>(
    value: serde_json::Value,
    expected_method: &str,
) -> Result<T, DebugProtocolError> {
    let JsonRpcMessage::Request(request) = decode_rpc_value(value)? else {
        return Err(DebugProtocolError::UnexpectedMessage);
    };
    if !request.is_notification() {
        return Err(DebugProtocolError::Rpc(JsonRpcError::new(
            INVALID_REQUEST,
            "notification must not contain an id",
        )));
    }
    if request.method != expected_method {
        return Err(DebugProtocolError::UnexpectedMethod(request.method));
    }
    serde_json::from_value(request.params.ok_or_else(|| {
        DebugProtocolError::Rpc(JsonRpcError::new(
            INVALID_PARAMS,
            "missing notification params",
        ))
    })?)
    .map_err(Into::into)
}

pub fn encode_rpc(message: JsonRpcMessage) -> Result<WireMessage, DebugProtocolError> {
    Ok(WireMessage::text(serde_json::to_string(&message)?))
}

/// The request id of an incoming frame, recovered without consuming it.
///
/// A decode failure still has to be answered, and answered *to the caller*. A
/// JSON-RPC client matches responses by id, so an error carrying `id: null` is
/// delivered and then discarded, and the caller waits until it times out. That
/// turns "you named a field wrong" into "the app is hung", which is a much
/// worse and much slower thing to debug.
pub fn peek_request_id(message: &WireMessage) -> Option<JsonRpcId> {
    let WireMessage::Text(text) = message else {
        return None;
    };
    match parse(text) {
        Ok(JsonRpcMessage::Request(request)) => request.id,
        _ => None,
    }
}

/// Recover a request id from an already parsed JSON value.
pub fn peek_value_request_id(value: &serde_json::Value) -> Option<JsonRpcId> {
    serde_json::from_value(value.get("id")?.clone()).ok()
}

pub fn decode_wire_value(message: WireMessage) -> Result<serde_json::Value, DebugProtocolError> {
    let WireMessage::Text(text) = message else {
        return Err(DebugProtocolError::NonTextFrame);
    };
    serde_json::from_str(&text).map_err(Into::into)
}

pub fn decode_rpc_value(value: serde_json::Value) -> Result<JsonRpcMessage, DebugProtocolError> {
    serde_json::from_value(value).map_err(Into::into)
}

pub fn decode_rpc(message: WireMessage) -> Result<JsonRpcMessage, DebugProtocolError> {
    let WireMessage::Text(text) = message else {
        return Err(DebugProtocolError::NonTextFrame);
    };
    parse(&text).map_err(DebugProtocolError::Rpc)
}

/// The framing the control socket speaks, and the socket type it speaks over.
///
/// Re-exported so a consumer that serves or fakes this protocol does not have to
/// depend on endpoint-libs and nagoya directly to name the two halves of a
/// connection. There is no tokio bridge here any more: the transport is nagoya
/// end to end.
#[cfg(any(feature = "server", feature = "client"))]
pub use endpoint_libs::libs::ws::transport::nagoya::NagoyaStream;

#[cfg(all(test, feature = "engine"))]
mod test_document;

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

    fn key_request() -> AgentControlRequest {
        AgentControlRequest::Act(AgentAction::Input(InputCommand::Key {
            phase: KeyPhase::Down,
            key: "2".into(),
            code: "Digit2".into(),
            modifiers: Modifiers {
                meta: true,
                ..Default::default()
            },
        }))
    }

    #[test]
    fn typed_modifier_input_round_trips_mcp_tools_call() {
        let request = key_request();
        let id = JsonRpcId::Number(7);
        assert_eq!(
            decode_agent_request(encode_agent_request(id.clone(), &request).unwrap()).unwrap(),
            (id, request)
        );
    }

    #[test]
    fn node_addressed_actions_round_trip() {
        for action in [
            AgentAction::Focus { node_id: 8 },
            AgentAction::Click { node_id: 9 },
            AgentAction::DoubleClick { node_id: 10 },
            AgentAction::Hover { node_id: 11 },
            AgentAction::SetValue {
                node_id: 12,
                value: "fixture".into(),
            },
            AgentAction::ScrollIntoView { node_id: 13 },
            AgentAction::ScrollBy {
                node_id: 14,
                delta_x: 1.0,
                delta_y: -2.0,
            },
            AgentAction::Input(InputCommand::Pointer {
                phase: PointerPhase::Move,
                x: 3.0,
                y: 4.0,
                button: 0,
                modifiers: Modifiers::default(),
            }),
            AgentAction::Input(InputCommand::Wheel {
                delta_x: 0.0,
                delta_y: 5.0,
                phase: WheelPhase::Moved,
                modifiers: Modifiers::default(),
            }),
        ] {
            let request = AgentControlRequest::Act(action);
            let id = JsonRpcId::Number(8);
            assert_eq!(
                decode_agent_request(encode_agent_request(id.clone(), &request).unwrap()).unwrap(),
                (id, request)
            );
        }

        for request in [
            AgentControlRequest::Navigate {
                url: "/second.html".into(),
            },
            AgentControlRequest::Relaunch,
            AgentControlRequest::Quit,
        ] {
            let id = JsonRpcId::Number(9);
            assert_eq!(
                decode_agent_request(encode_agent_request(id.clone(), &request).unwrap()).unwrap(),
                (id, request)
            );
        }
    }

    #[test]
    fn capture_scale_is_bounded_before_a_renderer_allocates() {
        for scale in [f32::NAN, f32::INFINITY, -1.0, 0.0, 0.24, 8.01] {
            assert!(
                CaptureRequest {
                    node_id: None,
                    scale
                }
                .validate()
                .is_err()
            );
        }
        for scale in [0.25, 1.0, 4.0, 8.0] {
            assert!(
                CaptureRequest {
                    node_id: None,
                    scale
                }
                .validate()
                .is_ok()
            );
        }
    }

    #[test]
    fn oversized_capture_response_is_rejected_before_framing() {
        let response = DebugResponse::Captured(CapturedImage {
            width: 1,
            height: 1,
            rgba_base64: "A".repeat(MAX_DEBUG_FRAME_BYTES),
            node_id: None,
        });
        assert!(matches!(
            encode_response(JsonRpcId::Number(1), &response),
            Err(DebugProtocolError::PayloadTooLarge(_))
        ));
    }

    #[test]
    fn click_wire_shape_is_literal_and_foreign_client_readable() {
        let message = encode_agent_request(
            JsonRpcId::Number(3),
            &AgentControlRequest::Act(AgentAction::Click { node_id: 9 }),
        )
        .unwrap();
        let WireMessage::Text(text) = message else {
            panic!("debug requests must be text frames")
        };
        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
        assert_eq!(value["method"], MCP_TOOLS_CALL);
        assert_eq!(value["params"]["name"], AGENT_CONTROL_TOOL);
        assert_eq!(value["params"]["arguments"]["command"], "act");
        assert_eq!(value["params"]["arguments"]["params"]["action"], "click");
        assert_eq!(
            value["params"]["arguments"]["params"]["params"]["nodeId"],
            9
        );
    }

    #[test]
    fn unrelated_mcp_tool_is_rejected_explicitly() {
        let message = JsonRpcMessage::Request(JsonRpcRequest::call(
            JsonRpcId::Number(1),
            MCP_TOOLS_CALL,
            serde_json::json!({"name": "other.tool", "arguments": {}}),
        ));
        assert!(matches!(
            decode_agent_request(encode_rpc(message).unwrap()),
            Err(DebugProtocolError::UnexpectedTool(tool)) if tool == "other.tool"
        ));
    }

    #[test]
    fn responses_and_notifications_round_trip() {
        let id = JsonRpcId::Number(19);
        let response = DebugResponse::Ack;
        assert_eq!(
            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap(),
            (id, response)
        );

        let event = AgentControlEvent::TreeChanged { revision: 12 };
        assert_eq!(
            decode_agent_event(encode_agent_event(&event).unwrap()).unwrap(),
            event
        );

        let event = DebugEvent::PaintCommitted { revision: 13 };
        assert_eq!(
            decode_diagnostics_event(encode_diagnostics_event(&event).unwrap()).unwrap(),
            event
        );
    }

    #[test]
    fn diagnostics_metrics_request_and_response_round_trip() {
        let id = JsonRpcId::Number(23);
        assert_eq!(
            decode_diagnostics_request(
                encode_diagnostics_request(id.clone(), &DiagnosticsRequest::Metrics).unwrap()
            )
            .unwrap(),
            (id.clone(), DiagnosticsRequest::Metrics)
        );

        let response = DebugResponse::Metrics(RendererMetrics {
            resident_bytes: Some(4096),
            ..Default::default()
        });
        assert_eq!(
            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap(),
            (id, response)
        );
    }

    #[test]
    fn native_window_composition_round_trips_without_pixel_inference() {
        let id = JsonRpcId::Number(24);
        assert_eq!(
            decode_diagnostics_request(
                encode_diagnostics_request(id.clone(), &DiagnosticsRequest::WindowComposition)
                    .unwrap()
            )
            .unwrap(),
            (id.clone(), DiagnosticsRequest::WindowComposition)
        );

        let response = DebugResponse::WindowComposition(WindowComposition {
            supported: true,
            surface_transparent: true,
            glass_enabled: true,
            glass_backend: Some("nativeGlass".into()),
            tint_rgba: Some([174, 50, 112, 0]),
            radius: Some(12.0),
        });
        assert_eq!(
            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap(),
            (id, response)
        );
    }

    #[test]
    fn tools_list_describes_the_typed_requests() {
        let message = encode_tools_list_response(JsonRpcId::Number(31), true).unwrap();
        let JsonRpcMessage::Response(response) = decode_rpc(message).unwrap() else {
            panic!("tools/list should be a response")
        };
        let tools = response.result.unwrap()["tools"]
            .as_array()
            .unwrap()
            .to_vec();

        let agent = &tools[0]["inputSchema"];
        let diagnostics = &tools[1]["inputSchema"];
        assert!(
            agent.get("oneOf").is_some() || agent.get("$defs").is_some(),
            "agent schema must describe its tagged command variants: {agent}"
        );
        assert!(
            diagnostics.get("oneOf").is_some() || diagnostics.get("$defs").is_some(),
            "diagnostics schema must describe its tagged command variants: {diagnostics}"
        );
        assert_ne!(agent, &serde_json::json!({"type": "object"}));
        assert_ne!(diagnostics, &serde_json::json!({"type": "object"}));
        let agent_text = agent.to_string();
        let diagnostics_text = diagnostics.to_string();
        assert!(agent_text.contains("command") && agent_text.contains("inspect"));
        assert!(diagnostics_text.contains("command") && diagnostics_text.contains("metrics"));
    }

    #[test]
    fn typed_layout_row_preserves_the_existing_wire_shape() {
        let row = LayoutDiagnosticRow {
            node_id: 7,
            bounds: LayoutBounds {
                x: 1.0,
                y: 2.0,
                width: 30.0,
                height: 40.0,
            },
            scroll_offset: LayoutOffset { x: 3.0, y: 4.0 },
            client_size: LayoutSize {
                width: 30.0,
                height: 40.0,
            },
            scroll_size: LayoutSize {
                width: 50.0,
                height: 60.0,
            },
            scroll_range: LayoutSize {
                width: 20.0,
                height: 20.0,
            },
            border: LayoutEdges {
                top: 1.0,
                right: 2.0,
                bottom: 3.0,
                left: 4.0,
            },
            padding: LayoutEdges {
                top: 5.0,
                right: 6.0,
                bottom: 7.0,
                left: 8.0,
            },
            content_size: LayoutSize {
                width: 10.0,
                height: 11.0,
            },
        };
        let old_wire_shape = serde_json::json!({
            "nodeId": 7,
            "bounds": [1.0, 2.0, 30.0, 40.0],
            "scrollOffset": [3.0, 4.0],
            "clientSize": [30.0, 40.0],
            "scrollSize": [50.0, 60.0],
            "scrollRange": [20.0, 20.0],
            "border": [1.0, 2.0, 3.0, 4.0],
            "padding": [5.0, 6.0, 7.0, 8.0],
            "contentSize": [10.0, 11.0]
        });

        assert_eq!(serde_json::to_value(&row).unwrap(), old_wire_shape);
        assert_eq!(
            serde_json::from_value::<LayoutDiagnosticRow>(old_wire_shape).unwrap(),
            row
        );
    }

    #[test]
    fn semantic_node_keeps_authored_dom_identity_separate_from_node_handle() {
        let node = SemanticNode {
            dom_id: Some("settings-save".into()),
            id: 42,
            parent: None,
            role: "button".into(),
            name: "Save settings".into(),
            value: None,
            enabled: true,
            focusable: true,
            viewport_fixed: false,
            visible: true,
            selected: false,
            bounds: Some([1.0, 2.0, 30.0, 20.0]),
            slot: Some("button".into()),
            attributes: [("aria-sort".into(), "ascending".into())]
                .into_iter()
                .collect(),
        };

        let encoded = serde_json::to_value(&node).unwrap();
        assert_eq!(encoded["domId"], "settings-save");
        assert_eq!(encoded["id"], 42);
        assert_eq!(encoded["attributes"]["aria-sort"], "ascending");
        assert_eq!(
            serde_json::from_value::<SemanticNode>(encoded).unwrap(),
            node
        );
    }

    #[test]
    fn frame_metrics_round_trip_and_keep_unmeasured_fields_empty() {
        let id = JsonRpcId::Number(24);
        let response = DebugResponse::Metrics(RendererMetrics {
            frame: Some(FrameMetrics {
                resolve_ms: 1.5,
                scene_ms: 2.25,
                renderer_ms: 3.0,
                total_ms: 6.75,
                age_ms: 12.0,
                ..Default::default()
            }),
            frame_window: Some(FrameWindowMetrics {
                frames_total: 900,
                window_frames: 256,
                total: TimingStats {
                    mean_ms: 6.0,
                    p95_ms: 11.0,
                    max_ms: 40.0,
                },
                active_fps: 59.4,
                missed_refreshes: 2,
                display_refresh_hz: Some(60.0),
                ..Default::default()
            }),
            snapshot: Some(SnapshotCost {
                poll_ms: 0.5,
                resolve_ms: 1.0,
                total_ms: 4.0,
            }),
            ..Default::default()
        });

        let (decoded_id, decoded) =
            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap();
        assert_eq!(decoded_id, id);
        assert_eq!(decoded, response);

        let DebugResponse::Metrics(metrics) = decoded else {
            panic!("expected renderer metrics")
        };
        let frame = metrics.frame.unwrap();
        // Fields blitz does not measure must stay empty on the wire. Sending 0.0
        // is the defect this guards: a zero reads as "measured, and fast".
        assert_eq!(frame.input_to_present_ms, None);
        assert_eq!(frame.style_ms, None);
        assert_eq!(frame.layout_ms, None);
        assert_eq!(frame.submit_ms, None);
        assert_eq!(frame.present_ms, None);
        assert_eq!(metrics.queue_depth, None);
    }
}