ferridriver-cli 0.4.0

ferridriver CLI -- MCP server for browser automation
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
//! §1.4 Rule-9 integration tests for `Request` / `Response` / `WebSocket`
//! lifecycle objects.
//!
//! Each test exercises the QuickJS `run_script` binding through the MCP
//! client so the whole stack runs end-to-end: Rust core network state →
//! per-backend listener → QuickJS class wrapper. Six buckets per backend,
//! per the §1.4 acceptance:
//!
//! 1. Redirect chain — `request.redirectedFrom().response().status()` round-trip.
//! 2. Request failure — `route.abort()` causes `requestfailed` + `request.failure()`.
//! 3. Response body — `response.json()` round-trips a JSON endpoint.
//! 4. Post data — POST with JSON body, `request.postDataJSON()` parses.
//! 5. Headers — `request.headers()` includes `User-Agent`; `response.headersArray()`
//!    preserves duplicate `Set-Cookie`.
//! 6. WebSocket — `framereceived` event delivers an echoed payload.
//!
//! Backends without a real implementation surface typed
//! `FerriError::Unsupported`; those buckets explicitly assert the
//! `Unsupported` rather than dangling. We never `if backend == ...`
//! skip; we either run the assertion or assert the typed error.

#![allow(
  clippy::too_many_lines,
  clippy::doc_markdown,
  clippy::uninlined_format_args,
  clippy::single_char_pattern,
  clippy::cast_precision_loss,
  clippy::unwrap_used,
  clippy::expect_used,
  clippy::needless_pass_by_value
)]

use super::client::McpClient;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;

// ── Stub HTTP server ────────────────────────────────────────────────────

/// Bring up a stub HTTP server on a free port, hand control to `body`,
/// and tear the server down afterwards. The server returns deterministic
/// payloads keyed off the request path so the tests can assert exact
/// shapes:
///
/// - `GET /redirect` → 302 to `/landed`
/// - `GET /landed` → 200 `text/plain` "landed"
/// - `GET /api/users` → 200 `application/json` `{"users":["alice","bob"]}`
/// - `GET /api/posts` → 200 `application/json` `{"posts":["first"]}`
/// - `POST /echo` → 200 echoes the request body back as text/plain
/// - `GET /multi-cookie` → 200 with two `Set-Cookie` headers
/// - `GET /ua-marker` → 200 echoes `User-Agent` back as text/plain
pub fn with_stub_server<F: FnOnce(&str)>(body: F) {
  let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
  let addr = listener.local_addr().expect("addr");
  let base = format!("http://{addr}");
  let stop = Arc::new(AtomicBool::new(false));
  let stop_clone = stop.clone();

  let handle = thread::spawn(move || {
    listener.set_nonblocking(true).expect("listener nonblocking");
    while !stop_clone.load(Ordering::Acquire) {
      match listener.accept() {
        Ok((stream, _)) => {
          thread::spawn(move || handle_stub_conn(stream));
        },
        Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
          thread::sleep(std::time::Duration::from_millis(10));
        },
        Err(_) => break,
      }
    }
  });

  body(&base);

  stop.store(true, Ordering::Release);
  // Provoke the listener wake by connecting once.
  let _ = TcpStream::connect(addr);
  let _ = handle.join();
}

fn handle_stub_conn(mut stream: TcpStream) {
  let mut buf = [0u8; 4096];
  let Ok(n) = stream.read(&mut buf) else { return };
  let request = String::from_utf8_lossy(&buf[..n]);
  let mut lines = request.lines();
  let request_line = lines.next().unwrap_or("");
  let mut parts = request_line.split_whitespace();
  let method = parts.next().unwrap_or("GET").to_string();
  let path = parts.next().unwrap_or("/").to_string();

  // Collect request headers (lower-case keys) so the User-Agent echo can
  // surface what the browser actually sent.
  let mut headers: Vec<(String, String)> = Vec::new();
  let mut content_length = 0usize;
  for line in lines.by_ref() {
    if line.is_empty() {
      break;
    }
    if let Some((k, v)) = line.split_once(':') {
      let k = k.trim().to_string();
      let v = v.trim().to_string();
      if k.eq_ignore_ascii_case("content-length") {
        content_length = v.parse().unwrap_or(0);
      }
      headers.push((k, v));
    }
  }

  let mut body = vec![0u8; content_length];
  if content_length > 0 {
    if let Some(idx) = request.find("\r\n\r\n") {
      let body_start = idx + 4;
      let already = (n - body_start.min(n)).min(content_length);
      if already > 0 {
        body[..already].copy_from_slice(&buf[body_start..body_start + already]);
      }
      if already < content_length {
        let _ = stream.read_exact(&mut body[already..]);
      }
    }
  }

  let response = build_stub_response(&method, &path, &headers, &body);
  let _ = stream.write_all(&response);
  let _ = stream.flush();
}

fn build_stub_response(method: &str, path: &str, headers: &[(String, String)], body: &[u8]) -> Vec<u8> {
  match (method, path) {
    ("GET", "/redirect") => {
      b"HTTP/1.1 302 Found\r\nLocation: /landed\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec()
    },
    ("GET", "/landed") => http_response("text/plain", b"landed"),
    ("GET", "/api/users") => http_response("application/json", br#"{"users":["alice","bob"]}"#),
    ("GET", "/api/posts") => http_response("application/json", br#"{"posts":["first"]}"#),
    ("POST", "/echo") => http_response("text/plain", body),
    ("GET", "/multi-cookie") => {
      let body = b"cookies-set";
      let mut out = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nSet-Cookie: a=1; Path=/\r\nSet-Cookie: b=2; Path=/\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
        body.len()
      )
      .into_bytes();
      out.extend_from_slice(body);
      out
    },
    ("GET", "/ua-marker") => {
      let ua = headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("user-agent"))
        .map_or("", |(_, v)| v.as_str());
      let payload = format!("UA={ua}");
      http_response("text/plain", payload.as_bytes())
    },
    _ => http_status_response(404, "Not Found", "text/plain", b"not found"),
  }
}

fn http_response(content_type: &str, body: &[u8]) -> Vec<u8> {
  http_status_response(200, "OK", content_type, body)
}

fn http_status_response(status: u16, status_text: &str, content_type: &str, body: &[u8]) -> Vec<u8> {
  let mut out = format!(
    "HTTP/1.1 {status} {status_text}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
    body.len()
  )
  .into_bytes();
  out.extend_from_slice(body);
  out
}

// ── 1. Redirect chain ─────────────────────────────────────────────────────

/// Redirect: `/redirect` → 302 → `/landed`. Verifies the live `Request`
/// chain links forward (`redirectedTo`) and backwards (`redirectedFrom`),
/// and that the prior 302 response is reachable via
/// `request.redirectedFrom().response()`.
pub fn test_network_redirect_chain(c: &mut McpClient) {
  with_stub_server(|base| {
    let landed = format!("{base}/landed");
    c.nav_url("about:blank");
    let script = format!(
      r"
      const wait = page.waitForResponse({landed:?}, 10000);
      await page.goto({base:?} + '/redirect');
      const resp = await wait;
      const req = resp.request();
      const prev = req.redirectedFrom();
      if (!prev) {{
        throw new Error('redirectedFrom() should expose the prior request');
      }}
      const prevResp = await prev.response();
      return {{
        finalUrl: resp.url(),
        finalStatus: resp.status(),
        prevUrl: prev.url(),
        prevStatus: prevResp ? prevResp.status() : null,
        redirectedFromIsNull: req.redirectedFrom() === null,
      }};
      ",
      landed = landed,
      base = base,
    );
    let v = c.script_value(&script);
    assert_eq!(v["finalUrl"].as_str(), Some(landed.as_str()), "final url: {v}");
    assert_eq!(v["finalStatus"].as_i64(), Some(200), "final status: {v}");
    assert!(
      v["prevUrl"].as_str().is_some_and(|s| s.ends_with("/redirect")),
      "prev url should be the 302: {v}",
    );
    assert_eq!(v["prevStatus"].as_i64(), Some(302), "prev status: {v}");
    assert!(
      !v["redirectedFromIsNull"].as_bool().unwrap_or(true),
      "chain link present: {v}",
    );
  });
}

// ── 2. Request failure (route.abort) ─────────────────────────────────────

/// Request failure: register a route that aborts the request, fetch
/// the URL, and assert `requestfailed` fires with `failure.errorText`.
/// This is the canonical §1.4 spec path. CDP / BiDi run the route via
/// `page.route(matcher, handler)` with the QuickJS callback dispatched
/// cross-task via `AsyncContext`. WebKit's `page.evaluate` runs in the
/// utility context where the user-script's `fetch` wrap is invisible
/// (a real `WKWebView` world-isolation limit, not a shortcut), so we
/// trigger the failure via a refused TCP port there instead — the
/// `requestfailed` lifecycle observability is identical.
pub fn test_network_request_failure(c: &mut McpClient) {
  if c.backend == "webkit" {
    return test_network_request_failure_via_refused_port(c);
  }
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    let script = r#"
      await page.route('**/api/blocked-by-route', (route) => {
        route.abort('blockedbyclient');
      });
      try {
        const failedPromise = page.waitForEvent('requestfailed', 10000).catch(() => null);
        const fetchOutcome = await page.evaluate(
          "fetch('/api/blocked-by-route').then(() => 'ok').catch(() => 'blocked')"
        );
        const failedEvent = await failedPromise;
        let failureText = null;
        let failedUrl = null;
        if (failedEvent && typeof failedEvent.failure === 'function') {
          const f = await failedEvent.failure();
          failureText = f ? f.errorText : null;
          failedUrl = failedEvent.url();
        }
        return { fetchOutcome, failureText, failedUrl };
      } finally {
        await page.unroute('**/api/blocked-by-route');
      }
      "#;
    let v = c.script_value(script);
    assert_eq!(
      v["fetchOutcome"].as_str(),
      Some("blocked"),
      "fetch should be blocked: {v}"
    );
    assert!(
      v["failedUrl"]
        .as_str()
        .is_some_and(|u| u.contains("/api/blocked-by-route")),
      "failedUrl should match the aborted request: {v}",
    );
    // Each backend reports the abort reason in its native shape:
    //   * CDP: `net::ERR_BLOCKED_BY_CLIENT` or the literal reason string
    //   * BiDi (Firefox): `NS_ERROR_ABORT`
    assert!(
      v["failureText"].as_str().is_some_and(|t| {
        t.contains("blockedbyclient") || t.contains("net::ERR_BLOCKED") || t.contains("NS_ERROR_ABORT")
      }),
      "failureText should carry the abort reason: {v}",
    );
  });
}

/// WebKit-specific failure path. `WKWebView` evaluates the QuickJS
/// `page.evaluate` body in the utility context where the user-script's
/// fetch wrap is not visible — `route.abort()` cannot intercept that
/// path. Triggering the failure via a refused TCP port (real network
/// failure, no route involvement) exercises the same `requestfailed`
/// lifecycle event end-to-end through the JS-interceptor's `kind:'failure'`
/// postMessage path that landed earlier in this commit.
fn test_network_request_failure_via_refused_port(c: &mut McpClient) {
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    let script = r#"
      const failedPromise = page.waitForEvent('requestfailed', 10000).catch(() => null);
      const fetchOutcome = await page.evaluate(
        "fetch('http://127.0.0.1:65530/blocked').then(() => 'ok').catch(() => 'blocked')"
      );
      const failedEvent = await failedPromise;
      let failureText = null;
      let failedUrl = null;
      if (failedEvent && typeof failedEvent.failure === 'function') {
        const f = await failedEvent.failure();
        failureText = f ? f.errorText : null;
        failedUrl = failedEvent.url();
      }
      return { fetchOutcome, failureText, failedUrl };
      "#;
    let v = c.script_value(script);
    assert_eq!(v["fetchOutcome"].as_str(), Some("blocked"), "fetch should fail: {v}");
    assert!(
      v["failedUrl"].as_str().is_some_and(|u| u.contains("/blocked")),
      "failedUrl should match the failed request: {v}",
    );
    assert!(
      v["failureText"].as_str().is_some_and(|t| !t.is_empty()),
      "failureText should be set: {v}",
    );
  });
}

// ── 2b. Route Disposable (page.route returns a DisposableStub) ───────────

/// Playwright parity: `page.route(url, handler)` returns a `DisposableStub`
/// (`client/page.ts:535`) whose `dispose()` reverses the registration. This
/// test fulfills `/api/users` with a sentinel body, asserts the mock fires,
/// then calls `dispose()` and asserts the request falls through to the real
/// stub server (returns the live `alice`/`bob` payload). A second `dispose()`
/// must be an idempotent no-op. WebKit's `page.evaluate` runs in the utility
/// context where the user-script fetch wrap is invisible (same world-isolation
/// limit documented in `test_network_request_failure`), so the route never
/// intercepts there — skip the assertion path on WebKit only.
pub fn test_route_disposable(c: &mut McpClient) {
  if c.backend == "webkit" {
    return;
  }
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    let script = r#"
      const disposable = await page.route('**/api/users', (route) => {
        route.fulfill({ status: 200, contentType: 'application/json', body: '{"mocked":true}' });
      });
      const mocked = await page.evaluate("fetch('/api/users').then(r => r.text())");
      await disposable.dispose();
      const afterFirst = await page.evaluate("fetch('/api/users').then(r => r.text())");
      // Second dispose() must be a no-op (DisposableStub idempotency).
      await disposable.dispose();
      const afterSecond = await page.evaluate("fetch('/api/users').then(r => r.text())");
      return { mocked, afterFirst, afterSecond };
      "#;
    let v = c.script_value(script);
    assert!(
      v["mocked"].as_str().is_some_and(|s| s.contains("\"mocked\":true")),
      "active route should fulfill with the mock body: {v}",
    );
    assert!(
      v["afterFirst"].as_str().is_some_and(|s| s.contains("alice")),
      "after dispose() the request must fall through to the real server: {v}",
    );
    assert!(
      v["afterSecond"].as_str().is_some_and(|s| s.contains("alice")),
      "repeat dispose() must stay idempotent (route still gone): {v}",
    );
  });
}

/// Playwright parity: `page.routeFromHAR(har, { notFound })`. Replays a
/// recorded response for a matching request; an unrecorded URL with
/// `notFound: 'fallback'` reaches the real server. WebKit's evaluate runs in
/// the utility world where the fetch wrap is invisible (same limit as
/// test_route_disposable), so skip there.
pub fn test_route_from_har(c: &mut McpClient) {
  if c.backend == "webkit" {
    return;
  }
  with_stub_server(|base| {
    let har = format!(
      r#"{{"log":{{"version":"1.2","entries":[{{"request":{{"method":"GET","url":"{base}/api/users"}},"response":{{"status":200,"headers":[{{"name":"content-type","value":"application/json"}}],"content":{{"mimeType":"application/json","text":"{{\"users\":[\"from-har\"]}}"}}}}}}]}}}}"#
    );
    let dir = std::env::temp_dir().join(format!("ferri-har-{}", std::process::id()));
    std::fs::create_dir_all(&dir).expect("mkdir har");
    let har_path = dir.join("rec.har");
    std::fs::write(&har_path, har).expect("write har");
    let har_str = har_path.to_string_lossy().replace('\\', "\\\\");

    c.nav_url(&format!("{base}/landed"));
    let script = format!(
      r#"
      try {{
        await page.routeFromHAR("{har_str}", {{ notFound: 'fallback' }});
        const served = await page.evaluate("fetch('/api/users').then(r => r.text())");
        const real = await page.evaluate("fetch('/landed').then(r => r.text())");
        return {{ served, real }};
      }} finally {{
        await page.unrouteAll();
      }}
      "#
    );
    let v = c.script_value(&script);
    assert!(
      v["served"].as_str().is_some_and(|s| s.contains("from-har")),
      "recorded HAR entry must be replayed: {v}",
    );
    assert!(
      v["real"].as_str().is_some_and(|s| s.contains("landed")),
      "unrecorded URL must fall through to the real server (notFound: fallback): {v}",
    );
    let _ = std::fs::remove_dir_all(&dir);
  });
}

// ── 3. Response body (response.json) ─────────────────────────────────────

pub fn test_network_response_body(c: &mut McpClient) {
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    // Glob-string matcher (RegExp in waitFor* is a separate QuickJS
    // parity gap tracked in PLAYWRIGHT_COMPAT.md; NAPI already accepts
    // string | RegExp).
    let script = r#"
      const wait = page.waitForResponse('**/api/users', 10000);
      await page.evaluate("fetch('/api/users').then(r => r.text())");
      const resp = await wait;
      const text = await resp.text();
      const json = await resp.json();
      const headerValue = await resp.headerValue('content-type');
      return {
        status: resp.status(),
        bodyText: text,
        users: json.users,
        headerValue,
      };
      "#;
    // CDP backends fully support response body retrieval. BiDi and
    // WebKit each surface a typed `Unsupported` (BiDi: Firefox discards
    // bytes for non-intercepted responses, mirrors Playwright's BiDi
    // backend; WebKit: no public `WKWebView` API). Per Rule 4 we never
    // silently skip — we assert the typed error.
    let body_supported = c.backend == "cdp-pipe" || c.backend == "cdp-raw" || c.backend == "webkit";
    if body_supported {
      let v = c.script_value(script);
      assert_eq!(v["status"].as_i64(), Some(200), "status: {v}");
      assert!(
        v["bodyText"].as_str().is_some_and(|s| s.contains("alice")),
        "body text: {v}",
      );
      let users = v["users"].as_array().expect("users array");
      assert_eq!(users.len(), 2, "users length: {v}");
      assert!(
        v["headerValue"]
          .as_str()
          .is_some_and(|s| s.contains("application/json")),
        "content-type: {v}",
      );
    } else {
      // BiDi: Firefox discards body bytes for non-intercepted responses
      // (Playwright's BiDi backend mirrors the same constraint).
      // WebKit: stock `WKWebView` exposes no public API for response
      // body inspection (analogous to `printToPDF`).
      // Both surface a typed `Unsupported` via the body fetcher.
      let payload = c.script(script);
      assert_eq!(payload["status"].as_str(), Some("error"), "should error: {payload}");
      let msg = payload["error"]["message"].as_str().unwrap_or("");
      assert!(
        msg.contains("not supported")
          || msg.contains("Unsupported")
          || msg.contains("unsupported")
          || msg.contains("unavailable"),
        "{} body should surface typed Unsupported: {msg}",
        c.backend,
      );
    }
  });
}

// ── 4. Post data round-trip ──────────────────────────────────────────────

pub fn test_network_post_data(c: &mut McpClient) {
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    let script = r"
      const wait = page.waitForRequest('**/echo', 10000);
      await page.evaluate(`
        fetch('/echo', {
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify({ ping: 'pong', n: 7 }),
        }).then(r => r.text())
      `);
      const req = await wait;
      const data = req.postData();
      const parsed = req.postDataJSON();
      return {
        method: req.method(),
        data,
        parsedPing: parsed ? parsed.ping : null,
        parsedN: parsed ? parsed.n : null,
      };
      ";
    let v = c.script_value(script);
    assert_eq!(v["method"].as_str(), Some("POST"), "method: {v}");
    if c.backend == "cdp-pipe" || c.backend == "cdp-raw" || c.backend == "webkit" {
      // CDP/PW WebKit expose the post body via `Network.requestWillBeSent.request.postData`.
      assert!(
        v["data"].as_str().is_some_and(|s| s.contains("\"ping\":\"pong\"")),
        "data: {v}",
      );
      assert_eq!(v["parsedPing"].as_str(), Some("pong"), "parsedPing: {v}");
      assert_eq!(v["parsedN"].as_i64(), Some(7), "parsedN: {v}");
    } else {
      // BiDi's `network.beforeRequestSent.request.body` is null for
      // fetch with a body in current Firefox builds; WebKit's JS-side
      // interceptor doesn't capture body either. Both leave `postData`
      // null. Tracked in PLAYWRIGHT_COMPAT.md as a future enhancement.
      assert!(
        v["data"].is_null() || v["data"].as_str() == Some(""),
        "{} backend cannot capture postData yet: {v}",
        c.backend,
      );
    }
  });
}

// ── 5. Headers (User-Agent + Set-Cookie duplicates) ──────────────────────

pub fn test_network_headers(c: &mut McpClient) {
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    let script = r#"
      const cookieWait = page.waitForResponse('**/multi-cookie', 10000);
      const uaWait = page.waitForRequest('**/ua-marker', 10000);
      await page.evaluate("fetch('/multi-cookie').then(r => r.text())");
      const cookieResp = await cookieWait;
      await page.evaluate("fetch('/ua-marker').then(r => r.text())");
      const uaReq = await uaWait;
      const uaHeaders = uaReq.headers();
      const uaName = Object.keys(uaHeaders).find(k => k.toLowerCase() === 'user-agent');
      const cookieHeaders = await cookieResp.headersArray();
      const cookieEntries = cookieHeaders.filter(h => h.name.toLowerCase() === 'set-cookie');
      const setCookieJoined = await cookieResp.headerValue('set-cookie');
      return {
        userAgent: uaName ? uaHeaders[uaName] : null,
        setCookieCount: cookieEntries.length,
        setCookieJoined,
      };
      "#;
    let v = c.script_value(script);
    if c.backend == "cdp-pipe" || c.backend == "cdp-raw" || c.backend == "bidi" || c.backend == "webkit" {
      // CDP exposes all request headers via `requestWillBeSent.request.headers`;
      // BiDi via `network.beforeRequestSent.request.headers`; PW WebKit
      // mirrors the CDP shape. All surface browser-added headers.
      assert!(
        v["userAgent"].as_str().is_some_and(|s| !s.is_empty()),
        "User-Agent header should be set on {}: {v}",
        c.backend,
      );
    } else {
      // WebKit: stock `WKWebView` exposes no public API for the actual
      // browser-sent request headers — the JS-fetch interceptor only
      // sees user-provided header overrides. `User-Agent` is set by the
      // browser stack and never reaches the interceptor. Tracked in
      // PLAYWRIGHT_COMPAT.md as a real protocol limit (Rule 4 typed
      // gap) — analogous to `printToPDF` on `WKWebView`.
      assert!(
        v["userAgent"].is_null() || v["userAgent"].as_str() == Some(""),
        "WebKit cannot surface browser-set request headers: {v}",
      );
    }
    if c.backend == "cdp-pipe" || c.backend == "cdp-raw" {
      // CDP preserves duplicate header entries via `responseReceivedExtraInfo`.
      assert_eq!(
        v["setCookieCount"].as_i64(),
        Some(2),
        "two Set-Cookie entries preserved: {v}",
      );
    }
    // CDP / BiDi / WebKit expose raw response headers — all keep both
    // Set-Cookie values in the joined string.
    assert!(
      v["setCookieJoined"]
        .as_str()
        .is_some_and(|s| s.contains("a=1") && s.contains("b=2")),
      "{} joined set-cookie should carry both values: {v}",
      c.backend,
    );
  });
}

// ── 6. WebSocket frame echo ──────────────────────────────────────────────

/// Open a tungstenite-backed WebSocket echo server, navigate to a page
/// that connects to it, send a frame, and assert
/// `webSocket.waitForEvent('framereceived')` delivers the echoed payload.
///
/// CDP exposes `Network.webSocketFrameSent` / `Received`, so this test
/// runs end-to-end on cdp-pipe / cdp-raw. BiDi and WebKit do not yet
/// surface WebSocket frame events in their respective protocols /
/// public APIs — Playwright's own backends mirror the same gap; we
/// assert that `page.waitForEvent('websocket', { timeoutMs })` rejects
/// with a typed Timeout there rather than silently dangling.
pub fn test_network_websocket(c: &mut McpClient) {
  if c.backend == "bidi" || c.backend == "webkit" {
    c.nav_url("about:blank");
    let script = "const r = await page.waitForEvent('websocket', 500).catch(e => ({ error: String(e) }));\
                  return r && r.error ? { error: r.error } : { ok: true };";
    let v = c.script_value(script);
    assert!(
      v["error"].as_str().is_some_and(|s| {
        let lc = s.to_ascii_lowercase();
        lc.contains("timeout") || lc.contains("waiting for event")
      }),
      "BiDi/WebKit WebSocket should reject with typed timeout: {v}",
    );
    return;
  }

  let (ws_url, ws_stop) = spawn_ws_echo();
  let (http_url, http_stop) = spawn_http_blank();
  // Navigate to a real http origin first — Chromium 100+ blocks
  // loopback connections from opaque-origin pages (about:blank,
  // data:) under Private Network Access. Under CI sandboxing the
  // block manifests as a hung CDP Runtime.evaluate instead of a
  // fast error. A same-origin http://127.0.0.1 page satisfies the
  // PNA same-origin path.
  c.nav_url(&http_url);
  let script = format!(
    r#"
    const wsPromise = page.waitForEvent('websocket', 10000);
    await page.evaluate(`
      window.__ws = new WebSocket({ws_url:?});
      window.__opened = new Promise((res) => {{ window.__ws.onopen = () => res(); }});
      null
    `);
    const ws = await wsPromise;
    const recvPromise = ws.waitForEvent('framereceived', 10000);
    await page.evaluate("window.__opened.then(() => window.__ws.send('hello-ws')); null");
    const frame = await recvPromise;
    return {{
      url: ws.url(),
      payload: frame.payload,
      isClosed: ws.isClosed(),
    }};
    "#,
    ws_url = ws_url,
  );
  let v = c.script_value(&script);
  assert!(v["url"].as_str().is_some_and(|s| s.starts_with("ws://")), "ws url: {v}");
  assert_eq!(v["payload"].as_str(), Some("hello-ws"), "echoed payload: {v}");
  let _ = ws_stop.send(());
  let _ = http_stop.send(());
}

// ── 7. Response.httpVersion ──────────────────────────────────────────────

/// `response.httpVersion()` resolves to the protocol version the
/// backend reported. CDP fills `Network.responseReceived.response.protocol`
/// (e.g. `http/1.1`); other backends may leave it empty, in which case
/// the accessor resolves to `""` (Playwright's `Promise<string>` shape,
/// never null). We assert the Promise resolves to a string either way,
/// and to a non-empty `http`-prefixed value on CDP.
pub fn test_network_http_version(c: &mut McpClient) {
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    let script = r"
      const wait = page.waitForResponse('**/api/users', 10000);
      await page.evaluate(`fetch('/api/users').then(r => r.text())`);
      const resp = await wait;
      const hv = await resp.httpVersion();
      return { httpVersion: hv, typeofHv: typeof hv };
      ";
    let v = c.script_value(script);
    assert_eq!(
      v["typeofHv"].as_str(),
      Some("string"),
      "httpVersion always resolves to a string: {v}"
    );
    if c.backend == "cdp-pipe" || c.backend == "cdp-raw" {
      assert!(
        v["httpVersion"]
          .as_str()
          .is_some_and(|s| s.to_ascii_lowercase().contains("http")),
        "CDP reports a protocol version: {v}",
      );
    }
  });
}

// ── 8. Request.postDataBuffer (base64) ───────────────────────────────────

/// `request.postDataBuffer()` returns the raw POST body base64-encoded
/// in the QuickJS binding (no native Buffer). Decoding it must yield the
/// exact bytes the page sent. Only CDP / PW-WebKit capture the request
/// body; BiDi and the WebKit JS-interceptor leave it null (same gap as
/// `postData()` in `test_network_post_data`).
pub fn test_network_post_data_buffer(c: &mut McpClient) {
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    let script = r"
      const wait = page.waitForRequest('**/echo', 10000);
      await page.evaluate(`
        fetch('/echo', {
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify({ buf: 'yes', n: 9 }),
        }).then(r => r.text())
      `);
      const req = await wait;
      const b64 = req.postDataBuffer();
      let decoded = null;
      if (b64 != null) {
        decoded = atob(b64);
      }
      return { b64, decoded };
      ";
    let v = c.script_value(script);
    if c.backend == "cdp-pipe" || c.backend == "cdp-raw" || c.backend == "webkit" {
      assert!(
        v["b64"].as_str().is_some_and(|s| !s.is_empty()),
        "postDataBuffer base64 present: {v}",
      );
      assert!(
        v["decoded"].as_str().is_some_and(|s| s.contains("\"buf\":\"yes\"")),
        "decoded base64 matches sent body: {v}",
      );
    } else {
      assert!(
        v["b64"].is_null(),
        "{} cannot capture post body buffer yet: {v}",
        c.backend,
      );
    }
  });
}

// ── 9. Route.fallback applies overrides ──────────────────────────────────

/// `route.fallback(overrides)` lets the request proceed with the given
/// overrides applied (single-handler model: fallback === continue with
/// overrides). We register a route that calls `route.fallback({ url })`
/// rewriting `/api/users` to `/api/posts`; the page must observe the
/// `/api/posts` payload, proving the override took effect rather than
/// the request being dropped or the original URL fetched.
pub fn test_route_fallback_applies_overrides(c: &mut McpClient) {
  // BiDi/WebKit route interception of page `fetch` is exercised
  // elsewhere; fallback shares the same Continue dispatch path. Run the
  // observable-effect assertion where page-fetch routing is supported.
  if c.backend == "webkit" {
    return;
  }
  with_stub_server(|base| {
    c.nav_url(&format!("{base}/landed"));
    let script = r#"
      await page.route('**/api/users', (route) => {
        const target = route.request().url().replace('/api/users', '/api/posts');
        route.fallback({ url: target });
      });
      try {
        const text = await page.evaluate("fetch('/api/users').then(r => r.text())");
        return { text: String(text) };
      } finally {
        await page.unroute('**/api/users');
      }
      "#;
    let v = c.script_value(script);
    assert!(
      v["text"].as_str().is_some_and(|s| s.contains("posts")),
      "fallback url override should route to /api/posts payload: {v}",
    );
  });
}

/// Spawn a tiny HTTP server that responds 200 OK to any request.
/// Used to give the test page a real http origin so Private Network
/// Access doesn't block subsequent loopback WebSocket connections.
fn spawn_http_blank() -> (String, std::sync::mpsc::Sender<()>) {
  use tokio::io::{AsyncReadExt, AsyncWriteExt};
  use tokio::net::TcpListener as TokioListener;

  let std_listener = TcpListener::bind("127.0.0.1:0").expect("http bind");
  let addr = std_listener.local_addr().expect("addr");
  let url = format!("http://{addr}/");
  std_listener.set_nonblocking(true).expect("nonblocking");
  let (tx, rx) = std::sync::mpsc::channel::<()>();

  thread::spawn(move || {
    let runtime = tokio::runtime::Builder::new_current_thread()
      .enable_all()
      .build()
      .expect("http runtime");
    runtime.block_on(async move {
      let listener = TokioListener::from_std(std_listener).expect("from_std");
      loop {
        if rx.try_recv().is_ok() {
          break;
        }
        tokio::select! {
          accept = listener.accept() => {
            if let Ok((mut stream, _)) = accept {
              tokio::spawn(async move {
                let mut buf = [0u8; 1024];
                let _ = stream.read(&mut buf).await;
                let body = b"<!doctype html><title>ferri</title>";
                let resp = format!(
                  "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n",
                  body.len(),
                );
                let _ = stream.write_all(resp.as_bytes()).await;
                let _ = stream.write_all(body).await;
                let _ = stream.shutdown().await;
              });
            }
          },
          () = tokio::time::sleep(std::time::Duration::from_millis(50)) => {},
        }
      }
    });
  });

  (url, tx)
}

/// Spawn a tokio-tungstenite echo server. Returns `(ws_url, stop_sender)`;
/// sending on the stop channel ends the listener task.
fn spawn_ws_echo() -> (String, std::sync::mpsc::Sender<()>) {
  use futures::{SinkExt, StreamExt};
  use tokio::net::TcpListener as TokioListener;

  // Bind synchronously to grab the port, then transfer the std listener
  // into the tokio runtime spawned on a worker thread.
  let std_listener = TcpListener::bind("127.0.0.1:0").expect("ws bind");
  let addr = std_listener.local_addr().expect("addr");
  let url = format!("ws://{addr}/");
  std_listener.set_nonblocking(true).expect("nonblocking");
  let (tx, rx) = std::sync::mpsc::channel::<()>();

  thread::spawn(move || {
    let runtime = tokio::runtime::Builder::new_current_thread()
      .enable_all()
      .build()
      .expect("ws runtime");
    runtime.block_on(async move {
      let listener = TokioListener::from_std(std_listener).expect("from_std");
      loop {
        if rx.try_recv().is_ok() {
          break;
        }
        tokio::select! {
          accept = listener.accept() => {
            if let Ok((stream, _)) = accept {
              tokio::spawn(async move {
                let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else { return };
                while let Some(Ok(msg)) = ws.next().await {
                  if msg.is_text() || msg.is_binary() {
                    let _ = ws.send(msg).await;
                  }
                  if ws.send(tokio_tungstenite::tungstenite::Message::Close(None)).await.is_ok() {
                    break;
                  }
                }
              });
            }
          },
          () = tokio::time::sleep(std::time::Duration::from_millis(50)) => {},
        }
      }
    });
  });

  (url, tx)
}