mnml-rs 0.2.13

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
//! Chrome DevTools Protocol (CDP) + browser pane methods on `App`.
//!
//! Extracted from `app/mod.rs` in the file-split refactor.
//! Pure non-destructive move: no API
//! change. Owns the `browser.*` palette commands, the CDP event drain,
//! all browser sub-panel pickers (DOM / cookies / storage / perf /
//! targets / devices / URL history), the Chrome profile-dir resolver,
//! and the small free-fn parsers (`bbox_from_quad`, `cdp_short_url`,
//! etc.) the browser methods reach for.

use super::*;

/// qa-feature 2026-07-02 — cheap best-effort check for a launchable
/// Chrome/Chromium/CfT. Returns true if the puppeteer cache has an
/// install OR any of the well-known binaries is on PATH. Doesn't
/// launch Chrome; just checks paths/executable-in-PATH.
fn chrome_is_available() -> bool {
    if crate::cdp::find_chrome_for_testing_puppeteer_cache().is_some() {
        return true;
    }
    for name in [
        "google-chrome",
        "google-chrome-stable",
        "chromium",
        "chromium-browser",
        "chrome",
    ] {
        if crate::integration_detect::is_binary_installed(name) {
            return true;
        }
    }
    for path in [
        "/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
        "/Applications/Chromium.app/Contents/MacOS/Chromium",
        "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
    ] {
        if std::path::Path::new(path).exists() {
            return true;
        }
    }
    false
}

/// A short text rendering of a CDP `RemoteObject` (console args, eval results).
fn cdp_remote_object_str(o: &serde_json::Value) -> String {
    if let Some(v) = o.get("value") {
        return match v {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        };
    }
    if let Some(u) = o
        .get("unserializableValue")
        .and_then(serde_json::Value::as_str)
    {
        return u.to_string();
    }
    if let Some(d) = o.get("description").and_then(serde_json::Value::as_str) {
        return d.to_string();
    }
    o.get("type")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("?")
        .to_string()
}

/// True if a CDP `Network.*` event's resource `type` is worth showing in the
/// browser pane (the page + its data calls — not the asset firehose). `None`
/// (type absent) is treated as interesting (it's usually the main document).
fn cdp_resource_type_is_interesting(rtype: Option<&str>) -> bool {
    !matches!(
        rtype,
        Some(
            "Image"
                | "Media"
                | "Font"
                | "Stylesheet"
                | "Script"
                | "TextTrack"
                | "Manifest"
                | "Other"
                | "Prefetch"
                | "SignedExchange"
        )
    )
}

/// Shorten a URL for a log line: drop the scheme, keep `host/path` (no query),
/// truncate. (Cross-origin hosts are kept so it's clear; same-origin still shows
/// the host — fine for a one-line log.)
fn cdp_short_url(url: &str) -> String {
    let body = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))
        .unwrap_or(url);
    let body = body.split(['?', '#']).next().unwrap_or(body);
    if body.chars().count() <= 70 {
        body.to_string()
    } else {
        let keep: String = body.chars().take(69).collect();
        format!("{keep}")
    }
}

/// Extract just the host (no scheme, no port, no path) from a URL.
/// Returns empty when the URL has no recognizable host (e.g.
/// `about:blank`). Used by the cookie-add flow to scope a new cookie
/// to the active browser pane's origin.
pub(super) fn host_of_url(url: &str) -> String {
    let s = url
        .trim()
        .strip_prefix("https://")
        .or_else(|| url.trim().strip_prefix("http://"))
        .unwrap_or(url.trim());
    s.split(['/', '?', '#', ':'])
        .next()
        .unwrap_or("")
        .to_string()
}

/// `DOM.getBoxModel.content` is `[x1, y1, x2, y2, x3, y3, x4, y4]` — the
/// four corners of the node's content quad in viewport coords. Compute
/// the axis-aligned bounding box `(x, y, width, height)` we can hand
/// to `Page.captureScreenshot.clip`. Returns `None` when the array
/// isn't 8 numeric entries (off-screen / detached nodes can yield an
/// empty / shorter quad).
fn bbox_from_quad(q: &[serde_json::Value]) -> Option<(f64, f64, f64, f64)> {
    if q.len() != 8 {
        return None;
    }
    let mut nums = q.iter().map(|v| v.as_f64());
    let mut xs = [0.0_f64; 4];
    let mut ys = [0.0_f64; 4];
    for i in 0..4 {
        xs[i] = nums.next()??;
        ys[i] = nums.next()??;
    }
    let x_min = xs.iter().cloned().fold(f64::INFINITY, f64::min);
    let y_min = ys.iter().cloned().fold(f64::INFINITY, f64::min);
    let x_max = xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    let y_max = ys.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    if !x_min.is_finite() || !y_min.is_finite() || !x_max.is_finite() || !y_max.is_finite() {
        return None;
    }
    Some((x_min, y_min, x_max - x_min, y_max - y_min))
}

/// Render a `Runtime.evaluate` reply (`{result:{result:<RemoteObject>, exceptionDetails?}}`) to text.
fn cdp_eval_result_text(v: &serde_json::Value) -> String {
    let res = v.get("result");
    if let Some(ex) = res.and_then(|r| r.get("exceptionDetails")) {
        let msg = ex
            .get("exception")
            .and_then(|e| e.get("description"))
            .and_then(serde_json::Value::as_str)
            .or_else(|| ex.get("text").and_then(serde_json::Value::as_str))
            .unwrap_or("exception");
        return format!("{}", msg.lines().next().unwrap_or(msg));
    }
    res.and_then(|r| r.get("result"))
        .map(cdp_remote_object_str)
        .unwrap_or_else(|| "undefined".to_string())
}

impl App {
    /// `browser.open_url` — prompt for a URL, then launch Chrome on
    /// it. `browser.open` (rail chip default) skips the prompt and
    /// goes straight to `about:blank`. Multiple browser panes can
    /// coexist; each gets its own CDP worker + (in
    /// `workspace` / `shared` modes) a per-pane integration profile dir.
    pub fn open_browser_prompt(&mut self) {
        // Empty seed — the prompt UI paints a dimmed "https://example.com"
        // placeholder that clears on the first keystroke, mirroring
        // browser address bars (Chrome / Safari / Firefox all do this).
        // Was previously seeded with "https://" which read as a stuck
        // string the user had to backspace or ignore.
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::BrowserUrl,
            "Open URL in Chrome",
        ));
    }

    /// Resolve the `--user-data-dir` for Chrome based on the
    /// `[browser] profile_mode` config:
    /// * `"workspace"` (default) — `<workspace>/.mnml/chrome-profile/`.
    ///   Per-workspace, persists across mnml relaunches in the same
    ///   workspace.
    /// * `"shared"` — `$HOME/.mnml/chrome-profile/`. One profile across
    ///   every workspace; handy when you sign into the same services
    ///   from multiple repos.
    /// * `"ephemeral"` — a fresh `tempfile::tempdir()` per `open_browser`
    ///   call. Clean-slate for login testing; state vanishes when the
    ///   pane closes.
    fn chrome_profile_dir(&self) -> std::path::PathBuf {
        self.chrome_profile_dir_for_pane(0)
    }

    /// Same as [`Self::chrome_profile_dir`] but tagged with `pane_index`
    /// — when another browser pane is already running, the second + later
    /// opens land in an integration dir (`-1`, `-2`, …) so Chrome doesn't refuse
    /// to start against a `--user-data-dir` that already has a process
    /// holding the lock. `pane_index == 0` ⇒ no suffix (the first / only
    /// pane keeps the existing single-pane path).
    fn chrome_profile_dir_for_pane(&self, pane_index: usize) -> std::path::PathBuf {
        let suffix = if pane_index == 0 {
            String::new()
        } else {
            format!("-{pane_index}")
        };
        match self.config.browser.profile_mode.as_str() {
            "shared" => {
                // Portable mode: keep the profile under mnml-data
                // so a portable install stays fully self-contained.
                // HOME mode: `~/.mnml/chrome-profile*` (legacy
                // scheme, predates data_root — kept for backwards
                // compat with existing installs).
                if crate::data_root::data_root_kind() == crate::data_root::DataRootKind::Portable {
                    crate::data_root::data_root().join(format!("chrome-profile{suffix}"))
                } else {
                    match std::env::var_os("HOME").map(PathBuf::from) {
                        Some(h) => h.join(".mnml").join(format!("chrome-profile{suffix}")),
                        None => self
                            .workspace
                            .join(".mnml")
                            .join(format!("chrome-profile{suffix}")),
                    }
                }
            }
            "ephemeral" => match tempfile::tempdir() {
                Ok(td) => {
                    // The TempDir RAII guard would delete the dir as
                    // soon as it dropped, but we need Chrome to outlive
                    // this fn. `into_path` keeps it on disk; the OS
                    // will clean it up next reboot, or the user can
                    // `:browser.wipe_profile` to drop it sooner.
                    td.keep()
                }
                Err(_) => self
                    .workspace
                    .join(".mnml")
                    .join("chrome-profile-ephemeral"),
            },
            _ => self
                .workspace
                .join(".mnml")
                .join(format!("chrome-profile{suffix}")),
        }
    }

    /// `browser.wipe_profile` — remove the workspace-scoped (or shared)
    /// Chrome profile dir so the next `browser.open` starts fresh.
    /// No-op in `ephemeral` mode (every open already starts fresh).
    /// Refuses to run while a browser pane is open (Chrome would have
    /// the files locked).
    pub fn wipe_browser_profile(&mut self) {
        if self.panes.iter().any(|p| matches!(p, Pane::Browser(_))) {
            self.toast("close the browser pane first — Chrome has the profile locked");
            return;
        }
        if self.config.browser.profile_mode == "ephemeral" {
            self.toast("profile_mode = ephemeral — every open already starts fresh");
            return;
        }
        let dir = self.chrome_profile_dir();
        if !dir.exists() {
            self.toast("no profile to wipe");
            return;
        }
        match std::fs::remove_dir_all(&dir) {
            Ok(_) => self.toast(format!("wiped {}", dir.display())),
            Err(e) => self.toast(format!("wipe failed: {e}")),
        }
    }

    /// Helper — returns the active pane as `Pane::Browser` if it is one.
    /// With multi-pane browsers, callers that used to do
    /// `panes.iter().find(|p| matches!(p, Pane::Browser(_)))` need to
    /// scope to the *focused* pane instead, or the wrong browser pane
    /// receives the operation.
    pub fn active_browser_mut(&mut self) -> Option<&mut crate::browser_pane::BrowserPane> {
        let idx = self.active?;
        match self.panes.get_mut(idx)? {
            Pane::Browser(b) => Some(b),
            _ => None,
        }
    }

    /// Immutable counterpart of [`Self::active_browser_mut`].
    pub fn active_browser(&self) -> Option<&crate::browser_pane::BrowserPane> {
        let idx = self.active?;
        match self.panes.get(idx)? {
            Pane::Browser(b) => Some(b),
            _ => None,
        }
    }

    /// Launch Chrome on `url` over CDP and open a `Pane::Browser` (split below).
    /// Multiple browser panes can coexist — each gets its own CDP worker +
    /// per-pane channels. The second + later panes (in `workspace` /
    /// `shared` profile modes) land in an integration `chrome-profile-N` dir so
    /// Chrome doesn't refuse to start against an already-locked user-data-dir.
    pub fn open_browser(&mut self, url: &str) {
        // qa-feature 2026-07-02 — upfront Chrome availability check.
        // Was: opened a browser pane, then failed silently when the
        // worker couldn't find any Chrome. Now toast a helpful hint
        // that points at `:browser.install_cft`.
        if !chrome_is_available() {
            self.toast(
                "no Chrome found — run `:browser.install_cft` to install Chrome for Testing",
            );
            return;
        }
        let existing_browsers = self
            .panes
            .iter()
            .filter(|p| matches!(p, Pane::Browser(_)))
            .count();
        let url = url.trim().to_string();
        let (ev_tx, ev_rx) = std::sync::mpsc::channel::<crate::cdp::CdpEvent>();
        let (cmd_tx, cmd_rx) = std::sync::mpsc::channel::<crate::cdp::CdpCommand>();
        let profile_dir = self.chrome_profile_dir_for_pane(existing_browsers);
        let _ = std::fs::create_dir_all(&profile_dir);
        let headless = self.config.browser.headless;
        let (worker_url, worker_dir) = (url.clone(), profile_dir);
        std::thread::spawn(move || {
            crate::cdp::run_session(&worker_url, &worker_dir, headless, &ev_tx, &cmd_rx);
        });
        let mut browser_pane = crate::browser_pane::BrowserPane::with_channel(url, cmd_tx, ev_rx);
        // Re-apply the user's most-recent device-emulation preset so the
        // choice survives across `browser.open` calls (and mnml relaunches
        // via session.json). The commands queue on cmd_tx and the worker
        // dispatches them as soon as the CDP WS is up.
        if let Some(idx) = self.last_browser_device
            && idx < crate::browser_pane::DEVICE_PRESETS.len()
        {
            browser_pane.set_device(idx);
        }
        let pane = Pane::Browser(browser_pane);
        match self.active {
            Some(cur) => {
                // #polish 2026-07-07 — was Vertical (stacked below the
                // active pane), which felt cramped when the browser
                // opens next to a Request pane. Horizontal (side-by-
                // side) matches the "look at the request while
                // watching the network log" workflow that the CAPTURED
                // chip drives.
                let new_id = self.split_leaf_with(cur, crate::layout::SplitDir::Horizontal, pane);
                self.active = Some(new_id);
            }
            None => {
                self.panes.push(pane);
                let id = self.panes.len() - 1;
                *self.layout_mut() = Layout::leaf(id);
                self.active = Some(id);
            }
        }
        self.focus = Focus::Pane;
        // NOTE: previously auto-switched to the HTTP activity section
        // here to surface network-debug files. Removed 2026-08-05
        // (api-workflow SEV-1): `set_activity_section(Http)` has a
        // side effect that unconditionally spawns a blank scratch
        // Request pane, which then covers the browser we just opened.
        // The guard meant to prevent this reads `self.active` after
        // it's already been pointed at the Browser pane, so it never
        // fires. If we want to nudge the user toward HTTP later,
        // reach it a different way (e.g. a toast with a click-to-
        // open, or a purely visual section change with no pane spawn).
    }

    /// `g` in a browser pane — prompt for a URL to navigate to (seeded with the
    /// current URL).
    pub fn browser_navigate_prompt(&mut self) {
        let url = match self.active.and_then(|i| self.panes.get(i)) {
            Some(Pane::Browser(b)) => b.url.clone(),
            _ => return,
        };
        // R7 vscode-mouse F5 2026-08-09: when the URL is non-empty
        // (the common case — you're already on a page and hit `g`),
        // use `seeded_select_all` so the first typed char replaces
        // the seed. Chrome's URL-bar behavior. When empty, seed
        // `https://` as usual — no "select" needed, the user is
        // just going to append.
        self.prompt = Some(if url.trim().is_empty() {
            crate::prompt::Prompt::seeded(
                crate::prompt::PromptKind::BrowserNavigate,
                "Navigate to",
                "https://",
            )
        } else {
            crate::prompt::Prompt::seeded_select_all(
                crate::prompt::PromptKind::BrowserNavigate,
                "Navigate to",
                url,
            )
        });
    }

    /// `e` in a browser pane — prompt for JS to evaluate in the page.
    pub fn browser_eval_prompt(&mut self) {
        if !matches!(
            self.active.and_then(|i| self.panes.get(i)),
            Some(Pane::Browser(_))
        ) {
            return;
        }
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::BrowserEval,
            "Eval JS in the page",
        ));
    }

    /// qa-feature 2026-07-02 — Dock Ghostty (~55% left) alongside
    /// Chrome (~45% right) on the current display via AppleScript.
    /// Toggles: first call moves + snapshots prior bounds; second
    /// call restores. macOS-only; no-op with a toast elsewhere.
    /// Requires Accessibility permission on first run.
    pub fn browser_dock_toggle(&mut self) {
        // CI on ubuntu fails on `clippy::needless_return` in this
        // branch — on macOS `#[cfg(target_os = "macos")]` matches
        // (below) so the return here is actually needed, but on
        // ubuntu the non-macOS branch IS the whole function body
        // and the `return` is redundant. Restructure so both
        // targets see clean code — the non-macOS branch just
        // toasts and falls through; the macOS branch is gated so
        // its body only compiles when applicable.
        #[cfg(not(target_os = "macos"))]
        {
            self.toast("browser.dock: macOS only");
        }
        #[cfg(target_os = "macos")]
        {
            if let Some((ghostty_prev, chrome_prev)) = self.browser_dock_saved.take() {
                // Restore.
                let script = format!(
                    r#"tell application "System Events"
    try
        set position of window 1 of application process "ghostty" to {{{gx}, {gy}}}
        set size of window 1 of application process "ghostty" to {{{gw}, {gh}}}
    end try
    try
        set position of window 1 of application process "Google Chrome for Testing" to {{{cx}, {cy}}}
        set size of window 1 of application process "Google Chrome for Testing" to {{{cw}, {ch}}}
    end try
end tell"#,
                    gx = ghostty_prev.0,
                    gy = ghostty_prev.1,
                    gw = ghostty_prev.2,
                    gh = ghostty_prev.3,
                    cx = chrome_prev.0,
                    cy = chrome_prev.1,
                    cw = chrome_prev.2,
                    ch = chrome_prev.3,
                );
                let _ = std::process::Command::new("osascript")
                    .args(["-e", &script])
                    .status();
                self.toast("browser.dock: restored");
                return;
            }
            // Dock: snapshot current bounds, then move.
            //
            // The bounds query runs in a separate osascript so we can parse
            // its stdout easily. Position + size are returned newline-
            // separated: "x,y" then "w,h".
            let read_bounds = |proc: &str| -> Option<(i32, i32, i32, i32)> {
                let script = format!(
                    r#"tell application "System Events"
    try
        set p to position of window 1 of application process "{proc}"
        set s to size of window 1 of application process "{proc}"
        return (item 1 of p as text) & "," & (item 2 of p as text) & "|" & (item 1 of s as text) & "," & (item 2 of s as text)
    on error
        return "err"
    end try
end tell"#
                );
                let out = std::process::Command::new("osascript")
                    .args(["-e", &script])
                    .output()
                    .ok()?;
                let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
                if s == "err" || s.is_empty() {
                    return None;
                }
                let (pos, size) = s.split_once('|')?;
                let (px, py) = pos.split_once(',')?;
                let (sw, sh) = size.split_once(',')?;
                Some((
                    px.trim().parse().ok()?,
                    py.trim().parse().ok()?,
                    sw.trim().parse().ok()?,
                    sh.trim().parse().ok()?,
                ))
            };
            let ghostty = match read_bounds("ghostty") {
                Some(b) => b,
                None => {
                    self.toast("browser.dock: can't read ghostty bounds (Accessibility?)");
                    return;
                }
            };
            let chrome = match read_bounds("Google Chrome for Testing")
                .or_else(|| read_bounds("Google Chrome"))
            {
                Some(b) => b,
                None => {
                    self.toast("browser.dock: no Chrome window found — open the browser first");
                    return;
                }
            };
            // Screen bounds from Ghostty's current display via
            // `bounds of window 1 of desktop 1` — good enough for a
            // single-display setup; multi-display would need a real
            // desktop query per screen.
            let screen_script = r#"tell application "Finder"
    set b to bounds of window of desktop
    return (item 1 of b as text) & "," & (item 2 of b as text) & "," & (item 3 of b as text) & "," & (item 4 of b as text)
end tell"#;
            let screen = std::process::Command::new("osascript")
                .args(["-e", screen_script])
                .output()
                .ok()
                .and_then(|o| String::from_utf8(o.stdout).ok())
                .and_then(|s| {
                    let parts: Vec<&str> = s.trim().split(',').collect();
                    if parts.len() != 4 {
                        return None;
                    }
                    let x = parts[0].trim().parse::<i32>().ok()?;
                    let y = parts[1].trim().parse::<i32>().ok()?;
                    let r = parts[2].trim().parse::<i32>().ok()?;
                    let b = parts[3].trim().parse::<i32>().ok()?;
                    Some((x, y, r - x, b - y))
                })
                .unwrap_or((0, 0, 1920, 1080));
            let (sx, sy, sw, sh) = screen;
            // Ghostty left ~55%, Chrome right ~45%. Leave 24px top
            // for the macOS menu bar; the Finder desktop query
            // already excludes it on newer macOS but the padding
            // is harmless.
            let gw = (sw as f32 * 0.55) as i32;
            let cw = sw - gw;
            let target_ghostty = (sx, sy, gw, sh);
            let target_chrome = (sx + gw, sy, cw, sh);
            let script = format!(
                r#"tell application "System Events"
    try
        set position of window 1 of application process "ghostty" to {{{gx}, {gy}}}
        set size of window 1 of application process "ghostty" to {{{gw}, {gh}}}
    end try
    try
        set position of window 1 of application process "Google Chrome for Testing" to {{{cx}, {cy}}}
        set size of window 1 of application process "Google Chrome for Testing" to {{{cw}, {ch}}}
    on error
        try
            set position of window 1 of application process "Google Chrome" to {{{cx}, {cy}}}
            set size of window 1 of application process "Google Chrome" to {{{cw}, {ch}}}
        end try
    end try
end tell"#,
                gx = target_ghostty.0,
                gy = target_ghostty.1,
                gw = target_ghostty.2,
                gh = target_ghostty.3,
                cx = target_chrome.0,
                cy = target_chrome.1,
                cw = target_chrome.2,
                ch = target_chrome.3,
            );
            let _ = std::process::Command::new("osascript")
                .args(["-e", &script])
                .status();
            self.browser_dock_saved = Some((ghostty, chrome));
            self.toast("browser.dock: docked (run again to restore)");
        }
    }

    /// qa-feature 2026-07-02 — spawn a Pty pane that installs Chrome
    /// for Testing via `npx @puppeteer/browsers install chrome@stable`.
    /// Requires `npx` (Node) on PATH; toasts a hint otherwise. The
    /// install lands in `~/.cache/puppeteer/chrome/` where
    /// `spawn_chrome` will find it on the next `browser.open`.
    pub fn browser_install_cft(&mut self) {
        if !crate::integration_detect::is_binary_installed("npx") {
            self.toast(
                "npx not found — install Node.js first, then run `:browser.install_cft` again",
            );
            return;
        }
        let profile = crate::pty_pane::BinaryProfile {
            label: "install: chrome for testing".to_string(),
            exe: "npx".to_string(),
            args: vec![
                "@puppeteer/browsers".to_string(),
                "install".to_string(),
                "chrome@stable".to_string(),
            ],
            cwd: None,
            env: Vec::new(),
            session_id: None,
            integration_id: None,
        };
        self.open_pty(profile);
        self.toast("installing Chrome for Testing… try `:browser.open` when done");
    }

    /// `r` in a browser pane — reload the page.
    pub fn browser_reload(&mut self) {
        if let Some(Pane::Browser(b)) = self.active.and_then(|i| self.panes.get_mut(i)) {
            b.reload();
        }
    }

    /// `:browser.back` — `window.history.back()` via Runtime.evaluate.
    /// CDP doesn't expose Page.goBack directly; runtime eval is the
    /// portable path.
    pub fn browser_back(&mut self) {
        match self.active_browser_mut() {
            Some(b) => b.eval_silent("window.history.back()"),
            None => self.toast("browser.back: no browser pane focused"),
        }
    }

    /// `:browser.forward` — `window.history.forward()` via Runtime.evaluate.
    pub fn browser_forward(&mut self) {
        match self.active_browser_mut() {
            Some(b) => b.eval_silent("window.history.forward()"),
            None => self.toast("browser.forward: no browser pane focused"),
        }
    }

    /// `:browser.devtools` — open Chrome's DevTools UI for the
    /// currently-driven page. CDP doesn't expose "open DevTools UI"
    /// as a method (it's a Chrome UI concern, not a protocol one),
    /// so we resolve the target's WebSocket debugger URL via the
    /// HTTP introspection endpoint (`/json`) and shell-out `open`
    /// (macOS) / `xdg-open` (Linux) to launch DevTools in the
    /// user's existing Chrome window. Falls back to a toast hint
    /// when introspection fails (no debugger port, etc.).
    pub fn browser_open_devtools_hint(&mut self) {
        let port = match self.active_browser_mut() {
            Some(b) => b.debugger_port,
            None => {
                self.toast("browser.devtools: no browser pane focused");
                return;
            }
        };
        let Some(port) = port else {
            self.toast("browser.devtools: no debugger port — open via :browser.open");
            return;
        };
        let cur_url = match self.active_browser_mut() {
            Some(b) => b.url.clone(),
            None => String::new(),
        };
        // Walk /json/list for the target whose `url` matches ours,
        // grab its devtoolsFrontendUrl, hand it to `open` (macOS) /
        // `xdg-open` (linux) to launch DevTools in Chrome itself.
        std::thread::spawn(move || {
            let json_url = format!("http://localhost:{port}/json/list");
            let Ok(resp) = reqwest::blocking::get(json_url) else {
                return;
            };
            let Ok(body) = resp.text() else { return };
            let Ok(targets) = serde_json::from_str::<serde_json::Value>(&body) else {
                return;
            };
            let arr = match targets.as_array() {
                Some(a) => a,
                None => return,
            };
            let target = arr
                .iter()
                .find(|t| t.get("url").and_then(|u| u.as_str()) == Some(cur_url.as_str()))
                .or_else(|| arr.first());
            let Some(t) = target else { return };
            let Some(dt_url) = t.get("devtoolsFrontendUrl").and_then(|u| u.as_str()) else {
                return;
            };
            let full = if dt_url.starts_with("http") {
                dt_url.to_string()
            } else {
                format!("http://localhost:{port}{dt_url}")
            };
            #[cfg(target_os = "macos")]
            let opener = "open";
            #[cfg(target_os = "linux")]
            let opener = "xdg-open";
            #[cfg(not(any(target_os = "macos", target_os = "linux")))]
            let opener = "open";
            let _ = std::process::Command::new(opener).arg(&full).status();
        });
        self.toast("browser.devtools: launching…");
    }

    /// `:browser.copy_url` — copy the active browser pane's current
    /// URL to the system clipboard. Toasts when there's no browser
    /// pane focused.
    pub fn browser_copy_url(&mut self) {
        let url = match self.active.and_then(|i| self.panes.get(i)) {
            Some(Pane::Browser(b)) => b.url.clone(),
            _ => {
                self.toast("browser.copy_url: no browser pane focused");
                return;
            }
        };
        if url.trim().is_empty() {
            self.toast("browser.copy_url: pane has no URL yet");
            return;
        }
        self.clipboard.set(url.clone(), false);
        let short = url
            .strip_prefix("https://")
            .or_else(|| url.strip_prefix("http://"))
            .unwrap_or(&url);
        let short: String = short.chars().take(48).collect();
        self.toast(format!("browser: {short} → clipboard"));
    }

    /// `s` in a browser pane (or `browser.screenshot`) — capture the viewport;
    /// the PNG is written to `.mnml/screenshots/` when the reply arrives.
    pub fn browser_screenshot(&mut self) {
        match self.active_browser_mut() {
            Some(b) => b.screenshot(),
            None => self.toast("no browser pane open"),
        }
    }

    /// `p` in a browser pane (or `browser.print_pdf`) — render the current
    /// page as a PDF via `Page.printToPDF`; the file lands in
    /// `.mnml/screenshots/page-<ms>.pdf` when the reply arrives.
    pub fn browser_print_pdf(&mut self) {
        match self.active_browser_mut() {
            Some(b) => b.print_pdf(),
            None => self.toast("no browser pane open"),
        }
    }

    /// `browser.snapshot` — freeze the active browser pane's state
    /// (URL + network + cookies + storage) into [`BrowserPane::snapshots`].
    /// Always refreshes cookies + storage first so the snapshot
    /// captures the latest server state, not just what was cached the
    /// last time the panels were opened.
    pub fn browser_snapshot(&mut self) {
        let Some(b) = self.active_browser_mut() else {
            self.toast("no browser pane open");
            return;
        };
        // Trigger cookie + storage refresh — these are fire-and-forget
        // (their replies arrive async via the CDP channel). The
        // capture below uses whatever's already cached; the diff a
        // few seconds later will reflect any updates that landed.
        b.fetch_cookies();
        b.fetch_storage();
        let n = b.capture_snapshot();
        let label = b
            .snapshots
            .last()
            .map(|s| s.label.clone())
            .unwrap_or_default();
        self.toast(format!("snapshot #{n} captured at {label}"));
    }

    /// `browser.diff_snapshot` — open the diff panel comparing the
    /// most-recent snapshot against the current live state. Toggle
    /// off when already open. Toasts when there's no snapshot yet.
    pub fn browser_diff_snapshot(&mut self) {
        let Some(b) = self.active_browser_mut() else {
            self.toast("no browser pane open");
            return;
        };
        if b.snapshots.is_empty() {
            self.toast("no snapshot to diff against — capture one with browser.snapshot");
            return;
        }
        b.snapshot_diff_open = !b.snapshot_diff_open;
        b.snapshot_diff_scroll = 0;
    }

    /// `browser.clear_snapshots` — drop every captured snapshot for
    /// the active pane and close the diff panel.
    pub fn browser_clear_snapshots(&mut self) {
        let Some(b) = self.active_browser_mut() else {
            self.toast("no browser pane open");
            return;
        };
        let n = b.snapshots.len();
        b.snapshots.clear();
        b.snapshot_diff_open = false;
        self.toast(format!("cleared {n} snapshot(s)"));
    }

    /// `Z` in a browser pane's DOM panel (`browser.scroll_node_into_view`)
    /// — `DOM.scrollIntoViewIfNeeded` for the selected node. Brings an
    /// off-screen node into the viewport so subsequent `S` (screenshot)
    /// / `h` (highlight) gestures actually see the node. Fire-and-forget;
    /// no reply handling needed.
    pub fn browser_scroll_node_into_view(&mut self) {
        match self.active_browser_mut() {
            Some(b) => {
                if !b.dom_focus {
                    self.toast("scroll-into-view needs the DOM panel open (D)");
                    return;
                }
                if b.selected_dom().map(|r| r.node_id).unwrap_or(0) == 0 {
                    self.toast("no node selected");
                    return;
                }
                b.scroll_selected_dom_into_view();
                self.toast("scrolled node into view");
            }
            None => self.toast("no browser pane open"),
        }
    }

    /// `S` in a browser pane's DOM panel (`browser.screenshot_node`) —
    /// capture a screenshot clipped to the selected DOM node's bounding
    /// box. Two-step CDP flow under the hood: `DOM.getBoxModel` →
    /// `Page.captureScreenshot { clip }`. The eventual PNG lands in
    /// `.mnml/screenshots/` via the same path as a full-page screenshot.
    pub fn browser_screenshot_node(&mut self) {
        match self.active_browser_mut() {
            Some(b) => {
                if !b.dom_focus {
                    self.toast("node screenshot needs the DOM panel open (D)");
                    return;
                }
                if b.selected_dom().map(|r| r.node_id).unwrap_or(0) == 0 {
                    self.toast("no node selected");
                    return;
                }
                b.screenshot_selected_dom();
            }
            None => self.toast("no browser pane open"),
        }
    }

    /// `Ctrl+R` in a browser pane — fuzzy picker over the App-wide
    /// `browser_url_history`. Accept ⇒ `Page.navigate` the active
    /// browser pane to the chosen URL. The history accumulates from
    /// `Page.frameNavigated` events across the session and persists in
    /// session.json so previously-visited URLs are available on fresh
    /// launch.
    pub fn open_browser_history_picker(&mut self) {
        use crate::picker::PickerItem;
        if !matches!(
            self.active.and_then(|i| self.panes.get(i)),
            Some(Pane::Browser(_))
        ) {
            self.toast("no browser pane open");
            return;
        }
        if self.browser_url_history.is_empty() {
            self.toast("no browser history yet");
            return;
        }
        // Best-effort short label: host + path, mirroring the
        // network-panel `short_url` shape. Full URL kept as detail.
        let items: Vec<PickerItem> = self
            .browser_url_history
            .iter()
            .map(|u| {
                let short = u
                    .strip_prefix("https://")
                    .or_else(|| u.strip_prefix("http://"))
                    .unwrap_or(u)
                    .to_string();
                PickerItem::new(u.clone(), short, u.clone())
            })
            .collect();
        self.open_picker(crate::picker::Picker::new(
            crate::picker::PickerKind::BrowserHistory,
            format!("Browser history ({})", self.browser_url_history.len()),
            items,
        ));
    }

    /// Accept handler for `PickerKind::BrowserHistory` — navigate the
    /// active browser pane to `url`. Empty / whitespace urls toast.
    pub fn browser_navigate_to(&mut self, url: &str) {
        let url = url.trim();
        if url.is_empty() {
            self.toast("history: empty URL");
            return;
        }
        if let Some(Pane::Browser(b)) = self.active.and_then(|i| self.panes.get_mut(i)) {
            b.navigate(url);
        } else {
            self.toast("no browser pane open");
        }
    }

    /// `T` in the browser pane — open a picker over discovered CDP targets
    /// (main page + auto-attached popups / new tabs / iframes). Accept ⇒
    /// `browser.switch_target` routes subsequent commands there.
    pub fn open_browser_target_picker(&mut self) {
        use crate::picker::PickerItem;
        let Some(b) = self.active_browser() else {
            self.toast("no browser pane open");
            return;
        };
        if b.targets.len() <= 1 {
            self.toast("only one target (no popups / iframes attached)");
            return;
        }
        let items: Vec<PickerItem> = b
            .targets
            .iter()
            .enumerate()
            .map(|(i, t)| {
                let star = if i == b.current_target { "" } else { "  " };
                let label = if t.session_id.is_empty() {
                    format!("{star}main · {}", t.url)
                } else {
                    let title = if t.title.is_empty() {
                        "(no title)"
                    } else {
                        &t.title
                    };
                    format!("{star}{} · {title}", t.kind)
                };
                PickerItem::new(i.to_string(), label, t.url.clone())
            })
            .collect();
        self.open_picker(crate::picker::Picker::new(
            crate::picker::PickerKind::BrowserTargets,
            format!("Browser targets ({})", b.targets.len()),
            items,
        ));
    }

    /// Accept handler for `PickerKind::BrowserTargets` — `idx` is parsed from
    /// `PickerItem.id`. Switches the active browser pane's current target.
    pub fn switch_browser_target(&mut self, idx: usize) {
        if let Some(b) = self.active_browser_mut() {
            b.switch_target(idx);
        }
    }

    /// Open a network-throttle picker over canned presets
    /// (Online / Offline / Slow 3G / Fast 3G / WiFi). Accept fires
    /// `Network.emulateNetworkConditions` on the active browser
    /// pane via `browser_set_network_throttle`.
    pub fn open_browser_network_throttle_picker(&mut self) {
        use crate::picker::PickerItem;
        if self.active_browser().is_none() {
            self.toast("no browser pane open");
            return;
        }
        let items = vec![
            PickerItem::new(
                "none",
                "Online — no throttling".to_string(),
                "real network".to_string(),
            ),
            PickerItem::new(
                "offline",
                "Offline — simulate no network".to_string(),
                "no requests".to_string(),
            ),
            PickerItem::new(
                "slow3g",
                "Slow 3G".to_string(),
                "400ms RTT · 400/400 Kbps".to_string(),
            ),
            PickerItem::new(
                "fast3g",
                "Fast 3G".to_string(),
                "150ms RTT · 1.5/750 Kbps".to_string(),
            ),
            PickerItem::new(
                "wifi",
                "WiFi".to_string(),
                "2ms RTT · 30/15 Mbps".to_string(),
            ),
        ];
        self.open_picker(crate::picker::Picker::new(
            crate::picker::PickerKind::BrowserNetworkThrottle,
            "Network throttle".to_string(),
            items,
        ));
    }

    /// Accept handler for the network-throttle picker — apply a
    /// preset to the active browser pane.
    pub fn browser_set_network_throttle(&mut self, id: &str) {
        let (offline, latency, dl, ul, label) = match id {
            "none" => (false, 0, -1, -1, "Online — no throttling"),
            "offline" => (true, 0, 0, 0, "Offline"),
            "slow3g" => (false, 400, 400 * 1024 / 8, 400 * 1024 / 8, "Slow 3G"),
            "fast3g" => (false, 150, 1_500 * 1024 / 8, 750 * 1024 / 8, "Fast 3G"),
            "wifi" => (false, 2, 30_000 * 1024 / 8, 15_000 * 1024 / 8, "WiFi"),
            _ => return,
        };
        let Some(b) = self.active_browser_mut() else {
            return;
        };
        b.set_network_throttle(label, offline, latency, dl, ul);
        self.toast(format!("network: {label}"));
    }

    /// `m` in a browser pane (or `browser.device_picker`) — open a picker
    /// over [`crate::browser_pane::DEVICE_PRESETS`] plus a top "Reset"
    /// entry. Accept ⇒ `browser_set_device` or `browser_clear_device`.
    pub fn open_browser_device_picker(&mut self) {
        use crate::picker::PickerItem;
        let Some(b) = self.active_browser() else {
            self.toast("no browser pane open");
            return;
        };
        let current = b.current_device;
        let mut items: Vec<PickerItem> =
            Vec::with_capacity(crate::browser_pane::DEVICE_PRESETS.len() + 1);
        let reset_star = if current.is_none() { "" } else { "  " };
        items.push(PickerItem::new(
            "reset",
            format!("{reset_star}Reset — clear device emulation"),
            "real Chrome viewport",
        ));
        for (i, p) in crate::browser_pane::DEVICE_PRESETS.iter().enumerate() {
            let star = if current == Some(i) { "" } else { "  " };
            let kind = if p.mobile { "mobile" } else { "desktop" };
            items.push(PickerItem::new(
                i.to_string(),
                format!("{star}{}", p.label),
                format!(
                    "{}×{} · {}× · {kind}",
                    p.width, p.height, p.device_scale_factor
                ),
            ));
        }
        self.open_picker(crate::picker::Picker::new(
            crate::picker::PickerKind::BrowserDevices,
            "Device emulation".to_string(),
            items,
        ));
    }

    /// Accept handler for the device picker (preset row). Applies the
    /// preset to the active browser pane (UA + viewport override).
    pub fn browser_set_device(&mut self, idx: usize) {
        match self.active_browser_mut() {
            Some(b) => {
                b.set_device(idx);
                if let Some(p) = crate::browser_pane::DEVICE_PRESETS.get(idx) {
                    let label = p.label.to_string();
                    let (w, h) = (p.width, p.height);
                    // Remember the choice so subsequent `browser.open` calls
                    // (in this session or after a relaunch via session.json)
                    // auto-apply it.
                    self.last_browser_device = Some(idx);
                    self.toast(format!("emulating: {label} ({w}×{h})"));
                }
            }
            None => self.toast("no browser pane open"),
        }
    }

    /// Accept handler for the device picker (Reset row). Clears any
    /// active device emulation on the active browser pane.
    pub fn browser_clear_device(&mut self) {
        match self.active_browser_mut() {
            Some(b) => {
                b.clear_device();
                self.last_browser_device = None;
                self.toast("device emulation cleared");
            }
            None => self.toast("no browser pane open"),
        }
    }

    /// `P` in a browser pane (or `browser.perf`) — fetch
    /// `performance.*` metrics via Runtime.evaluate if we haven't
    /// yet, and toggle into the perf panel. (`R` in the panel
    /// re-fetches.) Closes the other panels.
    pub fn browser_open_perf(&mut self) {
        let Some(b) = self.active_browser_mut() else {
            self.toast("no browser pane open");
            return;
        };
        if b.perf == crate::browser_pane::PerfMetrics::default() && b.pending_perf.is_none() {
            b.fetch_perf();
        }
        b.perf_focus = true;
        b.net_focus = false;
        b.dom_focus = false;
        b.cookies_focus = false;
        b.storage_focus = false;
    }

    /// `L` in a browser pane (or `browser.storage`) — fetch
    /// `localStorage` + `sessionStorage` via Runtime.evaluate if we
    /// haven't yet, and toggle into the Web Storage panel. (`R` in the
    /// panel re-fetches; `y` copies the selected `key=value`.) Closes
    /// the net / DOM / cookies panels if open.
    pub fn browser_open_storage(&mut self) {
        let Some(b) = self.active_browser_mut() else {
            self.toast("no browser pane open");
            return;
        };
        if b.storage.is_empty() && b.pending_storage.is_none() {
            b.fetch_storage();
        }
        b.storage_focus = true;
        b.net_focus = false;
        b.dom_focus = false;
        b.cookies_focus = false;
        b.storage_sel = b.storage_sel.min(b.storage.len().saturating_sub(1));
    }

    /// `K` in a browser pane (or `browser.cookies`) — fetch
    /// `Network.getCookies` if we haven't yet, and toggle into the
    /// cookies panel. (`R` in the panel re-fetches; `y` copies the
    /// selected `name=value`.) Closes the net + DOM panels if open.
    pub fn browser_open_cookies(&mut self) {
        let Some(b) = self.active_browser_mut() else {
            self.toast("no browser pane open");
            return;
        };
        if b.cookies.is_empty() && b.pending_cookies.is_none() {
            b.fetch_cookies();
        }
        b.cookies_focus = true;
        b.net_focus = false;
        b.dom_focus = false;
        b.storage_focus = false;
        b.cookies_sel = b.cookies_sel.min(b.cookies.len().saturating_sub(1));
    }

    /// `D` in a browser pane (or `browser.dom`) — fetch `DOM.getDocument` if we
    /// haven't yet, and toggle into the DOM panel. (`R` in the panel re-fetches.)
    pub fn browser_open_dom(&mut self) {
        let Some(b) = self.active_browser_mut() else {
            self.toast("no browser pane open");
            return;
        };
        if b.dom.is_empty() && b.pending_dom.is_none() {
            b.fetch_dom();
        }
        b.dom_focus = true;
        b.net_focus = false;
        b.cookies_focus = false;
        b.storage_focus = false;
        b.dom_sel = b.dom_sel.min(b.dom.len().saturating_sub(1));
    }

    /// Drain every browser pane's CDP worker event channel. Each pane owns
    /// its own `event_rx`; we walk the pane list, drain each receiver, then
    /// dispatch. Indices are captured up front so `apply_cdp_message`'s
    /// `idx` argument lines up with the pane that produced the event.
    pub(super) fn drain_cdp_events(&mut self) {
        let browser_idxs: Vec<usize> = self
            .panes
            .iter()
            .enumerate()
            .filter_map(|(i, p)| matches!(p, Pane::Browser(_)).then_some(i))
            .collect();
        for idx in browser_idxs {
            // Collect events from this pane's receiver up front so the
            // borrow ends before apply_cdp_message takes `&mut self`.
            let events: Vec<crate::cdp::CdpEvent> = {
                let Some(Pane::Browser(b)) = self.panes.get(idx) else {
                    continue;
                };
                let mut events = Vec::new();
                while let Ok(ev) = b.event_rx.try_recv() {
                    events.push(ev);
                }
                events
            };
            for ev in events {
                match ev {
                    crate::cdp::CdpEvent::Connected { ws_url } => {
                        // Parse the debugger port out of
                        // `ws://localhost:PORT/devtools/page/…` so
                        // `:browser.devtools` can hit `/json/list`.
                        let port = ws_url
                            .strip_prefix("ws://")
                            .or_else(|| ws_url.strip_prefix("wss://"))
                            .and_then(|rest| rest.split_once('/'))
                            .and_then(|(host, _)| host.rsplit_once(':'))
                            .and_then(|(_, p)| p.parse::<u16>().ok());
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.debugger_port = port;
                            b.push(crate::browser_pane::LogKind::System, "connected to Chrome");
                        }
                    }
                    crate::cdp::CdpEvent::Message(v) => self.apply_cdp_message(idx, v),
                    crate::cdp::CdpEvent::Closed(reason) => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.closed = true;
                            b.push(
                                crate::browser_pane::LogKind::System,
                                format!("session ended: {reason}"),
                            );
                        }
                    }
                }
            }
        }
    }

    /// Apply one raw CDP message (an event, or a reply to one of our requests) to
    /// the browser pane at `idx`.
    fn apply_cdp_message(&mut self, idx: usize, v: serde_json::Value) {
        use crate::browser_pane::LogKind;
        // A reply to a request we issued?
        if let Some(id) = v.get("id").and_then(serde_json::Value::as_i64) {
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.is_pending_perf(id)) {
                let value = v
                    .get("result")
                    .and_then(|r| r.get("result"))
                    .and_then(|ro| ro.get("value"));
                let parsed = value
                    .map(crate::browser_pane::parse_perf_eval)
                    .unwrap_or_else(|| Err("no value in reply".to_string()));
                match parsed {
                    Ok(m) => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.pending_perf = None;
                            b.perf = m;
                            b.push(LogKind::System, "performance loaded");
                        }
                    }
                    Err(e) => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.pending_perf = None;
                            b.push(LogKind::ConsoleErr, format!("perf: {e}"));
                        }
                        self.toast(format!("perf: {e}"));
                    }
                }
                return;
            }
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.is_pending_storage(id)) {
                // Web Storage eval reply (`L` panel). The result is a
                // `RemoteObject` with `type:'object', value:<obj>` —
                // already JSON-ified by `returnByValue:true`.
                let value = v
                    .get("result")
                    .and_then(|r| r.get("result"))
                    .and_then(|ro| ro.get("value"));
                let parsed = value
                    .map(crate::browser_pane::parse_storage_eval)
                    .unwrap_or_else(|| Err("no value in reply".to_string()));
                match parsed {
                    Ok(entries) => {
                        let n = entries.len();
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.pending_storage = None;
                            b.set_storage(entries);
                            b.push(LogKind::System, format!("storage loaded ({n} entries)"));
                        }
                    }
                    Err(e) => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.pending_storage = None;
                            b.push(LogKind::ConsoleErr, format!("storage: {e}"));
                        }
                        self.toast(format!("storage: {e}"));
                    }
                }
                return;
            }
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.pending_eval == Some(id)) {
                let text = cdp_eval_result_text(&v);
                if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                    b.pending_eval = None;
                    b.push(LogKind::Eval, format!("= {text}"));
                }
                return;
            }
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.pending_screenshot == Some(id))
            {
                if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                    b.pending_screenshot = None;
                }
                let data = v
                    .get("result")
                    .and_then(|r| r.get("data"))
                    .and_then(serde_json::Value::as_str);
                match data.map(|d| self.save_screenshot_png(d)) {
                    Some(Ok(path)) => {
                        let p = path.display().to_string();
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.push(LogKind::System, format!("screenshot → {p}"));
                        }
                        self.toast(format!("screenshot saved: {p}"));
                    }
                    Some(Err(e)) => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.push(LogKind::ConsoleErr, format!("screenshot failed: {e}"));
                        }
                        self.toast(format!("screenshot failed: {e}"));
                    }
                    None => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.push(LogKind::ConsoleErr, "screenshot: empty reply from Chrome");
                        }
                    }
                }
                return;
            }
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.is_pending_pdf(id)) {
                if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                    b.pending_pdf = None;
                }
                let data = v
                    .get("result")
                    .and_then(|r| r.get("data"))
                    .and_then(serde_json::Value::as_str);
                match data.map(|d| self.save_pdf_bytes(d)) {
                    Some(Ok(path)) => {
                        let p = path.display().to_string();
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.push(LogKind::System, format!("pdf → {p}"));
                        }
                        self.toast(format!("pdf saved: {p}"));
                    }
                    Some(Err(e)) => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.push(LogKind::ConsoleErr, format!("pdf failed: {e}"));
                        }
                        self.toast(format!("pdf failed: {e}"));
                    }
                    None => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.push(LogKind::ConsoleErr, "pdf: empty reply from Chrome");
                        }
                    }
                }
                return;
            }
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.is_pending_node_screenshot(id))
            {
                // `DOM.getBoxModel` reply → parse content quad → compute
                // bbox → fire `Page.captureScreenshot` with `clip`.
                if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                    b.pending_node_screenshot = None;
                }
                let quad = v
                    .get("result")
                    .and_then(|r| r.get("model"))
                    .and_then(|m| m.get("content"))
                    .and_then(|c| c.as_array());
                match quad.and_then(|q| bbox_from_quad(q)) {
                    Some((x, y, w, h)) if w > 0.0 && h > 0.0 => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.screenshot_clip(x, y, w, h);
                        }
                    }
                    _ => {
                        if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                            b.push(
                                LogKind::ConsoleErr,
                                "node screenshot: bbox unavailable (off-screen / display:none?)",
                            );
                        }
                        self.toast("node screenshot: bbox unavailable");
                    }
                }
                return;
            }
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.is_pending_post_data(id)) {
                let data = v
                    .get("result")
                    .and_then(|r| r.get("postData"))
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                    b.fill_post_data(id, data);
                }
                return;
            }
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.is_pending_cookies(id)) {
                let cookies = v
                    .get("result")
                    .and_then(|r| r.get("cookies"))
                    .map(crate::browser_pane::parse_cookies)
                    .unwrap_or_default();
                let n = cookies.len();
                if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                    b.pending_cookies = None;
                    b.set_cookies(cookies);
                    b.push(LogKind::System, format!("cookies loaded ({n} entries)"));
                }
                return;
            }
            if matches!(self.panes.get(idx), Some(Pane::Browser(b)) if b.pending_dom == Some(id)) {
                let rows = v
                    .get("result")
                    .and_then(|r| r.get("root"))
                    .map(crate::browser_pane::parse_dom)
                    .unwrap_or_default();
                let n = rows.len();
                if let Some(Pane::Browser(b)) = self.panes.get_mut(idx) {
                    b.pending_dom = None;
                    b.set_dom(rows);
                    b.push(LogKind::System, format!("DOM loaded ({n} rows)"));
                }
                return;
            }
            return;
        }
        let method = v
            .get("method")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("");
        let params = v.get("params");
        // URL captured during the match so we can push it onto the
        // App-wide `browser_url_history` after the `&mut b` borrow
        // ends. NLL drops `b` at last use, so the post-match write
        // compiles cleanly.
        let mut nav_url: Option<String> = None;
        // Same pattern for the new auto-capture-to-log path: the
        // match arms push (id, request-json) pairs here; we write
        // them to .rqst/captured/log.jsonl after the borrow ends.
        let mut autocapture_pending: Vec<(String, serde_json::Value)> = Vec::new();
        let Some(Pane::Browser(b)) = self.panes.get_mut(idx) else {
            return;
        };
        match method {
            "Runtime.consoleAPICalled" => {
                let typ = params
                    .and_then(|p| p.get("type"))
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("log");
                let text = params
                    .and_then(|p| p.get("args"))
                    .and_then(serde_json::Value::as_array)
                    .map(|a| {
                        a.iter()
                            .map(cdp_remote_object_str)
                            .collect::<Vec<_>>()
                            .join(" ")
                    })
                    .unwrap_or_default();
                let kind = if matches!(typ, "error" | "assert") {
                    LogKind::ConsoleErr
                } else {
                    LogKind::Console
                };
                b.push(kind, format!("console.{typ}: {text}"));
            }
            "Log.entryAdded" => {
                let entry = params.and_then(|p| p.get("entry"));
                let level = entry
                    .and_then(|e| e.get("level"))
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("info");
                let text = entry
                    .and_then(|e| e.get("text"))
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                let kind = if level == "error" {
                    LogKind::ConsoleErr
                } else {
                    LogKind::Console
                };
                b.push(kind, format!("[{level}] {text}"));
            }
            "Runtime.exceptionThrown" => {
                let det = params.and_then(|p| p.get("exceptionDetails"));
                let msg = det
                    .and_then(|d| d.get("exception"))
                    .and_then(|e| e.get("description"))
                    .and_then(serde_json::Value::as_str)
                    .or_else(|| {
                        det.and_then(|d| d.get("text"))
                            .and_then(serde_json::Value::as_str)
                    })
                    .unwrap_or("exception");
                b.push(
                    LogKind::ConsoleErr,
                    format!("{}", msg.lines().next().unwrap_or(msg)),
                );
            }
            "Page.frameNavigated" => {
                let frame = params.and_then(|p| p.get("frame"));
                let is_main = frame.map(|f| f.get("parentId").is_none()).unwrap_or(false);
                if is_main
                    && let Some(url) = frame
                        .and_then(|f| f.get("url"))
                        .and_then(serde_json::Value::as_str)
                {
                    b.url = url.to_string();
                    nav_url = Some(url.to_string());
                    b.push(LogKind::Nav, format!("{url}"));
                    // DevTools' default: don't carry the prior page's
                    // network log + DOM into the new page. Mirrors the
                    // "Preserve log: off" Chrome default. Selections reset
                    // so the panels open at the top of the new page's data.
                    b.net.clear();
                    b.net_sel = 0;
                    b.dom.clear();
                    b.dom_sel = 0;
                }
            }
            "Target.targetCreated" => {
                let ti = params.and_then(|p| p.get("targetInfo"));
                let ty = ti
                    .and_then(|i| i.get("type"))
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                // The page we're driving fires this for itself (`attached:true`) — skip.
                let attached = ti
                    .and_then(|i| i.get("attached"))
                    .and_then(serde_json::Value::as_bool)
                    .unwrap_or(false);
                if ty == "page" && !attached {
                    let url = ti
                        .and_then(|i| i.get("url"))
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("about:blank");
                    b.push(LogKind::Nav, format!("⤴ new tab → {url}"));
                }
            }
            "Target.attachedToTarget" => {
                // Multi-page: a popup / new tab / iframe auto-attached. Add
                // it to the pane's target list so the user can `T` to it.
                let session_id = params
                    .and_then(|p| p.get("sessionId"))
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                let ti = params.and_then(|p| p.get("targetInfo"));
                if !session_id.is_empty()
                    && let Some(ti) = ti
                {
                    b.note_attached_target(session_id, ti);
                    let label = b
                        .targets
                        .last()
                        .map(|t| {
                            if t.title.is_empty() {
                                t.url.clone()
                            } else {
                                t.title.clone()
                            }
                        })
                        .unwrap_or_default();
                    b.push(LogKind::System, format!("attached → {label}"));
                }
            }
            "Target.targetInfoChanged" => {
                if let Some(ti) = params.and_then(|p| p.get("targetInfo")) {
                    b.note_target_info_changed(ti);
                }
            }
            "Target.detachedFromTarget" => {
                let session_id = params
                    .and_then(|p| p.get("sessionId"))
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("");
                if !session_id.is_empty() {
                    b.note_detached_target(session_id);
                    b.push(LogKind::System, "detached target".to_string());
                }
            }
            "Network.requestWillBeSent" => {
                let rtype = params
                    .and_then(|p| p.get("type"))
                    .and_then(serde_json::Value::as_str);
                if cdp_resource_type_is_interesting(rtype) {
                    let req = params.and_then(|p| p.get("request"));
                    let method = req
                        .and_then(|r| r.get("method"))
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("GET");
                    let url = req
                        .and_then(|r| r.get("url"))
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("");
                    b.push(LogKind::Net, format!("{method} {}", cdp_short_url(url)));
                    if let (Some(id), Some(req)) = (
                        params
                            .and_then(|p| p.get("requestId"))
                            .and_then(serde_json::Value::as_str),
                        req,
                    ) {
                        b.note_net_request(id, req);
                        // Auto-capture: write the request to
                        // <workspace>/.rqst/captured/log.jsonl so the
                        // `:http.view_captured` picker reflects
                        // everything you've browsed, not just what
                        // you explicitly `:http.capture_now`-d. Config
                        // knob `[browser] autocapture_to_log` gates
                        // this; default on. 2026-06-19 user-requested
                        // — "rqst had this when you opened the browser."
                        autocapture_pending.push((id.to_string(), req.clone()));
                    }
                }
            }
            "Network.responseReceived" => {
                let rtype = params
                    .and_then(|p| p.get("type"))
                    .and_then(serde_json::Value::as_str);
                if cdp_resource_type_is_interesting(rtype) {
                    let resp = params.and_then(|p| p.get("response"));
                    let status = resp
                        .and_then(|r| r.get("status"))
                        .and_then(serde_json::Value::as_i64)
                        .unwrap_or(0);
                    let url = resp
                        .and_then(|r| r.get("url"))
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("");
                    b.push(LogKind::Net, format!("{status} {}", cdp_short_url(url)));
                    if let Some(id) = params
                        .and_then(|p| p.get("requestId"))
                        .and_then(serde_json::Value::as_str)
                    {
                        let mime = resp
                            .and_then(|r| r.get("mimeType"))
                            .and_then(serde_json::Value::as_str);
                        b.note_net_response(id, status, mime);
                    }
                }
            }
            "Network.loadingFailed" => {
                let rtype = params
                    .and_then(|p| p.get("type"))
                    .and_then(serde_json::Value::as_str);
                if cdp_resource_type_is_interesting(rtype) {
                    let why = params
                        .and_then(|p| p.get("errorText"))
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("failed");
                    b.push(LogKind::ConsoleErr, format!("✗ request failed: {why}"));
                    if let Some(id) = params
                        .and_then(|p| p.get("requestId"))
                        .and_then(serde_json::Value::as_str)
                    {
                        b.note_net_failed(id, why);
                    }
                }
            }
            _ => {} // loadEventFired, snapshots, etc. — not mirrored here
        }
        if let Some(url) = nav_url {
            self.note_browser_url(url);
        }
        if !autocapture_pending.is_empty() && self.config.browser.autocapture_to_log {
            self.append_browser_autocapture(autocapture_pending);
        }
    }

    /// Append each pending request to
    /// `<workspace>/.rqst/captured/log.jsonl` as a `CapturedRow` so
    /// `:http.view_captured` reflects everything the browser pane
    /// has seen. Best-effort: ignores I/O errors so a write failure
    /// doesn't poison the CDP loop. Gated by `[browser]
    /// autocapture_to_log` (default on). 2026-06-19 — user-requested
    /// "rqst had a button that captured what the browser did, do
    /// the same for the in-app browser."
    fn append_browser_autocapture(&self, rows: Vec<(String, serde_json::Value)>) {
        use std::io::Write;
        let log_path = self
            .workspace
            .join(".rqst")
            .join("captured")
            .join("log.jsonl");
        if let Some(parent) = log_path.parent()
            && std::fs::create_dir_all(parent).is_err()
        {
            return;
        }
        let Ok(mut f) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_path)
        else {
            return;
        };
        let at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        for (request_id, req) in rows {
            let method = req
                .get("method")
                .and_then(|m| m.as_str())
                .unwrap_or("GET")
                .to_string();
            let url = req
                .get("url")
                .and_then(|u| u.as_str())
                .unwrap_or("")
                .to_string();
            let headers: Vec<(String, String)> = req
                .get("headers")
                .and_then(|h| h.as_object())
                .map(|obj| {
                    obj.iter()
                        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                        .collect()
                })
                .unwrap_or_default();
            let body = req
                .get("postData")
                .and_then(|b| b.as_str())
                .map(str::to_string);
            let row = crate::http::captured::CapturedRow {
                at,
                request_id,
                method,
                url,
                headers,
                body,
                paused: false,
            };
            if let Ok(line) = serde_json::to_string(&row) {
                let _ = writeln!(f, "{line}");
            }
        }
    }

    /// Push `url` to the front of `browser_url_history` (de-duped),
    /// capping at [`BROWSER_URL_HISTORY_MAX`]. `about:blank` is skipped
    /// — it's the noisy initial state, not a real navigation target.
    /// Called from every main-frame `Page.frameNavigated`.
    pub fn note_browser_url(&mut self, url: String) {
        if url == "about:blank" || url.is_empty() {
            return;
        }
        self.browser_url_history.retain(|u| u != &url);
        self.browser_url_history.insert(0, url);
        if self.browser_url_history.len() > BROWSER_URL_HISTORY_MAX {
            self.browser_url_history.truncate(BROWSER_URL_HISTORY_MAX);
        }
    }

    /// Toggle CDP headless launch (`:set [no]headless`). Takes effect on the
    /// **next** `browser.open` — an in-flight browser pane is unaffected.
    pub fn set_browser_headless(&mut self, on: bool) {
        self.config.browser.headless = on;
        self.toast(if on {
            "browser: headless on (next open)"
        } else {
            "browser: headless off (next open)"
        });
    }

    pub fn toggle_browser_headless(&mut self) {
        self.set_browser_headless(!self.config.browser.headless);
    }
}

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

    #[test]
    fn note_browser_url_dedupes_and_caps() {
        let mut h: Vec<String> = Vec::new();
        // Inline the same shape `note_browser_url` uses on App so we can
        // exercise the dedupe / cap logic without spinning up a full App.
        let push = |h: &mut Vec<String>, url: &str| {
            if url == "about:blank" || url.is_empty() {
                return;
            }
            h.retain(|u| u != url);
            h.insert(0, url.to_string());
            if h.len() > BROWSER_URL_HISTORY_MAX {
                h.truncate(BROWSER_URL_HISTORY_MAX);
            }
        };
        push(&mut h, "https://a.test/");
        push(&mut h, "https://b.test/");
        push(&mut h, "https://a.test/"); // move-to-front, dedupe
        assert_eq!(h, vec!["https://a.test/", "https://b.test/"]);

        // about:blank + empty are skipped.
        push(&mut h, "about:blank");
        push(&mut h, "");
        assert_eq!(h.len(), 2);

        // Cap enforced.
        for i in 0..BROWSER_URL_HISTORY_MAX + 10 {
            push(&mut h, &format!("https://h.test/{i}"));
        }
        assert_eq!(h.len(), BROWSER_URL_HISTORY_MAX);
        assert!(h[0].ends_with(&format!("/{}", BROWSER_URL_HISTORY_MAX + 9)));
    }

    #[test]
    fn bbox_from_quad_computes_axis_aligned_rect() {
        // A 100×40 rectangle anchored at (10, 20). Corners walk clockwise:
        // (10,20) → (110,20) → (110,60) → (10,60).
        let q = vec![
            json!(10.0),
            json!(20.0),
            json!(110.0),
            json!(20.0),
            json!(110.0),
            json!(60.0),
            json!(10.0),
            json!(60.0),
        ];
        let (x, y, w, h) = bbox_from_quad(&q).expect("bbox");
        assert_eq!(x, 10.0);
        assert_eq!(y, 20.0);
        assert_eq!(w, 100.0);
        assert_eq!(h, 40.0);
    }

    #[test]
    fn bbox_from_quad_handles_rotated_input() {
        // A 50×50 square rotated ~45° so the bbox is wider than either side.
        let q = vec![
            json!(50.0),
            json!(0.0),
            json!(100.0),
            json!(50.0),
            json!(50.0),
            json!(100.0),
            json!(0.0),
            json!(50.0),
        ];
        let (x, y, w, h) = bbox_from_quad(&q).expect("bbox");
        assert_eq!(x, 0.0);
        assert_eq!(y, 0.0);
        assert_eq!(w, 100.0);
        assert_eq!(h, 100.0);
    }

    #[test]
    fn bbox_from_quad_rejects_malformed_input() {
        // Shorter array
        assert!(bbox_from_quad(&[json!(1.0), json!(2.0)]).is_none());
        // Non-numeric entry
        let q = vec![
            json!(0.0),
            json!(0.0),
            json!(10.0),
            json!(0.0),
            json!("bad"),
            json!(10.0),
            json!(0.0),
            json!(10.0),
        ];
        assert!(bbox_from_quad(&q).is_none());
    }

    #[test]
    fn chrome_profile_dir_honors_mode() {
        let d = tempfile::tempdir().unwrap();
        let mut cfg = Config::default();
        // workspace (default) ⇒ <workspace>/.mnml/chrome-profile
        let app = App::new(d.path().to_path_buf(), cfg.clone()).unwrap();
        let p = app.chrome_profile_dir();
        // App::new canonicalizes the workspace, so the workspace dir
        // in `app` is the canonical form of `d.path()`.
        let canon = d.path().canonicalize().unwrap();
        assert!(p.starts_with(&canon), "{p:?} should start with {canon:?}");
        assert!(p.ends_with("chrome-profile"));
        // ephemeral ⇒ a brand new dir per call, not under workspace
        cfg.browser.profile_mode = "ephemeral".to_string();
        let app = App::new(d.path().to_path_buf(), cfg.clone()).unwrap();
        let p1 = app.chrome_profile_dir();
        let p2 = app.chrome_profile_dir();
        assert_ne!(p1, p2, "ephemeral should hand back a fresh dir each call");
        // shared ⇒ under $HOME (when set)
        cfg.browser.profile_mode = "shared".to_string();
        // Serialize env mutation across test modules; EnvGuard restores
        // HOME on scope exit (including panic unwind).
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _home = crate::EnvGuard::set("HOME", "/tmp/mnml-test-home");
        let app = App::new(d.path().to_path_buf(), cfg).unwrap();
        let p = app.chrome_profile_dir();
        assert!(p.starts_with("/tmp/mnml-test-home"));
    }
}