deno 2.9.0

Provides the deno executable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
// Copyright 2018-2026 the Deno authors. MIT license.

//! CDP multiplexer for `deno desktop --inspect`.
//!
//! Architecture:
//!
//! ```text
//!                 ┌──────────────────────────────────────────┐
//!                 │   CDP Multiplexer (this file)            │
//!   DevTools ◄──► │   HTTP: /json/{version,list,protocol}    │
//!   (single ws)   │         /debugger-attached (gate)        │
//!                 │   WS:   /unified  (primary entry)        │
//!                 │         /deno, /cef (direct bypass)      │
//!                 │   HTTP: /devtools/* (frontend proxy)     │
//!                 └──────┬─────────────────────────┬─────────┘
//!                        │                         │
//!              Deno inspector                CEF renderer
//!              (internal port)               (internal port)
//! ```
//!
//! ## Unified session
//!
//! `/unified` is the primary session. CEF is the default (un-sessioned)
//! target; the Deno runtime appears as an attached child via a
//! synthetic `Target.attachedToTarget` event with a stable `sessionId`
//! the mux invents. Frame routing:
//!
//! - Client → mux frames with `sessionId == deno_session_id` have the
//!   field stripped and are forwarded to Deno.
//! - Deno → client frames get the `sessionId` re-injected.
//! - `Target.attachToTarget`/`detachFromTarget` for the Deno child are
//!   answered locally — CEF never learns of the synthetic session.
//! - `Runtime.executionContextCreated` gets its `context.name`
//!   rewritten ("Renderer" on the CEF leg, "Deno" on the Deno leg) so
//!   the Console dropdown shows meaningful labels instead of V8's
//!   defaults.
//! - The synthetic `Target.attachedToTarget` event is emitted lazily,
//!   on the first `Target.setAutoAttach`/`setDiscoverTargets` from the
//!   client — firing earlier loses the event to the frontend's
//!   not-yet-ready auto-attach manager.
//!
//! DevTools sees both isolates in one window: the Console dropdown
//! shows "Renderer" / "Deno", and the Sources panel Threads sidebar
//! lists both.
//!
//! ## `--inspect-brk` / `--inspect-wait`
//!
//! The child process blocks on `GET /debugger-attached` before
//! navigating CEF. The mux flips that endpoint to 200 only after the
//! DevTools client has connected AND — under `--inspect-brk` — the
//! `Debugger.enable` + `Debugger.pause` injection against CEF has
//! acked both responses. This guarantees the renderer pauses on the
//! first JS statement of the loaded page instead of racing past it.
//! Deno's own `--inspect-brk` handles the Deno isolate separately.
//!
//! ## Direct / frontend endpoints
//!
//! `/deno` and `/cef` are direct passthrough WebSockets for debugging
//! each isolate in isolation when the unified session misbehaves.
//! `/devtools/*` proxies CEF's bundled DevTools frontend assets
//! through the mux port so `openDevtools()` can pop a CEF window
//! without triggering CEF's own remote-debugging-port frontend
//! interception.

use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use deno_core::anyhow::Context;
use deno_core::anyhow::anyhow;
use deno_core::anyhow::bail;
use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::serde_json::Value;
use deno_core::serde_json::json;
use fastwebsockets::Frame;
use fastwebsockets::OpCode;
use fastwebsockets::WebSocket;
use fastwebsockets::WebSocketError;
use fastwebsockets::handshake;
use http_body_util::BodyExt;
use http_body_util::Empty;
use http_body_util::Full;
use hyper::body::Bytes;
use hyper::body::Incoming;
use hyper_util::rt::TokioIo;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use uuid::Uuid;

/// Configuration for the CDP multiplexer.
#[derive(Clone, Debug)]
pub struct MuxConfig {
  /// User-visible listen address (from `--inspect`).
  pub listen: SocketAddr,
  /// Internal listen address for Deno's native inspector.
  pub deno_internal: SocketAddr,
  /// Internal listen address for the CEF renderer debug port.
  pub cef_internal: SocketAddr,
  /// `true` when `--inspect-brk` was passed — the mux will inject
  /// `Debugger.enable` + `Debugger.pause` into the CEF session so the
  /// renderer breaks on the first JS statement after navigation.
  pub inspect_brk: bool,
  /// `true` when `--inspect-wait` or `--inspect-brk` was passed.
  /// Not read by the mux itself — the child process uses env vars to
  /// decide whether to poll `/debugger-attached` before navigating.
  #[allow(
    dead_code,
    reason = "read by the child process via env vars, not by the mux itself"
  )]
  pub wait_for_debugger: bool,
}

/// A running multiplexer. Dropping the handle shuts the server down.
pub struct MuxHandle {
  pub listen: SocketAddr,
  _shutdown_tx: oneshot::Sender<()>,
}

pub use deno_lib::util::net::allocate_random_port;

/// Spawn the mux on a background task. Returns once the listener is
/// bound — connection handling continues in the spawned task. The
/// upstream servers (Deno inspector, CEF) do not need to be up yet;
/// the mux polls them on demand when DevTools makes a request.
pub async fn spawn_mux(config: MuxConfig) -> Result<MuxHandle, AnyError> {
  let listener = TcpListener::bind(config.listen).await.with_context(|| {
    format!("failed to bind CDP multiplexer to {}", config.listen)
  })?;
  let listen = listener.local_addr()?;
  let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();

  let state = Arc::new(MuxState::new(config.clone(), listen));

  tokio::spawn(async move {
    let mut shutdown_rx = shutdown_rx;
    let mut consecutive_accept_errors: u32 = 0;
    loop {
      tokio::select! {
        _ = &mut shutdown_rx => {
          log::debug!("[devtools-mux] shutdown requested");
          break;
        }
        accept = listener.accept() => {
          match accept {
            Ok((stream, _)) => {
              consecutive_accept_errors = 0;
              let state = state.clone();
              tokio::spawn(async move {
                if let Err(err) = serve_connection(stream, state).await {
                  log::debug!("[devtools-mux] connection error: {err:?}");
                }
              });
            }
            Err(err) => {
              // A persistent failure (EMFILE, etc.) used to spin forever
              // logging at 5Hz. Throttle the log to every Nth attempt
              // and back off harder.
              consecutive_accept_errors =
                consecutive_accept_errors.saturating_add(1);
              if consecutive_accept_errors == 1
                || consecutive_accept_errors.is_power_of_two()
              {
                log::error!(
                  "[devtools-mux] accept failed (attempt {}): {err:?}",
                  consecutive_accept_errors,
                );
              }
              tokio::time::sleep(Duration::from_millis(200)).await;
            }
          }
        }
      }
    }
  });

  Ok(MuxHandle {
    listen,
    _shutdown_tx: shutdown_tx,
  })
}

/// Per-target identification. Kept small and stable so DevTools'
/// `webSocketDebuggerUrl` doesn't change across polls.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum TargetKind {
  /// Single CDP session fronting both isolates. CEF is the primary;
  /// Deno appears as an attached child target via `Target.*`.
  Unified,
  /// Direct passthrough to the Deno inspector.
  Deno,
  /// Direct passthrough to the CEF renderer's debug port.
  Cef,
}

impl TargetKind {
  fn path(self) -> &'static str {
    match self {
      TargetKind::Unified => "/unified",
      TargetKind::Deno => "/deno",
      TargetKind::Cef => "/cef",
    }
  }

  fn title(self) -> &'static str {
    match self {
      TargetKind::Unified => "Deno Desktop (unified)",
      TargetKind::Deno => "Deno Runtime",
      TargetKind::Cef => "CEF Renderer",
    }
  }
}

/// Synthetic CDP target id for the Deno isolate inside the unified
/// session. Stable per process; DevTools uses it in `Target.attachToTarget`.
const DENO_CHILD_TARGET_ID: &str = "deno-runtime-isolate";

struct MuxState {
  config: MuxConfig,
  listen: SocketAddr,
  // Stable UUIDs per target so repeated /json/list calls return the
  // same IDs. DevTools caches these.
  unified_id: Uuid,
  deno_id: Uuid,
  cef_id: Uuid,
  // Stable session id we hand DevTools when it attaches to the Deno
  // child target inside the unified session.
  deno_session_id: String,
  // Set to `true` when a DevTools client has connected to any session.
  // The child process polls `/debugger-attached` to gate navigation
  // when `--inspect-wait` or `--inspect-brk` is active.
  debugger_attached: Arc<std::sync::atomic::AtomicBool>,
}

impl MuxState {
  fn new(config: MuxConfig, listen: SocketAddr) -> Self {
    Self {
      config,
      listen,
      unified_id: Uuid::new_v4(),
      deno_id: Uuid::new_v4(),
      cef_id: Uuid::new_v4(),
      deno_session_id: Uuid::new_v4().to_string(),
      debugger_attached: Arc::new(std::sync::atomic::AtomicBool::new(false)),
    }
  }

  fn target_for_path(&self, path: &str) -> Option<TargetKind> {
    if path == TargetKind::Unified.path() {
      Some(TargetKind::Unified)
    } else if path == TargetKind::Deno.path() {
      Some(TargetKind::Deno)
    } else if path == TargetKind::Cef.path() {
      Some(TargetKind::Cef)
    } else {
      None
    }
  }
}

async fn serve_connection(
  stream: TcpStream,
  state: Arc<MuxState>,
) -> Result<(), AnyError> {
  let io = TokioIo::new(stream);
  let service = hyper::service::service_fn(move |req| {
    let state = state.clone();
    async move { Ok::<_, Infallible>(handle_request(req, state).await) }
  });

  hyper::server::conn::http1::Builder::new()
    .serve_connection(io, service)
    .with_upgrades()
    .await
    .map_err(|e| anyhow!("hyper serve error: {e}"))?;
  Ok(())
}

async fn handle_request(
  req: hyper::Request<Incoming>,
  state: Arc<MuxState>,
) -> hyper::Response<Full<Bytes>> {
  if req.method() != http::Method::GET {
    return simple_response(
      http::StatusCode::METHOD_NOT_ALLOWED,
      "Not Allowed",
    );
  }
  let path = req.uri().path().to_string();
  match path.as_str() {
    "/json/version" => json_version(&state),
    "/json" | "/json/list" => json_list(&state),
    "/json/protocol" => json_protocol(),
    "/debugger-attached" => {
      if state
        .debugger_attached
        .load(std::sync::atomic::Ordering::SeqCst)
      {
        simple_response(http::StatusCode::OK, "attached")
      } else {
        simple_response(http::StatusCode::SERVICE_UNAVAILABLE, "waiting")
      }
    }
    other => {
      if let Some(kind) = state.target_for_path(other) {
        match handle_upgrade(req, kind, state.clone()) {
          Ok(resp) => resp,
          Err(err) => {
            log::error!("[devtools-mux] upgrade failed for {other}: {err:?}");
            simple_response(http::StatusCode::BAD_REQUEST, "upgrade failed")
          }
        }
      } else if other.starts_with("/devtools/") {
        // Proxy DevTools frontend assets from CEF's bundled HTTP server.
        // Serving them through our port means the CEF window navigating
        // to the DevTools URL sees only `127.0.0.1:<mux_port>`, so it
        // doesn't special-case the remote-debugging port and steal the
        // frontend for the new window's own renderer.
        match proxy_devtools_asset(&req, state.config.cef_internal).await {
          Ok(resp) => resp,
          Err(err) => {
            log::error!("[devtools-mux] devtools asset proxy failed: {err:?}");
            simple_response(http::StatusCode::BAD_GATEWAY, "proxy failed")
          }
        }
      } else {
        simple_response(http::StatusCode::NOT_FOUND, "Not Found")
      }
    }
  }
}

/// GET `http://<cef_internal><path>` and return the response verbatim.
/// Used to proxy the bundled DevTools frontend (inspector.html + its
/// JS/CSS assets) through the mux's own port, bypassing CEF's
/// remote-debugging-port special-case that would otherwise wire the
/// frontend to the requesting window's renderer.
async fn proxy_devtools_asset(
  req: &hyper::Request<Incoming>,
  cef_internal: SocketAddr,
) -> Result<hyper::Response<Full<Bytes>>, AnyError> {
  let path_and_query = req
    .uri()
    .path_and_query()
    .map(|p| p.as_str())
    .unwrap_or("/");

  let stream = TcpStream::connect(cef_internal).await?;
  let io = TokioIo::new(stream);
  let (mut sender, conn) = hyper::client::conn::http1::handshake(io)
    .await
    .map_err(|e| anyhow!("devtools asset handshake failed: {e}"))?;
  tokio::spawn(async move {
    if let Err(err) = conn.await {
      log::trace!("[devtools-mux] devtools asset conn closed: {err:?}");
    }
  });

  let upstream_req = hyper::Request::builder()
    .method(http::Method::GET)
    .uri(path_and_query)
    .header(http::header::HOST, cef_internal.to_string())
    .body(Empty::<Bytes>::new())?;
  let resp = sender.send_request(upstream_req).await?;
  let (parts, body) = resp.into_parts();
  let bytes = body.collect().await?.to_bytes();

  let mut builder = hyper::Response::builder().status(parts.status);
  // Drop hop-by-hop headers that don't apply to our re-packaged body.
  for (name, value) in parts.headers.iter() {
    let skip = matches!(
      name.as_str().to_ascii_lowercase().as_str(),
      "transfer-encoding"
        | "content-length"
        | "connection"
        | "keep-alive"
        | "proxy-authenticate"
        | "proxy-authorization"
        | "te"
        | "trailer"
        | "upgrade"
    );
    if !skip {
      builder = builder.header(name, value);
    }
  }
  Ok(
    builder
      .header(http::header::CONTENT_LENGTH, bytes.len())
      .body(Full::new(bytes))
      .unwrap(),
  )
}

fn json_version(state: &MuxState) -> hyper::Response<Full<Bytes>> {
  let body = json!({
    "Browser": format!("deno-desktop/{}", env!("CARGO_PKG_VERSION")),
    "Protocol-Version": "1.3",
    "V8-Version": deno_core::v8::VERSION_STRING,
    // Advertise one of the two upstream WS URLs as the "browser" URL.
    // DevTools' `chrome://inspect` uses this to drive auto-attach; the
    // CEF upstream exposes the richer Target.* domain.
    "webSocketDebuggerUrl": format!(
      "ws://{}{}",
      state.listen,
      TargetKind::Cef.path(),
    ),
  });
  json_response(body)
}

fn json_list(state: &MuxState) -> hyper::Response<Full<Bytes>> {
  let listen = state.listen.to_string();
  let unified_url = format!("ws://{listen}{}", TargetKind::Unified.path());
  let deno_url = format!("ws://{listen}{}", TargetKind::Deno.path());
  let cef_url = format!("ws://{listen}{}", TargetKind::Cef.path());

  // Primary entry: the unified session. DevTools opens one window
  // (inspector.html — full browser DevTools) and gets both isolates as
  // attached targets in the Sources panel.
  let unified_entry = json!({
    "id": state.unified_id.to_string(),
    "type": "page",
    "title": TargetKind::Unified.title(),
    "description": "Unified DevTools (CEF page + Deno runtime)",
    "url": "deno-desktop://unified",
    "faviconUrl": "https://deno.land/favicon.ico",
    "devtoolsFrontendUrl": format!(
      "devtools://devtools/bundled/inspector.html?ws={}",
      strip_scheme(&unified_url),
    ),
    "webSocketDebuggerUrl": unified_url,
  });
  // Fallback entries: direct passthrough to each isolate. Useful when
  // the unified session misbehaves and you want to debug each side in
  // isolation.
  let deno_entry = json!({
    "id": state.deno_id.to_string(),
    "type": "node",
    "title": TargetKind::Deno.title(),
    "description": "Deno runtime V8 isolate (direct)",
    "url": format!("deno://{}", state.config.deno_internal),
    "faviconUrl": "https://deno.land/favicon.ico",
    "devtoolsFrontendUrl": format!(
      "devtools://devtools/bundled/js_app.html?ws={}&experiments=true&v8only=true",
      strip_scheme(&deno_url),
    ),
    "webSocketDebuggerUrl": deno_url,
  });
  let cef_entry = json!({
    "id": state.cef_id.to_string(),
    "type": "page",
    "title": TargetKind::Cef.title(),
    "description": "CEF renderer V8 isolate (direct)",
    "url": format!("cef://{}", state.config.cef_internal),
    "faviconUrl": "https://deno.land/favicon.ico",
    "devtoolsFrontendUrl": format!(
      "devtools://devtools/bundled/inspector.html?ws={}",
      strip_scheme(&cef_url),
    ),
    "webSocketDebuggerUrl": cef_url,
  });

  json_response(Value::Array(vec![unified_entry, deno_entry, cef_entry]))
}

/// Return an empty protocol descriptor. DevTools tolerates this and
/// falls back to the built-in protocol.
fn json_protocol() -> hyper::Response<Full<Bytes>> {
  json_response(json!({
    "version": { "major": "1", "minor": "3" },
    "domains": [],
  }))
}

fn json_response(value: Value) -> hyper::Response<Full<Bytes>> {
  let body = Full::new(Bytes::from(serde_json::to_vec(&value).unwrap()));
  hyper::Response::builder()
    .status(http::StatusCode::OK)
    .header(http::header::CONTENT_TYPE, "application/json")
    .body(body)
    .unwrap()
}

fn simple_response(
  status: http::StatusCode,
  msg: &'static str,
) -> hyper::Response<Full<Bytes>> {
  hyper::Response::builder()
    .status(status)
    .body(Full::new(Bytes::from(msg)))
    .unwrap()
}

fn strip_scheme(ws_url: &str) -> String {
  ws_url
    .strip_prefix("ws://")
    .or_else(|| ws_url.strip_prefix("wss://"))
    .unwrap_or(ws_url)
    .to_string()
}

/// Upgrade an incoming HTTP request to a WebSocket, open a matching
/// WebSocket to the upstream target, and shuttle frames in both
/// directions.
fn handle_upgrade(
  mut req: hyper::Request<Incoming>,
  kind: TargetKind,
  state: Arc<MuxState>,
) -> Result<hyper::Response<Full<Bytes>>, AnyError> {
  let (resp, upgrade_fut) = fastwebsockets::upgrade::upgrade(&mut req)
    .map_err(|e| anyhow!("not a valid websocket upgrade: {e}"))?;

  tokio::spawn(async move {
    let client = match upgrade_fut.await {
      Ok(ws) => ws,
      Err(err) => {
        log::error!("[devtools-mux] client upgrade failed: {err:?}");
        return;
      }
    };

    // `debugger_attached` is what releases the child process from its
    // `/debugger-attached` poll so it can navigate CEF. Under
    // `--inspect-brk` we MUST inject `Debugger.enable` + `Debugger.pause`
    // into the CEF isolate BEFORE the child navigates, otherwise the
    // page's JS executes before the pause request arrives. So each
    // target-specific handler signals attachment at its own right moment.

    match kind {
      TargetKind::Unified => {
        if let Err(err) = run_unified_session(client, state).await {
          log::debug!("[devtools-mux] unified session ended: {err:?}");
        }
      }
      TargetKind::Deno => {
        // Deno has its own `--inspect-brk` mechanism that blocks the
        // isolate until a client attaches — nothing to inject here.
        mark_debugger_attached(&state);
        match connect_upstream(&state, kind).await {
          Ok(upstream) => {
            if let Err(err) = proxy_frames(client, upstream).await {
              log::debug!("[devtools-mux] proxy ended: {err:?}");
            }
          }
          Err(err) => {
            log::error!(
              "[devtools-mux] failed to connect upstream for Deno: {err:?}"
            );
          }
        }
      }
      TargetKind::Cef => match connect_upstream(&state, kind).await {
        Ok(mut upstream) => {
          if state.config.inspect_brk
            && let Err(err) = inject_cef_pause(&mut upstream).await
          {
            log::error!(
              "[devtools-mux] failed to inject pause into CEF: {err:?}"
            );
          }
          mark_debugger_attached(&state);
          if let Err(err) = proxy_frames(client, upstream).await {
            log::debug!("[devtools-mux] proxy ended: {err:?}");
          }
        }
        Err(err) => {
          log::error!(
            "[devtools-mux] failed to connect upstream for CEF: {err:?}"
          );
        }
      },
    }
  });

  let (parts, _) = resp.into_parts();
  Ok(hyper::Response::from_parts(parts, Full::new(Bytes::new())))
}

/// Open a WebSocket to the right upstream target, performing target
/// discovery as needed. For CEF we hit `/json/list` to find the live
/// `webSocketDebuggerUrl`; for Deno we call the inspector server's
/// same endpoint. The upstream is retried briefly since the renderer
/// may not have finished booting.
async fn connect_upstream(
  state: &MuxState,
  kind: TargetKind,
) -> Result<WebSocket<TokioIo<hyper::upgrade::Upgraded>>, AnyError> {
  let upstream_host = match kind {
    TargetKind::Deno => state.config.deno_internal,
    TargetKind::Cef => state.config.cef_internal,
    TargetKind::Unified => {
      bail!("connect_upstream cannot be called with the Unified target")
    }
  };

  // Poll until the upstream has a live WebSocket debugger URL.
  let mut last_err: Option<AnyError> = None;
  let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
  while tokio::time::Instant::now() < deadline {
    match fetch_upstream_ws_url(upstream_host).await {
      Ok(ws_url) => match connect_ws(&ws_url).await {
        Ok(ws) => return Ok(ws),
        Err(err) => {
          last_err = Some(err);
        }
      },
      Err(err) => {
        last_err = Some(err);
      }
    }
    tokio::time::sleep(Duration::from_millis(250)).await;
  }
  Err(last_err.unwrap_or_else(|| anyhow!("upstream connect timed out")))
}

/// GET `http://<host>/json/list` and pick the first entry's
/// `webSocketDebuggerUrl`. Both Deno's inspector server and CEF's
/// remote-debugging endpoint implement this.
async fn fetch_upstream_ws_url(host: SocketAddr) -> Result<String, AnyError> {
  let stream = TcpStream::connect(host).await?;
  let io = TokioIo::new(stream);
  let (mut sender, conn) = hyper::client::conn::http1::handshake(io)
    .await
    .map_err(|e| anyhow!("http handshake to {host} failed: {e}"))?;
  tokio::spawn(async move {
    if let Err(err) = conn.await {
      log::trace!("[devtools-mux] upstream conn closed: {err:?}");
    }
  });

  let req = hyper::Request::builder()
    .method(http::Method::GET)
    .uri("/json/list")
    .header(http::header::HOST, host.to_string())
    .body(Empty::<Bytes>::new())?;
  let resp = sender.send_request(req).await?;
  if !resp.status().is_success() {
    bail!("upstream /json/list at {host} returned {}", resp.status());
  }
  let body = resp.collect().await?.to_bytes();
  let value: Value = serde_json::from_slice(&body)
    .with_context(|| format!("upstream /json/list at {host} not JSON"))?;

  let ws_url = value
    .as_array()
    .and_then(|arr| {
      arr.iter().find_map(|v| {
        // Skip targets that are our own DevTools frontend window — when
        // openDevtools() creates a CEF window pointed at inspector.html,
        // CEF registers it as a debuggable target. Connecting to it
        // instead of the real app window would show "DevTools for
        // DevTools".
        let url = v.get("url").and_then(|u| u.as_str()).unwrap_or("");
        if url.contains("/devtools/") || url.contains("devtools://") {
          return None;
        }
        v.get("webSocketDebuggerUrl")
      })
    })
    .and_then(|v| v.as_str())
    .ok_or_else(|| {
      anyhow!("no webSocketDebuggerUrl in /json/list at {host}")
    })?;

  // Upstream responds with its own listen host; some backends return
  // `0.0.0.0` or `localhost`. Force to the target host so we connect
  // to the right address.
  let rewritten = rewrite_ws_host(ws_url, host);
  Ok(rewritten)
}

fn rewrite_ws_host(ws_url: &str, host: SocketAddr) -> String {
  let rest = ws_url
    .strip_prefix("ws://")
    .or_else(|| ws_url.strip_prefix("wss://"))
    .unwrap_or(ws_url);
  let path = rest.find('/').map(|i| &rest[i..]).unwrap_or("/");
  format!("ws://{host}{path}")
}

async fn connect_ws(
  ws_url: &str,
) -> Result<WebSocket<TokioIo<hyper::upgrade::Upgraded>>, AnyError> {
  let url: http::Uri = ws_url.parse()?;
  let host = url
    .host()
    .ok_or_else(|| anyhow!("ws url missing host: {ws_url}"))?;
  // Don't fall back to port 80: a malformed `/json/list` response
  // missing the port would otherwise route the WS connect to whatever
  // is listening on port 80 of the upstream host.
  let port = url
    .port_u16()
    .ok_or_else(|| anyhow!("ws url missing port: {ws_url}"))?;
  let authority = format!("{host}:{port}");

  let stream = TcpStream::connect(&authority).await?;
  let req = hyper::Request::builder()
    .method(http::Method::GET)
    .uri(url.path_and_query().map(|p| p.as_str()).unwrap_or("/"))
    .header(http::header::HOST, &authority)
    .header(http::header::UPGRADE, "websocket")
    .header(http::header::CONNECTION, "upgrade")
    .header("Sec-WebSocket-Key", handshake::generate_key())
    .header("Sec-WebSocket-Version", "13")
    .body(Empty::<Bytes>::new())?;

  let (ws, _) = handshake::client(&TokioExec, req, stream).await?;
  Ok(ws)
}

struct TokioExec;
impl<F> hyper::rt::Executor<F> for TokioExec
where
  F: std::future::Future + Send + 'static,
  F::Output: Send + 'static,
{
  fn execute(&self, fut: F) {
    tokio::spawn(fut);
  }
}

/// Bidirectionally forward frames between the DevTools client and the
/// upstream inspector. The loop ends when either side closes or errors.
async fn proxy_frames(
  mut client: WebSocket<TokioIo<hyper::upgrade::Upgraded>>,
  mut upstream: WebSocket<TokioIo<hyper::upgrade::Upgraded>>,
) -> Result<(), AnyError> {
  // We forward control frames (ping/pong/close) verbatim between the
  // two peers, so disable fastwebsockets' built-in handling.
  client.set_auto_close(false);
  client.set_auto_pong(false);
  upstream.set_auto_close(false);
  upstream.set_auto_pong(false);

  // Split both sides so the two pump directions can run concurrently
  // without holding a single mutex across `.await` points.
  let (mut client_rx, mut client_tx) = client.split(tokio::io::split);
  let (mut up_rx, mut up_tx) = upstream.split(tokio::io::split);

  let client_to_up = async {
    // The send_fn is used by fastwebsockets to auto-respond to control
    // frames; with auto_close/auto_pong disabled it is never called.
    let mut noop = |_: Frame<'_>| async { Ok::<(), WebSocketError>(()) };
    loop {
      let frame = match client_rx.read_frame(&mut noop).await {
        Ok(f) => f,
        Err(err) => {
          log::debug!("[devtools-mux] client read: {err:?}");
          return;
        }
      };
      let is_close = frame.opcode == OpCode::Close;
      if let Err(err) = up_tx.write_frame(frame).await {
        log::debug!("[devtools-mux] upstream write: {err:?}");
        return;
      }
      if is_close {
        return;
      }
    }
  };

  let up_to_client = async {
    let mut noop = |_: Frame<'_>| async { Ok::<(), WebSocketError>(()) };
    loop {
      let frame = match up_rx.read_frame(&mut noop).await {
        Ok(f) => f,
        Err(err) => {
          log::debug!("[devtools-mux] upstream read: {err:?}");
          return;
        }
      };
      let is_close = frame.opcode == OpCode::Close;
      if let Err(err) = client_tx.write_frame(frame).await {
        log::debug!("[devtools-mux] client write: {err:?}");
        return;
      }
      if is_close {
        return;
      }
    }
  };

  tokio::join!(client_to_up, up_to_client);
  Ok(())
}

// ─── Unified session (v2) ──────────────────────────────────────────
//
// One DevTools window, two isolates. CEF is the primary session;
// Deno appears as an "attached" child target via the standard
// `Target.attachedToTarget` event with a synthetic `sessionId`.
// Frames flow through CDP-aware routers that strip/inject `sessionId`
// on the Deno leg and pass everything else through to CEF.

/// Owned representation of a WebSocket frame, suitable for sending
/// through an mpsc channel. `fastwebsockets::Frame` borrows from the
/// reader's internal buffer and so can't cross task boundaries.
struct OwnedFrame {
  opcode: OpCode,
  payload: Vec<u8>,
}

impl OwnedFrame {
  fn text(payload: Vec<u8>) -> Self {
    Self {
      opcode: OpCode::Text,
      payload,
    }
  }

  fn into_frame(self) -> Frame<'static> {
    Frame::new(
      true,
      self.opcode,
      None,
      fastwebsockets::Payload::Owned(self.payload),
    )
  }
}

/// Set `debugger_attached` so the child process's `/debugger-attached`
/// poll returns 200 and it can proceed with navigation. Only call this
/// once the CEF pause injection (if any) has completed.
fn mark_debugger_attached(state: &MuxState) {
  state
    .debugger_attached
    .store(true, std::sync::atomic::Ordering::SeqCst);
}

/// Send `Debugger.enable` + `Debugger.pause` to the CEF upstream,
/// swallowing their responses. Called before the child is released to
/// navigate, so the renderer stops on the first JS statement of the
/// loaded page.
///
/// Any CEF → client frames that arrive during the injection window are
/// discarded. This is acceptable because the renderer has not yet
/// navigated to a user page (the child is blocked on
/// `/debugger-attached`), so the only traffic is CEF's own protocol
/// setup (e.g. unsolicited `Target.targetCreated` for about:blank),
/// which DevTools will re-observe via `Target.setDiscoverTargets` once
/// the session opens.
async fn inject_cef_pause<S>(cef: &mut WebSocket<S>) -> Result<(), AnyError>
where
  S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
  let enable = json!({"id": -1, "method": "Debugger.enable"});
  cef
    .write_frame(Frame::new(
      true,
      OpCode::Text,
      None,
      fastwebsockets::Payload::Owned(serde_json::to_vec(&enable).unwrap()),
    ))
    .await?;

  let pause = json!({"id": -2, "method": "Debugger.pause"});
  cef
    .write_frame(Frame::new(
      true,
      OpCode::Text,
      None,
      fastwebsockets::Payload::Owned(serde_json::to_vec(&pause).unwrap()),
    ))
    .await?;

  // Read frames until we've observed both responses. CEF may interleave
  // unsolicited events, which we drop.
  let mut saw_enable = false;
  let mut saw_pause = false;
  while !(saw_enable && saw_pause) {
    let frame = cef.read_frame().await?;
    if frame.opcode != OpCode::Text {
      continue;
    }
    let value: Value = match serde_json::from_slice(&frame.payload) {
      Ok(v) => v,
      Err(_) => continue,
    };
    match value.get("id").and_then(|v| v.as_i64()) {
      Some(-1) => saw_enable = true,
      Some(-2) => saw_pause = true,
      _ => {}
    }
  }

  log::debug!(
    "[devtools-mux] injected Debugger.enable + Debugger.pause into CEF"
  );
  Ok(())
}

/// Run the unified DevTools session: one client WebSocket fronting two
/// upstreams (CEF as the default session, Deno attached via a
/// synthetic `sessionId`).
async fn run_unified_session(
  client: WebSocket<TokioIo<hyper::upgrade::Upgraded>>,
  state: Arc<MuxState>,
) -> Result<(), AnyError> {
  let mut client = client;
  client.set_auto_close(false);
  client.set_auto_pong(false);

  let (cef, deno) = tokio::try_join!(
    connect_upstream(&state, TargetKind::Cef),
    connect_upstream(&state, TargetKind::Deno),
  )?;
  let mut cef = cef;
  let mut deno = deno;
  cef.set_auto_close(false);
  cef.set_auto_pong(false);
  deno.set_auto_close(false);
  deno.set_auto_pong(false);

  let session_id = state.deno_session_id.clone();

  // When --inspect-brk is active, inject Debugger.enable + Debugger.pause
  // into the CEF session BEFORE the child is allowed to navigate. The
  // child polls `/debugger-attached` and will only navigate once we
  // signal attachment, so doing the injection first — and releasing
  // attachment afterwards — guarantees the renderer pauses on the very
  // first JS statement of the loaded page.
  if state.config.inspect_brk {
    inject_cef_pause(&mut cef).await?;
  }
  mark_debugger_attached(&state);

  let (mut client_rx, mut client_tx) = client.split(tokio::io::split);
  let (mut cef_rx, mut cef_tx) = cef.split(tokio::io::split);
  let (mut deno_rx, mut deno_tx) = deno.split(tokio::io::split);

  let (client_send, mut client_recv) = mpsc::unbounded_channel::<OwnedFrame>();
  let (cef_send, mut cef_recv) = mpsc::unbounded_channel::<OwnedFrame>();
  let (deno_send, mut deno_recv) = mpsc::unbounded_channel::<OwnedFrame>();

  // Deno is announced lazily, the first time DevTools asks about
  // targets — firing too early causes the event to be dropped before
  // the frontend's auto-attach manager has subscribed. See
  // `route_client_text` for the trigger.
  let deno_announced = Arc::new(std::sync::atomic::AtomicBool::new(false));

  // Writer tasks: pump owned frames from a channel into the WS half.
  let client_writer = tokio::spawn(async move {
    while let Some(owned) = client_recv.recv().await {
      let close = owned.opcode == OpCode::Close;
      if let Err(err) = client_tx.write_frame(owned.into_frame()).await {
        log::debug!("[devtools-mux] unified client write: {err:?}");
        return;
      }
      if close {
        return;
      }
    }
  });
  let cef_writer = tokio::spawn(async move {
    while let Some(owned) = cef_recv.recv().await {
      let close = owned.opcode == OpCode::Close;
      if let Err(err) = cef_tx.write_frame(owned.into_frame()).await {
        log::debug!("[devtools-mux] unified cef write: {err:?}");
        return;
      }
      if close {
        return;
      }
    }
  });
  let deno_writer = tokio::spawn(async move {
    while let Some(owned) = deno_recv.recv().await {
      let close = owned.opcode == OpCode::Close;
      if let Err(err) = deno_tx.write_frame(owned.into_frame()).await {
        log::debug!("[devtools-mux] unified deno write: {err:?}");
        return;
      }
      if close {
        return;
      }
    }
  });

  // Reader: client → CEF/Deno (with CDP-aware routing).
  let mut client_reader = {
    let client_send = client_send.clone();
    let cef_send = cef_send.clone();
    let deno_send = deno_send.clone();
    let session_id = session_id.clone();
    let deno_announced = deno_announced.clone();
    tokio::spawn(async move {
      let mut noop = |_: Frame<'_>| async { Ok::<(), WebSocketError>(()) };
      loop {
        let frame = match client_rx.read_frame(&mut noop).await {
          Ok(f) => f,
          Err(err) => {
            log::debug!("[devtools-mux] unified client read: {err:?}");
            return;
          }
        };
        let opcode = frame.opcode;
        let payload = frame.payload.to_vec();
        match opcode {
          OpCode::Text => {
            route_client_text(
              &payload,
              &session_id,
              &client_send,
              &cef_send,
              &deno_send,
              &deno_announced,
            );
          }
          OpCode::Close => {
            let _ = cef_send.send(OwnedFrame {
              opcode,
              payload: payload.clone(),
            });
            let _ = deno_send.send(OwnedFrame { opcode, payload });
            return;
          }
          _ => {
            // Binary, Ping, Pong, Continuation: forward to CEF (the
            // primary session). Ping/pong on the client connection is
            // for keep-alive; CEF will reply.
            let _ = cef_send.send(OwnedFrame { opcode, payload });
          }
        }
      }
    })
  };

  // Reader: CEF → client. No sessionId injection, but we do rewrite
  // the execution-context name so the Console dropdown reads
  // "Renderer" instead of V8's default "top".
  let mut cef_reader = {
    let client_send = client_send.clone();
    tokio::spawn(async move {
      let mut noop = |_: Frame<'_>| async { Ok::<(), WebSocketError>(()) };
      loop {
        let frame = match cef_rx.read_frame(&mut noop).await {
          Ok(f) => f,
          Err(err) => {
            log::debug!("[devtools-mux] unified cef read: {err:?}");
            return;
          }
        };
        let opcode = frame.opcode;
        let payload = frame.payload.to_vec();
        let owned = if opcode == OpCode::Text {
          OwnedFrame::text(rewrite_text_from_upstream(
            &payload, None, "Renderer",
          ))
        } else {
          OwnedFrame { opcode, payload }
        };
        if client_send.send(owned).is_err() {
          return;
        }
      }
    })
  };

  // Reader: Deno → client. Inject sessionId so DevTools routes frames
  // to the synthetic child target, and relabel the execution context
  // to "Deno" instead of V8's "main realm".
  let mut deno_reader = {
    let client_send = client_send.clone();
    let session_id = session_id.clone();
    tokio::spawn(async move {
      let mut noop = |_: Frame<'_>| async { Ok::<(), WebSocketError>(()) };
      loop {
        let frame = match deno_rx.read_frame(&mut noop).await {
          Ok(f) => f,
          Err(err) => {
            log::debug!("[devtools-mux] unified deno read: {err:?}");
            return;
          }
        };
        let opcode = frame.opcode;
        let payload = frame.payload.to_vec();
        let owned = if opcode == OpCode::Text {
          OwnedFrame::text(rewrite_text_from_upstream(
            &payload,
            Some(&session_id),
            "Deno",
          ))
        } else {
          OwnedFrame { opcode, payload }
        };
        if client_send.send(owned).is_err() {
          return;
        }
      }
    })
  };

  // Drop the originals so writers exit once readers finish.
  drop(client_send);
  drop(cef_send);
  drop(deno_send);

  // Wait for any reader to exit, then tear down everything else.
  tokio::select! {
    _ = &mut client_reader => {},
    _ = &mut cef_reader => {},
    _ = &mut deno_reader => {},
  }

  client_reader.abort();
  cef_reader.abort();
  deno_reader.abort();
  client_writer.abort();
  cef_writer.abort();
  deno_writer.abort();

  Ok(())
}

/// CDP-aware routing for a text frame coming from the DevTools client.
///
/// - `sessionId == deno_session_id` → strip and send to Deno.
/// - `Target.setAutoAttach` / `Target.setDiscoverTargets(true)` →
///   forward to CEF AND lazily emit our synthetic
///   `Target.attachedToTarget` for Deno (once). We piggyback on these
///   calls because they are the frontend's signal that it's ready to
///   process target events; firing earlier causes the event to be
///   silently dropped.
/// - `Target.attachToTarget(deno-id)` → reply locally with the
///   synthetic sessionId; never reaches CEF (which doesn't know it).
/// - `Target.detachFromTarget(deno-session)` → reply locally and
///   synthesize the corresponding `Target.detachedFromTarget` event.
/// - everything else → forward to CEF.
fn route_client_text(
  payload: &[u8],
  session_id: &str,
  client_send: &mpsc::UnboundedSender<OwnedFrame>,
  cef_send: &mpsc::UnboundedSender<OwnedFrame>,
  deno_send: &mpsc::UnboundedSender<OwnedFrame>,
  deno_announced: &Arc<std::sync::atomic::AtomicBool>,
) {
  let mut value: Value = match serde_json::from_slice(payload) {
    Ok(v) => v,
    Err(_) => {
      let _ = cef_send.send(OwnedFrame::text(payload.to_vec()));
      return;
    }
  };

  let session = value.get("sessionId").and_then(|v| v.as_str());
  if session == Some(session_id) {
    if let Some(obj) = value.as_object_mut() {
      obj.remove("sessionId");
    }
    let bytes = serde_json::to_vec(&value).unwrap_or_else(|_| payload.to_vec());
    let _ = deno_send.send(OwnedFrame::text(bytes));
    return;
  }

  let id = value.get("id").and_then(|v| v.as_i64());
  let method = value
    .get("method")
    .and_then(|v| v.as_str())
    .map(str::to_owned);

  // The frontend is now listening for target events — announce Deno.
  if matches!(
    method.as_deref(),
    Some("Target.setAutoAttach") | Some("Target.setDiscoverTargets")
  ) && !deno_announced.swap(true, std::sync::atomic::Ordering::SeqCst)
  {
    let event = attached_to_target_event(session_id);
    let _ =
      client_send.send(OwnedFrame::text(serde_json::to_vec(&event).unwrap()));
  }

  if method.as_deref() == Some("Target.attachToTarget") {
    let target_id = value
      .get("params")
      .and_then(|p| p.get("targetId"))
      .and_then(|v| v.as_str());
    if target_id == Some(DENO_CHILD_TARGET_ID) {
      if let Some(rid) = id {
        let reply = json!({
          "id": rid,
          "result": { "sessionId": session_id },
        });
        let _ = client_send
          .send(OwnedFrame::text(serde_json::to_vec(&reply).unwrap()));
      }
      return;
    }
  }

  if method.as_deref() == Some("Target.detachFromTarget") {
    let detach_session = value
      .get("params")
      .and_then(|p| p.get("sessionId"))
      .and_then(|v| v.as_str());
    if detach_session == Some(session_id) {
      if let Some(rid) = id {
        let reply = json!({ "id": rid, "result": {} });
        let _ = client_send
          .send(OwnedFrame::text(serde_json::to_vec(&reply).unwrap()));
      }
      let event = json!({
        "method": "Target.detachedFromTarget",
        "params": {
          "sessionId": session_id,
          "targetId": DENO_CHILD_TARGET_ID,
        },
      });
      let _ =
        client_send.send(OwnedFrame::text(serde_json::to_vec(&event).unwrap()));
      return;
    }
  }

  let _ = cef_send.send(OwnedFrame::text(payload.to_vec()));
}

/// Rewrite a JSON CDP frame on its way from an upstream to the
/// DevTools client:
///
/// - Optionally inject `sessionId = session_id` so DevTools attributes
///   the frame to the synthetic Deno child target.
/// - Rename `Runtime.executionContextCreated.params.context.name` to
///   `context_name` so the Console "execution context" dropdown shows
///   a meaningful label instead of V8's defaults (`"top"`, `"main
///   realm"`).
///
/// If the payload isn't valid JSON, return it unchanged.
fn rewrite_text_from_upstream(
  payload: &[u8],
  inject_session_id: Option<&str>,
  context_name: &str,
) -> Vec<u8> {
  let mut value: Value = match serde_json::from_slice(payload) {
    Ok(v) => v,
    Err(_) => return payload.to_vec(),
  };
  let Some(obj) = value.as_object_mut() else {
    return payload.to_vec();
  };
  if let Some(sid) = inject_session_id {
    obj.insert("sessionId".to_string(), Value::String(sid.to_string()));
  }
  if obj.get("method").and_then(|v| v.as_str())
    == Some("Runtime.executionContextCreated")
    && let Some(ctx) = obj
      .get_mut("params")
      .and_then(|v| v.get_mut("context"))
      .and_then(|v| v.as_object_mut())
  {
    ctx.insert("name".to_string(), Value::String(context_name.to_string()));
  }
  serde_json::to_vec(&value).unwrap_or_else(|_| payload.to_vec())
}

/// Build a `Target.attachedToTarget` event advertising the Deno
/// runtime isolate as a child of the unified session.
fn attached_to_target_event(session_id: &str) -> Value {
  // `inspector.html` only renders attached child targets in the Sources
  // panel "Threads" sidebar when their type matches a known
  // worker-style kind (`worker`, `shared_worker`, `service_worker`).
  // We pick `worker` so the Deno runtime isolate shows up alongside
  // the CEF renderer's main thread.
  json!({
    "method": "Target.attachedToTarget",
    "params": {
      "sessionId": session_id,
      "targetInfo": {
        "targetId": DENO_CHILD_TARGET_ID,
        "type": "worker",
        "title": "Deno Runtime",
        "url": "deno://runtime",
        "attached": true,
        "canAccessOpener": false,
      },
      "waitingForDebugger": false,
    },
  })
}

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

  #[test]
  fn rewrite_ws_host_forces_host() {
    let host: SocketAddr = "127.0.0.1:9230".parse().unwrap();
    assert_eq!(
      rewrite_ws_host("ws://0.0.0.0:9230/devtools/browser/abc", host),
      "ws://127.0.0.1:9230/devtools/browser/abc"
    );
    assert_eq!(
      rewrite_ws_host("ws://localhost/ws/deadbeef", host),
      "ws://127.0.0.1:9230/ws/deadbeef"
    );
  }

  fn test_config() -> MuxConfig {
    MuxConfig {
      listen: "127.0.0.1:9229".parse().unwrap(),
      deno_internal: "127.0.0.1:9230".parse().unwrap(),
      cef_internal: "127.0.0.1:9231".parse().unwrap(),
      inspect_brk: false,
      wait_for_debugger: false,
    }
  }

  #[test]
  fn target_path_round_trip() {
    let state = MuxState::new(test_config(), "127.0.0.1:9229".parse().unwrap());
    assert_eq!(state.target_for_path("/unified"), Some(TargetKind::Unified));
    assert_eq!(state.target_for_path("/deno"), Some(TargetKind::Deno));
    assert_eq!(state.target_for_path("/cef"), Some(TargetKind::Cef));
    assert_eq!(state.target_for_path("/bogus"), None);
  }

  // ── sessionId dispatch ────────────────────────────────────────────

  #[test]
  fn route_client_text_strips_session_and_forwards_to_deno() {
    let (client_tx, _client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, _cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, mut deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(false));

    let session_id = "test-session-123";
    let msg = json!({
      "id": 1,
      "method": "Debugger.enable",
      "sessionId": session_id,
    });
    let payload = serde_json::to_vec(&msg).unwrap();

    route_client_text(
      &payload, session_id, &client_tx, &cef_tx, &deno_tx, &announced,
    );

    // Should arrive at Deno with sessionId stripped.
    let frame = deno_rx.try_recv().expect("expected frame on deno channel");
    let value: Value = serde_json::from_slice(&frame.payload).unwrap();
    assert_eq!(value.get("id").unwrap(), 1);
    assert_eq!(value.get("method").unwrap(), "Debugger.enable");
    assert!(
      value.get("sessionId").is_none(),
      "sessionId should be stripped"
    );
  }

  #[test]
  fn route_client_text_forwards_non_session_to_cef() {
    let (client_tx, _client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, mut cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, _deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(true));

    let msg = json!({"id": 5, "method": "DOM.getDocument"});
    let payload = serde_json::to_vec(&msg).unwrap();

    route_client_text(
      &payload,
      "some-session",
      &client_tx,
      &cef_tx,
      &deno_tx,
      &announced,
    );

    let frame = cef_rx.try_recv().expect("expected frame on cef channel");
    let value: Value = serde_json::from_slice(&frame.payload).unwrap();
    assert_eq!(value.get("id").unwrap(), 5);
  }

  #[test]
  fn route_client_text_attach_to_deno_target_replies_locally() {
    let (client_tx, mut client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, mut cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, _deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(true));

    let session_id = "deno-sess";
    let msg = json!({
      "id": 10,
      "method": "Target.attachToTarget",
      "params": { "targetId": DENO_CHILD_TARGET_ID },
    });
    let payload = serde_json::to_vec(&msg).unwrap();

    route_client_text(
      &payload, session_id, &client_tx, &cef_tx, &deno_tx, &announced,
    );

    // Should reply to client with the synthetic sessionId.
    let frame = client_rx.try_recv().expect("expected reply on client");
    let value: Value = serde_json::from_slice(&frame.payload).unwrap();
    assert_eq!(value["id"], 10);
    assert_eq!(value["result"]["sessionId"], session_id);

    // Should NOT have forwarded to CEF.
    assert!(cef_rx.try_recv().is_err());
  }

  #[test]
  fn route_client_text_lazily_announces_deno() {
    let (client_tx, mut client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, _cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, _deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(false));

    let msg = json!({
      "id": 1,
      "method": "Target.setAutoAttach",
      "params": { "autoAttach": true, "waitForDebuggerOnStart": false },
    });
    let payload = serde_json::to_vec(&msg).unwrap();

    route_client_text(
      &payload, "sess", &client_tx, &cef_tx, &deno_tx, &announced,
    );

    // Should have emitted Target.attachedToTarget event.
    let frame = client_rx.try_recv().expect("expected announce event");
    let value: Value = serde_json::from_slice(&frame.payload).unwrap();
    assert_eq!(value["method"], "Target.attachedToTarget");
    assert_eq!(value["params"]["targetInfo"]["type"], "worker");
    assert!(announced.load(std::sync::atomic::Ordering::SeqCst));

    // Calling again should NOT emit a second event.
    route_client_text(
      &payload, "sess", &client_tx, &cef_tx, &deno_tx, &announced,
    );
    // Only the forwarded-to-cef frame, no second announce.
    assert!(client_rx.try_recv().is_err());
  }

  #[test]
  fn route_client_text_set_discover_targets_also_triggers_announce() {
    // The lazy-announce trigger is either setAutoAttach OR
    // setDiscoverTargets — DevTools sometimes uses one, sometimes the
    // other, depending on which panel initialised first.
    let (client_tx, mut client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, _cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, _deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(false));

    let msg = json!({
      "id": 7,
      "method": "Target.setDiscoverTargets",
      "params": { "discover": true },
    });
    let payload = serde_json::to_vec(&msg).unwrap();

    route_client_text(
      &payload, "sess", &client_tx, &cef_tx, &deno_tx, &announced,
    );

    let frame = client_rx
      .try_recv()
      .expect("setDiscoverTargets should also trigger announce");
    let value: Value = serde_json::from_slice(&frame.payload).unwrap();
    assert_eq!(value["method"], "Target.attachedToTarget");
    assert!(announced.load(std::sync::atomic::Ordering::SeqCst));
  }

  #[test]
  fn route_client_text_attach_to_cef_target_forwards_to_cef() {
    // `Target.attachToTarget` for any target ID that isn't ours (e.g.
    // a real CEF subframe or worker) must pass through — only the
    // synthetic Deno target is answered locally.
    let (client_tx, mut client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, mut cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, _deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(true));

    let msg = json!({
      "id": 11,
      "method": "Target.attachToTarget",
      "params": { "targetId": "some-cef-subframe-target" },
    });
    let payload = serde_json::to_vec(&msg).unwrap();

    route_client_text(
      &payload,
      "deno-sess",
      &client_tx,
      &cef_tx,
      &deno_tx,
      &announced,
    );

    let forwarded = cef_rx.try_recv().expect("expected frame on cef");
    let value: Value = serde_json::from_slice(&forwarded.payload).unwrap();
    assert_eq!(value["method"], "Target.attachToTarget");
    assert_eq!(value["params"]["targetId"], "some-cef-subframe-target");
    assert!(client_rx.try_recv().is_err());
  }

  // ── context name rewriting ────────────────────────────────────────

  #[test]
  fn rewrite_injects_session_id() {
    let input = json!({"id": 1, "result": {}});
    let payload = serde_json::to_vec(&input).unwrap();
    let out = rewrite_text_from_upstream(&payload, Some("my-sess"), "Deno");
    let value: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(value["sessionId"], "my-sess");
  }

  #[test]
  fn rewrite_renames_execution_context() {
    let input = json!({
      "method": "Runtime.executionContextCreated",
      "params": {
        "context": {
          "id": 1,
          "origin": "",
          "name": "top",
        },
      },
    });
    let payload = serde_json::to_vec(&input).unwrap();
    let out = rewrite_text_from_upstream(&payload, None, "Renderer");
    let value: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(value["params"]["context"]["name"], "Renderer");
  }

  #[test]
  fn rewrite_no_session_leaves_field_absent() {
    let input = json!({"method": "Console.messageAdded"});
    let payload = serde_json::to_vec(&input).unwrap();
    let out = rewrite_text_from_upstream(&payload, None, "Renderer");
    let value: Value = serde_json::from_slice(&out).unwrap();
    assert!(value.get("sessionId").is_none());
  }

  #[test]
  fn rewrite_leaves_non_execution_context_messages_unchanged() {
    // Any `name` field on other methods must not be touched — only
    // `Runtime.executionContextCreated.params.context.name` is rewritten.
    let input = json!({
      "method": "Target.targetInfoChanged",
      "params": { "targetInfo": { "name": "something" } },
    });
    let payload = serde_json::to_vec(&input).unwrap();
    let out = rewrite_text_from_upstream(&payload, None, "Renderer");
    let value: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(value["params"]["targetInfo"]["name"], "something");
  }

  #[test]
  fn rewrite_invalid_json_returned_verbatim() {
    let payload = b"totally not json".to_vec();
    let out = rewrite_text_from_upstream(&payload, Some("sid"), "Renderer");
    assert_eq!(out, payload);
  }

  #[test]
  fn rewrite_non_object_json_returned_verbatim() {
    // Arrays / scalars have no "sessionId" slot to inject into —
    // they must pass through untouched rather than being wrapped.
    let input = json!([1, 2, 3]);
    let payload = serde_json::to_vec(&input).unwrap();
    let out = rewrite_text_from_upstream(&payload, Some("sid"), "Renderer");
    assert_eq!(out, payload);
  }

  // ── /json/list shape ──────────────────────────────────────────────

  #[tokio::test]
  async fn json_list_returns_three_targets() {
    let state = MuxState::new(test_config(), "127.0.0.1:9229".parse().unwrap());
    let resp = json_list(&state);
    let body = resp.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let list: Vec<Value> = serde_json::from_slice(&bytes).unwrap();

    assert_eq!(list.len(), 3);

    // Unified target.
    assert_eq!(list[0]["type"], "page");
    assert_eq!(list[0]["title"], "Deno Desktop (unified)");
    assert!(
      list[0]["webSocketDebuggerUrl"]
        .as_str()
        .unwrap()
        .ends_with("/unified")
    );

    // Deno direct target.
    assert_eq!(list[1]["type"], "node");
    assert_eq!(list[1]["title"], "Deno Runtime");
    assert!(
      list[1]["webSocketDebuggerUrl"]
        .as_str()
        .unwrap()
        .ends_with("/deno")
    );

    // CEF direct target.
    assert_eq!(list[2]["type"], "page");
    assert_eq!(list[2]["title"], "CEF Renderer");
    assert!(
      list[2]["webSocketDebuggerUrl"]
        .as_str()
        .unwrap()
        .ends_with("/cef")
    );

    // Every entry must expose a devtoolsFrontendUrl that points at
    // its own ws:// endpoint — DevTools uses it to launch the right
    // frontend (inspector.html vs js_app.html) against the right mux
    // route. Every entry must also advertise a stable UUID id and
    // include description + faviconUrl, which DevTools renders in the
    // target picker.
    for entry in &list {
      let frontend = entry["devtoolsFrontendUrl"].as_str().unwrap();
      let ws = entry["webSocketDebuggerUrl"].as_str().unwrap();
      let ws_host_path = ws.strip_prefix("ws://").unwrap();
      assert!(
        frontend.contains(ws_host_path),
        "frontend {frontend} must embed ws host+path {ws_host_path}"
      );

      let id = entry["id"].as_str().unwrap();
      Uuid::parse_str(id).unwrap_or_else(|_| panic!("id {id} is not a UUID"));
      assert!(entry["description"].is_string());
      assert!(entry["faviconUrl"].is_string());
    }

    // Deno direct entry uses `js_app.html` (DevTools' node variant)
    // while CEF and unified use the full `inspector.html`.
    assert!(
      list[1]["devtoolsFrontendUrl"]
        .as_str()
        .unwrap()
        .contains("js_app.html"),
      "deno direct entry should launch js_app.html"
    );
    for page_entry in [&list[0], &list[2]] {
      assert!(
        page_entry["devtoolsFrontendUrl"]
          .as_str()
          .unwrap()
          .contains("inspector.html"),
      );
    }

    // IDs must be stable across calls — DevTools caches them.
    let resp2 = json_list(&state);
    let bytes2 = resp2.into_body().collect().await.unwrap().to_bytes();
    let list2: Vec<Value> = serde_json::from_slice(&bytes2).unwrap();
    for (a, b) in list.iter().zip(list2.iter()) {
      assert_eq!(
        a["id"], b["id"],
        "target id changed across /json/list calls"
      );
    }
  }

  #[tokio::test]
  async fn json_version_shape() {
    let state = MuxState::new(test_config(), "127.0.0.1:9229".parse().unwrap());
    let resp = json_version(&state);
    assert_eq!(resp.status(), http::StatusCode::OK);
    let ct = resp.headers().get(http::header::CONTENT_TYPE).unwrap();
    assert_eq!(ct, "application/json");

    let bytes = resp.into_body().collect().await.unwrap().to_bytes();
    let value: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(value["Protocol-Version"], "1.3");
    assert!(
      value["Browser"]
        .as_str()
        .unwrap()
        .starts_with("deno-desktop/")
    );
    assert!(value["V8-Version"].is_string());
    // The browser-level webSocketDebuggerUrl must point at the CEF
    // target — DevTools' chrome://inspect auto-attach needs the
    // richer Target.* domain that CEF implements.
    let ws = value["webSocketDebuggerUrl"].as_str().unwrap();
    assert!(ws.ends_with("/cef"), "got {ws}");
  }

  // ── Target.detachFromTarget dispatch ──────────────────────────────

  #[test]
  fn route_client_text_detach_from_deno_session_synthesizes_reply_and_event() {
    let (client_tx, mut client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, mut cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, _deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(true));

    let session_id = "deno-sess-xyz";
    let msg = json!({
      "id": 42,
      "method": "Target.detachFromTarget",
      "params": { "sessionId": session_id },
    });
    let payload = serde_json::to_vec(&msg).unwrap();

    route_client_text(
      &payload, session_id, &client_tx, &cef_tx, &deno_tx, &announced,
    );

    // First frame: the id=42 reply.
    let reply = client_rx.try_recv().expect("expected detach reply");
    let reply_val: Value = serde_json::from_slice(&reply.payload).unwrap();
    assert_eq!(reply_val["id"], 42);
    assert!(reply_val["result"].is_object());

    // Second frame: the synthesized Target.detachedFromTarget event.
    let event = client_rx.try_recv().expect("expected detached event");
    let event_val: Value = serde_json::from_slice(&event.payload).unwrap();
    assert_eq!(event_val["method"], "Target.detachedFromTarget");
    assert_eq!(event_val["params"]["sessionId"], session_id);
    assert_eq!(event_val["params"]["targetId"], DENO_CHILD_TARGET_ID);

    // Must NOT be forwarded to CEF — CEF has no knowledge of our
    // synthetic Deno session.
    assert!(cef_rx.try_recv().is_err());
  }

  #[test]
  fn route_client_text_detach_from_unknown_session_forwards_to_cef() {
    // A detach for a session CEF owns (not our synthetic Deno one)
    // must flow through to CEF unchanged.
    let (client_tx, mut client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, mut cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, _deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(true));

    let msg = json!({
      "id": 99,
      "method": "Target.detachFromTarget",
      "params": { "sessionId": "some-cef-session" },
    });
    let payload = serde_json::to_vec(&msg).unwrap();

    route_client_text(
      &payload,
      "deno-sess",
      &client_tx,
      &cef_tx,
      &deno_tx,
      &announced,
    );

    let forwarded = cef_rx.try_recv().expect("expected frame forwarded");
    let value: Value = serde_json::from_slice(&forwarded.payload).unwrap();
    assert_eq!(value["id"], 99);
    assert!(client_rx.try_recv().is_err());
  }

  // ── Malformed / edge-case dispatch ────────────────────────────────

  #[test]
  fn route_client_text_invalid_json_forwards_to_cef() {
    let (client_tx, mut client_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (cef_tx, mut cef_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (deno_tx, _deno_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let announced = Arc::new(std::sync::atomic::AtomicBool::new(true));

    let payload = b"not-json".to_vec();
    route_client_text(
      &payload, "sess", &client_tx, &cef_tx, &deno_tx, &announced,
    );

    let frame = cef_rx.try_recv().expect("expected frame on cef");
    assert_eq!(frame.payload, b"not-json");
    assert!(client_rx.try_recv().is_err());
  }

  // ── End-to-end integration ────────────────────────────────────────
  //
  // Spin up mock upstream HTTP+WS servers for CEF and Deno, start the
  // mux in front of them, then drive a real WebSocket client through
  // the `/unified` endpoint to exercise routing, context rewriting,
  // and the `--inspect-brk` pause injection.

  /// Simple mock upstream: serves `/json/list` pointing at its own
  /// `/ws` path, accepts a WebSocket upgrade there, and exposes
  /// unbounded channels so tests can pump frames in/out.
  struct MockUpstream {
    listen: SocketAddr,
    /// Frames received from the mux.
    from_mux: tokio::sync::Mutex<mpsc::UnboundedReceiver<OwnedFrame>>,
    /// Frames to send to the mux.
    to_mux: mpsc::UnboundedSender<OwnedFrame>,
  }

  async fn spawn_mock_upstream() -> Arc<MockUpstream> {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let listen = listener.local_addr().unwrap();
    let (in_tx, in_rx) = mpsc::unbounded_channel::<OwnedFrame>();
    let (out_tx, out_rx) = mpsc::unbounded_channel::<OwnedFrame>();

    let upstream = Arc::new(MockUpstream {
      listen,
      from_mux: tokio::sync::Mutex::new(in_rx),
      to_mux: out_tx,
    });

    // Shared across every connection the mux makes to this upstream —
    // the mux opens one TCP connection for `/json/list` and a separate
    // one for the WS upgrade, so the out_rx must only be consumed when
    // the upgrade actually happens.
    let shared_out_rx = Arc::new(std::sync::Mutex::new(Some(out_rx)));

    tokio::spawn(async move {
      loop {
        let (stream, _) = match listener.accept().await {
          Ok(v) => v,
          Err(_) => return,
        };
        let in_tx = in_tx.clone();
        let shared_out_rx = shared_out_rx.clone();
        let listen_str = listen.to_string();
        tokio::spawn(async move {
          let io = TokioIo::new(stream);
          let service = hyper::service::service_fn(move |mut req| {
            let in_tx = in_tx.clone();
            let shared_out_rx = shared_out_rx.clone();
            let listen_str = listen_str.clone();
            async move {
              let path = req.uri().path().to_string();
              if path == "/json/list" {
                let body = serde_json::to_vec(&json!([{
                  "id": "mock-target",
                  "type": "page",
                  "webSocketDebuggerUrl": format!("ws://{listen_str}/ws"),
                }]))
                .unwrap();
                return Ok::<_, Infallible>(
                  hyper::Response::builder()
                    .status(http::StatusCode::OK)
                    .header(http::header::CONTENT_TYPE, "application/json")
                    .body(Full::new(Bytes::from(body)))
                    .unwrap(),
                );
              }
              if path == "/ws" {
                let Ok((resp, upgrade_fut)) =
                  fastwebsockets::upgrade::upgrade(&mut req)
                else {
                  return Ok(simple_response(
                    http::StatusCode::BAD_REQUEST,
                    "bad upgrade",
                  ));
                };
                let in_tx = in_tx.clone();
                let out_rx = shared_out_rx.lock().unwrap().take();
                tokio::spawn(async move {
                  let mut ws = match upgrade_fut.await {
                    Ok(w) => w,
                    Err(_) => return,
                  };
                  ws.set_auto_close(false);
                  ws.set_auto_pong(false);
                  let (mut rx, mut tx) = ws.split(tokio::io::split);
                  let reader = async move {
                    let mut noop =
                      |_: Frame<'_>| async { Ok::<(), WebSocketError>(()) };
                    loop {
                      let frame = match rx.read_frame(&mut noop).await {
                        Ok(f) => f,
                        Err(_) => return,
                      };
                      let owned = OwnedFrame {
                        opcode: frame.opcode,
                        payload: frame.payload.to_vec(),
                      };
                      let is_close = owned.opcode == OpCode::Close;
                      if in_tx.send(owned).is_err() || is_close {
                        return;
                      }
                    }
                  };
                  let writer = async move {
                    let Some(mut out_rx) = out_rx else { return };
                    while let Some(owned) = out_rx.recv().await {
                      let close = owned.opcode == OpCode::Close;
                      if tx.write_frame(owned.into_frame()).await.is_err() {
                        return;
                      }
                      if close {
                        return;
                      }
                    }
                  };
                  tokio::join!(reader, writer);
                });
                let (parts, _) = resp.into_parts();
                return Ok(hyper::Response::from_parts(
                  parts,
                  Full::new(Bytes::new()),
                ));
              }
              Ok(simple_response(http::StatusCode::NOT_FOUND, "Not Found"))
            }
          });
          let _ = hyper::server::conn::http1::Builder::new()
            .serve_connection(io, service)
            .with_upgrades()
            .await;
        });
      }
    });

    upstream
  }

  /// Open a WebSocket from the test to `ws://<addr><path>`.
  async fn test_connect_ws(
    ws_url: &str,
  ) -> WebSocket<TokioIo<hyper::upgrade::Upgraded>> {
    connect_ws(ws_url).await.unwrap()
  }

  async fn read_text_value<S>(ws: &mut WebSocket<S>) -> Value
  where
    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
  {
    loop {
      let frame = ws.read_frame().await.unwrap();
      if frame.opcode != OpCode::Text {
        continue;
      }
      return serde_json::from_slice(&frame.payload).unwrap();
    }
  }

  async fn write_json<S>(ws: &mut WebSocket<S>, v: &Value)
  where
    S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
  {
    let payload = serde_json::to_vec(v).unwrap();
    ws.write_frame(Frame::new(
      true,
      OpCode::Text,
      None,
      fastwebsockets::Payload::Owned(payload),
    ))
    .await
    .unwrap();
  }

  async fn spawn_test_mux(
    cef: &MockUpstream,
    deno: &MockUpstream,
    inspect_brk: bool,
  ) -> MuxHandle {
    let listen_port = allocate_random_port().unwrap();
    spawn_mux(MuxConfig {
      listen: format!("127.0.0.1:{listen_port}").parse().unwrap(),
      deno_internal: deno.listen,
      cef_internal: cef.listen,
      inspect_brk,
      wait_for_debugger: inspect_brk,
    })
    .await
    .unwrap()
  }

  /// GET a path from the mux over raw HTTP and return the body bytes.
  async fn http_get(addr: SocketAddr, path: &str) -> (http::StatusCode, Bytes) {
    let stream = TcpStream::connect(addr).await.unwrap();
    let io = TokioIo::new(stream);
    let (mut sender, conn) =
      hyper::client::conn::http1::handshake(io).await.unwrap();
    tokio::spawn(async move {
      let _ = conn.await;
    });
    let req = hyper::Request::builder()
      .method(http::Method::GET)
      .uri(path)
      .header(http::header::HOST, addr.to_string())
      .body(Empty::<Bytes>::new())
      .unwrap();
    let resp = sender.send_request(req).await.unwrap();
    let status = resp.status();
    let bytes = resp.collect().await.unwrap().to_bytes();
    (status, bytes)
  }

  #[tokio::test]
  async fn integration_http_endpoints() {
    let cef = spawn_mock_upstream().await;
    let deno = spawn_mock_upstream().await;
    let mux = spawn_test_mux(&cef, &deno, false).await;

    // /json/list — the mux advertises three targets; the HTTP path
    // does not need upstream WS to be live.
    let (status, body) = http_get(mux.listen, "/json/list").await;
    assert_eq!(status, http::StatusCode::OK);
    let list: Vec<Value> = serde_json::from_slice(&body).unwrap();
    assert_eq!(list.len(), 3);

    // /json/version.
    let (status, body) = http_get(mux.listen, "/json/version").await;
    assert_eq!(status, http::StatusCode::OK);
    let v: Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(v["Protocol-Version"], "1.3");

    // /debugger-attached returns 503 before any client connects.
    let (status, _) = http_get(mux.listen, "/debugger-attached").await;
    assert_eq!(status, http::StatusCode::SERVICE_UNAVAILABLE);

    // Unknown path → 404.
    let (status, _) = http_get(mux.listen, "/nope").await;
    assert_eq!(status, http::StatusCode::NOT_FOUND);
  }

  #[tokio::test]
  async fn integration_unified_session_routes_and_rewrites() {
    let cef = spawn_mock_upstream().await;
    let deno = spawn_mock_upstream().await;
    let mux = spawn_test_mux(&cef, &deno, false).await;

    let ws_url = format!("ws://{}/unified", mux.listen);
    let mut client = test_connect_ws(&ws_url).await;
    client.set_auto_close(false);
    client.set_auto_pong(false);

    // Before any client activity, /debugger-attached should flip to 200.
    // Give the spawned upgrade task a moment to run.
    for _ in 0..50 {
      let (status, _) = http_get(mux.listen, "/debugger-attached").await;
      if status == http::StatusCode::OK {
        break;
      }
      tokio::time::sleep(Duration::from_millis(20)).await;
    }

    // 1) Client sends Target.setAutoAttach. Mux should forward it to
    //    CEF *and* synthesize Target.attachedToTarget to the client.
    write_json(
      &mut client,
      &json!({
        "id": 1,
        "method": "Target.setAutoAttach",
        "params": { "autoAttach": true, "waitForDebuggerOnStart": false },
      }),
    )
    .await;

    let attached = read_text_value(&mut client).await;
    assert_eq!(attached["method"], "Target.attachedToTarget");
    let session_id = attached["params"]["sessionId"]
      .as_str()
      .unwrap()
      .to_string();
    assert_eq!(attached["params"]["targetInfo"]["type"], "worker");

    // CEF upstream should have received the setAutoAttach verbatim.
    let received = {
      let mut rx = cef.from_mux.lock().await;
      tokio::time::timeout(Duration::from_secs(2), rx.recv())
        .await
        .unwrap()
        .unwrap()
    };
    let received_val: Value =
      serde_json::from_slice(&received.payload).unwrap();
    assert_eq!(received_val["method"], "Target.setAutoAttach");

    // 2) Client sends a frame with sessionId=deno. Mux strips it and
    //    forwards to Deno upstream.
    write_json(
      &mut client,
      &json!({
        "id": 2,
        "method": "Debugger.enable",
        "sessionId": session_id,
      }),
    )
    .await;
    let deno_received = {
      let mut rx = deno.from_mux.lock().await;
      tokio::time::timeout(Duration::from_secs(2), rx.recv())
        .await
        .unwrap()
        .unwrap()
    };
    let deno_val: Value =
      serde_json::from_slice(&deno_received.payload).unwrap();
    assert_eq!(deno_val["id"], 2);
    assert_eq!(deno_val["method"], "Debugger.enable");
    assert!(deno_val["sessionId"].is_null());

    // 3) Upstream CEF emits Runtime.executionContextCreated. The mux
    //    rewrites context.name to "Renderer" and forwards to client
    //    WITHOUT a sessionId.
    cef
      .to_mux
      .send(OwnedFrame::text(
        serde_json::to_vec(&json!({
          "method": "Runtime.executionContextCreated",
          "params": { "context": { "id": 1, "origin": "", "name": "top" } },
        }))
        .unwrap(),
      ))
      .unwrap();
    let from_cef = read_text_value(&mut client).await;
    assert_eq!(from_cef["method"], "Runtime.executionContextCreated");
    assert_eq!(from_cef["params"]["context"]["name"], "Renderer");
    assert!(from_cef["sessionId"].is_null());

    // 4) Upstream Deno emits the same. Mux rewrites to "Deno" AND
    //    injects the synthetic sessionId.
    deno
      .to_mux
      .send(OwnedFrame::text(
        serde_json::to_vec(&json!({
          "method": "Runtime.executionContextCreated",
          "params": { "context": { "id": 1, "origin": "", "name": "main realm" } },
        }))
        .unwrap(),
      ))
      .unwrap();
    let from_deno = read_text_value(&mut client).await;
    assert_eq!(from_deno["method"], "Runtime.executionContextCreated");
    assert_eq!(from_deno["params"]["context"]["name"], "Deno");
    assert_eq!(from_deno["sessionId"], session_id);

    drop(client);
    drop(mux);
  }

  #[tokio::test]
  async fn integration_inspect_brk_injects_before_marking_attached() {
    // The core contract: under --inspect-brk the mux must send
    // Debugger.enable + Debugger.pause to the CEF upstream BEFORE
    // /debugger-attached flips to 200. If that order is reversed the
    // child process navigates CEF before the pause is in flight and
    // the renderer races past the first JS statement.
    let cef = spawn_mock_upstream().await;
    let deno = spawn_mock_upstream().await;
    let mux = spawn_test_mux(&cef, &deno, true).await;

    let ws_url = format!("ws://{}/unified", mux.listen);
    let client_connect =
      tokio::spawn(async move { test_connect_ws(&ws_url).await });

    // Observe the first two frames CEF receives. With inspect_brk=true
    // they must be Debugger.enable then Debugger.pause.
    let enable_frame = {
      let mut rx = cef.from_mux.lock().await;
      tokio::time::timeout(Duration::from_secs(5), rx.recv())
        .await
        .expect("no frame received on CEF upstream")
        .unwrap()
    };
    let enable_val: Value =
      serde_json::from_slice(&enable_frame.payload).unwrap();
    assert_eq!(enable_val["method"], "Debugger.enable");

    // /debugger-attached MUST still be 503 until we ack enable+pause.
    // We haven't replied yet, so the mux is still blocked waiting.
    let (status, _) = http_get(mux.listen, "/debugger-attached").await;
    assert_eq!(
      status,
      http::StatusCode::SERVICE_UNAVAILABLE,
      "debugger_attached must not be signalled until pause injection completes"
    );

    let pause_frame = {
      let mut rx = cef.from_mux.lock().await;
      tokio::time::timeout(Duration::from_secs(5), rx.recv())
        .await
        .expect("no pause frame received")
        .unwrap()
    };
    let pause_val: Value =
      serde_json::from_slice(&pause_frame.payload).unwrap();
    assert_eq!(pause_val["method"], "Debugger.pause");

    // Now ack both from the upstream side, simulating CEF's responses.
    cef
      .to_mux
      .send(OwnedFrame::text(
        serde_json::to_vec(&json!({"id": -1, "result": {}})).unwrap(),
      ))
      .unwrap();
    cef
      .to_mux
      .send(OwnedFrame::text(
        serde_json::to_vec(&json!({"id": -2, "result": {}})).unwrap(),
      ))
      .unwrap();

    // With both injection acks in flight, the mux should mark
    // attached. Give it a moment to run.
    let mut saw_attached = false;
    for _ in 0..100 {
      let (status, _) = http_get(mux.listen, "/debugger-attached").await;
      if status == http::StatusCode::OK {
        saw_attached = true;
        break;
      }
      tokio::time::sleep(Duration::from_millis(20)).await;
    }
    assert!(
      saw_attached,
      "debugger_attached never flipped to 200 after injection completed"
    );

    let _client = client_connect.await.unwrap();
    drop(mux);
  }
}