zendriver 0.2.14

Async-first, undetectable browser automation via the Chrome DevTools Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
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
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
//! Browser lifecycle: executable discovery, subprocess spawn, WS attach,
//! graceful teardown.
//!
//! Entry point is [`Browser::builder`] — start there for any zendriver
//! workflow. The launched [`Browser`] owns the Chrome subprocess and the
//! transport actor; dropping it terminates Chrome. Spawn additional pages
//! via [`Browser::new_tab`] and reach the initial page via
//! [`Browser::main_tab`].
//!
//! ```no_run
//! # async fn ex() -> zendriver::Result<()> {
//! let browser = zendriver::Browser::builder()
//!     .headless(true)
//!     .launch().await?;
//! let tab = browser.main_tab();
//! tab.goto("https://example.com").await?;
//! browser.close().await?;
//! # Ok(()) }
//! ```

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Arc, OnceLock, Weak};
use std::time::Duration;

use serde_json::json;
use tempfile::TempDir;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::{Child, Command};
use tokio::time::timeout;
use tracing::{debug, info, warn};
use zendriver_stealth::{Persona, Seed, StealthObserver, StealthProfile, Strategy, Surface};
use zendriver_transport::{
    Connection, ObserverError, PausedSession, SessionHandle, TargetObserver,
};

use crate::error::{BrowserError, ZendriverError};
use crate::input::InputController;
use crate::tab::Tab;

/// Which Chromium-family browser channel to discover at launch.
///
/// Passed via [`BrowserBuilder::channel`]; consumed by
/// [`find_chrome_executable_for_channel`] to pick the per-OS candidate path
/// table. [`BrowserBuilder::executable`] still overrides channel discovery
/// entirely.
///
/// # Examples
///
/// ```no_run
/// use zendriver::Channel;
/// let builder = zendriver::Browser::builder().channel(Channel::Brave);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Channel {
    /// Google Chrome (stable). Same discovery as [`Channel::Auto`] minus the
    /// Chromium fallbacks.
    Chrome,
    /// Open-source Chromium build.
    Chromium,
    /// Brave Browser.
    Brave,
    /// Microsoft Edge.
    Edge,
    /// First Chromium-family browser found — the historical default (Chrome,
    /// then Chromium). Use a specific channel to force Brave / Edge.
    #[default]
    Auto,
}

/// Look for a Chromium-family binary on PATH and in conventional locations.
///
/// Returns the first path that exists, scanning the [`Channel::Auto`]
/// candidate table (Chrome, then Chromium). For a specific browser channel
/// (Brave / Edge / …) use [`find_chrome_executable_for_channel`].
///
/// # Errors
///
/// Returns [`BrowserError::ExecutableNotFound`] with the full list of
/// searched paths when no installation is found.
///
/// # Examples
///
/// ```no_run
/// match zendriver::browser::find_chrome_executable() {
///     Ok(p) => println!("found chrome at {}", p.display()),
///     Err(e) => eprintln!("no chrome installed: {e}"),
/// }
/// ```
pub fn find_chrome_executable() -> Result<PathBuf, BrowserError> {
    find_chrome_executable_for_channel(Channel::Auto)
}

/// Look for the binary of a specific [`Channel`] on PATH and in conventional
/// per-OS install locations.
///
/// Returns the first candidate that exists. [`Channel::Auto`] reproduces the
/// historical first-found behavior (Chrome, then Chromium).
///
/// # Errors
///
/// Returns [`BrowserError::ExecutableNotFound`] with the searched candidate
/// list when none of the channel's paths exist.
pub fn find_chrome_executable_for_channel(channel: Channel) -> Result<PathBuf, BrowserError> {
    let candidates = candidate_paths_for_channel(channel);
    for c in &candidates {
        if c.exists() {
            return Ok(c.clone());
        }
    }
    Err(BrowserError::ExecutableNotFound {
        searched: candidates,
    })
}

/// Build the ordered candidate-path list for `channel`.
///
/// PATH lookups come first (so a PATH-resolved binary wins over a fixed
/// install dir), followed by the per-OS conventional install locations for
/// the requested channel. Factored out (and `pub(crate)`) so unit tests can
/// assert the table without requiring the browser installed.
pub(crate) fn candidate_paths_for_channel(channel: Channel) -> Vec<PathBuf> {
    let mut v = Vec::new();

    // PATH lookups — names vary by channel.
    let path_names: &[&str] = match channel {
        Channel::Chrome => &["google-chrome", "google-chrome-stable", "chrome"],
        Channel::Chromium => &["chromium", "chromium-browser"],
        Channel::Brave => &["brave-browser", "brave"],
        Channel::Edge => &["microsoft-edge", "microsoft-edge-stable"],
        Channel::Auto => &[
            "google-chrome",
            "google-chrome-stable",
            "chromium",
            "chromium-browser",
            "chrome",
        ],
    };
    for name in path_names {
        if let Some(p) = which_on_path(name) {
            v.push(p);
        }
    }

    // Platform-specific known locations, per channel.
    #[cfg(target_os = "macos")]
    {
        let chrome = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
        let chromium = "/Applications/Chromium.app/Contents/MacOS/Chromium";
        let brave = "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser";
        let edge = "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge";
        match channel {
            Channel::Chrome => v.push(PathBuf::from(chrome)),
            Channel::Chromium => v.push(PathBuf::from(chromium)),
            Channel::Brave => v.push(PathBuf::from(brave)),
            Channel::Edge => v.push(PathBuf::from(edge)),
            Channel::Auto => {
                v.push(PathBuf::from(chrome));
                v.push(PathBuf::from(chromium));
            }
        }
    }
    #[cfg(target_os = "linux")]
    {
        match channel {
            Channel::Chrome => {
                v.push(PathBuf::from("/usr/bin/google-chrome"));
                v.push(PathBuf::from("/usr/bin/google-chrome-stable"));
            }
            Channel::Chromium => {
                v.push(PathBuf::from("/usr/bin/chromium"));
                v.push(PathBuf::from("/usr/bin/chromium-browser"));
                v.push(PathBuf::from("/snap/bin/chromium"));
            }
            Channel::Brave => {
                v.push(PathBuf::from("/usr/bin/brave-browser"));
                v.push(PathBuf::from("/usr/bin/brave"));
                v.push(PathBuf::from("/opt/brave.com/brave/brave-browser"));
            }
            Channel::Edge => {
                v.push(PathBuf::from("/usr/bin/microsoft-edge"));
                v.push(PathBuf::from("/usr/bin/microsoft-edge-stable"));
                v.push(PathBuf::from("/opt/microsoft/msedge/microsoft-edge"));
            }
            Channel::Auto => {
                v.push(PathBuf::from("/usr/bin/google-chrome"));
                v.push(PathBuf::from("/usr/bin/chromium"));
                v.push(PathBuf::from("/usr/bin/chromium-browser"));
                v.push(PathBuf::from("/snap/bin/chromium"));
            }
        }
    }
    #[cfg(target_os = "windows")]
    {
        let chrome = [
            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
        ];
        let brave = [
            r"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
            r"C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\brave.exe",
        ];
        let edge = [
            r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
            r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
        ];
        match channel {
            Channel::Chrome | Channel::Chromium | Channel::Auto => {
                for p in chrome {
                    v.push(PathBuf::from(p));
                }
            }
            Channel::Brave => {
                for p in brave {
                    v.push(PathBuf::from(p));
                }
            }
            Channel::Edge => {
                for p in edge {
                    v.push(PathBuf::from(p));
                }
            }
        }
    }

    v
}

fn which_on_path(name: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path) {
        let full = dir.join(name);
        if full.is_file() {
            return Some(full);
        }
        #[cfg(target_os = "windows")]
        {
            let with_exe = dir.join(format!("{name}.exe"));
            if with_exe.is_file() {
                return Some(with_exe);
            }
        }
    }
    None
}

/// Extract the `host:port` authority from a `ws://HOST:PORT/...` (or `wss://`)
/// DevTools endpoint URL.
///
/// Returns `None` for inputs that don't carry a recognizable
/// `scheme://authority` shape. Used to compose [`Tab::inspector_url`] from the
/// endpoint the browser connected to.
pub(crate) fn debug_host_port_from_ws(ws_url: &str) -> Option<String> {
    // Strip the scheme, then take everything up to the first `/` (the path).
    let after_scheme = ws_url
        .strip_prefix("ws://")
        .or_else(|| ws_url.strip_prefix("wss://"))?;
    let authority = after_scheme
        .split('/')
        .next()
        .unwrap_or(after_scheme)
        .trim();
    if authority.is_empty() {
        None
    } else {
        Some(authority.to_string())
    }
}

/// Parse a `DevTools listening on ws://...` line from Chrome's stderr.
pub(crate) fn parse_devtools_line(line: &str) -> Option<String> {
    // Format: `DevTools listening on ws://127.0.0.1:NNNN/devtools/browser/UUID`
    let needle = "DevTools listening on ";
    let idx = line.find(needle)?;
    let rest = &line[idx + needle.len()..];
    let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
    let url = rest[..end].trim();
    if url.starts_with("ws://") || url.starts_with("wss://") {
        Some(url.to_string())
    } else {
        None
    }
}

/// Load (or first-time generate + persist) the fingerprint [`Seed`] bound to a
/// `user_data_dir`.
///
/// Stored as a single base-10 `u64` in `<dir>/.zd_persona_seed`. On reuse the
/// file is read and parsed; on first use (or any read/parse failure) a fresh
/// [`Seed::random`] is generated and written, giving a stable per-profile
/// fingerprint across runs. All filesystem errors are swallowed (best-effort):
/// a dir that can't be written simply yields a fresh random seed each launch
/// rather than failing the build.
fn persisted_seed(dir: &Path) -> Seed {
    let path = dir.join(".zd_persona_seed");
    if let Ok(contents) = std::fs::read_to_string(&path) {
        if let Ok(value) = contents.trim().parse::<u64>() {
            return Seed::from_u64(value);
        }
    }
    let seed = Seed::random();
    let _ = std::fs::create_dir_all(dir);
    let _ = std::fs::write(&path, seed.value().to_string());
    seed
}

/// Fluent builder for a [`Browser`] launch.
///
/// Start with [`Browser::builder`] (seeded with [`zendriver_stealth::StealthProfile::native`]),
/// chain configuration calls, terminate with [`BrowserBuilder::launch`].
///
/// # Examples
///
/// ```no_run
/// # async fn ex() -> zendriver::Result<()> {
/// let browser = zendriver::Browser::builder()
///     .headless(true)
///     .arg("--lang=en-US")
///     .launch().await?;
/// # browser.close().await?;
/// # Ok(()) }
/// ```
#[derive(Default, Clone)]
pub struct BrowserBuilder {
    pub(crate) headless: Option<bool>,
    pub(crate) executable: Option<PathBuf>,
    pub(crate) user_data_dir: Option<PathBuf>,
    pub(crate) downloads_dir: Option<PathBuf>,
    /// `--lang=<v>` UI locale override. See [`BrowserBuilder::lang`].
    pub(crate) lang: Option<String>,
    /// Static `--user-agent=<v>` launch override. See
    /// [`BrowserBuilder::user_agent`].
    pub(crate) user_agent: Option<String>,
    /// Sandbox toggle. `None`/`Some(true)` = sandbox on (no flag);
    /// `Some(false)` = emit `--no-sandbox`. See [`BrowserBuilder::sandbox`].
    pub(crate) sandbox: Option<bool>,
    /// Which browser [`Channel`] to discover when no explicit `executable` is
    /// set. Defaults to [`Channel::Auto`].
    pub(crate) channel: Channel,
    /// Unpacked-extension directory (or `.crx`) paths to side-load. See
    /// [`BrowserBuilder::add_extension`]. `.crx` entries are unzipped to a
    /// tempdir at launch; directory entries pass through unchanged.
    pub(crate) extensions: Vec<PathBuf>,
    /// Expert-mode toggle. When `true`, `build_flags` emits
    /// `--disable-web-security` + `--disable-site-isolation-trials`. See
    /// [`BrowserBuilder::expert`].
    pub(crate) expert: bool,
    /// When `true`, a [`ShadowRootObserver`] is added to the observer chain so
    /// every new target gets an `Element.prototype.attachShadow` override that
    /// forces `{mode: "open"}`. See
    /// [`BrowserBuilder::force_open_shadow_roots`]. **Detectable.**
    pub(crate) force_open_shadow_roots: bool,
    pub(crate) extra_args: Vec<String>,
    pub(crate) stealth: Option<StealthProfile>,
    /// Base fingerprint [`Persona`] driving the spoofed-mode surface patches.
    /// `None` → [`Persona::system`] (host-probed) is used. See
    /// [`BrowserBuilder::persona`] and [`BrowserBuilder::resolved_persona`].
    pub(crate) persona: Option<Persona>,
    /// Optional overlay merged on top of the base persona (field-wise, `Some`
    /// wins). See [`BrowserBuilder::persona_overlay`].
    pub(crate) persona_overlay: Option<Persona>,
    /// Per-surface render-strategy overrides, applied last over the resolved
    /// persona. See [`BrowserBuilder::surface`].
    pub(crate) surface_overrides: Vec<(Surface, Strategy)>,
    pub(crate) extra_observers: Vec<Arc<dyn TargetObserver>>,
    /// Chrome profile preferences (dotted key + JSON value), merged into the
    /// profile's `Default/Preferences` at launch. User entries override the
    /// default suppression set. See [`BrowserBuilder::preference`].
    pub(crate) preferences: Vec<(String, serde_json::Value)>,
    /// Optional `(username, password)` for proxy / HTTP basic-auth handling.
    /// Only honored when the `interception` feature is enabled; when present
    /// at launch, an interception actor is spawned on the main tab session
    /// that auto-replies to `Fetch.authRequired`. See cdpdriver/zendriver#208.
    #[cfg(feature = "interception")]
    pub(crate) proxy_auth: Option<(String, String)>,
    /// Enable the bundled curated tracker/fingerprinter blocklist.
    #[cfg(feature = "tracker-blocking")]
    pub(crate) block_trackers: bool,
    /// Extra hostnames to block (inline), accumulated across calls.
    #[cfg(feature = "tracker-blocking")]
    pub(crate) tracker_blocklist_domains: Vec<String>,
    /// Local files (newline host lists) to block, accumulated across calls.
    #[cfg(feature = "tracker-blocking")]
    pub(crate) tracker_blocklist_files: Vec<std::path::PathBuf>,
    /// Remote URLs (newline host lists, fetched+cached at launch).
    #[cfg(feature = "tracker-blocking")]
    pub(crate) tracker_blocklist_urls: Vec<String>,
}

// Hand-rolled `Debug` because `Vec<Arc<dyn TargetObserver>>` doesn't derive
// (trait objects are intentionally not `Debug`-bounded). Renders the observers
// field as `<N observers>` so the rest of the builder stays inspectable.
impl std::fmt::Debug for BrowserBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("BrowserBuilder");
        s.field("headless", &self.headless)
            .field("executable", &self.executable)
            .field("user_data_dir", &self.user_data_dir)
            .field("downloads_dir", &self.downloads_dir)
            .field("lang", &self.lang)
            .field("user_agent", &self.user_agent)
            .field("sandbox", &self.sandbox)
            .field("channel", &self.channel)
            .field("extensions", &self.extensions)
            .field("expert", &self.expert)
            .field("force_open_shadow_roots", &self.force_open_shadow_roots)
            .field("extra_args", &self.extra_args)
            .field("stealth", &self.stealth)
            .field("persona", &self.persona)
            .field("persona_overlay", &self.persona_overlay)
            .field("surface_overrides", &self.surface_overrides)
            .field(
                "extra_observers",
                &format_args!("<{} observers>", self.extra_observers.len()),
            )
            .field("preferences", &self.preferences);
        #[cfg(feature = "interception")]
        s.field(
            "proxy_auth",
            &self
                .proxy_auth
                .as_ref()
                .map(|(u, _)| format!("Some({u:?}, <redacted>)"))
                .unwrap_or_else(|| "None".into()),
        );
        #[cfg(feature = "tracker-blocking")]
        s.field("block_trackers", &self.block_trackers)
            .field("tracker_blocklist_domains", &self.tracker_blocklist_domains)
            .field("tracker_blocklist_files", &self.tracker_blocklist_files)
            .field("tracker_blocklist_urls", &self.tracker_blocklist_urls);
        s.finish()
    }
}

impl BrowserBuilder {
    /// Builder seeded with the default [`StealthProfile::native`] profile.
    ///
    /// Pass `.stealth(StealthProfile::off())` to opt out, or
    /// `.stealth(StealthProfile::spoofed())` for the full anti-detection set.
    /// Equivalent to [`Browser::builder`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::BrowserBuilder::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            stealth: Some(StealthProfile::native()),
            ..Self::default()
        }
    }

    /// Toggle headless mode (default: `true`).
    ///
    /// When `on`, Chrome runs with `--headless=new --disable-gpu`. Pass
    /// `false` to launch a visible window (useful for local debugging).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder().headless(false);
    /// ```
    #[must_use]
    pub fn headless(mut self, on: bool) -> Self {
        self.headless = Some(on);
        self
    }

    /// Override the Chrome executable path.
    ///
    /// When unset, [`find_chrome_executable`] discovers one at launch time.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder()
    ///     .executable("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
    /// ```
    #[must_use]
    pub fn executable(mut self, path: impl Into<PathBuf>) -> Self {
        self.executable = Some(path.into());
        self
    }

    /// Override the `--user-data-dir` for the launched Chrome instance.
    ///
    /// When unset, a fresh tempdir is created and cleaned up on
    /// [`Browser::close`] / drop.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder()
    ///     .user_data_dir("/tmp/zendriver-profile");
    /// ```
    #[must_use]
    pub fn user_data_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.user_data_dir = Some(path.into());
        self
    }

    /// Auto-respond to proxy / HTTP basic-auth challenges with
    /// `(username, password)`.
    ///
    /// At launch, an interception actor is spawned on the main tab session
    /// that sends `Fetch.enable { handleAuthRequests: true }` and answers
    /// every `Fetch.authRequired` event with `Fetch.continueWithAuth`
    /// carrying these credentials. Combine with `.arg("--proxy-server=...")`
    /// to drive Chrome through an authenticated upstream proxy without the
    /// extension-based workarounds the upstream Python project requires.
    ///
    /// Scope: applies to the main tab only — tabs opened later via
    /// [`Browser::new_tab`] do **not** inherit auth handling. For those,
    /// wire `tab.intercept().handle_auth(user, pass).start()` yourself.
    ///
    /// See cdpdriver/zendriver#208.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder()
    ///     .arg("--proxy-server=http://my-proxy.example:3128")
    ///     .proxy_auth("user", "pass")
    ///     .launch().await?;
    /// # browser.close().await?;
    /// # Ok(()) }
    /// ```
    #[cfg(feature = "interception")]
    #[must_use]
    pub fn proxy_auth(mut self, user: impl Into<String>, pass: impl Into<String>) -> Self {
        self.proxy_auth = Some((user.into(), pass.into()));
        self
    }

    /// Enable the bundled curated tracker/fingerprinter blocklist for this
    /// browser. Blocks third-party passive fingerprinters and cross-site
    /// trackers (host-only, suffix-on-dot) by failing their requests with
    /// `net::ERR_BLOCKED_BY_CLIENT` — the same error a real adblocker raises.
    ///
    /// Opt-in (off by default — least-opinionated). Combine with
    /// [`tracker_blocklist_add`](Self::tracker_blocklist_add) /
    /// [`tracker_blocklist_file`](Self::tracker_blocklist_file) /
    /// [`tracker_blocklist_url`](Self::tracker_blocklist_url) for custom hosts.
    #[cfg(feature = "tracker-blocking")]
    #[must_use]
    pub fn block_trackers(mut self, enable: bool) -> Self {
        self.block_trackers = enable;
        self
    }

    /// Add inline hostnames to the tracker blocklist. Supplying any custom
    /// source implicitly enables blocking (you do not also need
    /// [`block_trackers(true)`](Self::block_trackers) unless you also want the
    /// bundled list). Repeatable.
    #[cfg(feature = "tracker-blocking")]
    #[must_use]
    pub fn tracker_blocklist_add(mut self, domains: impl IntoIterator<Item = String>) -> Self {
        self.tracker_blocklist_domains.extend(domains);
        self
    }

    /// Add a local file (newline-delimited host list; `#` comments and
    /// hosts-file `0.0.0.0 host` lines tolerated) to the tracker blocklist.
    /// Implicitly enables blocking. Read at launch. Repeatable.
    #[cfg(feature = "tracker-blocking")]
    #[must_use]
    pub fn tracker_blocklist_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.tracker_blocklist_files.push(path.into());
        self
    }

    /// Add a remote URL (newline-delimited host list) to the tracker
    /// blocklist. Fetched once at launch and cached on disk
    /// (download-on-first-use). Implicitly enables blocking. Repeatable.
    ///
    /// Use this to point at an external list (uBlock, Peter Lowe's, …) under
    /// your own acceptance of that list's license — the bundle ships only our
    /// own clean list.
    #[cfg(feature = "tracker-blocking")]
    #[must_use]
    pub fn tracker_blocklist_url(mut self, url: impl Into<String>) -> Self {
        self.tracker_blocklist_urls.push(url.into());
        self
    }

    /// Direct file downloads to `path` instead of the OS default Downloads
    /// folder.
    ///
    /// When set, `launch` sends `Browser.setDownloadBehavior {behavior:"allow",
    /// downloadPath}` at browser scope after Chrome is ready, so every tab —
    /// including new tabs opened later — saves files into `path`. The directory
    /// is **not** created for you; ensure it exists before launching.
    ///
    /// See <https://github.com/cdpdriver/zendriver/issues/88>.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder()
    ///     .downloads_dir("/tmp/zendriver-downloads")
    ///     .launch().await?;
    /// # browser.close().await?;
    /// # Ok(()) }
    /// ```
    #[must_use]
    pub fn downloads_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.downloads_dir = Some(path.into());
        self
    }

    /// Set Chrome's UI locale via `--lang=<v>` (e.g. `"en-US"`, `"de-DE"`).
    ///
    /// Influences the browser-chrome language and the default
    /// `Accept-Language` header. For full stealth-coherent locale spoofing,
    /// prefer configuring it through the [`StealthProfile`] instead.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder().lang("en-US");
    /// ```
    #[must_use]
    pub fn lang(mut self, lang: impl Into<String>) -> Self {
        self.lang = Some(lang.into());
        self
    }

    /// Set a static `--user-agent=<v>` for the launched Chrome process.
    ///
    /// This is the **launch-time** User-Agent override. Two other UA paths
    /// exist and are usually a better fit:
    /// - [`Tab::set_user_agent`] — a runtime per-tab override (also sets
    ///   `Accept-Language` + UA-CH client hints) applied after launch.
    /// - the stealth-profile UA — a fingerprint-coherent UA (with matching
    ///   UA-CH metadata) set via the [`StealthProfile`]; preferred when
    ///   stealth is on, since a bare `--user-agent` flag leaves the
    ///   JS-visible UA-CH hints inconsistent with the header.
    ///
    /// Use this flag only when you need the UA fixed at process start for
    /// every tab and don't need UA-CH coherence.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder()
    ///     .user_agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36");
    /// ```
    #[must_use]
    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
        self.user_agent = Some(ua.into());
        self
    }

    /// Toggle Chrome's setuid/namespace sandbox (default: **on**).
    ///
    /// Passing `false` appends `--no-sandbox`. Leaving it unset (or `true`)
    /// keeps the sandbox enabled and emits no flag.
    ///
    /// Independent of the CI auto-disable: when the `CI` env var is set,
    /// `launch` still auto-adds `--no-sandbox` + `--disable-dev-shm-usage`
    /// (the GitHub-Actions / Docker containers run as root, where the
    /// user-namespace sandbox refuses to start). Calling `sandbox(false)`
    /// just opts in explicitly outside CI.
    ///
    /// Disabling the sandbox weakens Chrome's process isolation — only do so
    /// in trusted, throwaway environments (containers, ephemeral VMs).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder().sandbox(false);
    /// ```
    #[must_use]
    pub fn sandbox(mut self, on: bool) -> Self {
        self.sandbox = Some(on);
        self
    }

    /// Pick which browser [`Channel`] to discover at launch (default:
    /// [`Channel::Auto`]).
    ///
    /// Selects the per-OS candidate-path table used to locate the browser
    /// binary — e.g. [`Channel::Brave`] / [`Channel::Edge`] resolve their
    /// real install locations. [`BrowserBuilder::executable`] still overrides
    /// channel discovery entirely; when an explicit executable is set the
    /// channel is ignored.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zendriver::Channel;
    /// let builder = zendriver::Browser::builder().channel(Channel::Brave);
    /// ```
    #[must_use]
    pub fn channel(mut self, channel: Channel) -> Self {
        self.channel = channel;
        self
    }

    /// Side-load a single unpacked extension directory (or a `.crx` file).
    ///
    /// Extensions accumulate; call this once per extension or use
    /// [`BrowserBuilder::extensions`] for a batch. At launch the resolved
    /// directories are passed via `--load-extension=<dir1,dir2,…>`, paired with
    /// `--disable-extensions-except=<dir1,dir2,…>` and
    /// `--enable-unsafe-extension-debugging`. zendriver also forces the
    /// `DisableLoadExtensionCommandLineSwitch` feature off regardless of the
    /// active [`StealthProfile`] — Chrome 136+ otherwise ignores
    /// `--load-extension` entirely (see the type-level note on this builder).
    ///
    /// A `.crx` path is unzipped into a temporary directory that lives for the
    /// [`Browser`]'s lifetime; directory paths are used as-is. Mixing the two
    /// is fine.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder()
    ///     .add_extension("/path/to/unpacked-ext")
    ///     .add_extension("/path/to/packed.crx");
    /// ```
    #[must_use]
    pub fn add_extension(mut self, path: impl Into<PathBuf>) -> Self {
        self.extensions.push(path.into());
        self
    }

    /// Side-load several extensions at once.
    ///
    /// Equivalent to calling [`BrowserBuilder::add_extension`] for each entry;
    /// see it for the flag set and `.crx` handling.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use std::path::PathBuf;
    /// let builder = zendriver::Browser::builder().extensions([
    ///     PathBuf::from("/ext/one"),
    ///     PathBuf::from("/ext/two"),
    /// ]);
    /// ```
    #[must_use]
    pub fn extensions(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
        self.extensions.extend(paths);
        self
    }

    /// Relax Chrome's web-security + site-isolation guards (default: **off**).
    ///
    /// When `on`, `build_flags` appends `--disable-web-security` (drops the
    /// same-origin policy for cross-origin `fetch` / DOM access) and
    /// `--disable-site-isolation-trials` (so cross-origin frames stay
    /// in-process and are reachable from the parent). Mirrors nodriver's
    /// `start(expert=True)` / zendriver-py's expert launch.
    ///
    /// This is **flags only** — it does not touch the JS environment. For the
    /// closed-shadow-root walk that nodriver's expert mode also enables, opt in
    /// separately via [`BrowserBuilder::force_open_shadow_roots`].
    ///
    /// Disabling web security weakens the browser's origin isolation; use only
    /// in trusted, throwaway automation contexts.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder().expert(true);
    /// ```
    #[must_use]
    pub fn expert(mut self, on: bool) -> Self {
        self.expert = on;
        self
    }

    /// Force every `Element.prototype.attachShadow` call to open mode so closed
    /// shadow roots become walkable (default: **off**).
    ///
    /// When `on`, a small built-in [`TargetObserver`] injects a
    /// `Page.addScriptToEvaluateOnNewDocument` patch into every new target that
    /// rewrites the `attachShadow` init dict to `{ mode: "open" }` (other init
    /// keys are preserved). The patched element's `shadowRoot` is then
    /// reachable from automation even when the page requested a closed root.
    /// This runs independently of the [`StealthProfile`] — it works with
    /// stealth off and does **not** become part of the spoofed fingerprint
    /// bundle.
    ///
    /// # Detectability
    ///
    /// **This patch is detectable.** A page can notice that `attachShadow`
    /// always yields an open root (e.g. by calling it with `{ mode: "closed" }`
    /// and observing a non-null `.shadowRoot`), so anti-bot scripts can use it
    /// as a signal. Enable it only when you genuinely need to traverse closed
    /// shadow roots (some challenge widgets), and prefer leaving it off for
    /// stealth-sensitive workloads.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder().force_open_shadow_roots(true);
    /// ```
    #[must_use]
    pub fn force_open_shadow_roots(mut self, on: bool) -> Self {
        self.force_open_shadow_roots = on;
        self
    }

    /// Append a single command-line flag to the Chrome launch argv.
    ///
    /// Flags accumulate; later calls do NOT replace earlier ones.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder()
    ///     .arg("--proxy-server=http://localhost:8080")
    ///     .arg("--lang=en-US");
    /// ```
    #[must_use]
    pub fn arg(mut self, flag: impl Into<String>) -> Self {
        self.extra_args.push(flag.into());
        self
    }

    /// Append multiple command-line flags to the Chrome launch argv.
    ///
    /// Equivalent to calling [`BrowserBuilder::arg`] for each entry.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder().args([
    ///     "--lang=en-US".to_string(),
    ///     "--window-size=1280,800".to_string(),
    /// ]);
    /// ```
    #[must_use]
    pub fn args(mut self, flags: impl IntoIterator<Item = String>) -> Self {
        self.extra_args.extend(flags);
        self
    }

    /// Set a Chrome profile preference, e.g.
    /// `.preference("profile.password_manager_enabled", serde_json::json!(false))`.
    ///
    /// Merged into `<user_data_dir>/Default/Preferences` at launch (dotted keys
    /// expand to nested objects). User preferences override the default
    /// popup-suppression set. For a *user-supplied* `user_data_dir`, ONLY your
    /// explicit preferences are written (the defaults are not, to avoid mutating
    /// a real profile); for a port-created temp profile, defaults + yours are
    /// written.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder()
    ///     .preference("profile.password_manager_enabled", serde_json::json!(false))
    ///     .launch()
    ///     .await?;
    /// # let _ = browser;
    /// # Ok(()) }
    /// ```
    #[must_use]
    pub fn preference(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.preferences.push((key.into(), value));
        self
    }

    /// Override the default [`StealthProfile::native`] profile.
    ///
    /// Pass [`StealthProfile::off`](zendriver_stealth::StealthProfile::off) to
    /// disable stealth entirely or
    /// [`StealthProfile::spoofed`](zendriver_stealth::StealthProfile::spoofed)
    /// for the full anti-detection set.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zendriver::stealth::StealthProfile;
    /// let builder = zendriver::Browser::builder().stealth(StealthProfile::spoofed());
    /// ```
    #[must_use]
    pub fn stealth(mut self, profile: StealthProfile) -> Self {
        self.stealth = Some(profile);
        self
    }

    /// Set the base fingerprint [`Persona`] driving the spoofed-mode surface
    /// patches (canvas/WebGL/audio/fonts/clientRects/WebRTC/hardware).
    ///
    /// When unset, [`Persona::system`] (host-probed) is used. Combine with
    /// [`BrowserBuilder::persona_overlay`] for field-wise tweaks and
    /// [`BrowserBuilder::surface`] for per-surface render-strategy overrides;
    /// [`BrowserBuilder::resolved_persona`] returns the effective result.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zendriver::Persona;
    /// let builder = zendriver::Browser::builder()
    ///     .persona(Persona::builder().device_memory_gb(16).build());
    /// ```
    #[must_use]
    pub fn persona(mut self, persona: Persona) -> Self {
        self.persona = Some(persona);
        self
    }

    /// Overlay a partial [`Persona`] on top of the base persona. Every `Some`
    /// field in the overlay wins; `None` inherits from the base.
    ///
    /// Handy for layering a small JSON tweak (e.g. just a timezone) over a
    /// host-probed or pool-sampled base persona.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let builder = zendriver::Browser::builder()
    ///     .persona_overlay(r#"{"timezone":"UTC"}"#.parse().unwrap());
    /// ```
    #[must_use]
    pub fn persona_overlay(mut self, overlay: Persona) -> Self {
        self.persona_overlay = Some(overlay);
        self
    }

    /// Set a coherent `locale` + `languages` derived from a country code
    /// (ISO 3166-1 alpha-2, e.g. `"US"`, `"de"`). Layered as a persona overlay,
    /// so it composes with `.persona(..)` and is overridden by an explicit
    /// `.persona_overlay(..)` locale. An invalid/unknown country is ignored
    /// (logged) — never locks a value.
    #[cfg(feature = "geo")]
    #[must_use]
    pub fn geo_locale(mut self, country: impl TryInto<zendriver_stealth::geo::Country>) -> Self {
        match country.try_into() {
            Ok(c) => {
                let derived = zendriver_stealth::geo::persona(c);
                self.persona_overlay = Some(match self.persona_overlay.take() {
                    Some(existing) => existing.overlay(derived),
                    None => derived,
                });
            }
            Err(_) => tracing::warn!("geo_locale: invalid country code; ignoring"),
        }
        self
    }

    /// Override a single fingerprint [`Surface`]'s render [`Strategy`].
    ///
    /// Applied last, on top of the resolved persona + overlay. Repeatable —
    /// each call layers another surface override.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zendriver::{Strategy, Surface};
    /// let builder = zendriver::Browser::builder()
    ///     .surface(Surface::Webrtc, Strategy::Native);
    /// ```
    #[must_use]
    pub fn surface(mut self, surface: Surface, strategy: Strategy) -> Self {
        self.surface_overrides.push((surface, strategy));
        self
    }

    /// Compute the effective [`Persona`] this builder will hand to the stealth
    /// observer.
    ///
    /// Resolution order: base persona ([`Persona::system`] when unset) →
    /// [`persona_overlay`](BrowserBuilder::persona_overlay) (field-wise merge) →
    /// each [`surface`](BrowserBuilder::surface) override → a seed persisted
    /// alongside [`user_data_dir`](BrowserBuilder::user_data_dir) when the
    /// resolved persona has no explicit seed.
    ///
    /// Callable before launch — it does not require a live browser.
    #[must_use]
    pub fn resolved_persona(&self) -> Persona {
        // Did the caller pin a seed explicitly (via `.persona` or
        // `.persona_overlay`)? Capture this BEFORE the `system()` fallback,
        // which injects a fresh random seed of its own — an explicit seed must
        // win over the `user_data_dir`-persisted one below.
        let explicit_seed = self
            .persona
            .as_ref()
            .and_then(|p| p.seed)
            .or_else(|| self.persona_overlay.as_ref().and_then(|p| p.seed));

        let mut persona = self.persona.clone().unwrap_or_else(Persona::system);
        if let Some(overlay) = &self.persona_overlay {
            persona = persona.overlay(overlay.clone());
        }
        for (surface, strategy) in &self.surface_overrides {
            persona.apply_surface_override(*surface, *strategy);
        }

        // Seed persistence: when the caller did not pin a seed but a
        // `user_data_dir` is set, the seed is read from (or written to) a file
        // inside that dir so the same profile yields a stable fingerprint
        // across runs. This overrides the ephemeral random seed that
        // `Persona::system()` injects. Without a `user_data_dir`, the random
        // seed stands (fresh identity per launch).
        if explicit_seed.is_none() {
            if let Some(dir) = &self.user_data_dir {
                persona.seed = Some(persisted_seed(dir));
            }
        }

        persona
    }

    /// Register an additional [`TargetObserver`].
    ///
    /// Observers fire on each new attached page target. The stealth observer
    /// (if any) is added before user observers; user observers run in the
    /// order they were registered.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use std::sync::Arc;
    /// # use zendriver_transport::TargetObserver;
    /// # fn ex(my_obs: Arc<dyn TargetObserver>) {
    /// let builder = zendriver::Browser::builder().observer(my_obs);
    /// # }
    /// ```
    #[must_use]
    pub fn observer(mut self, obs: Arc<dyn TargetObserver>) -> Self {
        self.extra_observers.push(obs);
        self
    }

    /// Compute the full argv that would be passed to Chrome. Exposed to
    /// tests + snapshots; called internally by `launch`.
    pub(crate) fn build_flags(&self, user_data_dir: &Path) -> Vec<String> {
        let mut v = Vec::with_capacity(10 + self.extra_args.len());
        v.push("--remote-debugging-port=0".to_string());
        v.push(format!("--user-data-dir={}", user_data_dir.display()));
        v.push("--no-first-run".to_string());
        v.push("--no-default-browser-check".to_string());
        // Suppress the Chrome "Save password?" / autofill bubbles + onboarding
        // popups that otherwise hijack focus inside automated runs.
        // See cdpdriver/zendriver#13.
        v.push("--password-store=basic".to_string());
        v.push("--disable-save-password-bubble".to_string());
        // Base disable-features set. When extensions are requested we MUST also
        // turn off `DisableLoadExtensionCommandLineSwitch`, or Chrome 136+
        // silently ignores `--load-extension`. The stealth profiles carry that
        // feature in their own `--disable-features=IsolateOrigins,…` line, but
        // an Off profile would otherwise miss it, so merge it into the base
        // line here — Chrome unions every `--disable-features` occurrence, so
        // the redundancy under a stealth profile is harmless.
        if self.extensions.is_empty() {
            v.push(
                "--disable-features=PasswordManagerOnboarding,AutofillServerCommunication"
                    .to_string(),
            );
        } else {
            v.push(
                "--disable-features=PasswordManagerOnboarding,AutofillServerCommunication,DisableLoadExtensionCommandLineSwitch"
                    .to_string(),
            );
        }
        if self.headless.unwrap_or(true) {
            v.push("--headless=new".to_string());
            v.push("--disable-gpu".to_string());
        }
        // Expert mode: relax web-security + site isolation. Emitted only when
        // `expert(true)` so the default flag set / snapshots are unchanged.
        if self.expert {
            v.push("--disable-web-security".to_string());
            v.push("--disable-site-isolation-trials".to_string());
        }
        // Extension side-loading flags. `self.extensions` holds already-resolved
        // directories at this point (`launch` unzips any `.crx` into tempdirs
        // and rewrites the list before calling `build_flags`). Skipped entirely
        // when no extensions are configured so the default argv is untouched.
        if !self.extensions.is_empty() {
            let joined = self
                .extensions
                .iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join(",");
            v.push(format!("--load-extension={joined}"));
            v.push(format!("--disable-extensions-except={joined}"));
            v.push("--enable-unsafe-extension-debugging".to_string());
        }
        // C4 dedicated flags. Emitted only when explicitly configured so the
        // default-builder flag set (and its snapshots) is unchanged. Placed
        // before user `extra_args` so caller-supplied flags still come last.
        if let Some(lang) = self.lang.as_ref() {
            v.push(format!("--lang={lang}"));
        }
        if let Some(ua) = self.user_agent.as_ref() {
            v.push(format!("--user-agent={ua}"));
        }
        // Sandbox off → --no-sandbox. Default (None / Some(true)) emits
        // nothing; the CI auto-disable is handled separately in `launch`.
        // NOTE: root-uid (euid 0) auto-disable is intentionally NOT done here
        // — that needs a `geteuid` syscall (no std API) and we decline to add
        // a `rustix` / `unsafe libc` dependency for it. Callers running as
        // root should opt in explicitly with `.sandbox(false)`.
        if self.sandbox == Some(false) {
            v.push("--no-sandbox".to_string());
        }
        v.extend(self.extra_args.iter().cloned());
        // Start the initial tab on `about:blank` instead of Chrome's default
        // New Tab Page. The NTP (`chrome://new-tab-page`) issues its own
        // network requests — realbox icons plus, on a fresh user-data-dir,
        // external Google fetches (logo/doodle, OneGoogle, suggest, background
        // collections). Those land on the *main tab's* CDP session, so they
        // pollute the in-flight set that [`Tab::wait_for_idle`] watches; on a
        // network-restricted host (e.g. CI with no outbound egress) they never
        // complete, and the first `wait_for_idle` after launch hangs until its
        // timeout. A blank start page issues zero requests, so idle detection
        // sees only the caller's own navigation traffic. Every mainstream
        // driver (Puppeteer, Playwright, nodriver) starts on `about:blank` for
        // the same reason.
        //
        // Emitted as the final positional argument (a bare URL, not a flag),
        // and skipped when the caller already supplied their own positional
        // start URL via `.arg`/`.args` — an explicit start page still wins.
        if !self.extra_args.iter().any(|a| !a.starts_with('-')) {
            v.push("about:blank".to_string());
        }
        v
    }

    /// Build the combined [`HostMatcher`] from all configured sources, or
    /// `None` if nothing was requested. Called once at launch.
    #[cfg(feature = "tracker-blocking")]
    async fn build_tracker_matcher(
        &self,
    ) -> Result<Option<std::sync::Arc<crate::HostMatcher>>, ZendriverError> {
        let mut domains: Vec<String> = Vec::new();
        if self.block_trackers {
            domains.extend(crate::tracker::bundled_hosts());
        }
        domains.extend(self.tracker_blocklist_domains.iter().cloned());
        for path in &self.tracker_blocklist_files {
            let text = std::fs::read_to_string(path)?; // -> ZendriverError::Io
            domains.extend(crate::tracker::parse_blocklist(&text));
        }
        for url in &self.tracker_blocklist_urls {
            let hosts = crate::tracker::load_or_download_blocklist(url).await?; // -> Io
            domains.extend(hosts);
        }
        if domains.is_empty() {
            return Ok(None);
        }
        Ok(Some(std::sync::Arc::new(crate::HostMatcher::new(domains))))
    }
}

/// A running Chrome instance under zendriver control.
///
/// `Browser` is `Clone` (cheap — wraps an `Arc`) and `Send + Sync`, so the
/// same handle can be passed across `tokio::spawn` boundaries. Dropping
/// the last clone shuts down the transport and terminates Chrome via
/// `kill_on_drop` (for a graceful SIGTERM-then-SIGKILL teardown call
/// [`Browser::close`] explicitly).
///
/// Build one via [`Browser::builder`].
#[derive(Clone, Debug)]
pub struct Browser {
    pub(crate) inner: Arc<BrowserInner>,
}

#[derive(Debug)]
pub(crate) struct BrowserInner {
    pub(crate) conn: Connection,
    pub(crate) main_tab: Tab,
    pub(crate) child: tokio::sync::Mutex<Option<Child>>,
    pub(crate) _user_data: Option<TempDir>,
    /// Tempdirs holding `.crx` extensions unzipped at launch. Held here so the
    /// extracted unpacked directories outlive the Chrome process that was
    /// pointed at them via `--load-extension`; dropped with the [`Browser`].
    /// Empty when no `.crx` extensions were configured.
    pub(crate) _extension_dirs: Vec<TempDir>,
    /// Whether this handle owns the underlying Chrome process. `true` for a
    /// browser produced by [`BrowserBuilder::launch`] (we spawned Chrome, so
    /// `close()` / `Drop` terminate it); `false` for one produced by
    /// [`BrowserBuilder::connect`] (we attached to an already-running debug
    /// session and must leave the process alone — `close()` only shuts down
    /// the transport, and no `Child` is held so `kill_on_drop` never fires).
    pub(crate) owns_process: bool,
    /// Cached `InputProfile` from the active `StealthProfile` (or
    /// `InputProfile::native` when stealth is off). `Browser::new_tab` and
    /// the [`TabRegistrar`] observer read this to build a fresh per-Tab
    /// [`InputController`] for each new tab without re-resolving the
    /// stealth profile.
    ///
    /// Currently consumed only by the [`TabRegistrar`] (via the clone
    /// stashed inside the registrar at construction time); a direct
    /// `Browser::new_tab` path will read this field once T3 lands, so
    /// `dead_code` is suppressed in the interim.
    #[allow(dead_code)]
    pub(crate) stealth_input_profile: zendriver_stealth::InputProfile,
    /// Browser-wide tab registry keyed by `sessionId`. Populated by the
    /// [`TabRegistrar`] observer on `Target.attachedToTarget` (and the
    /// initial main tab, inserted manually after construction); pruned on
    /// `Target.detachedFromTarget`. Used by `Browser::new_tab` to discover
    /// the [`Tab`] handle for a freshly-created page target and by
    /// `Browser::tabs` / `Browser::tab_count` for snapshot reads.
    pub(crate) tabs: tokio::sync::RwLock<HashMap<String, Tab>>,
    /// `host:port` of the remote-debugging endpoint Chrome was launched with,
    /// parsed from the `DevTools listening on ws://HOST:PORT/...` stderr line
    /// at launch. `None` for test-constructed browsers that never launched a
    /// real Chrome. Consumed by [`Tab::inspector_url`] (reached via the Tab's
    /// `Weak<BrowserInner>`) to compose the DevTools front-end URL.
    pub(crate) debug_host_port: Option<String>,
    /// Full `ws://HOST:PORT/devtools/browser/<id>` endpoint Chrome was
    /// launched with (or attached to). This browser-level endpoint survives as
    /// long as the Chrome process lives — even across a dropped socket — so
    /// [`Browser::reconnect`] re-dials it to re-establish the transport.
    /// `None` for test-constructed browsers that never dialed a real Chrome
    /// (reconnect is then unavailable and returns an error).
    pub(crate) ws_url: Option<String>,
    /// Fires every time the [`TabRegistrar`] observer mutates [`Self::tabs`]
    /// (insert on attach, remove on detach). [`Browser::new_tab_at`] waits
    /// on this in lieu of the previous 50ms polling loop — it arms the
    /// notification before reading the map so a fire that lands between
    /// the read and the wait is still delivered.
    pub(crate) tabs_changed: tokio::sync::Notify,
    /// Optional RAII guard for the proxy-auth interception actor spawned in
    /// [`BrowserBuilder::launch`] when `proxy_auth` is set. Held here so
    /// the actor lives for the entire `Browser` lifetime; on `Browser` drop
    /// the handle drops and cancels the actor cleanly. See
    /// cdpdriver/zendriver#208.
    #[cfg(feature = "interception")]
    #[allow(dead_code)]
    pub(crate) proxy_auth_handle: std::sync::OnceLock<zendriver_interception::InterceptHandle>,
    /// Combined tracker/fingerprinter [`HostMatcher`] (bundled + custom),
    /// built once at launch. `None` when blocking is not configured. Read by
    /// the [`TabRegistrar`] to install a `BlockHosts` interception on each new
    /// page tab.
    #[cfg(feature = "tracker-blocking")]
    pub(crate) tracker_matcher: Option<std::sync::Arc<crate::HostMatcher>>,
    /// Live tracker-blocking interception handles keyed by `sessionId`
    /// (main tab + each page tab). Inserted on attach, removed on detach;
    /// dropping a handle stops that tab's actor. Held here so the actors live
    /// as long as the browser.
    #[cfg(feature = "tracker-blocking")]
    pub(crate) tracker_handles:
        tokio::sync::Mutex<HashMap<String, zendriver_interception::InterceptHandle>>,
}

impl BrowserInner {
    /// Wraps `Target.disposeBrowserContext`, the CDP command that destroys
    /// an incognito-style [browser context][1] previously created via
    /// `Target.createBrowserContext`. Sent at browser scope (no
    /// `sessionId`).
    ///
    /// Used by [`crate::BrowserContext`]'s `Drop` impl to free its backing
    /// context when the handle goes out of scope.
    ///
    /// [1]: https://chromedevtools.github.io/devtools-protocol/tot/Target/#method-disposeBrowserContext
    pub(crate) async fn dispose_browser_context(&self, id: &str) -> Result<(), ZendriverError> {
        self.conn
            .call_raw(
                "Target.disposeBrowserContext",
                json!({ "browserContextId": id }),
                None,
            )
            .await?;
        Ok(())
    }
}

/// Test-only helper that wraps [`test_only_inner_from_conn`] in a real
/// [`Browser`] handle. Used by inline unit tests that need to exercise
/// `Browser`-level methods (e.g. `create_browser_context_with`) without
/// launching Chrome.
#[cfg(test)]
pub(crate) fn test_only_browser_from_conn(conn: Connection) -> Browser {
    Browser {
        inner: test_only_inner_from_conn(conn),
    }
}

/// Test-only helper that constructs a minimal [`BrowserInner`] backed by a
/// caller-supplied [`Connection`] (typically the consumer side of a
/// [`zendriver_transport::testing::MockConnection`] pair). Mirrors the
/// shape `launch` produces post-step-12: a main tab keyed under `"S1"` /
/// target id `"T1"` in the registry.
///
/// Used by inline unit tests that need to exercise [`BrowserInner`]
/// methods without launching Chrome. Subsequent tasks in this series
/// (per-context proxy support) reuse the same helper.
#[cfg(test)]
pub(crate) fn test_only_inner_from_conn(conn: Connection) -> Arc<BrowserInner> {
    let input_profile = zendriver_stealth::InputProfile::native();
    Arc::new_cyclic(|weak: &std::sync::Weak<BrowserInner>| {
        let main_session = SessionHandle::new(conn.clone(), "S1");
        let main_input = InputController::new(input_profile.clone());
        let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
        let mut map = HashMap::new();
        map.insert("S1".to_string(), main_tab.clone());
        BrowserInner {
            conn,
            main_tab,
            child: tokio::sync::Mutex::new(None),
            _user_data: None,
            _extension_dirs: Vec::new(),
            owns_process: false,
            stealth_input_profile: input_profile,
            tabs: tokio::sync::RwLock::new(map),
            debug_host_port: None,
            ws_url: None,
            tabs_changed: tokio::sync::Notify::new(),
            #[cfg(feature = "interception")]
            proxy_auth_handle: std::sync::OnceLock::new(),
            #[cfg(feature = "tracker-blocking")]
            tracker_matcher: None,
            #[cfg(feature = "tracker-blocking")]
            tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
        }
    })
}

/// [`TargetObserver`] that maintains [`BrowserInner::tabs`] in step with
/// CDP target lifecycle events.
///
/// On `Target.attachedToTarget` with `target_info.kind == "page"`, it builds
/// a fresh [`Tab`] for the new session (with its own [`InputController`]
/// seeded from the cached [`zendriver_stealth::InputProfile`]) and inserts
/// it into the registry. On `Target.detachedFromTarget`, the matching entry
/// is removed.
///
/// The observer holds a [`Weak`] reference to [`BrowserInner`] so the
/// observer chain does not extend the browser's lifetime — if the browser is
/// dropped before a target event arrives, the upgrade fails silently and
/// the event is ignored. The weak ref is wired in via [`OnceLock::set`]
/// after the surrounding [`Arc::new_cyclic`] resolves; before that point
/// the registrar is constructed empty.
///
/// Registered AFTER [`StealthObserver`] in the observer chain so stealth
/// patches apply before any user code sees the new tab.
pub(crate) struct TabRegistrar {
    browser: OnceLock<Weak<BrowserInner>>,
    input_profile: zendriver_stealth::InputProfile,
}

impl TabRegistrar {
    fn new(input_profile: zendriver_stealth::InputProfile) -> Self {
        Self {
            browser: OnceLock::new(),
            input_profile,
        }
    }

    /// Wire the weak [`BrowserInner`] ref. Called once after
    /// [`Arc::new_cyclic`] resolves; subsequent calls are silently ignored.
    fn set_browser(&self, browser: Weak<BrowserInner>) {
        let _ = self.browser.set(browser);
    }
}

#[async_trait::async_trait]
impl TargetObserver for TabRegistrar {
    fn name(&self) -> &'static str {
        "tab-registrar"
    }

    async fn on_target_attached(&self, session: PausedSession<'_>) -> Result<(), ObserverError> {
        let Some(weak) = self.browser.get() else {
            // Registrar wired into observer chain before `set_browser` ran.
            // Should not happen in practice because launch wires the weak
            // before any observer can fire — log + bail gracefully if it
            // ever does.
            warn!("TabRegistrar fired before browser weak ref was wired; skipping");
            return Ok(());
        };
        let Some(browser) = weak.upgrade() else {
            // Browser dropped between event arrival and observer body —
            // nothing to register against.
            return Ok(());
        };

        match session.target_info.kind.as_str() {
            "iframe" => {
                // Out-of-process iframe: register a Frame under the parent
                // tab's frames map. The OOPIF carries a distinct child
                // session; the helper resolves the parent tab by walking
                // the tabs registry for a matching frame_id (preferring
                // `opener_frame_id` when present, falling back to
                // `target_id`).
                let conn = session.connection().clone();
                let new_session = SessionHandle::new(conn, session.session_id.to_string());
                crate::frame::oopif::register_oopif_frame(
                    &browser,
                    session.target_info,
                    new_session,
                )
                .await;
                Ok(())
            }
            "page" => {
                // Skip Chrome-internal pages (chrome://newtab/ that Chrome
                // auto-opens when the last user tab closes, devtools://, etc).
                // These aren't pages the caller drove zendriver to create and
                // would inflate `tab_count` / `tabs()` with unwanted entries.
                let url = &session.target_info.url;
                if url.starts_with("chrome://")
                    || url.starts_with("devtools://")
                    || url.starts_with("chrome-extension://")
                    || url.starts_with("chrome-untrusted://")
                {
                    return Ok(());
                }
                let conn = session.connection().clone();
                let new_session = SessionHandle::new(conn, session.session_id.to_string());
                // Clone the session before it is moved into Tab::new so the
                // tracker-blocking install can use it afterwards.
                #[cfg(feature = "tracker-blocking")]
                let new_session_for_tracker = new_session.clone();
                let input = InputController::new(self.input_profile.clone());
                let weak_inner = Arc::downgrade(&browser);
                let tab = Tab::new(
                    new_session,
                    weak_inner,
                    input,
                    session.target_info.target_id.clone(),
                );

                // Dedupe by `target_id`: if `flatten: true` re-fires
                // `attachedToTarget` for the same target under a different
                // sessionId (observed on `--headless=new`), the old entry
                // would otherwise linger and inflate `tab_count`.
                let target_id_str = session.target_info.target_id.clone();
                let mut tabs = browser.tabs.write().await;
                tabs.retain(|_, t| t.target_id() != target_id_str);
                tabs.insert(session.session_id.to_string(), tab);
                drop(tabs);
                // Wake any `new_tab_at` callers waiting on this insert.
                browser.tabs_changed.notify_waiters();

                // Tracker blocking: if configured, install a BlockHosts
                // interception on this new page tab's session and park the
                // handle (keyed by sessionId) so it lives with the browser.
                #[cfg(feature = "tracker-blocking")]
                if let Some(matcher) = browser.tracker_matcher.clone() {
                    let handle =
                        zendriver_interception::InterceptBuilder::new(&new_session_for_tracker)
                            .block_hosts(matcher)
                            .start();
                    browser
                        .tracker_handles
                        .lock()
                        .await
                        .insert(new_session_for_tracker.session_id().to_string(), handle);
                }

                Ok(())
            }
            _ => {
                // Workers / service workers / etc — out of scope for the
                // current registrar; ignored silently. Future P4 tasks
                // may add explicit handling.
                Ok(())
            }
        }
    }

    async fn on_target_detached(&self, session_id: &str) {
        let Some(weak) = self.browser.get() else {
            return;
        };
        let Some(browser) = weak.upgrade() else {
            return;
        };
        // Tab path first — if the detached session backs a Tab, remove it.
        // If it was an OOPIF (no matching tab), fall through to the OOPIF
        // sweep which walks each tab's frames map.
        let removed_tab = browser.tabs.write().await.remove(session_id).is_some();
        if removed_tab {
            // Mirror the insert-side notify so any future watchers (e.g.
            // a `wait_for_tab_count` helper) can listen on the same channel.
            browser.tabs_changed.notify_waiters();
        } else {
            let _ = crate::frame::oopif::deregister_oopif_frame(&browser, session_id).await;
        }
        // Drop any tracker-blocking handle for this session (stops its actor).
        #[cfg(feature = "tracker-blocking")]
        {
            browser.tracker_handles.lock().await.remove(session_id);
        }
    }
}

const WS_ENDPOINT_TIMEOUT: Duration = Duration::from_secs(15);
const SHUTDOWN_GRACE: Duration = Duration::from_secs(5);
/// How long [`resolve_ws_from_http`] waits for the `/json/version` round-trip.
const JSON_VERSION_TIMEOUT: Duration = Duration::from_secs(10);

/// Inputs to [`finish_connect`] — the post-connect handshake shared by
/// [`BrowserBuilder::launch`] (spawn) and [`BrowserBuilder::connect`]
/// (attach). Bundled into a struct to keep the function signature readable
/// (clippy `too_many_arguments`) and to make the spawn-vs-attach differences
/// explicit at the call site.
pub(crate) struct FinishConnect {
    /// The freshly-established transport (already wired with the observer
    /// chain via `connect_with_observers`).
    pub(crate) conn: Connection,
    /// The tab registrar from the observer chain; its weak `BrowserInner`
    /// ref is wired here once the cyclic `Arc` resolves.
    pub(crate) registrar: Arc<TabRegistrar>,
    /// Per-tab input profile cached on `BrowserInner` for new-tab construction.
    pub(crate) input_profile: zendriver_stealth::InputProfile,
    /// Owned Chrome child process — `Some` for `launch`, `None` for `connect`.
    pub(crate) child: Option<Child>,
    /// Owned `user_data_dir` tempdir — `Some` only when `launch` allocated one.
    pub(crate) owned_tmp: Option<TempDir>,
    /// Tempdirs for any `.crx` extensions `launch` unzipped. Empty for
    /// `connect` (no process launched) and when no `.crx` was configured.
    pub(crate) extension_dirs: Vec<TempDir>,
    /// `host:port` of the debug endpoint, for [`Tab::inspector_url`].
    pub(crate) debug_host_port: Option<String>,
    /// Full `ws://…/devtools/browser/<id>` endpoint, retained on
    /// [`BrowserInner`] so [`Browser::reconnect`] can re-dial it.
    pub(crate) ws_url: Option<String>,
    /// Whether the resulting handle owns (and must terminate) the process.
    pub(crate) owns_process: bool,
    /// Combined tracker matcher built by `launch` (`None` for `connect` and
    /// when blocking is unconfigured). Stored on `BrowserInner` and installed
    /// on the main tab + future tabs.
    #[cfg(feature = "tracker-blocking")]
    pub(crate) tracker_matcher: Option<std::sync::Arc<crate::HostMatcher>>,
}

/// Run the post-connect CDP handshake and assemble [`BrowserInner`].
///
/// Shared by [`BrowserBuilder::launch`] and [`BrowserBuilder::connect`]: both
/// arrive here with a live [`Connection`] (observer chain already attached)
/// and need the same sequence — enable browser-scoped auto-attach, discover +
/// attach the main page target, build the self-referential `Arc<BrowserInner>`,
/// then backfill the registrar's weak ref and the main-tab registry entry.
///
/// The only spawn-vs-attach differences are carried in [`FinishConnect`]: the
/// owned `Child` / `TempDir` (present only for `launch`) and the
/// `owns_process` flag.
pub(crate) async fn finish_connect(
    args: FinishConnect,
) -> Result<Arc<BrowserInner>, ZendriverError> {
    let FinishConnect {
        conn,
        registrar,
        input_profile,
        child,
        owned_tmp,
        extension_dirs,
        debug_host_port,
        ws_url,
        owns_process,
        #[cfg(feature = "tracker-blocking")]
        tracker_matcher,
    } = args;

    // Enable auto-attach with debugger-pause BEFORE attaching to the initial
    // target. Sent at browser scope (no session_id) so it covers both the
    // initial target and any subsequently-opened pages/iframes.
    conn.call_raw(
        "Target.setAutoAttach",
        json!({
            "autoAttach": true,
            "waitForDebuggerOnStart": true,
            "flatten": true,
        }),
        None,
    )
    .await?;

    // Discover the initial target via Target.getTargets (prefer a page).
    let list = conn.call_raw("Target.getTargets", json!({}), None).await?;
    let target_id = list["targetInfos"]
        .as_array()
        .and_then(|arr| {
            arr.iter()
                .find(|t| t["type"] == "page")
                .or_else(|| arr.first())
        })
        .and_then(|t| t["targetId"].as_str())
        .ok_or_else(|| ZendriverError::Navigation("no initial target found".into()))?
        .to_string();

    // Attach to the initial target. This triggers `Target.attachedToTarget`
    // which the actor routes through observers (`on_target_attached`) and
    // then releases via `Runtime.runIfWaitingForDebugger`.
    //
    // The `TabRegistrar` observer (in the chain) will try to insert into
    // `BrowserInner.tabs` for the main tab too. That insertion is a no-op
    // because the weak ref isn't wired yet (`OnceLock` empty → observer warns
    // + skips). We re-insert the main tab manually below so the registry is
    // consistent post-connect.
    let attach = conn
        .call_raw(
            "Target.attachToTarget",
            json!({ "targetId": target_id, "flatten": true }),
            None,
        )
        .await?;
    let session_id = attach["sessionId"]
        .as_str()
        .ok_or_else(|| ZendriverError::Navigation("attach returned no sessionId".into()))?
        .to_string();

    // Wrap session in Tab; build BrowserInner via the canonical
    // `Arc::new_cyclic` self-referential pattern.
    let session_id_for_registry = session_id.clone();
    let target_id_for_main_tab = target_id.clone();
    let inner = Arc::new_cyclic(|weak: &std::sync::Weak<BrowserInner>| {
        let session = SessionHandle::new(conn.clone(), session_id);
        let main_tab_input = InputController::new(input_profile.clone());
        let main_tab = Tab::new(
            session,
            weak.clone(),
            main_tab_input,
            target_id_for_main_tab,
        );
        BrowserInner {
            conn,
            main_tab,
            child: tokio::sync::Mutex::new(child),
            _user_data: owned_tmp,
            _extension_dirs: extension_dirs,
            owns_process,
            stealth_input_profile: input_profile,
            tabs: tokio::sync::RwLock::new(HashMap::new()),
            debug_host_port,
            ws_url,
            tabs_changed: tokio::sync::Notify::new(),
            #[cfg(feature = "interception")]
            proxy_auth_handle: std::sync::OnceLock::new(),
            #[cfg(feature = "tracker-blocking")]
            tracker_matcher,
            #[cfg(feature = "tracker-blocking")]
            tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
        }
    });

    // Wire the registrar's weak ref + manually insert the main tab (it was
    // attached before the weak ref existed, so the observer bailed early).
    registrar.set_browser(Arc::downgrade(&inner));
    inner
        .tabs
        .write()
        .await
        .insert(session_id_for_registry, inner.main_tab.clone());

    Ok(inner)
}

/// Resolve a `webSocketDebuggerUrl` from a DevTools HTTP base by issuing a
/// minimal `GET {endpoint}/json/version` over a raw [`tokio::net::TcpStream`].
///
/// Hand-rolled (HTTP/1.0, read-until-close, split headers from body, parse the
/// JSON body) so the always-on dependency set does not grow an HTTP client —
/// `connect`'s `ws://` path needs no HTTP at all, and the `fetcher`-gated
/// `reqwest` must not leak into the default build. Mirrors nodriver /
/// zendriver-py, which read the same `webSocketDebuggerUrl` field.
///
/// # Errors
///
/// Returns [`BrowserError::DevtoolsParse`] when the endpoint is malformed, the
/// TCP round-trip fails / times out, the response has no body, or the JSON
/// lacks a string `webSocketDebuggerUrl`.
pub(crate) async fn resolve_ws_from_http(endpoint: &str) -> Result<String, ZendriverError> {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpStream;

    // Parse `scheme://host[:port]` → (host, port). Strip any trailing path.
    let after_scheme = endpoint
        .strip_prefix("http://")
        .or_else(|| endpoint.strip_prefix("https://"))
        .ok_or(BrowserError::DevtoolsParse)?;
    let authority = after_scheme
        .split('/')
        .next()
        .unwrap_or(after_scheme)
        .trim();
    if authority.is_empty() {
        return Err(BrowserError::DevtoolsParse.into());
    }
    // host:port split — default to 80 when no explicit port (DevTools is
    // typically explicit, e.g. 9222, but be lenient).
    let (host, port) = match authority.rsplit_once(':') {
        Some((h, p)) => (
            h,
            p.parse::<u16>().map_err(|_| BrowserError::DevtoolsParse)?,
        ),
        None => (authority, 80u16),
    };

    let body = timeout(JSON_VERSION_TIMEOUT, async {
        let mut stream = TcpStream::connect((host, port))
            .await
            .map_err(BrowserError::SpawnFailed)?;
        // HTTP/1.0 + Connection: close → server closes the socket after the
        // response, so a read-to-end cleanly delimits the message.
        let req = format!(
            "GET /json/version HTTP/1.0\r\nHost: {authority}\r\nAccept: application/json\r\nConnection: close\r\n\r\n"
        );
        stream
            .write_all(req.as_bytes())
            .await
            .map_err(BrowserError::SpawnFailed)?;
        stream.flush().await.map_err(BrowserError::SpawnFailed)?;
        let mut buf = Vec::new();
        stream
            .read_to_end(&mut buf)
            .await
            .map_err(BrowserError::SpawnFailed)?;
        Ok::<Vec<u8>, ZendriverError>(buf)
    })
    .await
    .map_err(|_| BrowserError::WsTimeout)??;

    parse_ws_from_json_version(&body)
}

/// Split an HTTP/1.x response into its body and parse the
/// `webSocketDebuggerUrl` field from the JSON.
///
/// Factored out of [`resolve_ws_from_http`] so the parse — the part most worth
/// asserting — is unit-testable without a socket. Splits on the first
/// `\r\n\r\n` (header/body boundary); if absent, treats the whole buffer as the
/// JSON body (lenient toward bodies returned without standard headers in
/// tests).
pub(crate) fn parse_ws_from_json_version(raw: &[u8]) -> Result<String, ZendriverError> {
    let text = String::from_utf8_lossy(raw);
    // Header/body split on the blank line; fall back to the whole buffer.
    let body = text
        .split_once("\r\n\r\n")
        .map(|(_, b)| b)
        .unwrap_or(&text)
        .trim();
    if body.is_empty() {
        return Err(BrowserError::DevtoolsParse.into());
    }
    let parsed: serde_json::Value =
        serde_json::from_str(body).map_err(|_| BrowserError::DevtoolsParse)?;
    parsed["webSocketDebuggerUrl"]
        .as_str()
        .map(|s| s.to_string())
        .ok_or_else(|| BrowserError::DevtoolsParse.into())
}

/// Resolve every entry in `extensions` to an unpacked-extension *directory*,
/// in place, returning the tempdirs that back any unzipped `.crx` archives.
///
/// `--load-extension` only accepts directories, so a `.crx` file is unzipped
/// into a fresh [`TempDir`] and the slot is rewritten to that directory.
/// Entries that are already directories pass through unchanged. The returned
/// tempdirs MUST be kept alive for as long as Chrome runs (they are parked on
/// [`BrowserInner`]); dropping one deletes the extracted extension out from
/// under the running browser.
///
/// A `.crx` is a ZIP with a short binary header (magic `Cr24` + version +
/// signature lengths) prepended; we locate the embedded ZIP by scanning for
/// the local-file-header magic (`PK\x03\x04`) and unzip from there, so both
/// CRX2 and CRX3 layouts work without parsing the header fields.
///
/// # Errors
///
/// Returns [`BrowserError::ExtensionLoad`] when a configured path does not
/// exist, when a `.crx` cannot be read / contains no ZIP payload / fails to
/// unzip, or when an entry is neither a directory nor a `.crx` file.
async fn resolve_extension_dirs(
    extensions: &mut [PathBuf],
) -> Result<Vec<TempDir>, ZendriverError> {
    let mut tempdirs = Vec::new();
    for slot in extensions.iter_mut() {
        if slot.is_dir() {
            continue;
        }
        let is_crx = slot
            .extension()
            .is_some_and(|e| e.eq_ignore_ascii_case("crx"));
        if !is_crx {
            return Err(BrowserError::ExtensionLoad {
                path: slot.clone(),
                reason: if slot.exists() {
                    "extension path is neither a directory nor a .crx file".into()
                } else {
                    "extension path does not exist".into()
                },
            }
            .into());
        }
        let (dir, td) = unzip_crx(slot).await?;
        *slot = dir;
        tempdirs.push(td);
    }
    Ok(tempdirs)
}

/// Unzip a single `.crx` at `crx_path` into a fresh [`TempDir`], returning the
/// extracted directory path alongside the owning tempdir handle.
///
/// The blocking ZIP walk runs on [`tokio::task::spawn_blocking`]. Path safety
/// mirrors the fetcher's extractor: entries with absolute / parent-traversal
/// paths and (on Unix) symlink entries are rejected so a hostile `.crx` can't
/// escape the tempdir.
async fn unzip_crx(crx_path: &Path) -> Result<(PathBuf, TempDir), ZendriverError> {
    let crx_path = crx_path.to_path_buf();
    let td = tempfile::Builder::new()
        .prefix("zendriver-ext-")
        .tempdir()
        .map_err(BrowserError::SpawnFailed)?;
    let dest = td.path().to_path_buf();
    let dest_for_blocking = dest.clone();
    let crx_for_blocking = crx_path.clone();

    tokio::task::spawn_blocking(move || unzip_crx_blocking(&crx_for_blocking, &dest_for_blocking))
        .await
        .map_err(|e| BrowserError::ExtensionLoad {
            path: crx_path.clone(),
            reason: format!("unzip task join error: {e}"),
        })??;

    Ok((dest, td))
}

/// Synchronous `.crx` → directory unzip body (runs on a blocking thread).
fn unzip_crx_blocking(crx_path: &Path, dest_dir: &Path) -> Result<(), ZendriverError> {
    use std::io::Cursor;

    let bytes = std::fs::read(crx_path).map_err(|e| BrowserError::ExtensionLoad {
        path: crx_path.to_path_buf(),
        reason: format!("read failed: {e}"),
    })?;
    // A `.crx` prepends a binary header before the ZIP. Find the first ZIP
    // local-file-header signature (`PK\x03\x04`) and treat everything from
    // there as the archive. A bare `.zip` (no CRX header) also works since the
    // signature is at offset 0.
    let zip_start = bytes
        .windows(4)
        .position(|w| w == [0x50, 0x4B, 0x03, 0x04])
        .ok_or_else(|| BrowserError::ExtensionLoad {
            path: crx_path.to_path_buf(),
            reason: "no ZIP payload found in .crx".into(),
        })?;
    let mut archive = zip::ZipArchive::new(Cursor::new(&bytes[zip_start..])).map_err(|e| {
        BrowserError::ExtensionLoad {
            path: crx_path.to_path_buf(),
            reason: format!("not a valid ZIP: {e}"),
        }
    })?;

    for i in 0..archive.len() {
        let mut entry = archive
            .by_index(i)
            .map_err(|e| BrowserError::ExtensionLoad {
                path: crx_path.to_path_buf(),
                reason: format!("zip entry {i}: {e}"),
            })?;
        // Reject unsafe paths (absolute / parent-traversal).
        let Some(rel_path) = entry.enclosed_name() else {
            return Err(BrowserError::ExtensionLoad {
                path: crx_path.to_path_buf(),
                reason: format!("zip entry has unsafe path: {}", entry.name()),
            }
            .into());
        };
        // Refuse symlink entries — the primary zip-slip follow-on vector.
        #[cfg(unix)]
        if let Some(mode) = entry.unix_mode() {
            const S_IFMT: u32 = 0o170_000;
            const S_IFLNK: u32 = 0o120_000;
            if mode & S_IFMT == S_IFLNK {
                return Err(BrowserError::ExtensionLoad {
                    path: crx_path.to_path_buf(),
                    reason: format!("zip entry {rel_path:?} is a symlink; refusing"),
                }
                .into());
            }
        }
        let out_path = dest_dir.join(&rel_path);
        if entry.is_dir() {
            std::fs::create_dir_all(&out_path).map_err(|e| BrowserError::ExtensionLoad {
                path: crx_path.to_path_buf(),
                reason: format!("mkdir {out_path:?}: {e}"),
            })?;
            continue;
        }
        if let Some(parent) = out_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| BrowserError::ExtensionLoad {
                path: crx_path.to_path_buf(),
                reason: format!("mkdir {parent:?}: {e}"),
            })?;
        }
        let mut out =
            std::fs::File::create(&out_path).map_err(|e| BrowserError::ExtensionLoad {
                path: crx_path.to_path_buf(),
                reason: format!("create {out_path:?}: {e}"),
            })?;
        std::io::copy(&mut entry, &mut out).map_err(|e| BrowserError::ExtensionLoad {
            path: crx_path.to_path_buf(),
            reason: format!("write {out_path:?}: {e}"),
        })?;
    }
    Ok(())
}

impl BrowserBuilder {
    /// Spawn Chrome and attach. Returns once the main tab is bound.
    ///
    /// When a [`StealthProfile`] is set (the default), this:
    /// 1. Resolves a [`zendriver_stealth::Fingerprint`] from the resolved
    ///    Chrome executable.
    /// 2. Prepends the profile's [`StealthObserver`] to the observer chain.
    /// 3. Appends the profile's stealth flags to the launch argv.
    /// 4. Sends `Target.setAutoAttach { waitForDebuggerOnStart: true }` at
    ///    browser scope so the actor can route pauses through observers
    ///    before any page script runs.
    ///
    /// # Errors
    ///
    /// Returns [`ZendriverError::Browser`] when Chrome can't be discovered
    /// or spawned, [`ZendriverError::Stealth`] when fingerprint resolution
    /// fails, [`ZendriverError::Transport`] when the WebSocket attach times
    /// out.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder().launch().await?;
    /// # browser.close().await?;
    /// # Ok(()) }
    /// ```
    pub async fn launch(mut self) -> Result<Browser, ZendriverError> {
        // 1. Resolve Chrome executable.
        // Precedence: explicit `.executable(...)` > `CHROME_BIN` env var >
        // per-channel platform discovery. The env-var hop lets CI (and local
        // devs pointing at Canary / a downloaded Chrome-for-Testing build)
        // override the discovery path without code changes. The configured
        // `channel` (default `Auto`) only steers the final discovery step.
        let exe = match self.executable.clone() {
            Some(p) => p,
            None => match std::env::var("CHROME_BIN").ok().filter(|s| !s.is_empty()) {
                Some(p) => PathBuf::from(p),
                None => find_chrome_executable_for_channel(self.channel)?,
            },
        };

        // 1b. Resolve extensions: unzip any `.crx` into a tempdir and rewrite
        // `self.extensions` to the resolved unpacked-directory paths so
        // `build_flags` emits `--load-extension=<dir,…>`. Directory entries
        // pass through untouched. The returned tempdirs are handed to
        // `BrowserInner` below so the extracted dirs outlive Chrome.
        let extension_dirs = resolve_extension_dirs(&mut self.extensions).await?;

        // 2. Resolve the per-tab InputProfile from the active StealthProfile
        // (or zero-overhead `native` when stealth is off). Cached on
        // `BrowserInner` so `Browser::new_tab` + the `TabRegistrar` observer
        // can build fresh per-Tab controllers without re-resolving the
        // profile each time.
        let input_profile = self
            .stealth
            .as_ref()
            .map_or_else(zendriver_stealth::InputProfile::native, |sp| {
                sp.input_profile()
            });

        // 3. Build the `TabRegistrar` observer. Holds a `OnceLock` for the
        // `Weak<BrowserInner>` that gets wired in step 10 — observers must
        // be passed to `connect_with_observers` before the cyclic `Arc` is
        // resolved, so the weak ref is filled in later. Retained here so
        // we can `set_browser` after construction.
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));

        // 4. Resolve fingerprint + build observer chain + profile flags.
        // Observer order: stealth (patches each new target) → tab registrar
        // (records the resulting Tab handle) → user-supplied observers →
        // force-open-shadow-roots (independent of the stealth bundle).
        let (mut observers, extra_flags): (Vec<Arc<dyn TargetObserver>>, Vec<String>) =
            if let Some(ref profile) = self.stealth {
                let fp = profile.resolve_fingerprint(&exe)?;
                let stealth_obs: Arc<dyn TargetObserver> = Arc::new(StealthObserver::with_persona(
                    profile.clone(),
                    fp,
                    self.resolved_persona(),
                ));
                let mut obs_vec = Vec::with_capacity(3 + self.extra_observers.len());
                obs_vec.push(stealth_obs);
                obs_vec.push(registrar.clone() as Arc<dyn TargetObserver>);
                obs_vec.extend(self.extra_observers.iter().cloned());
                (obs_vec, profile.build_flags())
            } else {
                let mut obs_vec = Vec::with_capacity(2 + self.extra_observers.len());
                obs_vec.push(registrar.clone() as Arc<dyn TargetObserver>);
                obs_vec.extend(self.extra_observers.iter().cloned());
                (obs_vec, Vec::new())
            };
        // Append the force-open-shadow-roots observer last so its injected
        // attachShadow override runs independently of (and after) the stealth
        // bundle. Only added when the caller opted in — keeps the default
        // observer chain untouched.
        if self.force_open_shadow_roots {
            observers.push(Arc::new(crate::expert::ShadowRootObserver) as Arc<dyn TargetObserver>);
        }

        // 5. Allocate user_data_dir (or use a TempDir we keep alive until shutdown).
        let (user_data_path, owned_tmp) = match self.user_data_dir.clone() {
            Some(p) => (p, None),
            None => {
                let td = tempfile::Builder::new()
                    .prefix("zendriver-")
                    .tempdir()
                    .map_err(BrowserError::SpawnFailed)?;
                (td.path().to_path_buf(), Some(td))
            }
        };

        // Write Chrome profile preferences (popup suppression for owned temp
        // profiles; explicit user prefs always). Best-effort — see preferences.rs.
        crate::preferences::write_preferences(
            &user_data_path,
            owned_tmp.is_some(),
            &self.preferences,
        );

        let mut flags = self.build_flags(&user_data_path);
        flags.extend(extra_flags);
        // CI-friendly defaults: when running under CI (the runner sets
        // `CI=true`), Chrome's user-namespace sandbox refuses to start
        // because the GitHub-Actions / Docker container runs as root,
        // and the small /dev/shm in the container OOMs the renderer on
        // real workloads. Auto-add `--no-sandbox` and
        // `--disable-dev-shm-usage` unless the caller already supplied
        // them (so explicit user opt-in still wins).
        if std::env::var("CI").is_ok() {
            for needed in ["--no-sandbox", "--disable-dev-shm-usage"] {
                if !flags.iter().any(|f| f == needed) {
                    flags.push(needed.into());
                }
            }
        }
        info!(executable = %exe.display(), "launching chrome");

        // 6. Spawn chrome + parse WS URL.
        let mut cmd = Command::new(&exe);
        cmd.args(&flags)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .kill_on_drop(true);

        let mut child = cmd.spawn().map_err(BrowserError::SpawnFailed)?;

        // Read stderr line-by-line until we see the DevTools URL.
        let stderr = child.stderr.take().ok_or(BrowserError::DevtoolsParse)?;
        let mut lines = BufReader::new(stderr).lines();

        let ws_url = timeout(WS_ENDPOINT_TIMEOUT, async {
            while let Ok(Some(line)) = lines.next_line().await {
                debug!(line = %line, "chrome stderr");
                if let Some(url) = parse_devtools_line(&line) {
                    return Ok::<String, ZendriverError>(url);
                }
            }
            Err(BrowserError::DevtoolsParse.into())
        })
        .await
        .map_err(|_| BrowserError::WsTimeout)??;

        // 7. Connect with observers.
        debug!(ws_url = %ws_url, "connecting to chrome");
        let conn = zendriver_transport::connect_with_observers(&ws_url, observers).await?;

        // 8–12. Shared post-connect handshake (auto-attach, main-tab
        // discovery + attach, BrowserInner construction, registrar wiring).
        // Identical for spawn (`launch`) and attach (`connect`); the only
        // differences are the owned `Child` / `TempDir` we hand it and the
        // `owns_process` flag (true here — we spawned Chrome).
        #[cfg(feature = "tracker-blocking")]
        let tracker_matcher = self.build_tracker_matcher().await?;

        let inner = finish_connect(FinishConnect {
            conn,
            registrar,
            input_profile,
            child: Some(child),
            owned_tmp,
            extension_dirs,
            debug_host_port: debug_host_port_from_ws(&ws_url),
            ws_url: Some(ws_url),
            owns_process: true,
            #[cfg(feature = "tracker-blocking")]
            tracker_matcher,
        })
        .await?;

        // 13. If a custom downloads_dir was set, configure browser-scoped
        // download behavior so all tabs (current + future) save into it.
        // See cdpdriver/zendriver#88.
        if let Some(dir) = self.downloads_dir.as_ref() {
            inner
                .conn
                .call_raw(
                    "Browser.setDownloadBehavior",
                    json!({
                        "behavior": "allow",
                        "downloadPath": dir.display().to_string(),
                        "eventsEnabled": true,
                    }),
                    None,
                )
                .await?;
        }

        // 14. Spawn a single main-session interception actor carrying BOTH
        // proxy-auth (handle_auth) and tracker blocking (block_hosts), so they
        // don't double-resolve the same Fetch.requestPaused. New tabs get their
        // own tracker-only actor via the TabRegistrar (proxy auth is
        // main-tab-only). The InterceptHandle is parked on BrowserInner so the
        // actor lives as long as the Browser does; dropping BrowserInner drops
        // the handle which cancels the actor. See cdpdriver/zendriver#208.
        #[cfg(feature = "interception")]
        {
            let main_session = inner.main_tab.session().clone();
            let mut builder = zendriver_interception::InterceptBuilder::new(&main_session);
            let mut needs_actor = false;
            if let Some((user, pass)) = self.proxy_auth.clone() {
                builder = builder.handle_auth(user, pass);
                needs_actor = true;
            }
            #[cfg(feature = "tracker-blocking")]
            if let Some(matcher) = inner.tracker_matcher.clone() {
                builder = builder.block_hosts(matcher);
                needs_actor = true;
            }
            if needs_actor {
                let handle = builder.start();
                let _ = inner.proxy_auth_handle.set(handle);
            }
        }

        Ok(Browser { inner })
    }

    /// Attach to an already-running Chrome debug session instead of spawning
    /// a new process.
    ///
    /// `endpoint` is detected by scheme:
    /// - `ws://…` / `wss://…` — used directly as the DevTools browser
    ///   WebSocket URL (the `webSocketDebuggerUrl` Chrome prints to stderr as
    ///   `DevTools listening on …`).
    /// - `http://host:port` / `https://host:port` — a DevTools HTTP base;
    ///   `connect` performs `GET {endpoint}/json/version` and reads
    ///   `webSocketDebuggerUrl` from the JSON body (matching nodriver /
    ///   zendriver-py).
    ///
    /// The connected [`Browser`] does **not** own the Chrome process: its
    /// [`Browser::close`] shuts down only the transport, and dropping it does
    /// **not** terminate Chrome. Use this to drive a long-lived browser you
    /// started elsewhere.
    ///
    /// `.stealth(profile)` and `.observer(..)` still apply, but only to
    /// targets attached **after** this call — the stealth observer is wired
    /// into the same browser-wide `Target.setAutoAttach { flatten: true }`
    /// that fires on newly-attached targets. Tabs already open when you
    /// connect predate the observer chain and are **not** patched.
    ///
    /// The spawn-only builder fields — [`BrowserBuilder::executable`],
    /// [`BrowserBuilder::user_data_dir`], [`BrowserBuilder::downloads_dir`],
    /// and any launch flags ([`BrowserBuilder::arg`] / headless / sandbox /
    /// channel / lang / user-agent) — are **ignored** on the connect path,
    /// since no process is launched.
    ///
    /// # Errors
    ///
    /// Returns [`ZendriverError::Browser`] when an `http(s)://` endpoint
    /// cannot be resolved to a `webSocketDebuggerUrl`, and
    /// [`ZendriverError::Transport`] when the WebSocket attach fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// // Chrome already started with `--remote-debugging-port=9222`.
    /// let browser = zendriver::Browser::builder()
    ///     .connect("http://127.0.0.1:9222").await?;
    /// let tab = browser.main_tab();
    /// tab.goto("https://example.com").await?;
    /// // Does NOT kill the Chrome we attached to:
    /// browser.close().await?;
    /// # Ok(()) }
    /// ```
    pub async fn connect(self, endpoint: impl Into<String>) -> Result<Browser, ZendriverError> {
        let endpoint = endpoint.into();

        // Resolve the browser WebSocket URL from the endpoint scheme.
        let ws_url = if endpoint.starts_with("ws://") || endpoint.starts_with("wss://") {
            endpoint
        } else if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
            resolve_ws_from_http(&endpoint).await?
        } else {
            return Err(BrowserError::DevtoolsParse.into());
        };

        // Resolve the per-tab InputProfile + build the observer chain exactly
        // like `launch` does (stealth observer → tab registrar → user
        // observers). The spawn-only branches (`executable`, flags, TempDir)
        // are intentionally skipped — `connect` never launches a process.
        let input_profile = self
            .stealth
            .as_ref()
            .map_or_else(zendriver_stealth::InputProfile::native, |sp| {
                sp.input_profile()
            });
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let mut observers: Vec<Arc<dyn TargetObserver>> = if let Some(ref profile) = self.stealth {
            // No executable to resolve a fingerprint from on the connect path;
            // fall back to the profile's default fingerprint.
            let fp = profile.resolve_fingerprint(Path::new(""))?;
            let stealth_obs: Arc<dyn TargetObserver> = Arc::new(StealthObserver::with_persona(
                profile.clone(),
                fp,
                self.resolved_persona(),
            ));
            let mut obs_vec = Vec::with_capacity(3 + self.extra_observers.len());
            obs_vec.push(stealth_obs);
            obs_vec.push(registrar.clone() as Arc<dyn TargetObserver>);
            obs_vec.extend(self.extra_observers.iter().cloned());
            obs_vec
        } else {
            let mut obs_vec = Vec::with_capacity(2 + self.extra_observers.len());
            obs_vec.push(registrar.clone() as Arc<dyn TargetObserver>);
            obs_vec.extend(self.extra_observers.iter().cloned());
            obs_vec
        };
        // Same opt-in force-open-shadow-roots observer as the launch path.
        if self.force_open_shadow_roots {
            observers.push(Arc::new(crate::expert::ShadowRootObserver) as Arc<dyn TargetObserver>);
        }

        debug!(ws_url = %ws_url, "attaching to running chrome");
        let conn = zendriver_transport::connect_with_observers(&ws_url, observers).await?;

        // Same post-connect handshake as `launch`, but with no owned process:
        // no `Child`, no `TempDir`, `owns_process = false`.
        let inner = finish_connect(FinishConnect {
            conn,
            registrar,
            input_profile,
            child: None,
            owned_tmp: None,
            extension_dirs: Vec::new(),
            debug_host_port: debug_host_port_from_ws(&ws_url),
            ws_url: Some(ws_url),
            owns_process: false,
            #[cfg(feature = "tracker-blocking")]
            tracker_matcher: None,
        })
        .await?;

        Ok(Browser { inner })
    }
}

#[cfg(feature = "fetcher")]
impl BrowserBuilder {
    /// Ensure Chrome is downloaded + cached, then use its path.
    ///
    /// The default [`zendriver_fetcher::Fetcher`] resolves the latest stable
    /// Chrome for Testing build for the host platform and caches it under
    /// the OS-conventional cache dir. For custom version pinning, channel
    /// selection, or cache placement, build a [`zendriver_fetcher::Fetcher`]
    /// directly and call `.executable(path)` yourself.
    ///
    /// Gated by the `fetcher` cargo feature.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder()
    ///     .ensure_chrome().await?
    ///     .launch().await?;
    /// # browser.close().await?;
    /// # Ok(()) }
    /// ```
    pub async fn ensure_chrome(self) -> Result<Self, ZendriverError> {
        let path = zendriver_fetcher::Fetcher::new().ensure_chrome().await?;
        Ok(self.executable(path))
    }
}

/// A browser permission that can be granted or denied via
/// [`Browser::grant_permissions`].
///
/// Mirrors the CDP [`Browser.PermissionType`][1] enum. Each variant maps to a
/// camelCase wire string via [`PermissionType::as_cdp`]; the full set is
/// available as [`PermissionType::ALL`] (used by
/// [`Browser::grant_all_permissions`]).
///
/// [1]: https://chromedevtools.github.io/devtools-protocol/tot/Browser/#type-PermissionType
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PermissionType {
    /// `accessibilityEvents` — accessibility event delivery.
    AccessibilityEvents,
    /// `audioCapture` — microphone access (alias of [`Self::Microphone`] on
    /// the wire).
    AudioCapture,
    /// `backgroundSync` — Background Sync API.
    BackgroundSync,
    /// `backgroundFetch` — Background Fetch API.
    BackgroundFetch,
    /// Camera access. Ergonomic alias of [`Self::VideoCapture`]; both map to
    /// the `videoCapture` wire string.
    Camera,
    /// `clipboardReadWrite` — unsanitized clipboard read + write.
    ClipboardReadWrite,
    /// `clipboardSanitizedWrite` — sanitized clipboard write.
    ClipboardSanitizedWrite,
    /// `displayCapture` — screen / window capture.
    DisplayCapture,
    /// `durableStorage` — persistent storage grant.
    DurableStorage,
    /// `geolocation` — location access.
    Geolocation,
    /// `idleDetection` — Idle Detection API.
    IdleDetection,
    /// `localFonts` — local font enumeration.
    LocalFonts,
    /// `midi` — Web MIDI access (no SysEx).
    Midi,
    /// `midiSysex` — Web MIDI access including SysEx messages.
    MidiSysex,
    /// Microphone access. Ergonomic alias of [`Self::AudioCapture`]; both map
    /// to the `audioCapture` wire string.
    Microphone,
    /// `nfc` — Web NFC access.
    Nfc,
    /// `notifications` — desktop notifications.
    Notifications,
    /// `paymentHandler` — Payment Handler API.
    PaymentHandler,
    /// `periodicBackgroundSync` — Periodic Background Sync API.
    PeriodicBackgroundSync,
    /// `protectedMediaIdentifier` — protected media (EME) identifier.
    ProtectedMediaIdentifier,
    /// `sensors` — generic sensor access (accelerometer, gyroscope, …).
    Sensors,
    /// `storageAccess` — Storage Access API.
    StorageAccess,
    /// `topLevelStorageAccess` — top-level Storage Access API.
    TopLevelStorageAccess,
    /// `videoCapture` — camera access (alias of [`Self::Camera`] on the wire).
    VideoCapture,
    /// `videoCapturePanTiltZoom` — camera pan/tilt/zoom control.
    VideoCapturePanTiltZoom,
    /// `wakeLockScreen` — screen wake lock.
    WakeLockScreen,
    /// `wakeLockSystem` — system wake lock.
    WakeLockSystem,
    /// `windowManagement` — multi-screen window placement.
    WindowManagement,
}

impl PermissionType {
    /// Every [`PermissionType`] variant — the list
    /// [`Browser::grant_all_permissions`] grants.
    ///
    /// Mirrors nodriver's `grant_all_permissions`: the complete CDP permission
    /// set. `Camera` / `Microphone` are intentionally omitted because they are
    /// wire-string aliases of [`Self::VideoCapture`] / [`Self::AudioCapture`]
    /// (CDP would reject the duplicate strings).
    pub const ALL: &'static [PermissionType] = &[
        PermissionType::AccessibilityEvents,
        PermissionType::AudioCapture,
        PermissionType::BackgroundSync,
        PermissionType::BackgroundFetch,
        PermissionType::ClipboardReadWrite,
        PermissionType::ClipboardSanitizedWrite,
        PermissionType::DisplayCapture,
        PermissionType::DurableStorage,
        PermissionType::Geolocation,
        PermissionType::IdleDetection,
        PermissionType::LocalFonts,
        PermissionType::Midi,
        PermissionType::MidiSysex,
        PermissionType::Nfc,
        PermissionType::Notifications,
        PermissionType::PaymentHandler,
        PermissionType::PeriodicBackgroundSync,
        PermissionType::ProtectedMediaIdentifier,
        PermissionType::Sensors,
        PermissionType::StorageAccess,
        PermissionType::TopLevelStorageAccess,
        PermissionType::VideoCapture,
        PermissionType::VideoCapturePanTiltZoom,
        PermissionType::WakeLockScreen,
        PermissionType::WakeLockSystem,
        PermissionType::WindowManagement,
    ];

    /// The camelCase CDP wire string for this permission (e.g. `"geolocation"`,
    /// `"videoCapture"`).
    ///
    /// # Examples
    ///
    /// ```
    /// use zendriver::PermissionType;
    /// assert_eq!(PermissionType::ClipboardReadWrite.as_cdp(), "clipboardReadWrite");
    /// ```
    #[must_use]
    pub fn as_cdp(&self) -> &'static str {
        match self {
            PermissionType::AccessibilityEvents => "accessibilityEvents",
            // `Camera` / `Microphone` map to the same wire strings, so both
            // alias spellings collapse here.
            PermissionType::AudioCapture | PermissionType::Microphone => "audioCapture",
            PermissionType::BackgroundSync => "backgroundSync",
            PermissionType::BackgroundFetch => "backgroundFetch",
            PermissionType::ClipboardReadWrite => "clipboardReadWrite",
            PermissionType::ClipboardSanitizedWrite => "clipboardSanitizedWrite",
            PermissionType::DisplayCapture => "displayCapture",
            PermissionType::DurableStorage => "durableStorage",
            PermissionType::Geolocation => "geolocation",
            PermissionType::IdleDetection => "idleDetection",
            PermissionType::LocalFonts => "localFonts",
            PermissionType::Midi => "midi",
            PermissionType::MidiSysex => "midiSysex",
            PermissionType::Nfc => "nfc",
            PermissionType::Notifications => "notifications",
            PermissionType::PaymentHandler => "paymentHandler",
            PermissionType::PeriodicBackgroundSync => "periodicBackgroundSync",
            PermissionType::ProtectedMediaIdentifier => "protectedMediaIdentifier",
            PermissionType::Sensors => "sensors",
            PermissionType::StorageAccess => "storageAccess",
            PermissionType::TopLevelStorageAccess => "topLevelStorageAccess",
            PermissionType::VideoCapture | PermissionType::Camera => "videoCapture",
            PermissionType::VideoCapturePanTiltZoom => "videoCapturePanTiltZoom",
            PermissionType::WakeLockScreen => "wakeLockScreen",
            PermissionType::WakeLockSystem => "wakeLockSystem",
            PermissionType::WindowManagement => "windowManagement",
        }
    }
}

impl Browser {
    /// Construct a fresh [`BrowserBuilder`] (with stealth on by default).
    ///
    /// Equivalent to [`BrowserBuilder::new`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder().launch().await?;
    /// # browser.close().await?;
    /// # Ok(()) }
    /// ```
    #[must_use]
    pub fn builder() -> BrowserBuilder {
        BrowserBuilder::new()
    }

    /// Attach to an already-running Chrome debug session instead of spawning.
    ///
    /// Shortcut for [`Browser::builder().connect(endpoint)`][BrowserBuilder::connect]
    /// — see that method for endpoint formats (`ws://…` / `http://host:port`),
    /// the non-owning lifecycle (`close` / drop never kill the attached
    /// process), and which builder fields are ignored on the connect path.
    ///
    /// # Errors
    ///
    /// Same as [`BrowserBuilder::connect`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::connect("http://127.0.0.1:9222").await?;
    /// # browser.close().await?;
    /// # Ok(()) }
    /// ```
    pub async fn connect(endpoint: impl Into<String>) -> Result<Browser, ZendriverError> {
        BrowserBuilder::new().connect(endpoint).await
    }

    /// Handle for the tab that exists when Chrome launches.
    ///
    /// The main tab is registered eagerly at launch time and is the same
    /// [`Tab`] across every clone of this [`Browser`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// let tab = browser.main_tab();
    /// tab.goto("https://example.com").await?;
    /// # Ok(()) }
    /// ```
    #[must_use]
    pub fn main_tab(&self) -> Tab {
        self.inner.main_tab.clone()
    }

    /// Raw root [`Connection`] for browser-scope CDP commands.
    ///
    /// Escape hatch for advanced users who need to send CDP commands at
    /// browser scope (no `sessionId`) that the high-level API doesn't wrap.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// let conn = browser.cdp();
    /// let info = conn.call_raw("SystemInfo.getInfo", serde_json::json!({}), None).await?;
    /// println!("{info}");
    /// # Ok(()) }
    /// ```
    #[must_use]
    pub fn cdp(&self) -> &Connection {
        &self.inner.conn
    }

    /// Browser-wide cookie store handle. Cookies in Chrome are stored once
    /// per profile and shared across all tabs, so the jar binds to the
    /// browser's root [`Connection`] and dispatches `Network.*Cookies*`
    /// commands at browser scope (no `sessionId`).
    ///
    /// Cheap to call — [`crate::CookieJar`] is an `Arc`-backed handle, and
    /// each invocation constructs a fresh wrapper around the cloned
    /// connection.
    #[must_use]
    pub fn cookies(&self) -> crate::CookieJar {
        crate::CookieJar::new(self.inner.conn.clone())
    }

    /// Route downloads into `dir` at runtime, browser-wide, keeping each
    /// file's server-suggested name.
    ///
    /// Dispatches `Browser.setDownloadBehavior { behavior: "allow",
    /// downloadPath: <dir> }` on the root [`Connection`] (browser scope, no
    /// `sessionId`), so the policy applies to the current tab and any future
    /// tabs. `dir` must already exist.
    ///
    /// This is the runtime counterpart to
    /// [`BrowserBuilder::downloads_dir`](crate::BrowserBuilder::downloads_dir)
    /// (which sets the same behavior at launch). It is distinct from the
    /// `expect_download` capture flow ([`Tab::expect_download`]), which uses
    /// `allowAndName` against a private tempdir to await + save a single
    /// download; `set_download_path` simply lets downloads land in a known
    /// directory with their natural names.
    ///
    /// # Errors
    ///
    /// Returns [`ZendriverError::Transport`] / `Cdp` if the CDP call fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// browser.set_download_path("/tmp/downloads").await?;
    /// # Ok(()) }
    /// ```
    pub async fn set_download_path(&self, dir: impl Into<PathBuf>) -> Result<(), ZendriverError> {
        let dir = dir.into();
        self.inner
            .conn
            .call_raw(
                "Browser.setDownloadBehavior",
                json!({
                    "behavior": "allow",
                    "downloadPath": dir.to_string_lossy().to_string(),
                }),
                None,
            )
            .await?;
        Ok(())
    }

    /// Create a new isolated [`crate::BrowserContext`] bound to an optional
    /// proxy.
    ///
    /// Wraps the CDP [`Target.createBrowserContext`][1] command: when
    /// `proxy_server` is `Some`, the returned context routes all network
    /// traffic through that upstream (mirroring Chrome's `--proxy-server`
    /// flag — e.g. `"http://host:port"` or
    /// `"http://user:pass@host:port"`). When `proxy_bypass_list` is `Some`,
    /// hosts matching the pattern (e.g. `"<-loopback>"` or
    /// `"*.internal.example.com"`) bypass the proxy. Either field is
    /// **omitted** from the params when `None`, not sent as `null` — some
    /// CDP versions reject unknown null fields.
    ///
    /// Drop the returned handle to schedule asynchronous disposal via
    /// `Target.disposeBrowserContext`.
    ///
    /// [1]: https://chromedevtools.github.io/devtools-protocol/tot/Target/#method-createBrowserContext
    ///
    /// # Errors
    ///
    /// Returns [`ZendriverError::Navigation`] if the CDP response is missing
    /// the `browserContextId` field; bubbles up any transport-level error
    /// from the underlying `call_raw`.
    pub async fn create_browser_context_with(
        &self,
        proxy_server: Option<&str>,
        proxy_bypass_list: Option<&str>,
    ) -> Result<crate::BrowserContext, ZendriverError> {
        let mut params = serde_json::Map::new();
        if let Some(p) = proxy_server {
            params.insert(
                "proxyServer".into(),
                serde_json::Value::String(p.to_string()),
            );
        }
        if let Some(b) = proxy_bypass_list {
            params.insert(
                "proxyBypassList".into(),
                serde_json::Value::String(b.to_string()),
            );
        }

        let res = self
            .inner
            .conn
            .call_raw(
                "Target.createBrowserContext",
                serde_json::Value::Object(params),
                None,
            )
            .await?;

        let id = res
            .get("browserContextId")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                ZendriverError::Navigation(
                    "Target.createBrowserContext returned no browserContextId".into(),
                )
            })?
            .to_string();

        Ok(crate::BrowserContext {
            browser: self.inner.clone(),
            id,
        })
    }

    /// Create a new default [`crate::BrowserContext`] (no proxy, no bypass).
    ///
    /// Convenience wrapper over [`Browser::create_browser_context_with`]
    /// called with both arguments as `None`.
    ///
    /// # Errors
    ///
    /// Same as [`Browser::create_browser_context_with`].
    pub async fn create_browser_context(&self) -> Result<crate::BrowserContext, ZendriverError> {
        self.create_browser_context_with(None, None).await
    }

    /// Open a new tab navigated to `about:blank`.
    ///
    /// Returns once an internal tab registrar has registered the new [`Tab`]
    /// in the browser's tab registry — typically within a few milliseconds
    /// of `Target.createTarget`'s response.
    ///
    /// Internally:
    /// 1. Sends `Target.createTarget { url: "about:blank" }` at browser
    ///    scope (no session_id) — the response includes the new `targetId`.
    /// 2. Polls the internal tabs registry every 50ms for up to 5s, looking
    ///    for a [`Tab`] whose [`Tab::target_id`] matches. The tab registrar
    ///    populates that entry asynchronously when the
    ///    `Target.attachedToTarget` event arrives.
    /// 3. Returns the matching [`Tab`] on success.
    ///
    /// # Errors
    ///
    /// Returns [`ZendriverError::TabNotFound`] if the registrar fails to
    /// register the new tab within the 5s window — usually a sign that
    /// auto-attach is misconfigured or the registrar observer crashed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder().launch().await?;
    /// let tab = browser.new_tab().await?;
    /// tab.goto("https://example.com").await?;
    /// # Ok(()) }
    /// ```
    pub async fn new_tab(&self) -> Result<Tab, ZendriverError> {
        self.new_tab_at("about:blank").await
    }

    /// Open a new tab navigated to `url`.
    ///
    /// Behaves identically to [`Browser::new_tab`] but with a custom initial
    /// URL passed to `Target.createTarget`. The returned [`Tab`] handle is
    /// ready as soon as the internal tab registrar observer registers it;
    /// callers can issue `.wait_for_load()` if they need to block on the
    /// navigation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// let tab = browser.new_tab_at("https://example.com").await?;
    /// tab.wait_for_load().await?;
    /// # Ok(()) }
    /// ```
    pub async fn new_tab_at(&self, url: impl Into<String>) -> Result<Tab, ZendriverError> {
        self.create_target(url.into(), false).await
    }

    /// Open a new top-level OS window navigated to `about:blank`.
    ///
    /// Like [`Browser::new_tab`] but passes `newWindow: true` to
    /// `Target.createTarget`, so Chrome opens a separate browser window rather
    /// than a tab in the existing one. The returned [`Tab`] is registered via
    /// the same observer path as `new_tab`. Mirrors nodriver's
    /// `get(new_window=True)`.
    ///
    /// # Errors
    ///
    /// Same as [`Browser::new_tab`]: [`ZendriverError::TabNotFound`] if the
    /// registrar fails to register the new window's tab within the wait
    /// window.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder().launch().await?;
    /// let win = browser.new_window().await?;
    /// win.goto("https://example.com").await?;
    /// # Ok(()) }
    /// ```
    pub async fn new_window(&self) -> Result<Tab, ZendriverError> {
        self.create_target("about:blank".to_string(), true).await
    }

    /// Open a new top-level OS window navigated to `url`.
    ///
    /// [`Browser::new_window`] with a custom initial URL. Issue
    /// `.wait_for_load()` on the returned [`Tab`] to block on the navigation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// let win = browser.new_window_at("https://example.com").await?;
    /// win.wait_for_load().await?;
    /// # Ok(()) }
    /// ```
    pub async fn new_window_at(&self, url: impl Into<String>) -> Result<Tab, ZendriverError> {
        self.create_target(url.into(), true).await
    }

    /// Shared `Target.createTarget` → registrar-wait path behind
    /// [`Browser::new_tab_at`] (`new_window = false`) and
    /// [`Browser::new_window_at`] (`new_window = true`).
    async fn create_target(&self, url: String, new_window: bool) -> Result<Tab, ZendriverError> {
        let mut params = json!({ "url": url });
        if new_window {
            params["newWindow"] = serde_json::Value::Bool(true);
        }
        let res = self
            .inner
            .conn
            .call_raw("Target.createTarget", params, None)
            .await?;
        let target_id = res
            .get("targetId")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                ZendriverError::Navigation("Target.createTarget returned no targetId".into())
            })?
            .to_string();

        // Wait for the TabRegistrar observer to insert the new Tab.
        // The 5s outer bound covers the typical CDP roundtrip + observer
        // chain latency (stealth → tab-registrar) with comfortable
        // headroom; instead of polling, we wait on
        // `BrowserInner::tabs_changed`, which the registrar fires on every
        // tabs-map mutation. The notification is `enable()`d before each
        // read so a notify that lands between the read and the wait is
        // still delivered.
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        loop {
            let notif = self.inner.tabs_changed.notified();
            tokio::pin!(notif);
            notif.as_mut().enable();

            {
                let tabs = self.inner.tabs.read().await;
                if let Some(tab) = tabs.values().find(|t| t.target_id() == target_id) {
                    return Ok(tab.clone());
                }
            }

            if tokio::time::Instant::now() >= deadline {
                return Err(ZendriverError::TabNotFound(target_id));
            }

            tokio::select! {
                () = notif => {}
                () = tokio::time::sleep_until(deadline) => {}
            }
        }
    }

    /// Snapshot of all currently-registered tabs.
    ///
    /// Order is unspecified (the registry is a [`HashMap`] keyed by
    /// `sessionId`). Includes the main tab plus any tabs opened via
    /// [`Browser::new_tab`] or by page scripts (e.g. `window.open`) that
    /// auto-attach has wired into the registrar.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// for tab in browser.tabs().await {
    ///     println!("tab {}: {}", tab.target_id(), tab.url().await?);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn tabs(&self) -> Vec<Tab> {
        self.inner.tabs.read().await.values().cloned().collect()
    }

    /// Count of currently-registered tabs.
    ///
    /// Equivalent to `self.tabs().await.len()` but avoids the `Vec`
    /// allocation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// assert_eq!(browser.tab_count().await, 1);
    /// # Ok(()) }
    /// ```
    pub async fn tab_count(&self) -> usize {
        self.inner.tabs.read().await.len()
    }

    /// Re-establish a dropped connection to the **same** still-running Chrome
    /// process (scoped reconnect — see the invalidation caveat below).
    ///
    /// When a CDP call returns [`ZendriverError::Disconnected`] the WebSocket
    /// died but the Chrome process is typically still alive — its browser-level
    /// `/devtools/browser/<id>` endpoint survives. `reconnect` re-dials that
    /// endpoint on the existing [`Connection`] (so raw event subscribers stay
    /// attached to the same broadcast bus), re-applies the WebSocket size
    /// config, re-arms `Target.setAutoAttach { flatten: true }` — which
    /// re-fires the observer chain so the stealth patches re-inject on every
    /// target — and refreshes the tab registry.
    ///
    /// # Handle invalidation — IMPORTANT
    ///
    /// Re-attaching to Chrome's targets yields **new `sessionId`s**. Every
    /// [`Tab`], `Frame`, and `Element` handle obtained before the reconnect
    /// caches a now-stale session id and **must not be reused** — calls on
    /// them will fail. After `reconnect` returns, **re-acquire** handles:
    ///
    /// - live page handles via [`Browser::tabs`] (the registry is rebuilt from
    ///   the re-attached targets);
    /// - **not** via [`Browser::main_tab`], which still returns the
    ///   pre-reconnect handle (its cached session id is stale). Swapping the
    ///   cached main-tab handle in place is part of the deferred
    ///   transparent-reconnect work; for now treat `main_tab()` as invalid
    ///   after a reconnect and use `tabs()`.
    ///
    /// # What is NOT restored (deferred)
    ///
    /// This is the scoped v1. It does **not** replay per-feature domain arming
    /// (`Network.enable`, active `Fetch` interception rules, `DOMStorage.enable`,
    /// download behavior, …) that individual features turned on before the
    /// drop — re-arm those yourself after reconnecting. Transparent
    /// handle-preserving reconnect (session-id remap so existing `Tab`s keep
    /// working) is tracked as follow-up work.
    ///
    /// # Errors
    ///
    /// Returns [`ZendriverError::Disconnected`] if this browser was constructed
    /// without a known ws endpoint (e.g. a test harness) so there is nothing to
    /// re-dial, and [`ZendriverError::Transport`] / [`ZendriverError::Cdp`] if
    /// the re-dial or the post-reconnect handshake fails. On a failed re-dial
    /// the existing (dead) connection is left untouched.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # async fn do_work(_t: &zendriver::Tab) -> zendriver::Result<()> { Ok(()) }
    /// // A long-running scraper that survives a dropped socket:
    /// let tab = browser.main_tab();
    /// if let Err(zendriver::ZendriverError::Disconnected) = do_work(&tab).await {
    ///     browser.reconnect().await?; // re-dial the same Chrome process
    ///     // Old handles are stale now — re-acquire from the rebuilt registry:
    ///     let tab = browser.tabs().await.into_iter().next().unwrap();
    ///     do_work(&tab).await?;
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn reconnect(&self) -> Result<(), ZendriverError> {
        let ws_url = self
            .inner
            .ws_url
            .clone()
            .ok_or(ZendriverError::Disconnected)?;

        // Re-dial onto the SAME Connection (same event bus, same observer
        // chain). Dials first; only swaps the live socket on success, so a
        // failed reconnect doesn't tear down a connection that might recover.
        self.inner.conn.redial(&ws_url).await?;

        // Drop the stale tab registry — every entry's session id is invalid
        // now. The re-armed auto-attach below re-populates it from the
        // re-attached targets via the `TabRegistrar` observer.
        self.inner.tabs.write().await.clear();

        // Re-arm browser-scoped auto-attach. Chrome re-fires
        // `Target.attachedToTarget` for every existing target, which runs the
        // observer chain again — stealth re-injects on each target, and the
        // registrar re-inserts a fresh `Tab` (with a fresh session id) for each
        // page. `flatten: true` re-applies the single-socket flat session model.
        self.inner
            .conn
            .call_raw(
                "Target.setAutoAttach",
                json!({
                    "autoAttach": true,
                    "waitForDebuggerOnStart": true,
                    "flatten": true,
                }),
                None,
            )
            .await?;

        // Wake any `new_tab_at` waiters now that the registry has been reset
        // and is being repopulated by the observer chain.
        self.inner.tabs_changed.notify_waiters();
        Ok(())
    }

    /// Graceful shutdown of the Chrome subprocess.
    ///
    /// Cancels the transport, sends SIGTERM to Chrome, waits up to 5s, then
    /// SIGKILLs on timeout. Cleans up the `user_data_dir` tempdir if one was
    /// allocated at launch time.
    ///
    /// For a browser produced by [`BrowserBuilder::connect`] (we did not spawn
    /// Chrome) this shuts down only the transport and leaves the attached
    /// process running.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// let browser = zendriver::Browser::builder().launch().await?;
    /// // ... drive the browser ...
    /// browser.close().await?;
    /// # Ok(()) }
    /// ```
    pub async fn close(self) -> Result<(), ZendriverError> {
        self.inner.conn.shutdown();
        // Attached (non-owning) sessions must never terminate the process we
        // connected to — only the transport is torn down above. Spawn-only.
        if !self.inner.owns_process {
            return Ok(());
        }
        let mut child_guard = self.inner.child.lock().await;
        if let Some(mut child) = child_guard.take() {
            // Try graceful exit first. On Unix, tokio's `start_kill` is
            // `kill(pid, SIGKILL)` — too aggressive for graceful shutdown.
            // We send SIGTERM ourselves and fall back to SIGKILL on timeout.
            #[cfg(unix)]
            {
                if let Some(pid) = child.id() {
                    // SIGTERM gives Chrome a chance to flush + clean up; SIGKILL fallback below.
                    // Safety: just sending a signal to a known pid; no shared state.
                    #[allow(unsafe_code)]
                    unsafe {
                        libc::kill(pid as i32, libc::SIGTERM);
                    }
                }
            }
            #[cfg(not(unix))]
            {
                let _ = child.start_kill(); // best-effort on non-Unix
            }
            match timeout(SHUTDOWN_GRACE, child.wait()).await {
                Ok(Ok(_status)) => {}
                _ => {
                    let _ = child.kill().await;
                }
            }
        }
        Ok(())
    }

    /// Grant `perms` to `origin` (or browser-wide when `origin` is `None`).
    ///
    /// Wraps the CDP [`Browser.grantPermissions`][1] command, sent at browser
    /// scope (no `sessionId`). Each [`PermissionType`] is mapped to its
    /// camelCase wire string. When `origin` is `Some`, the grant is scoped to
    /// that origin (e.g. `"https://example.com"`); when `None`, the `origin`
    /// key is omitted so the grant applies browser-wide.
    ///
    /// Granting a permission pre-authorizes it without the usual user prompt —
    /// useful for unattended automation that would otherwise stall on a
    /// permission dialog (geolocation, clipboard, notifications, …).
    ///
    /// [1]: https://chromedevtools.github.io/devtools-protocol/tot/Browser/#method-grantPermissions
    ///
    /// # Errors
    ///
    /// Bubbles up any transport-level error from the underlying `call_raw`
    /// (e.g. the connection was shut down).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use zendriver::PermissionType;
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// browser
    ///     .grant_permissions(
    ///         &[PermissionType::Geolocation, PermissionType::Notifications],
    ///         Some("https://example.com"),
    ///     )
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn grant_permissions(
        &self,
        perms: &[PermissionType],
        origin: Option<&str>,
    ) -> Result<(), ZendriverError> {
        let mut params = serde_json::Map::new();
        let permissions: Vec<serde_json::Value> = perms
            .iter()
            .map(|p| serde_json::Value::String(p.as_cdp().to_string()))
            .collect();
        params.insert("permissions".into(), serde_json::Value::Array(permissions));
        // Omit `origin` entirely when None — a browser-wide grant. Some CDP
        // versions reject an explicit null here.
        if let Some(o) = origin {
            params.insert("origin".into(), serde_json::Value::String(o.to_string()));
        }
        self.inner
            .conn
            .call_raw(
                "Browser.grantPermissions",
                serde_json::Value::Object(params),
                None,
            )
            .await?;
        Ok(())
    }

    /// Grant every [`PermissionType`] browser-wide.
    ///
    /// Convenience wrapper over [`Browser::grant_permissions`] called with
    /// [`PermissionType::ALL`] and no origin — mirrors nodriver /
    /// zendriver-py's `grant_all_permissions`. Pre-authorizes the full CDP
    /// permission set so automated runs never stall on a permission prompt.
    ///
    /// # Errors
    ///
    /// Same as [`Browser::grant_permissions`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// browser.grant_all_permissions().await?;
    /// # Ok(()) }
    /// ```
    pub async fn grant_all_permissions(&self) -> Result<(), ZendriverError> {
        self.grant_permissions(PermissionType::ALL, None).await
    }

    /// Reset all previously-granted permissions to their default prompt state.
    ///
    /// Wraps the CDP [`Browser.resetPermissions`][1] command, sent at browser
    /// scope (no `sessionId`). Clears every override installed via
    /// [`Browser::grant_permissions`] / [`Browser::grant_all_permissions`].
    ///
    /// [1]: https://chromedevtools.github.io/devtools-protocol/tot/Browser/#method-resetPermissions
    ///
    /// # Errors
    ///
    /// Bubbles up any transport-level error from the underlying `call_raw`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// browser.reset_permissions().await?;
    /// # Ok(()) }
    /// ```
    pub async fn reset_permissions(&self) -> Result<(), ZendriverError> {
        self.inner
            .conn
            .call_raw("Browser.resetPermissions", json!({}), None)
            .await?;
        Ok(())
    }
}

/// Hard-shutdown fallback. `Drop` cannot be async, so it cannot perform the
/// SIGTERM-then-wait-then-SIGKILL dance [`Browser::close`] runs. Instead:
///
/// 1. [`Connection::shutdown`] signals the transport actor to stop reading;
///    pending CDP calls fail with a transport error.
/// 2. The child [`std::process::Child`] is dropped via tokio's
///    `kill_on_drop(true)` (set at spawn time), which sends `SIGKILL`
///    immediately — Chrome gets no grace period to flush state.
/// 3. The optional `user_data_dir` [`TempDir`] is dropped, deleting the
///    profile.
///
/// In short: dropping the [`Browser`] is the panic-safety / scope-exit path.
/// For a graceful shutdown that flushes Chrome state cleanly, call
/// [`Browser::close`] explicitly before the [`Browser`] goes out of scope.
///
/// For a browser produced by [`BrowserBuilder::connect`] (`owns_process ==
/// false`) there is no owned `Child`, so step 2 is a no-op: dropping detaches
/// the transport but never signals the attached Chrome process.
impl Drop for BrowserInner {
    fn drop(&mut self) {
        self.conn.shutdown();
        // We can't `.await` in Drop. If `close()` was not called explicitly,
        // we rely on `kill_on_drop(true)` set on the spawned Command, which
        // causes tokio to SIGKILL the child when the Child is dropped.
        // The TempDir for user_data_dir is dropped here too.
        //
        // Attached (`connect`) browsers hold no `Child` — `owns_process` is
        // false and the field is `None` — so nothing is killed here.
        debug_assert!(
            self.owns_process || self.child.try_lock().map(|g| g.is_none()).unwrap_or(true),
            "a non-owning Browser must not hold a Child handle",
        );
    }
}

#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn candidate_paths_is_nonempty() {
        let v = candidate_paths_for_channel(Channel::Auto);
        assert!(!v.is_empty());
    }

    #[test]
    fn builder_accepts_persona_and_overrides() {
        // Exercises the re-exported `zendriver::{Persona, Surface, Strategy}`
        // and the full resolve pipeline: base persona → overlay → surface
        // override. No browser launched — `resolved_persona` is `&self`.
        let b = Browser::builder()
            .persona(Persona::builder().device_memory_gb(16).build())
            .persona_overlay(r#"{"timezone":"UTC"}"#.parse().unwrap())
            .surface(Surface::Webrtc, Strategy::Native);
        let p = b.resolved_persona();
        assert_eq!(p.device_memory_gb, Some(16));
        assert_eq!(p.timezone.as_deref(), Some("UTC"));
        assert_eq!(
            p.webrtc.as_ref().and_then(|w| w.strategy),
            Some(Strategy::Native),
            "surface override must set the WebRTC strategy"
        );
    }

    #[test]
    fn seed_persists_in_user_data_dir() {
        // Two builders pointed at the same profile dir (no explicit seed) must
        // resolve to the SAME seed: the first writes `.zd_persona_seed`, the
        // second reads it back.
        let dir = tempfile::tempdir().unwrap();
        let s1 = Browser::builder()
            .user_data_dir(dir.path())
            .resolved_persona()
            .seed
            .unwrap();
        let s2 = Browser::builder()
            .user_data_dir(dir.path())
            .resolved_persona()
            .seed
            .unwrap();
        assert_eq!(s1, s2, "same profile dir → same seed across builders");
    }

    #[test]
    fn explicit_seed_overrides_user_data_dir_persistence() {
        // An explicitly-pinned seed must win over the persisted one.
        let dir = tempfile::tempdir().unwrap();
        let pinned = Browser::builder()
            .persona(Persona::builder().seed(Seed::from_u64(777)).build())
            .user_data_dir(dir.path())
            .resolved_persona()
            .seed
            .unwrap();
        assert_eq!(pinned, Seed::from_u64(777));
        // And the persistence file is NOT consulted/created for the pinned seed.
        assert!(!dir.path().join(".zd_persona_seed").exists());
    }

    #[cfg(feature = "geo")]
    #[test]
    fn geo_locale_sets_overlay() {
        let builder = Browser::builder().geo_locale("US");
        let p = builder.resolved_persona();
        assert_eq!(p.locale.as_deref(), Some("en-US"));
    }

    #[test]
    fn find_chrome_executable_returns_err_when_none_exist() {
        // Force an empty PATH and assert ExecutableNotFound on a system
        // without any default-location binaries. We can't reliably do this
        // cross-platform without mocking, so we just test the type signature
        // by calling the function in a save way:
        let _ = find_chrome_executable();
    }

    #[test]
    fn parse_devtools_line_extracts_ws_url() {
        let line = "DevTools listening on ws://127.0.0.1:54321/devtools/browser/abc-def-123\n";
        assert_eq!(
            parse_devtools_line(line).as_deref(),
            Some("ws://127.0.0.1:54321/devtools/browser/abc-def-123")
        );
    }

    #[test]
    fn parse_devtools_line_returns_none_for_unrelated() {
        assert!(parse_devtools_line("loading extension foo").is_none());
        assert!(parse_devtools_line("DevTools listening on http://x").is_none());
    }

    #[test]
    fn parse_devtools_line_handles_prefixed_log_lines() {
        // Real Chrome stderr is sometimes prefixed with [pid:tid:date:level].
        let line = "[12345:1234:0102/030405.000000:INFO:browser.cc] DevTools listening on ws://localhost:1/devtools/browser/x";
        assert_eq!(
            parse_devtools_line(line).as_deref(),
            Some("ws://localhost:1/devtools/browser/x")
        );
    }

    #[test]
    fn debug_host_port_from_ws_extracts_authority() {
        assert_eq!(
            debug_host_port_from_ws("ws://127.0.0.1:9222/devtools/browser/abc").as_deref(),
            Some("127.0.0.1:9222")
        );
        assert_eq!(
            debug_host_port_from_ws("wss://example.test:1/x").as_deref(),
            Some("example.test:1")
        );
        // No path component still yields the authority.
        assert_eq!(
            debug_host_port_from_ws("ws://localhost:5555").as_deref(),
            Some("localhost:5555")
        );
        // Non-ws schemes / garbage → None.
        assert_eq!(debug_host_port_from_ws("http://x:1/y"), None);
        assert_eq!(debug_host_port_from_ws("nonsense"), None);
    }

    #[test]
    fn build_flags_default_is_headless() {
        let b = BrowserBuilder::new();
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(flags.contains(&"--headless=new".to_string()));
        assert!(flags.contains(&"--disable-gpu".to_string()));
        assert!(flags.contains(&"--user-data-dir=/tmp/x".to_string()));
        assert!(flags.contains(&"--remote-debugging-port=0".to_string()));
    }

    #[test]
    fn build_flags_suppresses_password_popups() {
        let b = BrowserBuilder::new();
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(flags.contains(&"--password-store=basic".to_string()));
        assert!(flags.contains(&"--disable-save-password-bubble".to_string()));
        assert!(
            flags
                .iter()
                .any(|f| f.contains("PasswordManagerOnboarding"))
        );
    }

    #[test]
    fn build_flags_no_headless_when_disabled() {
        let b = BrowserBuilder::new().headless(false);
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(!flags.iter().any(|f| f.starts_with("--headless")));
        assert!(!flags.contains(&"--disable-gpu".to_string()));
    }

    #[test]
    fn build_flags_includes_extra_args_in_order() {
        let b = BrowserBuilder::new()
            .arg("--proxy-server=http://x")
            .arg("--lang=en-US");
        let flags = b.build_flags(Path::new("/tmp/x"));
        let proxy = flags
            .iter()
            .position(|f| f == "--proxy-server=http://x")
            .unwrap();
        let lang = flags.iter().position(|f| f == "--lang=en-US").unwrap();
        assert!(proxy < lang);
    }

    #[test]
    fn build_flags_appends_about_blank_start_page() {
        // Default launch must open the initial tab on about:blank (the final
        // positional argument), not Chrome's New Tab Page — the NTP's own
        // requests would otherwise pollute `wait_for_idle`'s in-flight set.
        let flags = BrowserBuilder::new().build_flags(Path::new("/tmp/x"));
        assert_eq!(
            flags.last().map(String::as_str),
            Some("about:blank"),
            "about:blank must be the final positional arg in {flags:?}"
        );
        assert_eq!(
            flags.iter().filter(|f| f.as_str() == "about:blank").count(),
            1,
            "exactly one start page expected in {flags:?}"
        );
    }

    #[test]
    fn build_flags_user_positional_url_suppresses_about_blank() {
        // A caller-supplied positional start URL wins; we must not also append
        // about:blank (which would open a second, blank tab).
        let flags = BrowserBuilder::new()
            .arg("https://example.com")
            .build_flags(Path::new("/tmp/x"));
        assert!(
            !flags.contains(&"about:blank".to_string()),
            "explicit positional URL should suppress about:blank in {flags:?}"
        );
        assert_eq!(
            flags.last().map(String::as_str),
            Some("https://example.com"),
            "explicit start URL should remain the final arg in {flags:?}"
        );
    }

    // ----- C4: lang / user_agent / sandbox / channel ---------------------

    #[test]
    fn lang_flag_present() {
        let b = BrowserBuilder::new().lang("en-US");
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(flags.contains(&"--lang=en-US".to_string()));
    }

    #[test]
    fn user_agent_flag_present() {
        let b = BrowserBuilder::new().user_agent("MyAgent/1.0");
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(flags.contains(&"--user-agent=MyAgent/1.0".to_string()));
    }

    #[test]
    fn sandbox_false_adds_no_sandbox() {
        let b = BrowserBuilder::new().sandbox(false);
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(flags.contains(&"--no-sandbox".to_string()));
    }

    #[test]
    fn sandbox_default_on_omits_no_sandbox() {
        // Default builder (sandbox on) must NOT emit --no-sandbox from
        // build_flags. The CI auto-add lives in `launch`, not build_flags,
        // so this is unaffected by the CI env var.
        let b = BrowserBuilder::new();
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(!flags.contains(&"--no-sandbox".to_string()));
    }

    // ----- C2: expert mode -----------------------------------------------

    #[test]
    fn expert_adds_web_security_and_site_isolation_flags() {
        let b = BrowserBuilder::new().expert(true);
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(
            flags.contains(&"--disable-web-security".to_string()),
            "expected --disable-web-security in {flags:?}"
        );
        assert!(
            flags.contains(&"--disable-site-isolation-trials".to_string()),
            "expected --disable-site-isolation-trials in {flags:?}"
        );
    }

    #[test]
    fn expert_off_omits_expert_flags() {
        let flags = BrowserBuilder::new().build_flags(Path::new("/tmp/x"));
        assert!(!flags.contains(&"--disable-web-security".to_string()));
        assert!(!flags.contains(&"--disable-site-isolation-trials".to_string()));
    }

    // ----- C3: extensions ------------------------------------------------

    #[test]
    fn extensions_add_load_and_disable_except_flags() {
        let b = BrowserBuilder::new().add_extension("a").add_extension("b");
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(
            flags.contains(&"--load-extension=a,b".to_string()),
            "expected --load-extension=a,b in {flags:?}"
        );
        assert!(
            flags.contains(&"--disable-extensions-except=a,b".to_string()),
            "expected --disable-extensions-except=a,b in {flags:?}"
        );
        assert!(
            flags.contains(&"--enable-unsafe-extension-debugging".to_string()),
            "expected --enable-unsafe-extension-debugging in {flags:?}"
        );
    }

    #[test]
    fn extensions_force_disable_load_extension_feature_even_off_profile() {
        // Stealth Off + extensions: build_flags is stealth-agnostic, so the
        // DisableLoadExtensionCommandLineSwitch feature must ride in the base
        // --disable-features line whenever extensions are present (otherwise
        // an Off-profile launch silently fails to load them on Chrome 136+).
        let b = BrowserBuilder::new()
            .stealth(StealthProfile::off())
            .add_extension("ext");
        let flags = b.build_flags(Path::new("/tmp/x"));
        assert!(
            flags.iter().any(|f| f.starts_with("--disable-features=")
                && f.contains("DisableLoadExtensionCommandLineSwitch")),
            "expected DisableLoadExtensionCommandLineSwitch in a --disable-features line: {flags:?}"
        );
    }

    #[test]
    fn no_extensions_omits_extension_flags() {
        // Default builder must not emit any extension flags (keeps the default
        // argv + snapshots unchanged).
        let flags = BrowserBuilder::new().build_flags(Path::new("/tmp/x"));
        assert!(!flags.iter().any(|f| f.starts_with("--load-extension")));
        assert!(
            !flags
                .iter()
                .any(|f| f.starts_with("--disable-extensions-except"))
        );
        assert!(!flags.contains(&"--enable-unsafe-extension-debugging".to_string()));
        assert!(
            !flags
                .iter()
                .any(|f| f.contains("DisableLoadExtensionCommandLineSwitch")),
            "default build must not carry the extension feature toggle: {flags:?}"
        );
    }

    #[tokio::test]
    async fn resolve_extension_dirs_passes_through_directories() {
        // A directory entry is used as-is (no tempdir allocated).
        let dir = tempfile::tempdir().unwrap();
        let mut exts = vec![dir.path().to_path_buf()];
        let tempdirs = resolve_extension_dirs(&mut exts).await.unwrap();
        assert!(
            tempdirs.is_empty(),
            "directories should not allocate tempdirs"
        );
        assert_eq!(exts, vec![dir.path().to_path_buf()]);
    }

    #[tokio::test]
    async fn resolve_extension_dirs_unzips_crx_to_tempdir() {
        // Build a minimal CRX (CRX3-ish: `Cr24` magic + a fake header, then a
        // ZIP carrying manifest.json) and assert it unzips to a real dir.
        use std::io::Write;
        let mut zip_buf = Vec::new();
        {
            let mut w = zip::ZipWriter::new(std::io::Cursor::new(&mut zip_buf));
            w.start_file("manifest.json", zip::write::SimpleFileOptions::default())
                .unwrap();
            w.write_all(br#"{"name":"t","version":"1","manifest_version":3}"#)
                .unwrap();
            w.finish().unwrap();
        }
        // Prepend a token CRX header before the ZIP payload.
        let mut crx = Vec::new();
        crx.extend_from_slice(b"Cr24");
        crx.extend_from_slice(&3u32.to_le_bytes()); // version
        crx.extend_from_slice(&0u32.to_le_bytes()); // header length (ignored)
        crx.extend_from_slice(&zip_buf);

        let crx_file = tempfile::Builder::new().suffix(".crx").tempfile().unwrap();
        std::fs::write(crx_file.path(), &crx).unwrap();

        let mut exts = vec![crx_file.path().to_path_buf()];
        let tempdirs = resolve_extension_dirs(&mut exts).await.unwrap();
        assert_eq!(tempdirs.len(), 1, "crx should allocate one tempdir");
        // The slot was rewritten to the extracted directory…
        assert!(exts[0].is_dir(), "crx slot should resolve to a directory");
        assert_ne!(exts[0], crx_file.path());
        // …and the manifest landed inside it.
        assert!(exts[0].join("manifest.json").is_file());
    }

    #[tokio::test]
    async fn resolve_extension_dirs_errors_on_missing_path() {
        let mut exts = vec![PathBuf::from("/nonexistent/zzz-does-not-exist")];
        let err = resolve_extension_dirs(&mut exts).await.unwrap_err();
        assert!(
            matches!(
                err,
                ZendriverError::Browser(BrowserError::ExtensionLoad { .. })
            ),
            "expected ExtensionLoad, got {err:?}"
        );
    }

    #[test]
    fn channel_brave_resolves_brave_path() {
        // Probe the candidate-path table directly so the test does not
        // require Brave to be installed. Every Brave candidate path must
        // mention "brave" somewhere (per-OS install dirs / binary names),
        // compared case-insensitively (Linux uses lowercase `brave-browser`,
        // macOS/Windows use `Brave Browser` / `Brave-Browser`).
        let paths = candidate_paths_for_channel(Channel::Brave);
        assert!(!paths.is_empty(), "Brave channel must yield candidates");
        assert!(
            paths
                .iter()
                .all(|p| p.to_string_lossy().to_lowercase().contains("brave")),
            "every Brave candidate path should reference Brave: {paths:?}"
        );
    }

    #[test]
    fn channel_edge_resolves_edge_path() {
        let paths = candidate_paths_for_channel(Channel::Edge);
        assert!(!paths.is_empty(), "Edge channel must yield candidates");
        assert!(
            paths
                .iter()
                .all(|p| p.to_string_lossy().to_lowercase().contains("edge")),
            "every Edge candidate path should reference Edge: {paths:?}"
        );
    }

    #[test]
    fn channel_auto_includes_chrome_family_candidates() {
        // Auto preserves the historical first-found behavior: it offers both
        // the Chrome and Chromium fallbacks (so neither a Chrome-only nor a
        // Chromium-only box regresses). `find_chrome_executable()` delegates
        // straight to this table.
        let paths = candidate_paths_for_channel(Channel::Auto);
        assert!(!paths.is_empty(), "Auto must yield candidates");
        let joined = paths
            .iter()
            .map(|p| p.to_string_lossy().to_lowercase())
            .collect::<Vec<_>>()
            .join("|");
        assert!(
            joined.contains("chrom"),
            "Auto candidates should reference a Chrome/Chromium binary: {paths:?}"
        );
    }

    #[test]
    fn default_launch_flags_snapshot() {
        let b = BrowserBuilder::new();
        let flags = b.build_flags(std::path::Path::new("/tmp/test-user-data"));
        insta::assert_yaml_snapshot!("default_launch_flags", flags);
    }

    #[tokio::test]
    async fn reconnect_without_ws_url_errors_disconnected() {
        use zendriver_transport::testing::MockConnection;
        // `test_only_browser_from_conn` builds a browser with `ws_url: None`
        // (no real Chrome was dialed), so there's nothing to re-dial — the
        // reconnect attempt must surface `Disconnected` rather than panic or
        // hang.
        let (_mock, conn) = MockConnection::pair();
        let browser = test_only_browser_from_conn(conn);
        let res = browser.reconnect().await;
        assert!(
            matches!(res, Err(ZendriverError::Disconnected)),
            "reconnect with no ws_url must error Disconnected, got {res:?}"
        );
    }

    #[test]
    fn non_headless_launch_flags_snapshot() {
        let b = BrowserBuilder::new().headless(false);
        let flags = b.build_flags(std::path::Path::new("/tmp/test-user-data"));
        insta::assert_yaml_snapshot!("non_headless_launch_flags", flags);
    }

    // ----- TabRegistrar observer (P4 T2) ---------------------------------

    /// Mock-drive a `Target.attachedToTarget` event with `type=page` and
    /// assert the [`TabRegistrar`] inserts the new [`Tab`] into the
    /// browser-wide tabs registry. The initial main tab (manually seeded
    /// by `launch` step 12) accounts for the first entry; this test
    /// confirms a second attach grows the map to 2.
    #[tokio::test]
    async fn tab_registrar_inserts_page_target_into_tabs_map() {
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (mut mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        // Seed a `BrowserInner` carrying a synthetic "main" tab — same
        // shape `launch` produces after step 12 (the main tab is inserted
        // under its real `sessionId`; here we use "S1" for the simulated
        // initial target).
        let inner = Arc::new_cyclic(|weak: &Weak<BrowserInner>| {
            let main_session = SessionHandle::new(conn.clone(), "S1");
            let main_input = InputController::new(input_profile.clone());
            let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
            let mut map = HashMap::new();
            map.insert("S1".to_string(), main_tab.clone());
            BrowserInner {
                conn: conn.clone(),
                main_tab,
                child: tokio::sync::Mutex::new(None),
                _user_data: None,
                _extension_dirs: Vec::new(),
                owns_process: false,
                stealth_input_profile: input_profile.clone(),
                tabs: tokio::sync::RwLock::new(map),
                debug_host_port: None,
                ws_url: None,
                tabs_changed: tokio::sync::Notify::new(),
                #[cfg(feature = "interception")]
                proxy_auth_handle: std::sync::OnceLock::new(),
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
                #[cfg(feature = "tracker-blocking")]
                tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
            }
        });
        registrar.set_browser(Arc::downgrade(&inner));

        // Sanity: one entry to start.
        assert_eq!(inner.tabs.read().await.len(), 1);

        // Emit the attach event for a second page target. The actor will
        // dispatch the registrar observer; once it returns Ok the actor
        // releases the debugger via `Runtime.runIfWaitingForDebugger`,
        // which is our signal that the observer body finished.
        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S2",
                "targetInfo": {
                    "targetId": "T2",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        let release_id = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            mock.expect_cmd("Runtime.runIfWaitingForDebugger"),
        )
        .await
        .expect("debugger-release did not fire within 2s");
        mock.reply(release_id, json!({})).await;

        // Give the actor a moment to drop its strong ref to the observer's
        // upgraded Arc and let our `inner.tabs` write land.
        for _ in 0..20 {
            if inner.tabs.read().await.len() == 2 {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }

        let tabs = inner.tabs.read().await;
        assert_eq!(tabs.len(), 2, "expected main + new tab in registry");
        assert!(tabs.contains_key("S1"), "main tab still registered");
        assert!(tabs.contains_key("S2"), "new tab registered by observer");

        drop(tabs);
        conn.shutdown();
    }

    // ----- Browser::new_tab + tabs + tab_count (P4 T3) -------------------

    /// End-to-end mock-drive of [`Browser::new_tab`]: send `Target.createTarget`,
    /// emit the corresponding `Target.attachedToTarget`, and assert the
    /// returned [`Tab`] matches the target_id from the create response while
    /// [`Browser::tabs`] grows to 2 entries.
    #[tokio::test]
    async fn new_tab_creates_target_then_returns_registered_tab() {
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (mut mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        // Same launch-step-12 shape as the T2 test: synthetic main tab seeded
        // under S1/T1 so the registry starts at len=1.
        let inner = Arc::new_cyclic(|weak: &Weak<BrowserInner>| {
            let main_session = SessionHandle::new(conn.clone(), "S1");
            let main_input = InputController::new(input_profile.clone());
            let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
            let mut map = HashMap::new();
            map.insert("S1".to_string(), main_tab.clone());
            BrowserInner {
                conn: conn.clone(),
                main_tab,
                child: tokio::sync::Mutex::new(None),
                _user_data: None,
                _extension_dirs: Vec::new(),
                owns_process: false,
                stealth_input_profile: input_profile.clone(),
                tabs: tokio::sync::RwLock::new(map),
                debug_host_port: None,
                ws_url: None,
                tabs_changed: tokio::sync::Notify::new(),
                #[cfg(feature = "interception")]
                proxy_auth_handle: std::sync::OnceLock::new(),
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
                #[cfg(feature = "tracker-blocking")]
                tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
            }
        });
        registrar.set_browser(Arc::downgrade(&inner));
        let browser = Browser {
            inner: inner.clone(),
        };

        // Drive `Browser::new_tab` from a spawned task so we can satisfy
        // both the `Target.createTarget` reply AND the
        // `Runtime.runIfWaitingForDebugger` reply from this thread.
        let fut = tokio::spawn({
            let b = browser.clone();
            async move { b.new_tab().await }
        });

        // Satisfy Target.createTarget with the targetId we will use in the
        // attach event below.
        let create_id = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            mock.expect_cmd("Target.createTarget"),
        )
        .await
        .expect("Target.createTarget not sent within 2s");
        assert_eq!(mock.last_sent()["params"]["url"], "about:blank");
        mock.reply(create_id, json!({ "targetId": "T2" })).await;

        // Emit the attach event for the new target — this fires the
        // TabRegistrar observer which inserts T2 into `inner.tabs`.
        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S2",
                "targetInfo": {
                    "targetId": "T2",
                    "type": "page",
                    "url": "about:blank",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        // Actor releases the debugger after the observer returns Ok.
        let release_id = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            mock.expect_cmd("Runtime.runIfWaitingForDebugger"),
        )
        .await
        .expect("debugger-release did not fire within 2s");
        mock.reply(release_id, json!({})).await;

        // `Browser::new_tab` polls every 50ms — give it up to 2s wall-clock
        // to observe the registrar insertion. In practice it lands on the
        // first or second poll.
        let new_tab = tokio::time::timeout(std::time::Duration::from_secs(2), fut)
            .await
            .expect("new_tab future did not resolve within 2s")
            .expect("spawned task panicked")
            .expect("new_tab returned Err");

        assert_eq!(new_tab.target_id(), "T2");
        assert_eq!(browser.tab_count().await, 2);
        let all = browser.tabs().await;
        assert_eq!(all.len(), 2);
        let target_ids: std::collections::HashSet<_> =
            all.iter().map(|t| t.target_id().to_string()).collect();
        assert!(target_ids.contains("T1"));
        assert!(target_ids.contains("T2"));

        conn.shutdown();
    }

    /// [`Browser::new_window_at`] must pass `newWindow: true` to
    /// `Target.createTarget` (vs `new_tab_at`, which omits the flag), while
    /// reusing the same registrar-wait registration path.
    #[tokio::test]
    async fn new_window_at_passes_new_window_true() {
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (mut mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        let inner = Arc::new_cyclic(|weak: &Weak<BrowserInner>| {
            let main_session = SessionHandle::new(conn.clone(), "S1");
            let main_input = InputController::new(input_profile.clone());
            let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
            let mut map = HashMap::new();
            map.insert("S1".to_string(), main_tab.clone());
            BrowserInner {
                conn: conn.clone(),
                main_tab,
                child: tokio::sync::Mutex::new(None),
                _user_data: None,
                _extension_dirs: Vec::new(),
                owns_process: false,
                stealth_input_profile: input_profile.clone(),
                tabs: tokio::sync::RwLock::new(map),
                debug_host_port: None,
                ws_url: None,
                tabs_changed: tokio::sync::Notify::new(),
                #[cfg(feature = "interception")]
                proxy_auth_handle: std::sync::OnceLock::new(),
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
                #[cfg(feature = "tracker-blocking")]
                tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
            }
        });
        registrar.set_browser(Arc::downgrade(&inner));
        let browser = Browser {
            inner: inner.clone(),
        };

        let fut = tokio::spawn({
            let b = browser.clone();
            async move { b.new_window_at("https://example.com").await }
        });

        let create_id = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            mock.expect_cmd("Target.createTarget"),
        )
        .await
        .expect("Target.createTarget not sent within 2s");
        let sent = mock.last_sent();
        assert_eq!(sent["params"]["url"], "https://example.com");
        assert_eq!(
            sent["params"]["newWindow"], true,
            "new_window_at must set newWindow:true"
        );
        mock.reply(create_id, json!({ "targetId": "TW" })).await;

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "SW",
                "targetInfo": {
                    "targetId": "TW",
                    "type": "page",
                    "url": "https://example.com",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        let release_id = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            mock.expect_cmd("Runtime.runIfWaitingForDebugger"),
        )
        .await
        .expect("debugger-release did not fire within 2s");
        mock.reply(release_id, json!({})).await;

        let win = tokio::time::timeout(std::time::Duration::from_secs(2), fut)
            .await
            .expect("new_window_at future did not resolve within 2s")
            .expect("spawned task panicked")
            .expect("new_window_at returned Err");
        assert_eq!(win.target_id(), "TW");

        conn.shutdown();
    }

    /// Mock-drive a `Target.detachedFromTarget` event with the second tab's
    /// `sessionId` and assert the [`TabRegistrar::on_target_detached`]
    /// handler removes it from the browser-wide tabs registry. Counterpart
    /// to the attach-event test above; together they cover the registry's
    /// full lifecycle wired through actor → observer.
    #[tokio::test]
    async fn tab_registrar_removes_session_on_detached_event() {
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        // Seed `BrowserInner` with two tabs (S1/T1 = main, S2/T2 = extra).
        let inner = Arc::new_cyclic(|weak: &Weak<BrowserInner>| {
            let main_session = SessionHandle::new(conn.clone(), "S1");
            let main_input = InputController::new(input_profile.clone());
            let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
            let extra_session = SessionHandle::new(conn.clone(), "S2");
            let extra_input = InputController::new(input_profile.clone());
            let extra_tab = Tab::new(extra_session, weak.clone(), extra_input, "T2".to_string());
            let mut map = HashMap::new();
            map.insert("S1".to_string(), main_tab.clone());
            map.insert("S2".to_string(), extra_tab);
            BrowserInner {
                conn: conn.clone(),
                main_tab,
                child: tokio::sync::Mutex::new(None),
                _user_data: None,
                _extension_dirs: Vec::new(),
                owns_process: false,
                stealth_input_profile: input_profile.clone(),
                tabs: tokio::sync::RwLock::new(map),
                debug_host_port: None,
                ws_url: None,
                tabs_changed: tokio::sync::Notify::new(),
                #[cfg(feature = "interception")]
                proxy_auth_handle: std::sync::OnceLock::new(),
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
                #[cfg(feature = "tracker-blocking")]
                tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
            }
        });
        registrar.set_browser(Arc::downgrade(&inner));

        assert_eq!(inner.tabs.read().await.len(), 2);

        // The actor dispatches `on_target_detached` from a background
        // `tokio::spawn`, so emit the event then poll until the registry
        // shrinks (same pattern as the attach test above).
        mock.emit_event(
            "Target.detachedFromTarget",
            json!({ "sessionId": "S2", "targetId": "T2" }),
        )
        .await;

        for _ in 0..50 {
            if inner.tabs.read().await.len() == 1 {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }

        let tabs = inner.tabs.read().await;
        assert_eq!(tabs.len(), 1, "expected S2 to be removed from registry");
        assert!(tabs.contains_key("S1"), "main tab still registered");
        assert!(!tabs.contains_key("S2"), "detached tab removed");

        drop(tabs);
        conn.shutdown();
    }

    // ----- Browser::cookies (P4 T10) -------------------------------------

    /// [`Browser::cookies`] returns a [`crate::CookieJar`] bound to the
    /// browser's root [`zendriver_transport::Connection`]. A `.set(...)` call
    /// must dispatch `Storage.setCookies` on that connection — confirming the
    /// jar shares the browser's CDP channel (not a per-tab session channel).
    #[tokio::test]
    async fn browser_cookies_returns_jar_bound_to_browser_connection() {
        use crate::cookies::Cookie;
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let (mut mock, conn) = MockConnection::pair();

        let inner = Arc::new_cyclic(|weak: &Weak<BrowserInner>| {
            let main_session = SessionHandle::new(conn.clone(), "S1");
            let main_input = InputController::new(input_profile.clone());
            let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
            let mut map = HashMap::new();
            map.insert("S1".to_string(), main_tab.clone());
            BrowserInner {
                conn: conn.clone(),
                main_tab,
                child: tokio::sync::Mutex::new(None),
                _user_data: None,
                _extension_dirs: Vec::new(),
                owns_process: false,
                stealth_input_profile: input_profile.clone(),
                tabs: tokio::sync::RwLock::new(map),
                debug_host_port: None,
                ws_url: None,
                tabs_changed: tokio::sync::Notify::new(),
                #[cfg(feature = "interception")]
                proxy_auth_handle: std::sync::OnceLock::new(),
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
                #[cfg(feature = "tracker-blocking")]
                tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
            }
        });
        let browser = Browser { inner };
        let jar = browser.cookies();

        let fut = tokio::spawn(async move {
            jar.set(Cookie {
                name: "sid".into(),
                value: "abc".into(),
                domain: ".example.com".into(),
                path: "/".into(),
                expires: None,
                http_only: false,
                secure: false,
                same_site: None,
                url: None,
                ..Default::default()
            })
            .await
        });

        let id = mock.expect_cmd("Storage.setCookies").await;
        let params = &mock.last_sent()["params"];
        let arr = params["cookies"]
            .as_array()
            .expect("setCookies payload must carry a cookies array");
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["name"], "sid");
        // Browser-scope command — no session_id.
        assert!(mock.last_sent().get("sessionId").is_none());
        mock.reply(id, json!({})).await;

        fut.await.unwrap().unwrap();
        conn.shutdown();
    }

    /// Smoke test for the empty-tabs case: [`Browser::tabs`] returns a
    /// (typically 1-entry) snapshot and [`Browser::tab_count`] agrees.
    #[tokio::test]
    async fn tabs_and_tab_count_agree_on_initial_state() {
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (_mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        let inner = Arc::new_cyclic(|weak: &Weak<BrowserInner>| {
            let main_session = SessionHandle::new(conn.clone(), "S1");
            let main_input = InputController::new(input_profile.clone());
            let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
            let mut map = HashMap::new();
            map.insert("S1".to_string(), main_tab.clone());
            BrowserInner {
                conn: conn.clone(),
                main_tab,
                child: tokio::sync::Mutex::new(None),
                _user_data: None,
                _extension_dirs: Vec::new(),
                owns_process: false,
                stealth_input_profile: input_profile.clone(),
                tabs: tokio::sync::RwLock::new(map),
                debug_host_port: None,
                ws_url: None,
                tabs_changed: tokio::sync::Notify::new(),
                #[cfg(feature = "interception")]
                proxy_auth_handle: std::sync::OnceLock::new(),
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
                #[cfg(feature = "tracker-blocking")]
                tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
            }
        });
        let browser = Browser { inner };

        assert_eq!(browser.tab_count().await, 1);
        let tabs = browser.tabs().await;
        assert_eq!(tabs.len(), 1);
        assert_eq!(tabs[0].target_id(), "T1");

        conn.shutdown();
    }

    // ----- OOPIF Frame attach (P4 T16) -----------------------------------

    /// Mock-drive a `Target.attachedToTarget` event with `type=iframe` and
    /// a `targetId` that matches an already-known frame_id in the parent
    /// tab's frames map. Asserts the [`TabRegistrar`] dispatches to the
    /// OOPIF branch (instead of the page branch) and replaces the parent's
    /// same-id frame entry with a [`crate::frame::Frame`] whose session is
    /// the OOPIF's distinct child session (`S2` in the fixture, not the
    /// parent tab's `S1`).
    ///
    /// The pre-seeded parent-frame entry simulates the
    /// `Page.frameAttached` event a real Chrome would emit on the parent's
    /// session before announcing the OOPIF target — `register_oopif_frame`
    /// uses that entry to locate the owning tab.
    #[tokio::test]
    async fn tab_registrar_attaches_oopif_frame_under_parent_tab() {
        use crate::frame::Frame;
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (mut mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        // Seed BrowserInner with one parent tab.
        let inner = Arc::new_cyclic(|weak: &Weak<BrowserInner>| {
            let main_session = SessionHandle::new(conn.clone(), "S1");
            let main_input = InputController::new(input_profile.clone());
            let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
            let mut map = HashMap::new();
            map.insert("S1".to_string(), main_tab.clone());
            BrowserInner {
                conn: conn.clone(),
                main_tab,
                child: tokio::sync::Mutex::new(None),
                _user_data: None,
                _extension_dirs: Vec::new(),
                owns_process: false,
                stealth_input_profile: input_profile.clone(),
                tabs: tokio::sync::RwLock::new(map),
                debug_host_port: None,
                ws_url: None,
                tabs_changed: tokio::sync::Notify::new(),
                #[cfg(feature = "interception")]
                proxy_auth_handle: std::sync::OnceLock::new(),
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
                #[cfg(feature = "tracker-blocking")]
                tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
            }
        });
        registrar.set_browser(Arc::downgrade(&inner));

        // Pre-seed the parent tab's frames map after `Arc::new_cyclic`
        // resolves (we need the live `Weak<TabInner>` for the placeholder
        // Frame). Simulates `Page.frameAttached` having already registered
        // the host iframe under frame_id "F_OOPIF" before the OOPIF
        // target announces itself. The placeholder Frame shares the
        // parent tab's session so we can later assert that the post-
        // attach entry carries a DIFFERENT session.
        {
            let main_tab = inner.tabs.read().await.get("S1").cloned().unwrap();
            let parent_session = main_tab.session().clone();
            let placeholder = Frame::new(
                "F_OOPIF".to_string(),
                Some("FROOT".to_string()),
                String::new(),
                None,
                parent_session,
                Arc::downgrade(&main_tab.inner),
            );
            main_tab
                .inner
                .frames
                .write()
                .await
                .insert("F_OOPIF".to_string(), placeholder);
        }

        // Sanity: parent tab is the only tab, parent has the placeholder
        // entry whose session matches the parent's "S1".
        assert_eq!(inner.tabs.read().await.len(), 1);
        let parent_tab = inner.tabs.read().await.get("S1").cloned().unwrap();
        {
            let frames = parent_tab.inner.frames.read().await;
            let placeholder = frames.get("F_OOPIF").expect("placeholder seeded");
            assert_eq!(placeholder.session().session_id(), "S1");
        }

        // Emit the OOPIF attach event. The actor will dispatch the
        // registrar's `on_target_attached` which routes to the iframe
        // branch; once it returns Ok the actor releases the debugger.
        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S2",
                "targetInfo": {
                    "targetId": "F_OOPIF",
                    "type": "iframe",
                    "url": "https://oopif.example.com/",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        let release_id = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            mock.expect_cmd("Runtime.runIfWaitingForDebugger"),
        )
        .await
        .expect("debugger-release did not fire within 2s");
        mock.reply(release_id, json!({})).await;

        // Poll until the replacement lands.
        for _ in 0..50 {
            let frames = parent_tab.inner.frames.read().await;
            if frames
                .get("F_OOPIF")
                .is_some_and(|f| f.session().session_id() == "S2")
            {
                break;
            }
            drop(frames);
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }

        // Parent tab's frames map still holds an F_OOPIF entry — but now
        // bound to S2 (the OOPIF's distinct child session). Browser-wide
        // tabs map is unchanged (OOPIFs do NOT become new tabs).
        let frames = parent_tab.inner.frames.read().await;
        let oopif = frames
            .get("F_OOPIF")
            .expect("OOPIF frame registered on parent");
        assert_eq!(
            oopif.session().session_id(),
            "S2",
            "OOPIF frame must carry the child session, not the parent's",
        );
        assert_eq!(oopif.id(), "F_OOPIF");
        drop(frames);
        assert_eq!(
            inner.tabs.read().await.len(),
            1,
            "OOPIF must not be registered as a tab",
        );

        conn.shutdown();
    }

    /// Mock-drive a `Target.attachedToTarget` event with `type=iframe` whose
    /// `targetId` does NOT match any frame in any tab. Asserts the
    /// registrar logs + skips registration (no crash, no spurious entry).
    #[tokio::test]
    async fn tab_registrar_skips_oopif_when_parent_unknown() {
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (mut mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        let inner = Arc::new_cyclic(|weak: &Weak<BrowserInner>| {
            let main_session = SessionHandle::new(conn.clone(), "S1");
            let main_input = InputController::new(input_profile.clone());
            let main_tab = Tab::new(main_session, weak.clone(), main_input, "T1".to_string());
            let mut map = HashMap::new();
            map.insert("S1".to_string(), main_tab.clone());
            BrowserInner {
                conn: conn.clone(),
                main_tab,
                child: tokio::sync::Mutex::new(None),
                _user_data: None,
                _extension_dirs: Vec::new(),
                owns_process: false,
                stealth_input_profile: input_profile.clone(),
                tabs: tokio::sync::RwLock::new(map),
                debug_host_port: None,
                ws_url: None,
                tabs_changed: tokio::sync::Notify::new(),
                #[cfg(feature = "interception")]
                proxy_auth_handle: std::sync::OnceLock::new(),
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
                #[cfg(feature = "tracker-blocking")]
                tracker_handles: tokio::sync::Mutex::new(HashMap::new()),
            }
        });
        registrar.set_browser(Arc::downgrade(&inner));

        mock.emit_event(
            "Target.attachedToTarget",
            json!({
                "sessionId": "S_ORPHAN",
                "targetInfo": {
                    "targetId": "F_NOWHERE",
                    "type": "iframe",
                    "url": "https://orphan.example.com/",
                    "attached": true,
                },
                "waitingForDebugger": true,
            }),
        )
        .await;

        // Observer must still complete + release the debugger even when
        // the orphan branch warns and skips. Without this Chrome would
        // hang the OOPIF target indefinitely.
        let release_id = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            mock.expect_cmd("Runtime.runIfWaitingForDebugger"),
        )
        .await
        .expect("debugger-release did not fire within 2s");
        mock.reply(release_id, json!({})).await;

        // Browser-wide tabs registry is unchanged; the parent tab's
        // frames map is still empty (no placeholder was seeded).
        assert_eq!(inner.tabs.read().await.len(), 1);
        let parent_tab = inner.tabs.read().await.get("S1").cloned().unwrap();
        assert!(parent_tab.inner.frames.read().await.is_empty());

        conn.shutdown();
    }

    // ----- BrowserInner::dispose_browser_context (per-context proxy) -----

    /// Asserts [`BrowserInner::dispose_browser_context`] issues exactly one
    /// `Target.disposeBrowserContext` CDP command at browser scope (no
    /// `sessionId`) carrying the supplied `browserContextId`, and that the
    /// awaited future resolves `Ok` once the mock replies.
    ///
    /// Wired into the per-context proxy support series: [`crate::BrowserContext`]'s
    /// `Drop` impl calls this method to release the context when the handle
    /// goes out of scope.
    #[tokio::test]
    async fn dispose_browser_context_sends_target_dispose() {
        use zendriver_transport::testing::MockConnection;

        let (mut mock, conn) = MockConnection::pair();
        let inner = test_only_inner_from_conn(conn.clone());

        let inner_for_task = inner.clone();
        let fut =
            tokio::spawn(async move { inner_for_task.dispose_browser_context("ctx-abc").await });

        let id = mock.expect_cmd("Target.disposeBrowserContext").await;
        assert_eq!(mock.last_sent()["params"]["browserContextId"], "ctx-abc");
        // Browser-scope command — no session_id.
        assert!(mock.last_sent().get("sessionId").is_none());
        mock.reply(id, json!({})).await;

        fut.await.unwrap().unwrap();
        conn.shutdown();
    }

    // ----- Browser::create_browser_context[_with] (per-context proxy) ----

    /// Asserts [`Browser::create_browser_context_with`] sends a
    /// `Target.createBrowserContext` command carrying `proxyServer` and
    /// `proxyBypassList` exactly as supplied, and that the returned
    /// [`BrowserContext`] handle exposes the `browserContextId` from the
    /// CDP reply.
    #[tokio::test]
    async fn create_browser_context_with_sends_correct_cdp() {
        use zendriver_transport::testing::MockConnection;
        let (mut mock, conn) = MockConnection::pair();
        let browser = test_only_browser_from_conn(conn.clone());

        let fut = tokio::spawn({
            let b = browser.clone();
            async move {
                b.create_browser_context_with(
                    Some("http://user:pass@p.webshare.io:80"),
                    Some("<-loopback>"),
                )
                .await
            }
        });

        let id = mock.expect_cmd("Target.createBrowserContext").await;
        let sent = mock.last_sent();
        assert_eq!(
            sent["params"]["proxyServer"],
            "http://user:pass@p.webshare.io:80"
        );
        assert_eq!(sent["params"]["proxyBypassList"], "<-loopback>");
        mock.reply(id, json!({ "browserContextId": "ctx-new" }))
            .await;

        let ctx = fut.await.unwrap().unwrap();
        assert_eq!(ctx.id(), "ctx-new");

        conn.shutdown();
    }

    /// Asserts that when both `proxy_server` and `proxy_bypass_list` are
    /// `None`, neither key is sent as a non-null value. CDP rejects unknown
    /// null fields on some commands, so the implementation must **omit**
    /// the keys entirely from the params object (a `null` value is also
    /// accepted for forward-compat, but `Some(value)` of any kind would
    /// fail the assertion).
    #[tokio::test]
    async fn create_browser_context_without_proxy_omits_fields() {
        use zendriver_transport::testing::MockConnection;
        let (mut mock, conn) = MockConnection::pair();
        let browser = test_only_browser_from_conn(conn.clone());

        let fut = tokio::spawn({
            let b = browser.clone();
            async move { b.create_browser_context_with(None, None).await }
        });

        let id = mock.expect_cmd("Target.createBrowserContext").await;
        let sent = mock.last_sent();
        let proxy_server_field = sent["params"].get("proxyServer");
        assert!(proxy_server_field.is_none() || proxy_server_field.unwrap().is_null());
        let bypass_field = sent["params"].get("proxyBypassList");
        assert!(bypass_field.is_none() || bypass_field.unwrap().is_null());

        mock.reply(id, json!({ "browserContextId": "ctx-plain" }))
            .await;

        let ctx = fut.await.unwrap().unwrap();
        assert_eq!(ctx.id(), "ctx-plain");

        conn.shutdown();
    }

    // ----- Browser::grant_permissions / reset_permissions (C5) -----------

    /// [`Browser::grant_permissions`] maps each [`PermissionType`] to its
    /// CDP camelCase string and dispatches `Browser.grantPermissions` at
    /// browser scope (no `sessionId`) carrying both the `permissions` array
    /// and the supplied `origin`.
    #[tokio::test]
    async fn grant_permissions_dispatches_with_mapped_strings_and_origin() {
        use zendriver_transport::testing::MockConnection;

        let (mut mock, conn) = MockConnection::pair();
        let browser = test_only_browser_from_conn(conn.clone());

        let fut = tokio::spawn({
            let b = browser.clone();
            async move {
                b.grant_permissions(
                    &[
                        PermissionType::Geolocation,
                        PermissionType::VideoCapture,
                        PermissionType::ClipboardReadWrite,
                    ],
                    Some("https://example.com"),
                )
                .await
            }
        });

        let id = mock.expect_cmd("Browser.grantPermissions").await;
        let sent = mock.last_sent();
        let perms = sent["params"]["permissions"]
            .as_array()
            .expect("permissions must be an array");
        assert_eq!(
            perms,
            &vec![
                json!("geolocation"),
                json!("videoCapture"),
                json!("clipboardReadWrite"),
            ]
        );
        assert_eq!(sent["params"]["origin"], "https://example.com");
        // Browser-scope command — no session_id.
        assert!(sent.get("sessionId").is_none());
        mock.reply(id, json!({})).await;

        fut.await.unwrap().unwrap();
        conn.shutdown();
    }

    /// When `origin` is `None`, the `origin` key is omitted entirely from the
    /// params (granted browser-wide), not sent as `null`.
    #[tokio::test]
    async fn grant_permissions_omits_origin_when_none() {
        use zendriver_transport::testing::MockConnection;

        let (mut mock, conn) = MockConnection::pair();
        let browser = test_only_browser_from_conn(conn.clone());

        let fut = tokio::spawn({
            let b = browser.clone();
            async move {
                b.grant_permissions(&[PermissionType::Notifications], None)
                    .await
            }
        });

        let id = mock.expect_cmd("Browser.grantPermissions").await;
        let sent = mock.last_sent();
        assert_eq!(
            sent["params"]["permissions"].as_array().unwrap(),
            &vec![json!("notifications")]
        );
        let origin_field = sent["params"].get("origin");
        assert!(
            origin_field.is_none() || origin_field.unwrap().is_null(),
            "origin must be omitted when None"
        );
        mock.reply(id, json!({})).await;

        fut.await.unwrap().unwrap();
        conn.shutdown();
    }

    /// [`Browser::reset_permissions`] dispatches `Browser.resetPermissions`
    /// at browser scope.
    #[tokio::test]
    async fn reset_permissions_dispatches() {
        use zendriver_transport::testing::MockConnection;

        let (mut mock, conn) = MockConnection::pair();
        let browser = test_only_browser_from_conn(conn.clone());

        let fut = tokio::spawn({
            let b = browser.clone();
            async move { b.reset_permissions().await }
        });

        let id = mock.expect_cmd("Browser.resetPermissions").await;
        // Browser-scope command — no session_id.
        assert!(mock.last_sent().get("sessionId").is_none());
        mock.reply(id, json!({})).await;

        fut.await.unwrap().unwrap();
        conn.shutdown();
    }

    /// `grant_all_permissions` sends the full [`PermissionType::ALL`] list as
    /// mapped CDP strings, with no origin (browser-wide).
    #[tokio::test]
    async fn grant_all_permissions_sends_full_list() {
        use zendriver_transport::testing::MockConnection;

        let (mut mock, conn) = MockConnection::pair();
        let browser = test_only_browser_from_conn(conn.clone());

        let fut = tokio::spawn({
            let b = browser.clone();
            async move { b.grant_all_permissions().await }
        });

        let id = mock.expect_cmd("Browser.grantPermissions").await;
        let sent = mock.last_sent();
        let perms = sent["params"]["permissions"]
            .as_array()
            .expect("permissions must be an array");
        assert_eq!(perms.len(), PermissionType::ALL.len());
        // Spot-check a couple of the mapped strings are present.
        assert!(perms.contains(&json!("geolocation")));
        assert!(perms.contains(&json!("midiSysex")));
        let origin_field = sent["params"].get("origin");
        assert!(origin_field.is_none() || origin_field.unwrap().is_null());
        mock.reply(id, json!({})).await;

        fut.await.unwrap().unwrap();
        conn.shutdown();
    }

    #[test]
    fn permission_type_as_cdp_round_trips_known_strings() {
        assert_eq!(PermissionType::Geolocation.as_cdp(), "geolocation");
        assert_eq!(PermissionType::VideoCapture.as_cdp(), "videoCapture");
        assert_eq!(PermissionType::AudioCapture.as_cdp(), "audioCapture");
        assert_eq!(
            PermissionType::ClipboardReadWrite.as_cdp(),
            "clipboardReadWrite"
        );
        assert_eq!(PermissionType::MidiSysex.as_cdp(), "midiSysex");
    }

    // ----- BrowserBuilder::connect (C1) ----------------------------------

    /// Unit-test the `/json/version` body parse used by the `http(s)://`
    /// connect path: a `webSocketDebuggerUrl` string is extracted, with and
    /// without a leading HTTP/1.x header block.
    #[test]
    fn resolve_ws_from_http_parses_web_socket_debugger_url() {
        let ws = "ws://127.0.0.1:9222/devtools/browser/abc";

        // Bare JSON body (header/body split absent → whole buffer is JSON).
        let body = format!("{{\"webSocketDebuggerUrl\":\"{ws}\"}}");
        assert_eq!(parse_ws_from_json_version(body.as_bytes()).unwrap(), ws);

        // Full HTTP/1.1 response — header block must be stripped first.
        let resp = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{{\"Browser\":\"Chrome/120.0.0.0\",\"webSocketDebuggerUrl\":\"{ws}\"}}"
        );
        assert_eq!(parse_ws_from_json_version(resp.as_bytes()).unwrap(), ws);

        // Missing field → DevtoolsParse.
        let bad = b"HTTP/1.1 200 OK\r\n\r\n{\"Browser\":\"Chrome/120\"}";
        assert!(matches!(
            parse_ws_from_json_version(bad),
            Err(ZendriverError::Browser(BrowserError::DevtoolsParse))
        ));
    }

    /// The `connect` post-connect handshake (`finish_connect`) drives the same
    /// CDP sequence as launch over a [`MockConnection`] — proving the `ws://`
    /// connect path attaches via the already-established transport rather than
    /// spawning a process — and produces a `BrowserInner` that does NOT own a
    /// process: `owns_process` is false and no `Child` handle is held.
    #[tokio::test]
    async fn connect_ws_endpoint_does_not_spawn() {
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (mut mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        // Run the exact post-connect handshake `connect` invokes: no child,
        // no tempdir, owns_process = false.
        let fut = tokio::spawn(async move {
            finish_connect(FinishConnect {
                conn,
                registrar,
                input_profile,
                child: None,
                owned_tmp: None,
                extension_dirs: Vec::new(),
                debug_host_port: debug_host_port_from_ws(
                    "ws://127.0.0.1:9222/devtools/browser/abc",
                ),
                ws_url: Some("ws://127.0.0.1:9222/devtools/browser/abc".to_string()),
                owns_process: false,
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
            })
            .await
        });

        // 1. Browser-scoped auto-attach.
        let id = mock.expect_cmd("Target.setAutoAttach").await;
        let sent = mock.last_sent();
        assert_eq!(sent["params"]["flatten"], true);
        assert!(
            sent.get("sessionId").is_none(),
            "auto-attach is browser-scope"
        );
        mock.reply(id, json!({})).await;

        // 2. Initial-target discovery.
        let id = mock.expect_cmd("Target.getTargets").await;
        mock.reply(
            id,
            json!({ "targetInfos": [{ "targetId": "T1", "type": "page", "url": "about:blank" }] }),
        )
        .await;

        // 3. Attach to the discovered target.
        let id = mock.expect_cmd("Target.attachToTarget").await;
        assert_eq!(mock.last_sent()["params"]["targetId"], "T1");
        mock.reply(id, json!({ "sessionId": "S1" })).await;

        let inner = fut.await.unwrap().unwrap();

        // Ownership: attached, not spawned.
        assert!(!inner.owns_process, "connect path must not own the process");
        assert!(
            inner.child.lock().await.is_none(),
            "connect path holds no Child handle",
        );
        // Main tab registered under the attach sessionId.
        assert_eq!(inner.tabs.read().await.len(), 1);
        assert!(inner.tabs.read().await.contains_key("S1"));

        inner.conn.shutdown();
    }

    /// A connected (non-owning) [`Browser`] has `owns_process == false`, and
    /// [`Browser::close`] tears down only the transport: it returns `Ok`
    /// without attempting process termination (there is no `Child` to kill,
    /// and the `owns_process` guard short-circuits before the kill path).
    #[tokio::test]
    async fn connect_sets_owns_process_false_and_skips_kill() {
        use zendriver_transport::testing::MockConnection;

        let input_profile = zendriver_stealth::InputProfile::native();
        let registrar = Arc::new(TabRegistrar::new(input_profile.clone()));
        let (mut mock, conn) =
            MockConnection::pair_with_observers(vec![registrar.clone() as Arc<dyn TargetObserver>]);

        let fut = tokio::spawn(async move {
            finish_connect(FinishConnect {
                conn,
                registrar,
                input_profile,
                child: None,
                owned_tmp: None,
                extension_dirs: Vec::new(),
                debug_host_port: None,
                ws_url: None,
                owns_process: false,
                #[cfg(feature = "tracker-blocking")]
                tracker_matcher: None,
            })
            .await
        });

        let id = mock.expect_cmd("Target.setAutoAttach").await;
        mock.reply(id, json!({})).await;
        let id = mock.expect_cmd("Target.getTargets").await;
        mock.reply(
            id,
            json!({ "targetInfos": [{ "targetId": "T1", "type": "page", "url": "about:blank" }] }),
        )
        .await;
        let id = mock.expect_cmd("Target.attachToTarget").await;
        mock.reply(id, json!({ "sessionId": "S1" })).await;

        let inner = fut.await.unwrap().unwrap();
        assert!(!inner.owns_process);

        let browser = Browser { inner };
        // close() on a non-owning browser: shuts the transport, skips the
        // kill path entirely. No panic, no hang, returns Ok.
        browser.close().await.unwrap();
    }

    #[test]
    fn preference_accumulates_on_builder() {
        let b = Browser::builder()
            .preference("a.b", serde_json::json!(false))
            .preference("c", serde_json::json!(1));
        assert_eq!(b.preferences.len(), 2);
        assert_eq!(b.preferences[0].0, "a.b");
    }

    #[cfg(feature = "tracker-blocking")]
    #[tokio::test]
    async fn tracker_sources_accumulate_and_build_a_matcher() {
        let b = Browser::builder()
            .tracker_blocklist_add(["custom-tracker.test".to_string()])
            .tracker_blocklist_add(["another.test".to_string()]);
        let matcher = b
            .build_tracker_matcher()
            .await
            .unwrap()
            .expect("matcher built");
        assert!(matcher.is_blocked("custom-tracker.test"));
        assert!(matcher.is_blocked("sub.another.test"));
        assert!(!matcher.is_blocked("not-listed.test"));

        // No sources, no bundled toggle -> None (blocking stays off).
        let none = Browser::builder().build_tracker_matcher().await.unwrap();
        assert!(none.is_none());

        // Bundled toggle alone builds a matcher containing a known entry.
        let bundled = Browser::builder()
            .block_trackers(true)
            .build_tracker_matcher()
            .await
            .unwrap()
            .expect("bundled matcher");
        assert!(bundled.is_blocked("doubleclick.net"));
    }
}