buffr-blink-cdp 0.1.4

Headless Chromium CDP backend for buffr-engine (Phase 4 spike)
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
//! `BlinkCdpEngine` — `BrowserEngine` impl backed by headless Chromium via CDP.
//!
//! The CDP remote-debugging port is selected at runtime via an OS ephemeral-port
//! probe rather than a fixed value, so multiple engine instances can coexist
//! without port conflicts.
//!
//! # Phase 4 scope
//!
//! Implemented (minimal):
//!   - `open_tab` / `close_tab` / `close_all_browsers`
//!   - `navigate`
//!   - `osr_frame` (via `Page.startScreencast` push; replaced 5 FPS poll)
//!   - `osr_mouse_click` / `osr_mouse_move` / `osr_mouse_wheel`
//!   - `osr_key_event`
//!   - `osr_resize` (via `Page.setDeviceMetricsOverride` + screencast restart)
//!   - `tabs_summary`, `tab_count`, `active_index`, `active_tab`
//!
//! Stubbed (return `EngineError::Unimplemented`):
//!   - All popup_* methods
//!   - hint_*, find_*, zoom_*, devtools_*, scheme_handler_*, audio_*, video_*,
//!     permissions_* methods
//!   - `duplicate_active`, `move_tab`, `reopen_closed_tab`
//!
//! # Architecture
//!
//! ```text
//! UI thread                   worker thread
//! ─────────                   ─────────────
//! BlinkCdpEngine
//!   cmd_tx ──── Command ────▶ run()
//!//!                              ├─ tungstenite WebSocket (blocking)
//!                              └─ captures screenshots → SharedOsrFrame
//! ```
//!
//! # Phase 8f: `buffr://` and `view-source:` scheme translation
//!
//! Chromium rejects unknown schemes before CDP `Fetch` can intercept them.
//! Instead of fighting the network stack, we translate at the engine layer:
//!
//! | Input URL              | Translated to                          |
//! |------------------------|----------------------------------------|
//! | `buffr://new`          | `data:text/html;base64,<newtab_html>`  |
//! | `buffr://settings`     | `data:text/html;base64,<settings_html>`|
//! | `view-source:<url>`    | `data:text/html;base64,<source_html>`  |
//!
//! The original URL is stashed in [`EngineState::original_urls`] (keyed by
//! `target_id`) so `active_tab_live_url` and `tabs_summary` return the
//! human-readable URL rather than the opaque `data:` URL.

use std::collections::HashMap;
use std::path::Path;
use std::sync::mpsc::{self, SyncSender};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::Duration;

use base64::Engine as Base64Engine;
use buffr_core::DownloadNoticeQueue;
use buffr_core::find::{FindResult, FindResultSink, new_sink as new_find_sink};
use buffr_downloads::Downloads;
use buffr_engine::{
    BrowserEngine, EngineError, MouseButton, NeutralKeyEvent, OsrFrame, OsrViewState,
    PermissionsQueue, PopupCloseSink, PopupCreateSink, PopupQueue, PromptOutcome, SharedOsrFrame,
    SharedOsrViewState, TabId, TabSummary,
};
use serde_json::Value;

use crate::cdp::{
    AttachToTargetParams, CdpCommand, CloseTargetParams, CreateTargetParams,
    DetachFromTargetParams, DispatchKeyEventParams, DispatchMouseEventParams,
    SetDeviceMetricsParams, key_event_type, mouse_button_str, next_id,
};
use crate::context_menu::{ContextMenuSink, new_context_menu_sink};
use crate::error::BlinkError;
use crate::find::{find_expr, parse_find_result, stop_expr};
use crate::subprocess::{find_chromium, pick_free_port, probe_ws_url, spawn_headless};
use crate::worker::{Command, UrlUpdateSink, new_title_map, new_url_update_sink, run};
use crate::ws::WsClient;

// ── Internal tab representation ───────────────────────────────────────────────

/// Linear zoom scale factor applied via `document.body.style.zoom`.
///
/// Matches the CEF backend's 0.25-per-step increment (see
/// `buffr_cef::host::adjust_zoom` which calls `set_zoom_level(level ± 0.25)`).
///
/// CSS zoom `1.0` = 100 % (browser default).  Clamped to `[0.25, 5.0]`.
pub const ZOOM_STEP: f64 = 0.25;

/// Minimum zoom level (25 %).
pub const ZOOM_MIN: f64 = 0.25;

/// Maximum zoom level (500 %).
pub const ZOOM_MAX: f64 = 5.0;

/// Apply a zoom delta and clamp to `[ZOOM_MIN, ZOOM_MAX]`.
///
/// Pass `delta = 0.0` and `current = 1.0` to reset.
#[inline]
fn clamp_zoom(level: f64) -> f64 {
    level.clamp(ZOOM_MIN, ZOOM_MAX)
}

#[derive(Debug, Clone)]
struct CdpTab {
    id: TabId,
    target_id: String,
    session_id: String,
    url: String,
    title: String,
    /// CSS zoom factor for this tab. `1.0` = 100 % (default).
    zoom_level: f64,
}

impl CdpTab {
    /// Build a [`TabSummary`].
    ///
    /// `is_loading` — pass `true` when the per-session loading-state map says
    /// this session is still loading (P1-5).
    fn to_summary(&self, is_loading: bool) -> TabSummary {
        TabSummary {
            id: self.id,
            browser_id: 0, // CDP has no numeric browser_id; use 0
            title: self.title.clone(),
            url: self.url.clone(),
            progress: if is_loading { 0.5 } else { 1.0 },
            is_loading,
            pinned: false,
            private: false,
        }
    }
}

// ── Engine state (behind a Mutex) ─────────────────────────────────────────────

struct EngineState {
    tabs: Vec<CdpTab>,
    active: Option<TabId>,
    next_tab_id: u64,
    /// Chromium remote-debugging port chosen at startup.
    debug_port: u16,
    /// Maps `target_id → original_url` for tabs where the navigated URL
    /// was translated (e.g. `buffr://new` → `data:text/html;base64,...`).
    /// `active_tab_live_url` and `to_summary` prefer this over `CdpTab::url`
    /// so the address bar shows the human-readable `buffr://` URL.
    original_urls: HashMap<String, String>,
}

impl EngineState {
    fn new(debug_port: u16) -> Self {
        Self {
            tabs: Vec::new(),
            active: None,
            next_tab_id: 1,
            debug_port,
            original_urls: HashMap::new(),
        }
    }

    fn mint_tab_id(&mut self) -> TabId {
        let id = TabId(self.next_tab_id);
        self.next_tab_id += 1;
        id
    }

    fn tab_by_id(&self, id: TabId) -> Option<&CdpTab> {
        self.tabs.iter().find(|t| t.id == id)
    }

    fn active_tab(&self) -> Option<&CdpTab> {
        let id = self.active?;
        self.tab_by_id(id)
    }
}

// ── Public engine struct ──────────────────────────────────────────────────────

/// Closure invoked on each `buffr://new` (or `buffr://settings`) navigation
/// request to produce fresh page HTML bytes. Mirroring [`buffr_engine::NewTabHtmlProvider`]
/// but local to the blink-cdp engine instance.
pub type HtmlProvider = Arc<dyn Fn() -> Vec<u8> + Send + Sync>;

/// Return the display URL for a tab, preferring any stashed original URL
/// (set when the actual navigation used a translated `data:` URL).
fn display_url_for<'a>(tab: &'a CdpTab, original_urls: &'a HashMap<String, String>) -> &'a str {
    original_urls
        .get(&tab.target_id)
        .map(String::as_str)
        .unwrap_or(tab.url.as_str())
}

/// HTML-escape the five characters that matter in page source output.
fn html_escape_source(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(c),
        }
    }
    out
}

/// Synchronous ureq fetch + HTML wrapper for view-source. Called from the
/// background thread spawned by `spawn_view_source_fetch`.
///
/// Returns the complete HTML document bytes to encode as a data URL.
/// P0-7: uses ureq 3 Agent API with explicit 15 s connect + response timeouts.
fn view_source_html_sync(target_url: &str) -> Vec<u8> {
    let config = ureq::Agent::config_builder()
        .timeout_connect(Some(std::time::Duration::from_secs(15)))
        .timeout_recv_response(Some(std::time::Duration::from_secs(15)))
        .build();
    let agent = ureq::Agent::new_with_config(config);

    let body = match agent.get(target_url).call() {
        Ok(mut response) => {
            let status = response.status().as_u16();
            match response.body_mut().read_to_string() {
                Ok(text) => {
                    let escaped = html_escape_source(&text);
                    format!(
                        r#"<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>view-source:{target_url}</title>
  <style>
    body {{ margin: 0; background: #1a1a1a; color: #d4d4d4; font-family: monospace; font-size: 0.85rem; }}
    .header {{ background: #252526; padding: 0.5rem 1rem; border-bottom: 1px solid #333; color: #9cdcfe; }}
    pre {{ margin: 0; padding: 1rem; white-space: pre-wrap; word-break: break-all; line-height: 1.5; }}
  </style>
</head>
<body>
  <div class="header">view-source: <strong>{target_url}</strong> &mdash; HTTP {status}</div>
  <pre>{escaped}</pre>
</body>
</html>"#
                    )
                }
                Err(e) => format!(
                    "<!DOCTYPE html><html><body><p>Error reading response body: {e}</p></body></html>"
                ),
            }
        }
        Err(e) => format!(
            r#"<!DOCTYPE html>
<html>
<head><meta charset="utf-8"/><title>view-source error</title>
<style>body{{font-family:system-ui,sans-serif;background:#1a1a1a;color:#e0e0e0;margin:2rem;}}</style>
</head>
<body><h1>view-source error</h1><p>Could not fetch <code>{}</code>:</p><pre>{}</pre></body>
</html>"#,
            html_escape_source(target_url),
            html_escape_source(&e.to_string()),
        ),
    };
    body.into_bytes()
}

/// Build the "Fetching source…" placeholder data URL shown immediately when
/// a `view-source:` tab is opened. The real content replaces it once the
/// background fetch completes.
fn view_source_loading_data_url(target_url: &str) -> String {
    let html = format!(
        r#"<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>view-source: {target_url}</title>
  <style>
    body {{ margin: 0; display: flex; align-items: center; justify-content: center;
            height: 100vh; background: #1a1a1a; color: #9cdcfe;
            font-family: monospace; font-size: 1rem; }}
  </style>
</head>
<body>Fetching source: {target_url}</body>
</html>"#
    );
    let encoded = base64::engine::general_purpose::STANDARD.encode(html.as_bytes());
    format!("data:text/html;base64,{encoded}")
}

/// Spawn a background thread that fetches `target_url` via ureq (15 s timeout),
/// encodes the result as a `data:text/html;base64,…` URL, and posts a
/// `Command::Navigate` on `session_id` to replace the loading placeholder.
///
/// The `cmd_tx` is downgraded to a `Weak` equivalent by using
/// [`std::sync::mpsc::SyncSender::try_send`] — if the sender is gone (engine
/// shut down) the thread just exits without panicking (P0-7).
fn spawn_view_source_fetch(
    target_url: String,
    session_id: String,
    cmd_tx: std::sync::mpsc::SyncSender<Command>,
) {
    std::thread::Builder::new()
        .name(format!("blink-cdp-view-source:{target_url}"))
        .spawn(move || {
            tracing::debug!(
                target_url,
                session_id,
                "blink-cdp: view-source fetch thread started"
            );
            let html_bytes = view_source_html_sync(&target_url);
            let encoded = base64::engine::general_purpose::STANDARD.encode(&html_bytes);
            let data_url = format!("data:text/html;base64,{encoded}");

            let (reply_tx, _reply_rx) = std::sync::mpsc::channel();
            // try_send: if the engine is gone, the channel is disconnected and we silently bail.
            if let Err(e) = cmd_tx.try_send(Command::Navigate {
                session_id,
                url: data_url,
                reply: reply_tx,
            }) {
                tracing::debug!(
                    target_url,
                    error = %e,
                    "blink-cdp: view-source fetch thread: engine gone, dropping result"
                );
            }
        })
        .ok(); // If thread spawn fails, silently skip.
}

/// Headless Chromium engine driven over Chrome DevTools Protocol.
///
/// Construct via [`BlinkCdpEngine::new`].  Each instance owns a dedicated
/// Chromium subprocess and a single CDP WebSocket connection.
pub struct BlinkCdpEngine {
    state: Arc<Mutex<EngineState>>,
    cmd_tx: SyncSender<Command>,
    osr_frame: SharedOsrFrame,
    osr_view: SharedOsrViewState,
    /// Handle to the worker thread. Wrapped in `Option` so `Drop` can `take()` and join it.
    worker: Option<JoinHandle<()>>,
    /// Handle to the chromium subprocess.  Killed in `close_all_browsers` and `Drop`.
    subprocess: Arc<Mutex<Option<std::process::Child>>>,
    /// Provider for `buffr://new` HTML (keybinds + splash art substituted).
    /// `None` → serve the raw template with markers intact (tests / unconfigured).
    newtab_html_provider: Mutex<Option<HtmlProvider>>,
    /// Provider for `buffr://settings` HTML. `None` → use built-in placeholder.
    settings_html_provider: Mutex<Option<HtmlProvider>>,
    /// Neutral permissions queue — Phase 8a (#88). The worker pushes
    /// entries when the JS shim fires a `Runtime.bindingCalled` event for
    /// `__buffrPermissionRequest`. The UI thread drains via the trait.
    permissions_queue: PermissionsQueue,
    /// Maps `resolve_id → session_id` so `resolve_permission` can evaluate
    /// `__buffrPermissionResolve` on the correct CDP session.
    perm_session_map: Arc<Mutex<std::collections::HashMap<String, String>>>,
    /// Shared downloads store. Passed in at construction from the apps
    /// layer; the worker writes to it on CDP download events. `None` when
    /// no store was provided (private mode or blink-cdp without wiring).
    ///
    /// Held here to keep the `Arc` alive for the worker thread's clone;
    /// the engine itself does not call into the store directly.
    #[allow(dead_code)]
    downloads: Option<Arc<Downloads>>,
    /// Download notice queue for surfacing start/complete banners in the
    /// status-line chrome. `None` when not wired by the apps layer.
    ///
    /// Held here to keep the `Arc` alive for the worker thread's clone.
    #[allow(dead_code)]
    notice_queue: Option<DownloadNoticeQueue>,
    /// One-slot mailbox written by [`start_find`] / [`stop_find`] after
    /// each JS roundtrip. The apps layer polls this each tick via
    /// `buffr_core::take_find_result` to update the statusline.
    find_sink: FindResultSink,
    /// Most recent search query on the active tab. Preserved so
    /// `FindNext` / `FindPrev` (dispatched from `n` / `N` keybinds) can
    /// step through matches without repeating the full scan.
    find_query: Arc<Mutex<Option<String>>>,
    /// Context-menu request queue (Phase 8c, #87). The worker pushes entries
    /// when the JS shim fires `Runtime.bindingCalled` for `__buffrContextMenu`.
    /// The UI thread drains via `drain_context_menu_requests`.
    context_menu_sink: ContextMenuSink,
    /// URL/title updates from `Page.frameNavigated` events (audit P0-1).
    /// The worker pushes `(session_id, url, title)` entries; the engine drains
    /// them in `pump_address_changes` to keep `CdpTab::url`/`title` current.
    url_update_sink: UrlUpdateSink,
    /// Popup URL queue (P1-9). Stored here so every call to `popup_queue`
    /// returns the *same* `Arc` rather than a fresh allocation per call.
    popup_queue: PopupQueue,
    /// Popup-created sink (P1-9). Same rationale as `popup_queue`.
    popup_create_sink: PopupCreateSink,
    /// Popup-closed sink (P1-9). Same rationale as `popup_queue`.
    popup_close_sink: PopupCloseSink,
    /// Per-session loading state — updated via `Page.lifecycleEvent` pushes
    /// (audit P1-5). `true` = page is still loading; `false` = load complete.
    /// Keyed by session_id.
    loading_state: Arc<Mutex<HashMap<String, bool>>>,
    /// Per-session navigation-count — incremented on every `Page.frameNavigated`
    /// event (audit P1-5). Used as a proxy for history depth so
    /// `can_go_back/forward` returns `false` for freshly-opened tabs.
    /// Keyed by session_id.
    nav_count: Arc<Mutex<HashMap<String, usize>>>,
    /// Live title map (audit P2-5). The worker writes `target_id → title` on
    /// `Target.targetInfoChanged` events. The engine reads this in `tabs_summary`
    /// to serve current titles without a CDP round-trip.
    title_map: crate::worker::TitleMap,
}

impl BlinkCdpEngine {
    /// Construct a new engine instance.
    ///
    /// Locates a system Chromium binary, probes the OS for a free ephemeral
    /// port, spawns a headless subprocess on that port, waits for the CDP
    /// endpoint to become available, then connects the WebSocket and starts
    /// the worker thread.
    ///
    /// The port is selected via [`pick_free_port`] — multiple engine instances
    /// can therefore coexist without conflicts, and port 9222 is no longer
    /// special.
    ///
    /// `data_dir` is used as the Chromium user-data directory (persistent state:
    /// cookies, localStorage, history).
    ///
    /// `cache_dir` is an optional ephemeral cache directory. When `Some`,
    /// Chromium is launched with `--disk-cache-dir=<path>` so the HTTP cache,
    /// GPU shader cache, and code cache land outside `data_dir`. The directory
    /// is pre-created before spawn because Chromium silently falls back to its
    /// default location when the path does not exist.
    ///
    /// `download_dir` — if provided — is passed to `Browser.setDownloadBehavior`
    /// so Chromium saves files there instead of the default desktop location.
    ///
    /// `downloads` and `notice_queue` are the shared stores used to record
    /// download progress and surface status-line banners. Pass `None` when
    /// running without storage (e.g. private mode without a persistent store).
    ///
    /// `find_sink` is the one-slot mailbox shared with the apps layer so
    /// find results are visible in the statusline. Pass the same sink that
    /// `AppState::find_sink` was constructed with. If `None`, a private
    /// sink is created (results are computed but not surfaced to the UI).
    pub fn new(
        data_dir: &Path,
        cache_dir: Option<&Path>,
        download_dir: Option<&Path>,
        downloads: Option<Arc<Downloads>>,
        notice_queue: Option<DownloadNoticeQueue>,
        find_sink: Option<FindResultSink>,
    ) -> Result<Self, BlinkError> {
        let chromium = find_chromium().ok_or(BlinkError::ChromiumNotFound)?;

        // Ask the OS for a free ephemeral port.
        let port = pick_free_port()?;

        std::fs::create_dir_all(data_dir).map_err(BlinkError::SpawnFailed)?;

        let child = spawn_headless(&chromium, port, data_dir, cache_dir)?;

        // Wait for Chromium to start accepting connections.
        let ws_url = probe_ws_url(
            port,
            crate::subprocess::WS_PROBE_MAX_RETRIES,
            Duration::from_millis(crate::subprocess::WS_PROBE_INTERVAL_MS),
        )?;

        // Connect the browser-level WebSocket.
        let ws = WsClient::connect(&ws_url)?;

        // Build shared state.
        let osr_frame = Arc::new(Mutex::new(OsrFrame::new(1280, 800)));
        let osr_view = Arc::new(OsrViewState::new());

        // Permissions queue and session map (Phase 8a, #88).
        let permissions_queue = buffr_engine::permissions::new_queue();
        let perm_session_map: Arc<Mutex<std::collections::HashMap<String, String>>> =
            Arc::new(Mutex::new(std::collections::HashMap::new()));

        // Context-menu sink (Phase 8c, #87).
        let context_menu_sink = new_context_menu_sink();

        // URL update sink (audit P0-1): worker pushes frameNavigated updates here.
        let url_update_sink = new_url_update_sink();

        // Loading state map (P1-5): worker pushes Page.lifecycleEvent updates here.
        let loading_state: Arc<Mutex<HashMap<String, bool>>> = Arc::new(Mutex::new(HashMap::new()));

        // Navigation-count map (P1-5): worker increments on each Page.frameNavigated.
        let nav_count: Arc<Mutex<HashMap<String, usize>>> = Arc::new(Mutex::new(HashMap::new()));

        // Live title map (P2-5): worker writes target_id → title on Target.targetInfoChanged.
        let title_map = new_title_map();

        // Resolve the effective download directory.  If the caller did not
        // supply one, fall back to `<data_dir>/downloads` so downloads always
        // land somewhere deterministic rather than Chromium's default desktop
        // location.
        let effective_download_dir = download_dir
            .map(|p| p.to_path_buf())
            .unwrap_or_else(|| data_dir.join("downloads"));
        if let Err(e) = std::fs::create_dir_all(&effective_download_dir) {
            tracing::warn!(
                path = %effective_download_dir.display(),
                error = %e,
                "blink-cdp: failed to create download directory"
            );
        }

        // Spawn worker thread.
        let (cmd_tx, cmd_rx) = mpsc::sync_channel::<Command>(crate::worker::WORKER_CMD_CHANNEL_CAP);
        let worker_frame = Arc::clone(&osr_frame);
        let worker_view = Arc::clone(&osr_view);
        let worker_perm_queue = Arc::clone(&permissions_queue);
        let worker_perm_session = Arc::clone(&perm_session_map);
        let worker_downloads = downloads.clone();
        let worker_notice_queue = notice_queue.clone();
        let worker_download_dir = effective_download_dir.clone();
        let worker_context_menu_sink = Arc::clone(&context_menu_sink);
        let worker_url_update_sink = Arc::clone(&url_update_sink);
        let worker_loading_state = Arc::clone(&loading_state);
        let worker_nav_count = Arc::clone(&nav_count);
        let worker_title_map = Arc::clone(&title_map);
        let worker = std::thread::Builder::new()
            .name("blink-cdp-worker".to_owned())
            .spawn(move || {
                run(
                    ws,
                    cmd_rx,
                    worker_frame,
                    worker_view,
                    worker_perm_queue,
                    worker_perm_session,
                    worker_downloads,
                    worker_notice_queue,
                    worker_download_dir,
                    worker_context_menu_sink,
                    worker_url_update_sink,
                    worker_loading_state,
                    worker_nav_count,
                    worker_title_map,
                )
            })
            .map_err(BlinkError::SpawnFailed)?;

        // Configure Browser.setDownloadBehavior so downloads land in our
        // directory and the worker receives Browser.downloadWillBegin /
        // Browser.downloadProgress events.  This must be sent AFTER the
        // worker is started (it owns the WebSocket) via a BrowserCmd round-trip.
        let (reply_tx, reply_rx) = mpsc::channel();
        let download_behavior_cmd = crate::cdp::CdpCommand {
            id: crate::cdp::next_id(),
            method: "Browser.setDownloadBehavior",
            params: Some(serde_json::json!({
                "behavior": "allow",
                "downloadPath": effective_download_dir.to_string_lossy().as_ref(),
                "eventsEnabled": true,
            })),
            session_id: None,
        };
        let _ = cmd_tx.try_send(Command::BrowserCmd {
            cmd: download_behavior_cmd,
            reply: reply_tx,
        });
        // Best-effort: don't block startup on a timing failure.
        match reply_rx.recv_timeout(Duration::from_secs(5)) {
            Ok(Ok(_)) => {
                tracing::debug!(
                    path = %effective_download_dir.display(),
                    "blink-cdp: Browser.setDownloadBehavior configured"
                );
            }
            Ok(Err(e)) => {
                tracing::warn!(error = %e, "blink-cdp: Browser.setDownloadBehavior failed");
            }
            Err(_) => {
                tracing::warn!("blink-cdp: Browser.setDownloadBehavior timed out");
            }
        }

        Ok(Self {
            state: Arc::new(Mutex::new(EngineState::new(port))),
            cmd_tx,
            osr_frame,
            osr_view,
            worker: Some(worker),
            subprocess: Arc::new(Mutex::new(Some(child))),
            newtab_html_provider: Mutex::new(None),
            settings_html_provider: Mutex::new(None),
            permissions_queue,
            perm_session_map,
            downloads,
            notice_queue,
            find_sink: find_sink.unwrap_or_else(new_find_sink),
            find_query: Arc::new(Mutex::new(None)),
            context_menu_sink,
            url_update_sink,
            popup_queue: buffr_engine::new_popup_queue(),
            popup_create_sink: buffr_engine::new_popup_create_sink(),
            popup_close_sink: buffr_engine::new_popup_close_sink(),
            loading_state,
            nav_count,
            title_map,
        })
    }

    // ── Public configuration ──────────────────────────────────────────────────

    /// Set the HTML provider for `buffr://new` navigation.
    ///
    /// Called by the apps layer after construction, passing the same closure
    /// that was registered with the CEF backend's scheme handler factory.
    /// The provider is invoked once per navigation to produce fresh HTML
    /// (keybind hot-reloads, splash art).
    pub fn set_newtab_html_provider(&self, provider: HtmlProvider) {
        if let Ok(mut guard) = self.newtab_html_provider.lock() {
            *guard = Some(provider);
        }
    }

    /// Set the HTML provider for `buffr://settings` navigation.
    pub fn set_settings_html_provider(&self, provider: HtmlProvider) {
        if let Ok(mut guard) = self.settings_html_provider.lock() {
            *guard = Some(provider);
        }
    }

    // ── Scheme translation (Phase 8f, #81) ───────────────────────────────────

    /// Produce the `buffr://new` page bytes: invoke the provider if wired,
    /// else fall back to the raw template.
    fn newtab_html_bytes(&self) -> Vec<u8> {
        if let Ok(guard) = self.newtab_html_provider.lock()
            && let Some(ref provider) = *guard
        {
            provider()
        } else {
            buffr_engine::newtab::NEW_TAB_HTML_TEMPLATE
                .as_bytes()
                .to_vec()
        }
    }

    /// Produce the `buffr://settings` page bytes: invoke the provider if wired,
    /// else return a minimal placeholder.
    fn settings_html_bytes(&self) -> Vec<u8> {
        if let Ok(guard) = self.settings_html_provider.lock()
            && let Some(ref provider) = *guard
        {
            provider()
        } else {
            b"<!DOCTYPE html><html><head><meta charset=\"utf-8\"/><title>buffr settings</title></head>\
              <body style=\"font-family:system-ui,sans-serif;background:#1a1a1a;color:#e0e0e0;margin:2rem\">\
              <h1>buffr settings</h1><p>Settings provider not configured.</p></body></html>"
                .to_vec()
        }
    }

    /// Translate an internal `buffr://` or `view-source:` URL into a
    /// `data:text/html;base64,…` URL that Chromium can actually load.
    ///
    /// Returns `Some(data_url)` when the URL is internal; `None` when it
    /// should be passed to Chromium as-is.
    ///
    /// P0-7: For `view-source:` URLs the returned data URL is a lightweight
    /// "Fetching source…" placeholder. The caller must invoke
    /// `schedule_view_source_fetch` with the session_id once the tab is open.
    fn translate_internal_url(&self, url: &str) -> Option<String> {
        if url.starts_with("buffr://settings") {
            let bytes = self.settings_html_bytes();
            let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
            Some(format!("data:text/html;base64,{encoded}"))
        } else if url.starts_with("buffr://") {
            // buffr://new, buffr://newtab, or any other buffr:// path → new-tab.
            let bytes = self.newtab_html_bytes();
            let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
            Some(format!("data:text/html;base64,{encoded}"))
        } else if url.starts_with("view-source:") {
            // P0-7: Return placeholder immediately; real fetch is async.
            Some(view_source_loading_data_url(
                url.trim_start_matches("view-source:"),
            ))
        } else {
            None
        }
    }

    /// If `url` is a `view-source:` URL, spawn the background fetch thread
    /// that will post `Command::Navigate` with the final data URL on `session_id`
    /// once the fetch completes (P0-7).
    fn schedule_view_source_fetch_if_needed(&self, url: &str, session_id: &str) {
        if let Some(target_url) = url.strip_prefix("view-source:") {
            spawn_view_source_fetch(
                target_url.to_owned(),
                session_id.to_owned(),
                self.cmd_tx.clone(),
            );
        }
    }

    // ── Internal helpers ──────────────────────────────────────────────────────

    /// Adjust the active tab's zoom by `delta` (clamped to `[ZOOM_MIN, ZOOM_MAX]`)
    /// and send a `Command::SetZoom` to the worker.
    fn adjust_zoom(&self, delta: f64) {
        let current = self
            .state
            .lock()
            .unwrap()
            .active_tab()
            .map(|t| t.zoom_level)
            .unwrap_or(1.0);
        self.apply_zoom(clamp_zoom(current + delta));
    }

    /// Set the active tab's zoom to `level` (already clamped) and send
    /// a `Command::SetZoom` to the worker.
    fn apply_zoom(&self, level: f64) {
        let session_id = {
            let mut state = self.state.lock().unwrap();
            let Some(id) = state.active else { return };
            let Some(tab) = state.tabs.iter_mut().find(|t| t.id == id) else {
                return;
            };
            tab.zoom_level = level;
            tab.session_id.clone()
        };
        tracing::debug!(level, "blink-cdp: apply_zoom");
        let _ = self.cmd_tx.try_send(Command::SetZoom { session_id, level });
    }

    /// Send a browser-level CDP command and wait for the response.
    fn browser_cmd(
        &self,
        method: &'static str,
        params: impl serde::Serialize,
    ) -> Result<Value, BlinkError> {
        let (reply_tx, reply_rx) = mpsc::channel();
        let cmd = CdpCommand {
            id: next_id(),
            method,
            params: Some(serde_json::to_value(params).unwrap_or(Value::Null)),
            session_id: None,
        };
        self.cmd_tx
            .try_send(Command::BrowserCmd {
                cmd,
                reply: reply_tx,
            })
            .map_err(|_| BlinkError::WorkerDead)?;
        reply_rx
            .recv_timeout(Duration::from_secs(
                crate::worker::CDP_RESPONSE_TIMEOUT_SECS,
            ))
            .map_err(|_| BlinkError::Timeout { method })
            .and_then(|r| r)
    }

    /// Send a session-scoped CDP command and wait for the response.
    fn session_cmd(
        &self,
        session_id: &str,
        method: &'static str,
        params: impl serde::Serialize,
    ) -> Result<Value, BlinkError> {
        let (reply_tx, reply_rx) = mpsc::channel();
        let cmd = CdpCommand {
            id: next_id(),
            method,
            params: Some(serde_json::to_value(params).unwrap_or(Value::Null)),
            session_id: Some(session_id.to_owned()),
        };
        self.cmd_tx
            .try_send(Command::SessionCmd {
                session_id: session_id.to_owned(),
                cmd,
                reply: reply_tx,
            })
            .map_err(|_| BlinkError::WorkerDead)?;
        reply_rx
            .recv_timeout(Duration::from_secs(
                crate::worker::CDP_RESPONSE_TIMEOUT_SECS,
            ))
            .map_err(|_| BlinkError::Timeout { method })
            .and_then(|r| r)
    }

    /// Create a new CDP target (page) and attach to it.
    ///
    /// Returns `(target_id, session_id)`.
    fn create_and_attach(&self, url: &str) -> Result<(String, String), BlinkError> {
        // Create target.
        let result = self.browser_cmd(
            "Target.createTarget",
            CreateTargetParams {
                url: url.to_owned(),
            },
        )?;
        let target_id = result
            .get("targetId")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                BlinkError::Protocol("missing targetId in createTarget response".into())
            })?
            .to_owned();

        // Attach.
        let result = self.browser_cmd(
            "Target.attachToTarget",
            AttachToTargetParams {
                target_id: target_id.clone(),
                flatten: true,
            },
        )?;
        let session_id = result
            .get("sessionId")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                BlinkError::Protocol("missing sessionId in attachToTarget response".into())
            })?
            .to_owned();

        Ok((target_id, session_id))
    }

    /// Internal open-tab implementation. Returns (TabId, tab_becomes_active).
    /// Internal tab-open implementation.
    ///
    /// `insert_idx` — when `Some(i)`, the new tab is inserted at position `i`
    /// (clamped to the current length) instead of being pushed at the end (P1-7).
    fn open_tab_internal(
        &self,
        url: &str,
        make_active: bool,
        insert_idx: Option<usize>,
    ) -> Result<TabId, EngineError> {
        // Phase 8f: translate internal schemes before handing the URL to Chromium.
        let translated = self.translate_internal_url(url);
        let navigate_url = translated.as_deref().unwrap_or(url);
        let original_url = if translated.is_some() {
            Some(url.to_owned())
        } else {
            None
        };

        // P0-3: Create the target with about:blank so the page is NOT loading
        // before we can inject bindings and shims. We navigate to the real URL
        // only after all addBinding + addScriptToEvaluateOnNewDocument calls.
        let (target_id, session_id) = self
            .create_and_attach("about:blank")
            .map_err(EngineError::from)?;

        // Helper: run a session setup command and warn (but continue) on failure.
        // Failures here leave the tab registered but with that feature broken —
        // the warn log makes the broken state diagnosable without aborting the
        // whole tab-open path.
        let setup_cmd = |engine: &Self, method: &'static str, params: serde_json::Value| {
            if let Err(e) = engine.session_cmd(&session_id, method, params) {
                tracing::warn!(
                    target_id = %target_id,
                    method,
                    error = %e,
                    "blink-cdp: session setup command failed"
                );
            }
        };

        // P0-2: Enable Page and Runtime domains BEFORE any other Page.*/Runtime.*
        // commands. Without these, Page.frameNavigated and Runtime.bindingCalled
        // event delivery is build-version-dependent.
        setup_cmd(self, "Page.enable", serde_json::json!({}));
        setup_cmd(self, "Runtime.enable", serde_json::json!({}));

        // P1-5: enable lifecycle events so the worker receives
        // `Page.lifecycleEvent` with names `init`, `DOMContentLoaded`, `load`.
        // We mark the session as loading at open time; the worker clears it on
        // receipt of a `load` event.
        setup_cmd(
            self,
            "Page.setLifecycleEventsEnabled",
            serde_json::json!({ "enabled": true }),
        );
        // Mark session as loading immediately so `is_loading` is accurate from
        // the first moment the tab exists.
        if let Ok(mut map) = self.loading_state.lock() {
            map.insert(session_id.clone(), true);
        }

        // Apply initial viewport metrics.
        let (w, h) = {
            let v = &self.osr_view;
            use std::sync::atomic::Ordering;
            (
                v.width.load(Ordering::Relaxed),
                v.height.load(Ordering::Relaxed),
            )
        };
        setup_cmd(
            self,
            "Page.setDeviceMetricsOverride",
            serde_json::to_value(SetDeviceMetricsParams {
                width: w.max(1),
                height: h.max(1),
                device_scale_factor: 1.0,
                mobile: false,
            })
            .unwrap_or(serde_json::Value::Null),
        );

        // Register the permission binding so the JS shim can post requests
        // (Phase 8a, #88). `Runtime.addBinding` makes `window.__buffrPermissionRequest`
        // available in the page's JS context.
        setup_cmd(
            self,
            "Runtime.addBinding",
            serde_json::json!({ "name": "__buffrPermissionRequest" }),
        );

        // Inject the permission shim for all future documents on this session.
        let shim_js = crate::permissions::permission_shim_js();
        setup_cmd(
            self,
            "Page.addScriptToEvaluateOnNewDocument",
            serde_json::json!({ "source": shim_js }),
        );

        // Inject the find-in-page shim (Phase 8b, #83). Provides
        // `__buffrFindNext`, `__buffrFindPrev`, and `__buffrFindStop`
        // globally. The shim uses a TreeWalker-based DOM scan and CSS span
        // overlays — no native CDP find API required.
        setup_cmd(
            self,
            "Page.addScriptToEvaluateOnNewDocument",
            serde_json::json!({ "source": crate::find::find_shim_js() }),
        );

        // Register the context-menu binding and inject the hit-test shim
        // (Phase 8c, #87). `Runtime.addBinding` makes `window.__buffrContextMenu`
        // callable from the page's JS context, which the shim uses to post
        // right-click metadata to the worker.
        setup_cmd(
            self,
            "Runtime.addBinding",
            serde_json::json!({ "name": "__buffrContextMenu" }),
        );
        setup_cmd(
            self,
            "Page.addScriptToEvaluateOnNewDocument",
            serde_json::json!({ "source": crate::context_menu::context_menu_shim_js() }),
        );

        // P0-3: Now that all bindings and shims are registered, navigate to
        // the real URL. Shims are already in addScriptToEvaluateOnNewDocument
        // so they will fire on the first committed document.
        tracing::debug!(
            navigate_url,
            "blink-cdp: P0-3 navigating to real URL after shim setup"
        );
        let (nav_reply_tx, nav_reply_rx) = mpsc::channel();
        self.cmd_tx
            .try_send(Command::Navigate {
                session_id: session_id.clone(),
                url: navigate_url.to_owned(),
                reply: nav_reply_tx,
            })
            .map_err(|_| EngineError::Other("worker channel full during open_tab".into()))?;
        // Best-effort: don't block tab creation on navigation completion.
        // Reply is Result<Value, BlinkError>; Ok(_) means the navigate started.
        match nav_reply_rx.recv_timeout(Duration::from_secs(
            crate::worker::CDP_RESPONSE_TIMEOUT_SECS,
        )) {
            Ok(Ok(_)) => {}
            Ok(Err(e)) => {
                tracing::warn!(navigate_url, error = %e, "blink-cdp: initial navigation error (continuing)");
            }
            Err(_) => {
                tracing::warn!(
                    navigate_url,
                    "blink-cdp: initial navigation timed out (continuing)"
                );
            }
        }

        // P0-7: If this is a view-source: URL, the navigate_url is only the loading
        // placeholder (fast). Spawn the background fetch that will post the real
        // content data URL when ready. We use the original `url` here (not `navigate_url`).
        self.schedule_view_source_fetch_if_needed(url, &session_id);

        let mut state = self.state.lock().unwrap();
        let tab_id = state.mint_tab_id();
        // Store the translated (navigate) URL in the tab so worker events
        // that carry `data:` URLs are matched correctly. The display URL is
        // served from original_urls when present.
        let tab = CdpTab {
            id: tab_id,
            target_id: target_id.clone(),
            session_id: session_id.clone(),
            url: navigate_url.to_owned(),
            title: original_url.as_deref().unwrap_or(navigate_url).to_owned(),
            zoom_level: 1.0,
        };
        // Stash original URL for address-bar display.
        if let Some(orig) = original_url {
            state.original_urls.insert(target_id, orig);
        }
        // P1-7: honour insert_idx — insert at the requested position rather than
        // always pushing at the end.
        match insert_idx {
            Some(idx) => {
                let clamped = idx.min(state.tabs.len());
                state.tabs.insert(clamped, tab);
            }
            None => state.tabs.push(tab),
        }
        if make_active || state.active.is_none() {
            state.active = Some(tab_id);
            drop(state);
            // Start screencast on the new session.
            let (w, h) = self.viewport_dims();
            let _ = self.cmd_tx.try_send(Command::SetActiveSession {
                session_id: Some(session_id),
                width: w,
                height: h,
            });
        }
        Ok(tab_id)
    }

    /// Read current viewport dimensions from the shared view state.
    fn viewport_dims(&self) -> (u32, u32) {
        use std::sync::atomic::Ordering;
        let v = &self.osr_view;
        (
            v.width.load(Ordering::Relaxed).max(1),
            v.height.load(Ordering::Relaxed).max(1),
        )
    }

    /// Evaluate `expr` on the active tab's session and write a
    /// [`FindResult`] into `self.find_sink`.  Logs on failure and no-ops
    /// rather than propagating errors — find is non-critical.
    fn run_find_js(&self, expr: &str) {
        let session_id = {
            let state = self.state.lock().unwrap();
            match state.active_tab().map(|t| t.session_id.clone()) {
                Some(s) => s,
                None => {
                    tracing::debug!("blink-cdp: run_find_js — no active tab");
                    return;
                }
            }
        };

        match self.session_cmd(
            &session_id,
            "Runtime.evaluate",
            serde_json::json!({ "expression": expr, "returnByValue": true }),
        ) {
            Ok(value) => {
                if let Some(result) = parse_find_result(&value) {
                    tracing::debug!(
                        current = result.current,
                        total = result.count,
                        "blink-cdp: find result"
                    );
                    if let Ok(mut guard) = self.find_sink.lock() {
                        *guard = Some(result);
                    }
                } else {
                    tracing::debug!(?value, expr, "blink-cdp: find result parse failed");
                    // Write a zero result so the UI shows "no matches" rather
                    // than stale counts from a previous query.
                    if let Ok(mut guard) = self.find_sink.lock() {
                        *guard = Some(FindResult {
                            count: 0,
                            current: 0,
                            final_update: true,
                        });
                    }
                }
            }
            Err(e) => {
                tracing::debug!(error = %e, expr, "blink-cdp: Runtime.evaluate for find failed");
            }
        }
    }
}

// ── Drop (P1-4) ───────────────────────────────────────────────────────────────

/// Graceful shutdown on drop: signal the worker to stop, join the thread, and
/// kill the Chromium subprocess so no orphan processes are left behind.
///
/// `close_all_browsers` handles the same cleanup path explicitly (e.g. when
/// the user quits via the UI).  `Drop` is the safety net for all other
/// destruction paths (panics, test teardown, backend swap).
impl Drop for BlinkCdpEngine {
    fn drop(&mut self) {
        tracing::debug!("blink-cdp: Drop — shutting down worker and subprocess");

        // Signal worker shutdown.  Use `send` (blocking) so the message is
        // guaranteed to be delivered even if the sync channel is full.
        // If the channel is already disconnected the error is harmless.
        if let Err(e) = self.cmd_tx.send(Command::Shutdown) {
            tracing::debug!(error = %e, "blink-cdp: Drop — Shutdown send failed (worker already gone)");
        }

        // Join the worker thread.
        if let Some(handle) = self.worker.take()
            && let Err(e) = handle.join()
        {
            tracing::warn!("blink-cdp: Drop — worker thread panicked: {:?}", e);
        }

        // Kill the Chromium subprocess if still running.
        if let Ok(mut guard) = self.subprocess.lock()
            && let Some(mut child) = guard.take()
        {
            let _ = child.kill();
            let _ = child.wait();
            tracing::debug!("blink-cdp: Drop — Chromium subprocess killed");
        }
    }
}

// ── BrowserEngine impl ────────────────────────────────────────────────────────

impl BrowserEngine for BlinkCdpEngine {
    // ── Lifecycle ────────────────────────────────────────────────────────────

    fn close_all_browsers(&self) {
        tracing::debug!("blink-cdp: close_all_browsers");
        // Stop screencast on the active session (worker will send stopScreencast).
        let _ = self.cmd_tx.try_send(Command::SetActiveSession {
            session_id: None,
            width: 1,
            height: 1,
        });
        // Shut down the worker.
        let _ = self.cmd_tx.try_send(Command::Shutdown);
        // Kill the subprocess.
        if let Ok(mut guard) = self.subprocess.lock()
            && let Some(mut child) = guard.take()
        {
            let _ = child.kill();
            let _ = child.wait();
        }
        // Clear tab state.
        if let Ok(mut state) = self.state.lock() {
            state.tabs.clear();
            state.active = None;
            state.original_urls.clear();
        }
    }

    // ── Tabs ─────────────────────────────────────────────────────────────────

    fn open_tab(&self, url: &str) -> Result<TabId, EngineError> {
        tracing::debug!(url, "blink-cdp: open_tab");
        self.open_tab_internal(url, true, None)
    }

    fn open_tab_background(&self, url: &str) -> Result<TabId, EngineError> {
        tracing::debug!(url, "blink-cdp: open_tab_background");
        self.open_tab_internal(url, false, None)
    }

    fn open_tab_at(&self, url: &str, insert_idx: usize) -> Result<TabId, EngineError> {
        // P1-7: honour insert_idx so the new tab appears at the requested position.
        tracing::debug!(url, insert_idx, "blink-cdp: open_tab_at");
        self.open_tab_internal(url, true, Some(insert_idx))
    }

    fn close_tab(&self, id: TabId) -> Result<bool, EngineError> {
        tracing::debug!(%id, "blink-cdp: close_tab");
        let (target_id, session_id, was_active) = {
            let state = self.state.lock().unwrap();
            let tab = state.tab_by_id(id).ok_or(EngineError::TabNotFound(id))?;
            (
                tab.target_id.clone(),
                tab.session_id.clone(),
                state.active == Some(id),
            )
        };

        // P1-8: detach from the session before closing the target so the session
        // is cleanly torn down on Chromium's side.
        if let Err(e) = self.browser_cmd(
            "Target.detachFromTarget",
            DetachFromTargetParams {
                session_id: session_id.clone(),
            },
        ) {
            tracing::warn!(%id, error = %e, "blink-cdp: close_tab — detachFromTarget failed (continuing)");
        }

        // Close the CDP target.  Log but don't fail — the tab is gone from our
        // perspective regardless of whether Chromium's close call succeeds.
        if let Err(e) = self.browser_cmd(
            "Target.closeTarget",
            CloseTargetParams {
                target_id: target_id.clone(),
            },
        ) {
            tracing::warn!(%id, error = %e, "blink-cdp: close_tab — closeTarget failed (continuing)");
        }

        // P1-8: remove any pending permission entries for this session so the
        // perm_session_map doesn't grow unboundedly across many tab opens/closes.
        if let Ok(mut map) = self.perm_session_map.lock() {
            map.retain(|_, sess| sess != &session_id);
        }

        // P1-5: clean up per-session loading/nav-count state.
        if let Ok(mut m) = self.loading_state.lock() {
            m.remove(&session_id);
        }
        if let Ok(mut m) = self.nav_count.lock() {
            m.remove(&session_id);
        }

        let mut state = self.state.lock().unwrap();
        state.tabs.retain(|t| t.id != id);
        // Clean up any stashed original URL for this target.
        state.original_urls.remove(&target_id);

        // Pick a new active tab if needed.
        if was_active {
            state.active = state.tabs.last().map(|t| t.id);
            let new_session = state.active.and_then(|active_id| {
                state
                    .tabs
                    .iter()
                    .find(|t| t.id == active_id)
                    .map(|t| t.session_id.clone())
            });
            drop(state);
            let (w, h) = self.viewport_dims();
            let _ = self.cmd_tx.try_send(Command::SetActiveSession {
                session_id: new_session,
                width: w,
                height: h,
            });
        }

        let remaining = self.state.lock().unwrap().tabs.len();
        Ok(remaining > 0)
    }

    fn close_active(&self) -> Result<bool, EngineError> {
        let id = self
            .state
            .lock()
            .unwrap()
            .active
            .ok_or(EngineError::NoActiveTab)?;
        self.close_tab(id)
    }

    fn select_tab(&self, id: TabId) {
        tracing::debug!(%id, "blink-cdp: select_tab");
        let mut state = self.state.lock().unwrap();
        if let Some(tab) = state.tab_by_id(id) {
            let session_id = tab.session_id.clone();
            state.active = Some(id);
            drop(state);
            let (w, h) = self.viewport_dims();
            let _ = self.cmd_tx.try_send(Command::SetActiveSession {
                session_id: Some(session_id),
                width: w,
                height: h,
            });
        }
    }

    fn next_tab(&self) {
        let (len, current_idx) = {
            let state = self.state.lock().unwrap();
            let len = state.tabs.len();
            let idx = state
                .active
                .and_then(|id| state.tabs.iter().position(|t| t.id == id))
                .unwrap_or(0);
            (len, idx)
        };
        if len == 0 {
            return;
        }
        let next_idx = (current_idx + 1) % len;
        let id = self.state.lock().unwrap().tabs[next_idx].id;
        self.select_tab(id);
    }

    fn prev_tab(&self) {
        let (len, current_idx) = {
            let state = self.state.lock().unwrap();
            let len = state.tabs.len();
            let idx = state
                .active
                .and_then(|id| state.tabs.iter().position(|t| t.id == id))
                .unwrap_or(0);
            (len, idx)
        };
        if len == 0 {
            return;
        }
        let prev_idx = if current_idx == 0 {
            len - 1
        } else {
            current_idx - 1
        };
        let id = self.state.lock().unwrap().tabs[prev_idx].id;
        self.select_tab(id);
    }

    fn move_tab(&self, _from: usize, _to: usize) {
        tracing::warn!("blink-cdp: move_tab not implemented in Phase 4");
    }

    fn duplicate_active(&self) -> Result<TabId, EngineError> {
        Err(EngineError::Unimplemented {
            method: "duplicate_active",
        })
    }

    fn toggle_pin_active(&self) {
        tracing::warn!("blink-cdp: toggle_pin_active not implemented in Phase 4");
    }

    fn set_pinned(&self, _id: TabId, _pinned: bool) {
        tracing::warn!("blink-cdp: set_pinned not implemented in Phase 4");
    }

    fn reopen_closed_tab(&self) -> Result<Option<TabId>, EngineError> {
        Err(EngineError::Unimplemented {
            method: "reopen_closed_tab",
        })
    }

    fn closed_stack_len(&self) -> usize {
        0
    }

    fn active_tab(&self) -> Option<TabSummary> {
        let state = self.state.lock().unwrap();
        let loading = self.loading_state.lock().ok();
        // P2-5: overlay live title from Target.targetInfoChanged if available.
        let titles = self.title_map.lock().ok();
        state.active_tab().map(|t| {
            let is_loading = loading
                .as_ref()
                .and_then(|m| m.get(&t.session_id))
                .copied()
                .unwrap_or(false);
            let display = display_url_for(t, &state.original_urls).to_owned();
            let mut summary = t.to_summary(is_loading);
            summary.url = display;
            // Use live title when available and non-empty.
            if let Some(live_title) = titles
                .as_ref()
                .and_then(|m| m.get(&t.target_id))
                .filter(|s| !s.is_empty())
            {
                summary.title = live_title.clone();
            }
            summary
        })
    }

    fn tabs_summary(&self) -> Vec<TabSummary> {
        let state = self.state.lock().unwrap();
        let loading = self.loading_state.lock().ok();
        // P2-5: overlay live title from Target.targetInfoChanged if available.
        let titles = self.title_map.lock().ok();
        state
            .tabs
            .iter()
            .map(|t| {
                let is_loading = loading
                    .as_ref()
                    .and_then(|m| m.get(&t.session_id))
                    .copied()
                    .unwrap_or(false);
                let display = display_url_for(t, &state.original_urls).to_owned();
                let mut summary = t.to_summary(is_loading);
                summary.url = display;
                // Use live title when available and non-empty.
                if let Some(live_title) = titles
                    .as_ref()
                    .and_then(|m| m.get(&t.target_id))
                    .filter(|s| !s.is_empty())
                {
                    summary.title = live_title.clone();
                }
                summary
            })
            .collect()
    }

    fn tab_count(&self) -> usize {
        self.state.lock().unwrap().tabs.len()
    }

    fn pinned_count(&self) -> usize {
        0
    }

    fn active_index(&self) -> Option<usize> {
        let state = self.state.lock().unwrap();
        let active = state.active?;
        state.tabs.iter().position(|t| t.id == active)
    }

    // P1-5: track nav-count per session so we can give a reasonable answer to
    // can_go_back / can_go_forward.  A tab with > 1 navigations (count >= 2) is
    // likely to have back/forward history; freshly-opened tabs (count == 1 or 0)
    // definitely cannot go back.
    //
    // This is a heuristic: CDP doesn't expose the real history depth without a
    // Runtime.evaluate("window.history.length") round-trip, which is too heavy
    // for a method called on every render tick.  The heuristic is safe to err on
    // the side of enabling the buttons (old default was always-true anyway).

    fn can_go_back(&self) -> bool {
        let session_id = {
            let state = self.state.lock().unwrap();
            state.active_tab().map(|t| t.session_id.clone())
        };
        let Some(sess) = session_id else { return false };
        self.nav_count
            .lock()
            .ok()
            .and_then(|m| m.get(&sess).copied())
            .unwrap_or(0)
            >= 2
    }

    fn can_go_forward(&self) -> bool {
        // CDP doesn't give us a forward-history signal without a JS call.
        // Return false by default (conservative — no false positives in the UI).
        false
    }

    // ── Navigation ───────────────────────────────────────────────────────────

    fn navigate(&self, url: &str) -> Result<(), EngineError> {
        tracing::debug!(url, "blink-cdp: navigate");
        // Phase 8f: translate internal schemes before handing to Chromium.
        let translated = self.translate_internal_url(url);
        let navigate_url = translated.as_deref().unwrap_or(url);

        let (session_id, target_id) = {
            let state = self.state.lock().unwrap();
            let tab = state.active_tab().ok_or(EngineError::NoActiveTab)?;
            (tab.session_id.clone(), tab.target_id.clone())
        };
        // Update URL in state (optimistic; real URL comes from Page.frameNavigated events).
        {
            let mut state = self.state.lock().unwrap();
            if let Some(id) = state.active
                && let Some(tab) = state.tabs.iter_mut().find(|t| t.id == id)
            {
                tab.url = navigate_url.to_owned();
                // Update title to show original URL for internal pages.
                tab.title = url.to_owned();
            }
            // Stash or clear original URL for this target.
            if translated.is_some() {
                state
                    .original_urls
                    .insert(target_id.clone(), url.to_owned());
            } else {
                state.original_urls.remove(&target_id);
            }
        }
        let (reply_tx, reply_rx) = mpsc::channel();
        self.cmd_tx
            .try_send(Command::Navigate {
                session_id: session_id.clone(),
                url: navigate_url.to_owned(),
                reply: reply_tx,
            })
            .map_err(|_| EngineError::Other("worker channel full".into()))?;
        // Reply is Result<Value, BlinkError>; map Ok(_) → Ok(()) at the engine layer.
        let result = reply_rx
            .recv_timeout(Duration::from_secs(
                crate::worker::CDP_RESPONSE_TIMEOUT_SECS,
            ))
            .map_err(|_| EngineError::Other("navigate timed out".into()))
            .and_then(|r| r.map(|_| ()).map_err(EngineError::from));

        // P0-7: If this is a view-source: URL, the navigate_url is only the
        // loading placeholder. Spawn the background fetch thread now that the
        // placeholder navigation is in flight.
        self.schedule_view_source_fetch_if_needed(url, &session_id);

        result
    }

    fn active_tab_live_url(&self) -> String {
        let state = self.state.lock().unwrap();
        state
            .active_tab()
            .map(|t| display_url_for(t, &state.original_urls).to_owned())
            .unwrap_or_default()
    }

    fn pump_address_changes(&self) -> bool {
        // P0-1: drain URL/title updates pushed by the worker on Page.frameNavigated.
        // For each (session_id, url, title), update the matching CdpTab in state.
        // Returns true when any tab was updated so the apps layer can redraw.
        //
        // The original_urls map wins for display: if a tab has an original_url stashed
        // (buffr://, view-source:, etc.), the address bar keeps showing that. This
        // function only updates CdpTab::url/title which are used when no original_url
        // is present (normal HTTP/HTTPS navigations, pushState, redirects).
        let updates: Vec<(String, String, String)> = {
            match self.url_update_sink.lock() {
                Ok(mut sink) => sink.drain(..).collect(),
                Err(_) => return false,
            }
        };

        if updates.is_empty() {
            return false;
        }

        let mut changed = false;
        let mut state = self.state.lock().unwrap();
        for (session_id, url, title) in updates {
            // Find the tab by session_id, check original_urls, then update.
            // Split into two passes to avoid simultaneous mutable + immutable borrows.
            let tab_info = state
                .tabs
                .iter()
                .find(|t| t.session_id == session_id)
                .map(|t| (t.target_id.clone(), t.url.clone()));

            if let Some((target_id, old_url)) = tab_info {
                // Only update url when no original_url is stashed for this target.
                // If there is an original_url, the data: URL navigation is for an
                // internal page and the original URL should win in the address bar.
                let has_original = state.original_urls.contains_key(&target_id);
                if !has_original && old_url != url {
                    tracing::debug!(
                        session_id,
                        old_url,
                        new_url = %url,
                        "pump_address_changes: updating tab url"
                    );
                    if let Some(t) = state.tabs.iter_mut().find(|t| t.target_id == target_id) {
                        t.url = url;
                        if !title.is_empty() {
                            t.title = title;
                        }
                    }
                    changed = true;
                }
            }
        }
        changed
    }

    // ── Viewport ─────────────────────────────────────────────────────────────

    fn resize(&self, width: u32, height: u32) {
        use std::sync::atomic::Ordering;
        self.osr_view.width.store(width, Ordering::Relaxed);
        self.osr_view.height.store(height, Ordering::Relaxed);
        self.osr_resize(width, height);
    }

    fn set_device_scale(&self, scale: f32) {
        self.osr_view.set_scale(scale);
        // Phase 4: no per-scale CDP override; Page.setDeviceMetricsOverride always
        // uses deviceScaleFactor: 1.0 for simplicity.
        tracing::debug!(
            scale,
            "blink-cdp: set_device_scale (scale stored, not forwarded to CDP)"
        );
    }

    fn set_frame_rate(&self, hz: u32) {
        use std::sync::atomic::Ordering;
        self.osr_view.frame_rate_hz.store(hz, Ordering::Relaxed);
        // startScreencast uses everyNthFrame=1; Chromium controls cadence naturally.
    }

    fn notify_screen_info_changed(&self) {
        // No-op in Phase 4.
    }

    fn osr_resize(&self, width: u32, height: u32) {
        tracing::debug!(width, height, "blink-cdp: osr_resize");
        let session_id = self
            .state
            .lock()
            .unwrap()
            .active_tab()
            .map(|t| t.session_id.clone());
        if let Some(sess) = session_id {
            // Worker will: update device metrics + stop/restart screencast at new dims.
            let _ = self.cmd_tx.try_send(Command::Resize {
                session_id: sess,
                width: width.max(1),
                height: height.max(1),
            });
        }
        // Mark frame as stale until the first screencast frame at new dimensions arrives.
        if let Ok(mut frame) = self.osr_frame.lock() {
            frame.needs_fresh = true;
        }
    }

    // ── Input ────────────────────────────────────────────────────────────────

    fn osr_key_event(&self, event: NeutralKeyEvent) {
        let session_id = self
            .state
            .lock()
            .unwrap()
            .active_tab()
            .map(|t| t.session_id.clone());
        let Some(session_id) = session_id else { return };

        // Build the CDP text field from the UTF-16 character.
        let text = if event.character != 0 {
            char::from_u32(event.character as u32)
                .map(|c| c.to_string())
                .unwrap_or_default()
        } else {
            String::new()
        };
        let unmodified_text = if event.unmodified_character != 0 {
            char::from_u32(event.unmodified_character as u32)
                .map(|c| c.to_string())
                .unwrap_or_default()
        } else {
            String::new()
        };

        let params = DispatchKeyEventParams {
            event_type: key_event_type(event.kind),
            windows_virtual_key_code: event.windows_key_code,
            native_virtual_key_code: event.native_key_code,
            text,
            unmodified_text,
            modifiers: event.modifiers,
            is_system_key: event.is_system_key,
        };
        let _ = self
            .cmd_tx
            .try_send(Command::KeyEvent { session_id, params });
    }

    fn osr_mouse_move(&self, x: i32, y: i32, modifiers: u32) {
        let session_id = self
            .state
            .lock()
            .unwrap()
            .active_tab()
            .map(|t| t.session_id.clone());
        let Some(session_id) = session_id else { return };
        let params = DispatchMouseEventParams {
            event_type: "mouseMoved",
            x,
            y,
            button: "none",
            click_count: 0,
            modifiers,
            delta_x: None,
            delta_y: None,
        };
        let _ = self
            .cmd_tx
            .try_send(Command::MouseEvent { session_id, params });
    }

    fn osr_mouse_click(
        &self,
        x: i32,
        y: i32,
        button: MouseButton,
        mouse_up: bool,
        click_count: i32,
        modifiers: u32,
    ) {
        let session_id = self
            .state
            .lock()
            .unwrap()
            .active_tab()
            .map(|t| t.session_id.clone());
        let Some(session_id) = session_id else { return };
        let event_type = if mouse_up {
            "mouseReleased"
        } else {
            "mousePressed"
        };
        let params = DispatchMouseEventParams {
            event_type,
            x,
            y,
            button: mouse_button_str(button),
            click_count,
            modifiers,
            delta_x: None,
            delta_y: None,
        };
        let _ = self
            .cmd_tx
            .try_send(Command::MouseEvent { session_id, params });
    }

    fn osr_mouse_leave(&self, _modifiers: u32) {
        // No direct CDP equivalent; ignore.
    }

    fn osr_mouse_wheel(&self, x: i32, y: i32, delta_x: i32, delta_y: i32, modifiers: u32) {
        let session_id = self
            .state
            .lock()
            .unwrap()
            .active_tab()
            .map(|t| t.session_id.clone());
        let Some(session_id) = session_id else { return };
        let params = DispatchMouseEventParams {
            event_type: "mouseWheel",
            x,
            y,
            button: "none",
            click_count: 0,
            modifiers,
            delta_x: Some(delta_x as f64),
            delta_y: Some(delta_y as f64),
        };
        let _ = self
            .cmd_tx
            .try_send(Command::MouseEvent { session_id, params });
    }

    fn osr_focus(&self, _focused: bool) {
        // No-op — CDP has no direct "focus window" command.
    }

    // ── OSR state ────────────────────────────────────────────────────────────

    fn osr_frame(&self) -> SharedOsrFrame {
        Arc::clone(&self.osr_frame)
    }

    fn osr_view(&self) -> SharedOsrViewState {
        Arc::clone(&self.osr_view)
    }

    fn force_repaint_active(&self) {
        // screencast pushes frames on demand; no explicit repaint needed.
    }

    fn osr_sleep(&self, _sleep: bool) {
        // Future: send stopScreencast / startScreencast on sleep/wake.
        // For now Chromium's ack backpressure handles idle naturally.
    }

    fn osr_invalidate_view(&self) {
        // screencast invalidation is implicit via the ack loop.
    }

    fn set_osr_wake(&self, wake: Arc<dyn Fn() + Send + Sync>) {
        // Store in the shared view state so callers can trigger redraws.
        self.osr_view.set_wake(wake);
    }

    // ── Find / zoom ──────────────────────────────────────────────────────────

    fn start_find(&self, query: &str, forward: bool) {
        tracing::debug!(%query, forward, "blink-cdp: start_find");
        // Persist the query so FindNext / FindPrev can step without re-scanning.
        if let Ok(mut guard) = self.find_query.lock() {
            *guard = if query.is_empty() {
                None
            } else {
                Some(query.to_owned())
            };
        }
        let expr = find_expr(query, false, forward);
        self.run_find_js(&expr);
    }

    fn stop_find(&self) {
        tracing::debug!("blink-cdp: stop_find");
        // Clear the stored query so FindNext / FindPrev are inert.
        if let Ok(mut guard) = self.find_query.lock() {
            *guard = None;
        }
        // Clear the find_sink so the statusline reflects no active find.
        if let Ok(mut guard) = self.find_sink.lock() {
            *guard = None;
        }
        self.run_find_js(stop_expr());
    }

    fn active_zoom_level(&self) -> f64 {
        self.state
            .lock()
            .unwrap()
            .active_tab()
            .map(|t| t.zoom_level)
            .unwrap_or(1.0)
    }

    fn zoom_in(&self) {
        self.adjust_zoom(ZOOM_STEP);
    }

    fn zoom_out(&self) {
        self.adjust_zoom(-ZOOM_STEP);
    }

    fn zoom_reset(&self) {
        self.apply_zoom(1.0);
    }

    // ── DevTools ─────────────────────────────────────────────────────────────

    fn open_devtools(&self, tab: TabId) -> Result<(), buffr_engine::EngineError> {
        let state = self
            .state
            .lock()
            .map_err(|e| buffr_engine::EngineError::Other(format!("state lock poisoned: {e}")))?;
        let port = state.debug_port;
        let cdp_tab = state
            .tabs
            .iter()
            .find(|t| t.id == tab)
            .ok_or(buffr_engine::EngineError::TabNotFound(tab))?;
        let target_id = cdp_tab.target_id.clone();
        drop(state);
        let url = format!(
            "http://127.0.0.1:{port}/devtools/inspector.html?ws=127.0.0.1:{port}/devtools/page/{target_id}"
        );
        tracing::debug!(%url, "blink-cdp: open_devtools");
        open::that(&url)
            .map_err(|e| buffr_engine::EngineError::Other(format!("open devtools url: {e}")))?;
        Ok(())
    }

    // ── Context menu (Phase 8c, #87) ─────────────────────────────────────────

    fn drain_context_menu_requests(&self) -> Vec<buffr_engine::ContextMenuRequest> {
        match self.context_menu_sink.lock() {
            Ok(mut q) => q.drain(..).collect(),
            Err(_) => Vec::new(),
        }
    }

    // ── Media (Phase 8g, #90) ────────────────────────────────────────────────────
    //
    // `media_picture_in_picture` is the only media method implemented by the
    // blink-cdp backend. The `(x, y)` coordinates from the trait (used by CEF
    // to identify the element under the context-menu cursor) are ignored here:
    // the IIFE in `pip::pip_toggle_js` selects the most relevant video via its
    // own heuristic (playing > unmuted > first). This matches the behaviour
    // expected from a keyboard shortcut rather than a right-click context-menu.

    fn media_picture_in_picture(&self, _x: i32, _y: i32) {
        let session_id = {
            let state = self.state.lock().unwrap();
            match state.active_tab().map(|t| t.session_id.clone()) {
                Some(s) => s,
                None => {
                    tracing::debug!("blink-cdp: media_picture_in_picture — no active tab");
                    return;
                }
            }
        };
        tracing::debug!("blink-cdp: media_picture_in_picture → Runtime.evaluate");
        let _ = self.session_cmd(
            &session_id,
            "Runtime.evaluate",
            serde_json::json!({
                "expression": crate::pip::pip_toggle_js(),
                "returnByValue": true,
            }),
        );
    }

    // ── Audio / video ────────────────────────────────────────────────────────

    fn any_audio_active(&self) -> bool {
        false
    }

    fn any_video_active(&self) -> bool {
        false
    }

    // ── Popup sinks (Phase 6a, #95) ──────────────────────────────────────────
    // CDP popup support: future work, see #95.

    // P1-9: return Arc::clone of the stored sinks so every call shares the same
    // backing queue rather than allocating a fresh, disconnected queue each time.

    fn popup_queue(&self) -> buffr_engine::popup::PopupQueue {
        Arc::clone(&self.popup_queue)
    }

    fn popup_create_sink(&self) -> buffr_engine::popup::PopupCreateSink {
        Arc::clone(&self.popup_create_sink)
    }

    fn popup_close_sink(&self) -> buffr_engine::popup::PopupCloseSink {
        Arc::clone(&self.popup_close_sink)
    }

    fn popup_resize(&self, _browser_id: i32, _width: u32, _height: u32) {}

    fn popup_close(&self, _browser_id: i32) {}

    fn popup_drain_address_changes(&self) -> Vec<(i32, String)> {
        Vec::new()
    }

    fn popup_drain_title_changes(&self) -> Vec<(i32, String)> {
        Vec::new()
    }

    fn popup_history_back(&self, _browser_id: i32) {}

    fn popup_history_forward(&self, _browser_id: i32) {}

    fn popup_osr_focus(&self, _browser_id: i32, _focused: bool) {}

    fn popup_osr_key_event(&self, _browser_id: i32, _event: buffr_engine::NeutralKeyEvent) {}

    #[allow(clippy::too_many_arguments)]
    fn popup_osr_mouse_click(
        &self,
        _browser_id: i32,
        _x: i32,
        _y: i32,
        _button: buffr_engine::MouseButton,
        _mouse_up: bool,
        _click_count: i32,
        _modifiers: u32,
    ) {
    }

    fn popup_osr_mouse_move(&self, _browser_id: i32, _x: i32, _y: i32, _modifiers: u32) {}

    fn popup_osr_mouse_wheel(
        &self,
        _browser_id: i32,
        _x: i32,
        _y: i32,
        _delta_x: i32,
        _delta_y: i32,
        _modifiers: u32,
    ) {
    }

    // ── Permissions (Phase 8a, #88) ───────────────────────────────────────────

    fn permissions_queue(&self) -> PermissionsQueue {
        Arc::clone(&self.permissions_queue)
    }

    fn resolve_permission(&self, resolve_id: Option<&str>, outcome: PromptOutcome) {
        let Some(id) = resolve_id else {
            tracing::debug!("blink-cdp: resolve_permission called with no id (no-op)");
            return;
        };
        let session_id = match self.perm_session_map.lock() {
            Ok(mut map) => map.remove(id),
            Err(_) => {
                tracing::warn!(id, "blink-cdp: perm_session_map poisoned");
                return;
            }
        };
        let Some(session_id) = session_id else {
            tracing::debug!(
                id,
                "blink-cdp: resolve_id not in session map (already resolved?)"
            );
            return;
        };
        let outcome_str = match outcome {
            PromptOutcome::Allow { .. } => "granted",
            PromptOutcome::Deny { .. } | PromptOutcome::Defer => "denied",
        };
        let expr = format!(
            "if (window.__buffrPermissionResolve) {{ window.__buffrPermissionResolve({id:?}, {outcome_str:?}); }}"
        );
        tracing::debug!(
            id,
            outcome_str,
            "blink-cdp: resolve_permission → Runtime.evaluate"
        );
        let _ = self.session_cmd(
            &session_id,
            "Runtime.evaluate",
            serde_json::json!({ "expression": expr }),
        );
    }

    // ── Hint mode (Phase 6b, #95) ─────────────────────────────────────────────
    // CDP hint mode: future work, see #95.

    fn is_hint_mode(&self) -> bool {
        false
    }

    fn hint_status(&self) -> Option<buffr_engine::HintStatus> {
        None
    }

    fn pump_hint_events(&self) -> bool {
        false
    }

    fn feed_hint_key(&self, _c: char) -> Option<buffr_engine::HintAction> {
        None
    }

    fn backspace_hint(&self) -> Option<buffr_engine::HintAction> {
        None
    }

    fn cancel_hint(&self) {}

    // ── Phase 6c (#95): JS execution + DevTools at point ─────────────────────
    //
    // The CDP backend can fulfil `run_js` and `run_main_frame_js` via
    // `Runtime.evaluate` on the active session. All frame_*, media_*, image_*,
    // run_edit_*, run_media_probe, and start_download fall through to the trait
    // defaults (debug-log + no-op / Unimplemented) because they are
    // CEF-specific or rely on context-menu coordinates unavailable over CDP.
    //
    // `show_dev_tools_at` ignores (x, y) and delegates to the existing
    // `open_devtools` impl, which opens the CDP inspector URL in the system
    // browser. The trait default is overridden with a thin wrapper so the
    // apps layer gets behaviour rather than a silent no-op.

    fn run_js(&self, code: &str) -> Result<(), buffr_engine::EngineError> {
        self.run_main_frame_js(code, "")
    }

    fn run_main_frame_js(&self, code: &str, _url: &str) -> Result<(), buffr_engine::EngineError> {
        let session_id = {
            let state = self
                .state
                .lock()
                .map_err(|e| buffr_engine::EngineError::Other(format!("lock poisoned: {e}")))?;
            let tab = state
                .active_tab()
                .ok_or(buffr_engine::EngineError::NoActiveTab)?;
            tab.session_id.clone()
        };
        self.session_cmd(
            &session_id,
            "Runtime.evaluate",
            serde_json::json!({ "expression": code }),
        )
        .map(|_| ())
        .map_err(|e| buffr_engine::EngineError::Other(e.to_string()))
    }

    fn show_dev_tools_at(&self, _x: i32, _y: i32) {
        // CDP has no inspect-element at a specific point; open the full
        // inspector via the existing open_devtools path, using the active tab.
        let tab_id = {
            match self.state.lock() {
                Ok(s) => s.active_tab().map(|t| t.id),
                Err(_) => None,
            }
        };
        if let Some(id) = tab_id {
            if let Err(err) = self.open_devtools(id) {
                tracing::debug!(error = %err, "blink-cdp: show_dev_tools_at failed");
            }
        } else {
            tracing::debug!("blink-cdp: show_dev_tools_at — no active tab");
        }
    }

    // ── Action dispatch (Phase 8b, #83 + audit P0-4, P0-5) ───────────────────
    //
    // Override the default no-op so `n` / `N` (`FindNext` / `FindPrev`)
    // actually step through the JS find overlay managed by `start_find`,
    // and so history/reload/stop/scroll actions work over CDP.

    fn dispatch(&self, action: &buffr_modal::PageAction) {
        use buffr_modal::PageAction as A;

        // Pixels per scroll-unit (matches CEF backend constant in buffr-cef/src/host.rs).
        const STEP_PX: i64 = 40;

        // Helper: evaluate JS on the active tab's session (fire-and-forget).
        let eval = |expr: String| {
            let session_id = {
                let state = self.state.lock().unwrap();
                state.active_tab().map(|t| t.session_id.clone())
            };
            if let Some(sess) = session_id {
                let _ = self.session_cmd(
                    &sess,
                    "Runtime.evaluate",
                    serde_json::json!({ "expression": expr }),
                );
            }
        };

        match action {
            // ── Find ────────────────────────────────────────────────────────
            A::FindNext => {
                let query = self.find_query.lock().ok().and_then(|g| g.clone());
                if let Some(q) = query {
                    tracing::debug!(query = %q, "blink-cdp: dispatch FindNext");
                    let expr = find_expr(&q, false, true);
                    self.run_find_js(&expr);
                } else {
                    tracing::debug!("blink-cdp: FindNext — no active find query");
                }
            }
            A::FindPrev => {
                let query = self.find_query.lock().ok().and_then(|g| g.clone());
                if let Some(q) = query {
                    tracing::debug!(query = %q, "blink-cdp: dispatch FindPrev");
                    let expr = find_expr(&q, false, false);
                    self.run_find_js(&expr);
                } else {
                    tracing::debug!("blink-cdp: FindPrev — no active find query");
                }
            }

            // ── History / reload / stop (P0-4) ──────────────────────────────
            A::HistoryBack => {
                tracing::debug!("blink-cdp: dispatch HistoryBack");
                eval("window.history.back();".to_owned());
            }
            A::HistoryForward => {
                tracing::debug!("blink-cdp: dispatch HistoryForward");
                eval("window.history.forward();".to_owned());
            }
            A::Reload => {
                tracing::debug!("blink-cdp: dispatch Reload");
                let session_id = {
                    let state = self.state.lock().unwrap();
                    state.active_tab().map(|t| t.session_id.clone())
                };
                if let Some(sess) = session_id {
                    let _ = self.session_cmd(
                        &sess,
                        "Page.reload",
                        serde_json::json!({ "ignoreCache": false }),
                    );
                }
            }
            A::ReloadHard => {
                tracing::debug!("blink-cdp: dispatch ReloadHard");
                let session_id = {
                    let state = self.state.lock().unwrap();
                    state.active_tab().map(|t| t.session_id.clone())
                };
                if let Some(sess) = session_id {
                    let _ = self.session_cmd(
                        &sess,
                        "Page.reload",
                        serde_json::json!({ "ignoreCache": true }),
                    );
                }
            }
            A::StopLoading => {
                tracing::debug!("blink-cdp: dispatch StopLoading");
                let session_id = {
                    let state = self.state.lock().unwrap();
                    state.active_tab().map(|t| t.session_id.clone())
                };
                if let Some(sess) = session_id {
                    let _ = self.session_cmd(&sess, "Page.stopLoading", serde_json::json!({}));
                }
            }

            // ── Scroll (P0-5) ────────────────────────────────────────────────
            A::ScrollUp(n) => {
                let dy = -(STEP_PX * (*n as i64));
                tracing::debug!(n, dy, "blink-cdp: dispatch ScrollUp");
                eval(format!("window.scrollBy(0, {dy});"));
            }
            A::ScrollDown(n) => {
                let dy = STEP_PX * (*n as i64);
                tracing::debug!(n, dy, "blink-cdp: dispatch ScrollDown");
                eval(format!("window.scrollBy(0, {dy});"));
            }
            A::ScrollLeft(n) => {
                let dx = -(STEP_PX * (*n as i64));
                tracing::debug!(n, dx, "blink-cdp: dispatch ScrollLeft");
                eval(format!("window.scrollBy({dx}, 0);"));
            }
            A::ScrollRight(n) => {
                let dx = STEP_PX * (*n as i64);
                tracing::debug!(n, dx, "blink-cdp: dispatch ScrollRight");
                eval(format!("window.scrollBy({dx}, 0);"));
            }
            A::ScrollPageDown | A::ScrollFullPageDown => {
                tracing::debug!("blink-cdp: dispatch ScrollPageDown");
                eval("window.scrollBy(0, window.innerHeight * 0.9);".to_owned());
            }
            A::ScrollPageUp | A::ScrollFullPageUp => {
                tracing::debug!("blink-cdp: dispatch ScrollPageUp");
                eval("window.scrollBy(0, -window.innerHeight * 0.9);".to_owned());
            }
            A::ScrollHalfPageDown => {
                tracing::debug!("blink-cdp: dispatch ScrollHalfPageDown");
                eval("window.scrollBy(0, window.innerHeight * 0.5);".to_owned());
            }
            A::ScrollHalfPageUp => {
                tracing::debug!("blink-cdp: dispatch ScrollHalfPageUp");
                eval("window.scrollBy(0, -window.innerHeight * 0.5);".to_owned());
            }
            A::ScrollTop => {
                tracing::debug!("blink-cdp: dispatch ScrollTop");
                eval("window.scrollTo(0, 0);".to_owned());
            }
            A::ScrollBottom => {
                tracing::debug!("blink-cdp: dispatch ScrollBottom");
                eval("window.scrollTo(0, document.body.scrollHeight);".to_owned());
            }

            // ── Zoom ─────────────────────────────────────────────────────────
            A::ZoomIn => self.adjust_zoom(ZOOM_STEP),
            A::ZoomOut => self.adjust_zoom(-ZOOM_STEP),
            A::ZoomReset => self.apply_zoom(1.0),

            other => {
                tracing::debug!(
                    action = ?other,
                    "blink-cdp: dispatch — action not handled by CDP backend (no-op)"
                );
            }
        }
    }

    // ── IME composition (Phase 8d, #86) ──────────────────────────────────────
    //
    // Routes winit IME events through the Chrome DevTools Protocol:
    //
    //   Preedit  → `Input.imeSetComposition`  (updates the composition window)
    //   Commit   → `Input.insertText`          (finalises the text)
    //   Cancel   → `Input.imeSetComposition` with `text: ""`  (clears preedit)
    //
    // CDP byte-offset semantics: `selectionStart` / `selectionEnd` are UTF-16
    // code-unit indices into `text`.  winit supplies byte offsets into a UTF-8
    // `&str`.  Because blink-cdp converts cursor positions only for the preedit
    // window (which is typically short and ASCII-heavy), the approximation of
    // using char counts (not UTF-16 code-unit counts) is acceptable here.
    // Exact UTF-16 conversion can be added later if needed.

    fn ime_set_composition(&self, text: &str, cursor: Option<(usize, usize)>) {
        let session_id = {
            let state = self.state.lock().unwrap();
            match state.active_tab().map(|t| t.session_id.clone()) {
                Some(s) => s,
                None => {
                    tracing::debug!("blink-cdp: ime_set_composition — no active tab");
                    return;
                }
            }
        };
        let (start, end) = cursor.unwrap_or((text.len(), text.len()));
        let params = serde_json::json!({
            "text": text,
            "selectionStart": start,
            "selectionEnd": end,
        });
        tracing::debug!(text, start, end, "blink-cdp: ime_set_composition");
        let _ = self.session_cmd(&session_id, "Input.imeSetComposition", params);
    }

    fn ime_commit(&self, text: &str) {
        let session_id = {
            let state = self.state.lock().unwrap();
            match state.active_tab().map(|t| t.session_id.clone()) {
                Some(s) => s,
                None => {
                    tracing::debug!("blink-cdp: ime_commit — no active tab");
                    return;
                }
            }
        };
        tracing::debug!(text, "blink-cdp: ime_commit");
        let _ = self.session_cmd(
            &session_id,
            "Input.insertText",
            serde_json::json!({ "text": text }),
        );
    }

    fn ime_cancel(&self) {
        let session_id = {
            let state = self.state.lock().unwrap();
            match state.active_tab().map(|t| t.session_id.clone()) {
                Some(s) => s,
                None => {
                    tracing::debug!("blink-cdp: ime_cancel — no active tab");
                    return;
                }
            }
        };
        tracing::debug!("blink-cdp: ime_cancel");
        let _ = self.session_cmd(
            &session_id,
            "Input.imeSetComposition",
            serde_json::json!({
                "text": "",
                "selectionStart": 0,
                "selectionEnd": 0,
            }),
        );
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── Zoom helper tests ─────────────────────────────────────────────────────

    #[test]
    fn zoom_level_clamps_to_range() {
        // Clamping below min.
        assert_eq!(clamp_zoom(0.0), ZOOM_MIN);
        assert_eq!(clamp_zoom(-1.0), ZOOM_MIN);
        // Clamping above max.
        assert_eq!(clamp_zoom(10.0), ZOOM_MAX);
        // Values inside range pass through unchanged.
        assert_eq!(clamp_zoom(1.0), 1.0);
        assert_eq!(clamp_zoom(ZOOM_MIN), ZOOM_MIN);
        assert_eq!(clamp_zoom(ZOOM_MAX), ZOOM_MAX);
        assert_eq!(clamp_zoom(2.5), 2.5);
    }

    #[test]
    fn zoom_step_constant_matches_cef() {
        // buffr-cef's `adjust_zoom` calls `set_zoom_level(level ± 0.25)`.
        // Verify blink-cdp uses the same step so both backends behave identically.
        assert!(
            (ZOOM_STEP - 0.25_f64).abs() < f64::EPSILON,
            "ZOOM_STEP must equal 0.25 to match the CEF backend"
        );
    }

    #[test]
    fn active_zoom_level_returns_tracked_value() {
        // Build a minimal EngineState with one tab and verify that
        // active_zoom_level reflects the stored zoom_level.
        let mut state = EngineState::new(9222);
        let tab_id = state.mint_tab_id();
        state.tabs.push(CdpTab {
            id: tab_id,
            target_id: "t1".into(),
            session_id: "s1".into(),
            url: "about:blank".into(),
            title: "about:blank".into(),
            zoom_level: 1.5,
        });
        state.active = Some(tab_id);

        // active_tab() returns the tab; zoom_level should be 1.5.
        let level = state.active_tab().map(|t| t.zoom_level).unwrap_or(1.0);
        assert!(
            (level - 1.5_f64).abs() < f64::EPSILON,
            "tracked zoom level should be 1.5, got {level}"
        );

        // No active tab → default 1.0.
        state.active = None;
        let level_none = state.active_tab().map(|t| t.zoom_level).unwrap_or(1.0);
        assert!(
            (level_none - 1.0_f64).abs() < f64::EPSILON,
            "no active tab should yield 1.0, got {level_none}"
        );
    }

    // ── DevTools URL format tests ─────────────────────────────────────────────

    #[test]
    fn devtools_url_format_is_correct() {
        // Verify the inspector URL template produces the expected shape.
        let port: u16 = 9222;
        let target_id = "ABCD1234-EF56-7890-ABCD-EF1234567890";
        let url = format!(
            "http://127.0.0.1:{port}/devtools/inspector.html?ws=127.0.0.1:{port}/devtools/page/{target_id}"
        );
        assert!(url.starts_with("http://127.0.0.1:9222/devtools/inspector.html"));
        assert!(url.contains("ws=127.0.0.1:9222/devtools/page/"));
        assert!(url.ends_with(target_id));
    }

    #[test]
    fn open_devtools_returns_tab_not_found_for_unknown_tab() {
        // Build a minimal EngineState with no tabs and verify that
        // open_devtools returns TabNotFound for an unknown tab id.
        let state = EngineState::new(9222);
        let unknown_id = TabId(99);
        let result = state.tabs.iter().find(|t| t.id == unknown_id);
        assert!(result.is_none(), "unknown tab should not be found");
        // Simulate the error path:
        let err = buffr_engine::EngineError::TabNotFound(unknown_id);
        assert!(matches!(err, buffr_engine::EngineError::TabNotFound(_)));
    }

    // ── Chromium detection tests ──────────────────────────────────────────────

    #[test]
    fn find_chromium_no_panic() {
        // Must not panic regardless of whether Chromium is installed.
        let _result = find_chromium();
        // If found, it should be a file.
        if let Some(path) = find_chromium() {
            assert!(
                path.exists() || !path.is_absolute(),
                "resolved absolute path should exist"
            );
        }
    }

    #[test]
    fn error_when_chromium_missing() {
        // Simulate no Chromium by pointing to a non-existent data dir
        // and attempting construction. If Chromium is not installed on
        // this machine, we should get ChromiumNotFound immediately.
        // If it IS installed, we skip (don't actually spawn in unit tests).
        if find_chromium().is_some() {
            // Chromium present — skip spawning; would be an integration test.
            return;
        }
        let result = BlinkCdpEngine::new(
            Path::new("/tmp/buffr-blink-cdp-test"),
            None,
            None,
            None,
            None,
            None,
        );
        match result {
            Err(BlinkError::ChromiumNotFound) => {} // expected
            Err(other) => panic!("unexpected error: {other}"),
            Ok(_) => panic!("expected error when Chromium is missing"),
        }
    }

    // ── Zoom boundary tests ───────────────────────────────────────────────────

    #[test]
    fn clamp_zoom_min_boundary() {
        assert!(
            (clamp_zoom(ZOOM_MIN) - ZOOM_MIN).abs() < f64::EPSILON,
            "clamp(MIN) should equal MIN"
        );
        assert!(
            (clamp_zoom(ZOOM_MIN - 0.01) - ZOOM_MIN).abs() < f64::EPSILON,
            "below MIN should clamp to MIN"
        );
    }

    #[test]
    fn clamp_zoom_max_boundary() {
        assert!(
            (clamp_zoom(ZOOM_MAX) - ZOOM_MAX).abs() < f64::EPSILON,
            "clamp(MAX) should equal MAX"
        );
        assert!(
            (clamp_zoom(ZOOM_MAX + 0.01) - ZOOM_MAX).abs() < f64::EPSILON,
            "above MAX should clamp to MAX"
        );
    }

    // ── EngineState helper tests ──────────────────────────────────────────────

    #[test]
    fn engine_state_mint_tab_id_monotonic() {
        let mut state = EngineState::new(9999);
        let id1 = state.mint_tab_id();
        let id2 = state.mint_tab_id();
        let id3 = state.mint_tab_id();
        assert!(id1.0 < id2.0 && id2.0 < id3.0, "tab ids must increase");
    }

    #[test]
    fn engine_state_tab_by_id_found_and_not_found() {
        let mut state = EngineState::new(9999);
        let id = state.mint_tab_id();
        state.tabs.push(CdpTab {
            id,
            target_id: "t1".into(),
            session_id: "s1".into(),
            url: "about:blank".into(),
            title: "about:blank".into(),
            zoom_level: 1.0,
        });
        assert!(state.tab_by_id(id).is_some());
        assert!(state.tab_by_id(TabId(999)).is_none());
    }

    #[test]
    fn engine_state_tracks_active_target_id() {
        let mut state = EngineState::new(8080);
        let id = state.mint_tab_id();
        state.tabs.push(CdpTab {
            id,
            target_id: "target-xyz".into(),
            session_id: "sess-xyz".into(),
            url: "https://example.com".into(),
            title: "Example".into(),
            zoom_level: 1.25,
        });
        state.active = Some(id);

        let tab = state.active_tab().expect("active tab should be present");
        assert_eq!(tab.target_id, "target-xyz");
        assert_eq!(tab.session_id, "sess-xyz");
        assert!((tab.zoom_level - 1.25).abs() < f64::EPSILON);
    }

    #[test]
    fn engine_state_no_active_tab_when_none() {
        let state = EngineState::new(9999);
        assert!(state.active_tab().is_none());
    }

    // ── IME CDP payload tests (#86) ───────────────────────────────────────────

    /// Helper mirroring the cursor → (start, end) resolution in
    /// `ime_set_composition`. Lifted out so tests can drive the same logic
    /// without re-triggering clippy's `unnecessary_literal_unwrap` on inline
    /// `Some`/`None` literals.
    fn ime_resolve_cursor(text: &str, cursor: Option<(usize, usize)>) -> (usize, usize) {
        cursor.unwrap_or((text.len(), text.len()))
    }

    /// Verify `Input.imeSetComposition` payload shape with explicit cursor.
    #[test]
    fn ime_set_composition_payload_shape() {
        let text = "こんにちは";
        let (start, end) = ime_resolve_cursor(text, Some((3, 6)));
        let params = serde_json::json!({
            "text": text,
            "selectionStart": start,
            "selectionEnd": end,
        });
        assert_eq!(params["text"], text);
        assert_eq!(params["selectionStart"], 3);
        assert_eq!(params["selectionEnd"], 6);
    }

    /// When no cursor is provided the selection collapses to the end of text.
    #[test]
    fn ime_set_composition_no_cursor_collapses_to_end() {
        let text = "hello";
        let (start, end) = ime_resolve_cursor(text, None);
        let params = serde_json::json!({
            "text": text,
            "selectionStart": start,
            "selectionEnd": end,
        });
        assert_eq!(params["selectionStart"], text.len());
        assert_eq!(params["selectionEnd"], text.len());
    }

    /// `Input.insertText` commit payload must contain just `text`.
    #[test]
    fn ime_commit_payload_shape() {
        let text = "確定";
        let params = serde_json::json!({ "text": text });
        assert_eq!(params["text"], text);
        // No selection fields expected.
        assert!(params.get("selectionStart").is_none());
    }

    /// Cancel sends `Input.imeSetComposition` with an empty string and zero offsets.
    #[test]
    fn ime_cancel_payload_shape() {
        let params = serde_json::json!({
            "text": "",
            "selectionStart": 0,
            "selectionEnd": 0,
        });
        assert_eq!(params["text"], "");
        assert_eq!(params["selectionStart"], 0);
        assert_eq!(params["selectionEnd"], 0);
    }

    // ── Phase 8f scheme-translation tests (#81) ───────────────────────────────

    /// Helper: build the base64-encoded `data:text/html;base64,...` prefix.
    fn data_html_prefix() -> String {
        "data:text/html;base64,".to_owned()
    }

    /// `display_url_for` returns the original URL when one is stashed.
    #[test]
    fn display_url_for_prefers_original() {
        let tab = CdpTab {
            id: TabId(1),
            target_id: "t1".into(),
            session_id: "s1".into(),
            url: "data:text/html;base64,ABC".into(),
            title: "buffr://new".into(),
            zoom_level: 1.0,
        };
        let mut originals = HashMap::new();
        originals.insert("t1".to_owned(), "buffr://new".to_owned());
        assert_eq!(display_url_for(&tab, &originals), "buffr://new");
    }

    /// `display_url_for` falls back to `CdpTab::url` when no original is stashed.
    #[test]
    fn display_url_for_falls_back_to_tab_url() {
        let tab = CdpTab {
            id: TabId(1),
            target_id: "t1".into(),
            session_id: "s1".into(),
            url: "https://example.com".into(),
            title: "Example".into(),
            zoom_level: 1.0,
        };
        let originals: HashMap<String, String> = HashMap::new();
        assert_eq!(display_url_for(&tab, &originals), "https://example.com");
    }

    /// `html_escape_source` escapes the five critical characters.
    #[test]
    fn html_escape_source_escapes_special_chars() {
        assert_eq!(html_escape_source("&"), "&amp;");
        assert_eq!(html_escape_source("<"), "&lt;");
        assert_eq!(html_escape_source(">"), "&gt;");
        assert_eq!(html_escape_source("\""), "&quot;");
        assert_eq!(html_escape_source("'"), "&#39;");
        assert_eq!(html_escape_source("plain"), "plain");
        assert_eq!(
            html_escape_source("<script>alert('xss')</script>"),
            "&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;"
        );
    }

    /// `view_source_html` on a non-existent URL renders an error page
    /// (not a panic or empty string).
    #[test]
    fn view_source_html_error_page_on_unreachable_url() {
        let html = view_source_html_sync("http://127.0.0.1:19999/no-such-server");
        let text = String::from_utf8_lossy(&html);
        // Must be valid HTML containing an error indicator.
        assert!(
            text.contains("<!DOCTYPE html>"),
            "should be an HTML document"
        );
        assert!(
            text.contains("view-source error") || text.contains("Error"),
            "should mention an error"
        );
    }

    /// `original_urls` is cleaned up when a tab's `target_id` is removed.
    #[test]
    fn original_urls_cleaned_on_tab_close() {
        let mut state = EngineState::new(9999);
        let id = state.mint_tab_id();
        state.tabs.push(CdpTab {
            id,
            target_id: "t-close".into(),
            session_id: "s-close".into(),
            url: "data:text/html;base64,X".into(),
            title: "buffr://new".into(),
            zoom_level: 1.0,
        });
        state
            .original_urls
            .insert("t-close".to_owned(), "buffr://new".to_owned());
        assert!(state.original_urls.contains_key("t-close"));

        // Simulate tab close: retain all tabs except the closed one and remove its URL.
        state.tabs.retain(|t| t.id != id);
        state.original_urls.remove("t-close");

        assert!(!state.original_urls.contains_key("t-close"));
        assert!(state.tabs.is_empty());
    }

    /// `buffr://` URLs translate to a `data:text/html;base64,` URL.
    /// Tests the translation logic via base64 round-trip (no live Chromium needed).
    #[test]
    fn buffr_newtab_url_translates_to_data_url() {
        let html = buffr_engine::newtab::NEW_TAB_HTML_TEMPLATE
            .as_bytes()
            .to_vec();
        let encoded = base64::engine::general_purpose::STANDARD.encode(&html);
        let data_url = format!("{}{}", data_html_prefix(), encoded);
        assert!(data_url.starts_with("data:text/html;base64,"));
        // Round-trip decode.
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(data_url.trim_start_matches("data:text/html;base64,"))
            .expect("base64 decode should succeed");
        assert_eq!(decoded, html);
    }

    /// `view-source:` URL parsing: strip prefix → target URL.
    #[test]
    fn view_source_url_prefix_strip() {
        let input = "view-source:https://example.com/page";
        let stripped = input.strip_prefix("view-source:");
        assert_eq!(stripped, Some("https://example.com/page"));
    }

    // ── P0-1: URL update sink plumbing ────────────────────────────────────────

    /// url_update_sink: pushing a (session_id, url, title) tuple is visible
    /// to the drainer without loss.
    #[test]
    fn url_update_sink_push_and_drain() {
        use crate::worker::new_url_update_sink;
        let sink = new_url_update_sink();

        {
            let mut guard = sink.lock().unwrap();
            guard.push_back((
                "sess-1".into(),
                "https://example.com".into(),
                "Example".into(),
            ));
            guard.push_back((
                "sess-2".into(),
                "https://rust-lang.org".into(),
                "Rust".into(),
            ));
        }

        let drained: Vec<_> = sink.lock().unwrap().drain(..).collect();
        assert_eq!(drained.len(), 2);
        assert_eq!(drained[0].0, "sess-1");
        assert_eq!(drained[0].1, "https://example.com");
        assert_eq!(drained[0].2, "Example");
        assert_eq!(drained[1].0, "sess-2");
        assert_eq!(drained[1].1, "https://rust-lang.org");

        // After drain, sink is empty.
        assert!(sink.lock().unwrap().is_empty());
    }

    /// pump_address_changes: updates CdpTab::url when session_id matches and
    /// no original_url is stashed. Returns true when a change occurred.
    #[test]
    fn pump_address_changes_updates_tab_url() {
        use crate::worker::new_url_update_sink;

        let url_sink = new_url_update_sink();

        // Push a url update before draining.
        url_sink.lock().unwrap().push_back((
            "sess-nav".into(),
            "https://example.com/page".into(),
            "Example Page".into(),
        ));

        // Build a minimal EngineState with a matching tab.
        let mut state = EngineState::new(9999);
        let tab_id = state.mint_tab_id();
        state.tabs.push(CdpTab {
            id: tab_id,
            target_id: "t-nav".into(),
            session_id: "sess-nav".into(),
            url: "https://example.com".into(),
            title: "Example".into(),
            zoom_level: 1.0,
        });
        state.active = Some(tab_id);

        // Drain the sink directly (simulating pump_address_changes logic).
        let updates: Vec<_> = url_sink.lock().unwrap().drain(..).collect();
        let mut changed = false;
        for (session_id, url, title) in updates {
            let tab_info = state
                .tabs
                .iter()
                .find(|t| t.session_id == session_id)
                .map(|t| (t.target_id.clone(), t.url.clone()));

            if let Some((target_id, old_url)) = tab_info {
                let has_original = state.original_urls.contains_key(&target_id);
                if !has_original && old_url != url {
                    if let Some(t) = state.tabs.iter_mut().find(|t| t.target_id == target_id) {
                        t.url = url;
                        if !title.is_empty() {
                            t.title = title;
                        }
                    }
                    changed = true;
                }
            }
        }

        assert!(changed, "should have detected a change");
        assert_eq!(state.tabs[0].url, "https://example.com/page");
        assert_eq!(state.tabs[0].title, "Example Page");
    }

    /// pump_address_changes: does NOT update url when an original_url is stashed
    /// (internal buffr:// pages must keep their original URL in the address bar).
    #[test]
    fn pump_address_changes_skips_original_url_tabs() {
        use crate::worker::new_url_update_sink;

        let url_sink = new_url_update_sink();
        url_sink.lock().unwrap().push_back((
            "sess-internal".into(),
            "data:text/html;base64,ABC".into(),
            "".into(),
        ));

        let mut state = EngineState::new(9999);
        let tab_id = state.mint_tab_id();
        state.tabs.push(CdpTab {
            id: tab_id,
            target_id: "t-internal".into(),
            session_id: "sess-internal".into(),
            url: "data:text/html;base64,ABC".into(),
            title: "buffr://new".into(),
            zoom_level: 1.0,
        });
        state.active = Some(tab_id);
        // Stash original URL — tab is on an internal page.
        state
            .original_urls
            .insert("t-internal".into(), "buffr://new".into());

        // Drain and apply logic.
        let updates: Vec<_> = url_sink.lock().unwrap().drain(..).collect();
        let mut changed = false;
        for (session_id, url, title) in updates {
            let tab_info = state
                .tabs
                .iter()
                .find(|t| t.session_id == session_id)
                .map(|t| (t.target_id.clone(), t.url.clone()));
            if let Some((target_id, old_url)) = tab_info {
                let has_original = state.original_urls.contains_key(&target_id);
                if !has_original && old_url != url {
                    if let Some(t) = state.tabs.iter_mut().find(|t| t.target_id == target_id) {
                        t.url = url;
                        if !title.is_empty() {
                            t.title = title;
                        }
                    }
                    changed = true;
                }
            }
        }

        // Tab url must remain unchanged.
        assert!(
            !changed,
            "should NOT have changed a tab with original_url stashed"
        );
        assert_eq!(state.tabs[0].url, "data:text/html;base64,ABC");
    }

    // ── P0-3: about:blank → real URL flow ─────────────────────────────────────

    /// The translated data URL for buffr:// pages is a valid data URL.
    /// open_tab_internal navigates about:blank first; the real URL flows via
    /// Command::Navigate. This test validates translate_internal_url returns
    /// the correct placeholder for view-source: (not a full fetch).
    #[test]
    fn view_source_translate_returns_placeholder_not_full_content() {
        // view_source_loading_data_url should return a data URL that contains
        // "Fetching source" text, not actual page content.
        let placeholder = view_source_loading_data_url("https://example.com");
        assert!(
            placeholder.starts_with("data:text/html;base64,"),
            "should be a data URL"
        );

        // Decode and check it contains the loading message.
        let encoded = placeholder.trim_start_matches("data:text/html;base64,");
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(encoded)
            .expect("valid base64");
        let html = String::from_utf8_lossy(&decoded);
        assert!(
            html.contains("Fetching source"),
            "placeholder must say 'Fetching source'"
        );
        assert!(
            !html.contains("<pre>"),
            "placeholder must NOT contain actual source content"
        );
    }

    // ── P0-4/P0-5: dispatch action coverage ──────────────────────────────────

    /// Verify the dispatch method handles scroll actions by checking that the
    /// pixel delta math is correct for the STEP_PX constant.
    #[test]
    fn dispatch_scroll_step_px_math() {
        // STEP_PX == 40 (matches CEF backend).
        const STEP_PX: i64 = 40;
        // ScrollDown(3) → 120 px.
        assert_eq!(STEP_PX * 3, 120);
        // ScrollUp(1) → -40 px.
        assert_eq!(-(STEP_PX), -40);
        // ScrollLeft(2) → -80 px.
        assert_eq!(-(STEP_PX * 2), -80);
        // ScrollRight(5) → 200 px.
        assert_eq!(STEP_PX * 5, 200);
    }

    /// Dispatch action variants used in P0-4 are all present in PageAction.
    #[test]
    fn dispatch_p0_4_action_variants_exist() {
        use buffr_modal::PageAction;
        // Construct each variant to verify enum shape matches what dispatch uses.
        let _back = PageAction::HistoryBack;
        let _fwd = PageAction::HistoryForward;
        let _reload = PageAction::Reload;
        let _hard = PageAction::ReloadHard;
        let _stop = PageAction::StopLoading;
    }

    /// Dispatch scroll variants from P0-5 are all present in PageAction.
    #[test]
    fn dispatch_p0_5_scroll_variants_exist() {
        use buffr_modal::PageAction;
        let _su = PageAction::ScrollUp(1);
        let _sd = PageAction::ScrollDown(1);
        let _sl = PageAction::ScrollLeft(1);
        let _sr = PageAction::ScrollRight(1);
        let _spd = PageAction::ScrollPageDown;
        let _spu = PageAction::ScrollPageUp;
        let _sfpd = PageAction::ScrollFullPageDown;
        let _sfpu = PageAction::ScrollFullPageUp;
        let _shpd = PageAction::ScrollHalfPageDown;
        let _shpu = PageAction::ScrollHalfPageUp;
        let _st = PageAction::ScrollTop;
        let _sb = PageAction::ScrollBottom;
    }

    // ── P0-6: download filename + path in notice ──────────────────────────────

    /// download_ids now maps guid → (DownloadId, filename). Verify the tuple
    /// structure is correct and the full path is constructed via download_dir.join.
    #[test]
    fn download_ids_stores_filename_alongside_id() {
        use buffr_downloads::DownloadId;
        use std::collections::HashMap;
        use std::path::Path;

        let mut download_ids: HashMap<String, (DownloadId, String)> = HashMap::new();
        let guid = "test-guid-001".to_owned();
        let filename = "report.pdf".to_owned();
        let row_id = DownloadId(42);

        download_ids.insert(guid.clone(), (row_id, filename.clone()));

        let (id, fname) = download_ids.get(&guid).cloned().unwrap();
        assert_eq!(id, row_id);
        assert_eq!(fname, "report.pdf");

        // Full path construction (P0-6 fix).
        let download_dir = Path::new("/home/user/Downloads");
        let full_path = download_dir.join(&fname);
        let expected = download_dir.join("report.pdf");
        assert_eq!(full_path, expected);
    }

    /// notice filename and path must be populated from the stored download_ids entry.
    #[test]
    fn download_notice_filename_populated() {
        use buffr_core::{DownloadNotice, DownloadNoticeKind};
        use std::path::Path;
        use std::time::Instant;

        // Simulate the "completed" notice construction from P0-6 fix.
        let filename = "image.png".to_owned();
        let download_dir = Path::new("/tmp/downloads");
        let full_path = download_dir.join(&filename);

        let notice = DownloadNotice {
            kind: DownloadNoticeKind::Completed,
            filename: filename.clone(),
            path: full_path.to_string_lossy().into_owned(),
            created_at: Instant::now(),
        };

        let expected_path = download_dir.join("image.png");
        assert_eq!(notice.filename, "image.png");
        assert_eq!(notice.path, expected_path.to_string_lossy().into_owned());
        assert!(matches!(notice.kind, DownloadNoticeKind::Completed));
    }

    // ── P0-7: view-source async fetch ────────────────────────────────────────

    /// view_source_loading_data_url returns a well-formed placeholder data URL.
    #[test]
    fn view_source_loading_placeholder_is_valid_data_url() {
        let url = "https://example.com/test";
        let placeholder = view_source_loading_data_url(url);

        assert!(
            placeholder.starts_with("data:text/html;base64,"),
            "placeholder must be a base64 data URL"
        );

        let b64 = placeholder.trim_start_matches("data:text/html;base64,");
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(b64)
            .expect("valid base64 in placeholder");
        let html = String::from_utf8(decoded).expect("valid UTF-8");

        assert!(html.contains("<!DOCTYPE html>"), "must be valid HTML");
        assert!(html.contains("Fetching source"), "must mention fetching");
        assert!(html.contains(url), "must mention the target URL");
    }

    /// view_source_html_sync on a reachable server returns a valid HTML document
    /// with the source content in a <pre> block.
    #[test]
    fn view_source_html_sync_error_page_on_unreachable_url() {
        // P0-7: uses view_source_html_sync (was view_source_html before rename).
        let html = view_source_html_sync("http://127.0.0.1:19999/no-such-server");
        let text = String::from_utf8_lossy(&html);
        assert!(
            text.contains("<!DOCTYPE html>"),
            "should be an HTML document"
        );
        assert!(
            text.contains("view-source error") || text.contains("Error"),
            "should mention an error"
        );
    }

    // ── P1-5: loading state + nav_count ──────────────────────────────────────

    /// loading_state map starts empty; inserting a session marks it loading.
    #[test]
    fn loading_state_tracks_session() {
        let loading: Arc<Mutex<HashMap<String, bool>>> = Arc::new(Mutex::new(HashMap::new()));
        loading.lock().unwrap().insert("sess-a".into(), true);
        loading.lock().unwrap().insert("sess-b".into(), false);

        let map = loading.lock().unwrap();
        assert!(
            map.get("sess-a").copied().unwrap_or(false),
            "sess-a should be loading"
        );
        assert!(
            !map.get("sess-b").copied().unwrap_or(true),
            "sess-b should not be loading"
        );
        assert!(
            !map.get("sess-c").copied().unwrap_or(false),
            "unknown session should default to not loading"
        );
    }

    /// nav_count increments per session and is independent across sessions.
    #[test]
    fn nav_count_increments_per_session() {
        let nav: Arc<Mutex<HashMap<String, usize>>> = Arc::new(Mutex::new(HashMap::new()));

        // Simulate two Page.frameNavigated events for sess-1.
        *nav.lock().unwrap().entry("sess-1".into()).or_insert(0) += 1;
        *nav.lock().unwrap().entry("sess-1".into()).or_insert(0) += 1;
        // One for sess-2.
        *nav.lock().unwrap().entry("sess-2".into()).or_insert(0) += 1;

        let map = nav.lock().unwrap();
        assert_eq!(map.get("sess-1").copied().unwrap_or(0), 2);
        assert_eq!(map.get("sess-2").copied().unwrap_or(0), 1);
        assert_eq!(
            map.get("sess-3").copied().unwrap_or(0),
            0,
            "unknown session has count 0"
        );
    }

    /// can_go_back heuristic: needs nav_count >= 2 for the session.
    #[test]
    fn can_go_back_requires_two_navigations() {
        // Simulate the heuristic logic inline.
        let counts: HashMap<String, usize> = [
            ("a".to_owned(), 0usize),
            ("b".to_owned(), 1usize),
            ("c".to_owned(), 2usize),
            ("d".to_owned(), 5usize),
        ]
        .into();

        let can_go_back = |sess: &str| counts.get(sess).copied().unwrap_or(0) >= 2;

        assert!(!can_go_back("a"), "0 navigations → no back");
        assert!(!can_go_back("b"), "1 navigation → no back");
        assert!(can_go_back("c"), "2 navigations → can go back");
        assert!(can_go_back("d"), "5 navigations → can go back");
        assert!(!can_go_back("unknown"), "unknown session → no back");
    }

    // ── P1-7: open_tab_at insert_idx ─────────────────────────────────────────

    /// Vec::insert semantics: inserting at index 1 in a 3-element vec places
    /// the item at position 1, pushing later items right.
    #[test]
    fn insert_at_index_places_tab_correctly() {
        let mut state = EngineState::new(9999);

        let make_tab = |n: u64, sess: &str| CdpTab {
            id: TabId(n),
            target_id: format!("t{n}"),
            session_id: sess.to_owned(),
            url: "about:blank".into(),
            title: "".into(),
            zoom_level: 1.0,
        };

        state.tabs.push(make_tab(1, "s1")); // idx 0
        state.tabs.push(make_tab(2, "s2")); // idx 1
        state.tabs.push(make_tab(3, "s3")); // idx 2

        // Insert at index 1 — should appear between tab 1 and tab 2.
        let new_tab = make_tab(99, "s99");
        let insert_idx = 1_usize;
        let clamped = insert_idx.min(state.tabs.len());
        state.tabs.insert(clamped, new_tab);

        assert_eq!(state.tabs[0].id, TabId(1));
        assert_eq!(state.tabs[1].id, TabId(99), "new tab should be at index 1");
        assert_eq!(state.tabs[2].id, TabId(2));
        assert_eq!(state.tabs[3].id, TabId(3));
    }

    /// Inserting at an index beyond the vec length is clamped to the end.
    #[test]
    fn insert_at_index_beyond_len_appends() {
        let mut v: Vec<u32> = vec![1, 2, 3];
        let idx = 99_usize;
        let clamped = idx.min(v.len());
        v.insert(clamped, 99);
        assert_eq!(v, vec![1, 2, 3, 99], "out-of-bounds insert should append");
    }

    // ── P1-8: perm_session_map cleanup on close ───────────────────────────────

    /// When a tab is closed, all perm_session_map entries for its session
    /// must be removed.
    #[test]
    fn perm_session_map_cleaned_on_tab_close() {
        let map: Arc<Mutex<HashMap<String, String>>> = Arc::new(Mutex::new(HashMap::new()));

        // Insert two permission requests for sess-closing and one for sess-other.
        map.lock()
            .unwrap()
            .insert("perm-1".into(), "sess-closing".into());
        map.lock()
            .unwrap()
            .insert("perm-2".into(), "sess-closing".into());
        map.lock()
            .unwrap()
            .insert("perm-3".into(), "sess-other".into());

        let closing_session = "sess-closing".to_owned();
        map.lock()
            .unwrap()
            .retain(|_, sess| sess != &closing_session);

        let m = map.lock().unwrap();
        assert!(!m.contains_key("perm-1"), "perm-1 should be cleaned up");
        assert!(!m.contains_key("perm-2"), "perm-2 should be cleaned up");
        assert!(
            m.contains_key("perm-3"),
            "perm-3 from other session should remain"
        );
    }

    // ── P1-9: popup sinks shared ─────────────────────────────────────────────

    /// The same Arc must back every call to popup_queue / popup_create_sink /
    /// popup_close_sink so callers share the same underlying queue.
    ///
    /// We can't construct a real BlinkCdpEngine without Chromium, so we verify
    /// the sharing property using Arc::ptr_eq on independently constructed clones.
    #[test]
    fn popup_queue_arc_clone_shares_underlying_queue() {
        let q = buffr_engine::new_popup_queue();
        let q2 = Arc::clone(&q);

        // Writing to one should be visible via the other.
        q.lock()
            .unwrap()
            .push_back("http://popup.example.com".into());
        let popped = q2.lock().unwrap().pop_front();
        assert_eq!(
            popped.as_deref(),
            Some("http://popup.example.com"),
            "Arc::clone must share the same underlying queue"
        );
    }

    #[test]
    fn popup_sinks_arc_ptr_eq() {
        let q = buffr_engine::new_popup_queue();
        let q2 = Arc::clone(&q);
        assert!(
            Arc::ptr_eq(&q, &q2),
            "Arc::clone must point to same allocation"
        );
    }
}