ff-rdp-cli 0.2.0

CLI for Firefox Remote Debugging Protocol
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
use std::path::PathBuf;

use super::support::{MockRdpServer, load_fixture};
use base64::Engine as _;

fn ff_rdp_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_ff-rdp"))
}

fn base_args(port: u16) -> Vec<String> {
    vec![
        "--host".to_owned(),
        "127.0.0.1".to_owned(),
        "--port".to_owned(),
        port.to_string(),
        "--no-daemon".to_owned(),
    ]
}

fn screenshot_server(eval_result_fixture: &str) -> MockRdpServer {
    MockRdpServer::new()
        .on("listTabs", load_fixture("list_tabs_response.json"))
        .on("getTarget", load_fixture("get_target_response.json"))
        .on_with_followup(
            "evaluateJSAsync",
            load_fixture("eval_immediate_response.json"),
            load_fixture(eval_result_fixture),
        )
}

/// Create a unique temp directory under the OS temp dir for one test.
///
/// Returns the path; the caller is responsible for cleaning it up (or leaving
/// it — test temp files are harmless and cleaned on the next reboot).
fn unique_temp_dir(label: &str) -> PathBuf {
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let dir = std::env::temp_dir().join(format!("ff_rdp_test_{label}_{ts}"));
    std::fs::create_dir_all(&dir).expect("create temp dir");
    dir
}

// ---------------------------------------------------------------------------
// Happy-path: data URL returned as a plain string value
// ---------------------------------------------------------------------------

#[test]
fn screenshot_saves_png_to_explicit_output_path() {
    let server = screenshot_server("eval_result_screenshot.json");
    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let out_dir = unique_temp_dir("screenshot_explicit");
    let out_path = out_dir.join("test.png");

    let mut args = base_args(port);
    args.extend([
        "screenshot".to_owned(),
        "--output".to_owned(),
        out_path.to_string_lossy().into_owned(),
    ]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // PNG file must exist and start with the PNG magic bytes.
    assert!(out_path.exists(), "PNG file should have been written");
    let png_bytes = std::fs::read(&out_path).expect("read png");
    assert_eq!(&png_bytes[..4], b"\x89PNG", "file should be a PNG");

    // JSON output envelope.
    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout must be valid JSON");

    assert_eq!(json["total"], 1);
    assert_eq!(json["results"]["width"], 1);
    assert_eq!(json["results"]["height"], 1);
    assert!(json["results"]["bytes"].as_u64().unwrap_or(0) > 0);
    assert!(
        json["results"]["path"]
            .as_str()
            .unwrap_or("")
            .ends_with("test.png"),
        "path should end with test.png: {}",
        json["results"]["path"]
    );

    let _ = std::fs::remove_dir_all(&out_dir);
}

#[test]
fn screenshot_auto_names_file_when_no_output_given() {
    let server = screenshot_server("eval_result_screenshot.json");
    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    // Run in a temp directory so the auto-named file lands there.
    let work_dir = unique_temp_dir("screenshot_auto");

    let mut args = base_args(port);
    args.push("screenshot".to_owned());

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .current_dir(&work_dir)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout must be valid JSON");

    let path_str = json["results"]["path"].as_str().unwrap_or("");
    assert!(
        path_str.contains("screenshot-")
            && std::path::Path::new(path_str)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("png")),
        "expected auto-named screenshot path, got: {path_str}"
    );

    // The file should also actually exist.
    assert!(
        PathBuf::from(path_str).exists(),
        "auto-named PNG should exist at {path_str}"
    );

    let _ = std::fs::remove_dir_all(&work_dir);
}

// ---------------------------------------------------------------------------
// Happy-path: data URL returned as a LongString (fetched via substring)
// ---------------------------------------------------------------------------

#[test]
fn screenshot_handles_longstring_data_url() {
    let server = MockRdpServer::new()
        .on("listTabs", load_fixture("list_tabs_response.json"))
        .on("getTarget", load_fixture("get_target_response.json"))
        .on_with_followup(
            "evaluateJSAsync",
            load_fixture("eval_immediate_response.json"),
            load_fixture("eval_result_screenshot_longstring.json"),
        )
        .on(
            "substring",
            load_fixture("substring_screenshot_response.json"),
        );

    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let out_dir = unique_temp_dir("screenshot_longstring");
    let out_path = out_dir.join("longstring.png");

    let mut args = base_args(port);
    args.extend([
        "screenshot".to_owned(),
        "--output".to_owned(),
        out_path.to_string_lossy().into_owned(),
    ]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    assert!(out_path.exists(), "PNG file should have been written");
    let png_bytes = std::fs::read(&out_path).expect("read png");
    assert_eq!(&png_bytes[..4], b"\x89PNG");

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout must be valid JSON");
    assert_eq!(json["total"], 1);
    assert_eq!(json["results"]["width"], 1);
    assert_eq!(json["results"]["height"], 1);

    let _ = std::fs::remove_dir_all(&out_dir);
}

// ---------------------------------------------------------------------------
// Error-path: JS returns null (drawWindow not available)
// ---------------------------------------------------------------------------

#[test]
fn screenshot_null_result_exits_nonzero_with_helpful_message() {
    let server = screenshot_server("eval_result_screenshot_null.json");
    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let mut args = base_args(port);
    args.push("screenshot".to_owned());

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        !output.status.success(),
        "expected failure when drawWindow is unavailable"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    // The error should mention either the failed mechanism or the required mode
    // so the user knows what went wrong and how to fix it.
    assert!(
        stderr.contains("screenshot")
            && (stderr.contains("headless")
                || stderr.contains("drawWindow")
                || stderr.contains("screenshotContentActor")),
        "stderr should contain a helpful screenshot error message: {stderr}"
    );
}

// ---------------------------------------------------------------------------
// Fallback path: drawWindow returns null but screenshotContentActor works
// ---------------------------------------------------------------------------

#[test]
fn screenshot_falls_back_to_screenshot_content_actor_when_draw_window_unavailable() {
    // The 1x1 PNG data URL used throughout these tests.
    let png_data_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4//8/AAX+Av4N70a4AAAAAElFTkSuQmCC";

    // Build captureScreenshot response inline — the actor ID must match what
    // get_target_response.json advertises: "server1.conn0.child2/screenshotContentActor15".
    let capture_response = serde_json::json!({
        "from": "server1.conn0.child2/screenshotContentActor15",
        "capture": {
            "data": png_data_url,
            "width": 1,
            "height": 1
        }
    });

    let server = MockRdpServer::new()
        .on("listTabs", load_fixture("list_tabs_response.json"))
        .on("getTarget", load_fixture("get_target_response.json"))
        .on_with_followup(
            "evaluateJSAsync",
            load_fixture("eval_immediate_response.json"),
            load_fixture("eval_result_screenshot_null.json"),
        )
        .on("captureScreenshot", capture_response);

    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let out_dir = unique_temp_dir("screenshot_fallback");
    let out_path = out_dir.join("fallback.png");

    let mut args = base_args(port);
    args.extend([
        "screenshot".to_owned(),
        "--output".to_owned(),
        out_path.to_string_lossy().into_owned(),
    ]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success via screenshotContentActor fallback, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    assert!(out_path.exists(), "PNG file should have been written");
    let png_bytes = std::fs::read(&out_path).expect("read png");
    assert_eq!(&png_bytes[..4], b"\x89PNG", "file should be a PNG");

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout must be valid JSON");
    assert_eq!(json["total"], 1);
    assert_eq!(json["results"]["width"], 1);
    assert_eq!(json["results"]["height"], 1);
    assert!(json["results"]["bytes"].as_u64().unwrap_or(0) > 0);

    let _ = std::fs::remove_dir_all(&out_dir);
}

// ---------------------------------------------------------------------------
// --base64 mode: returns PNG as base64 in JSON, no file written
// ---------------------------------------------------------------------------

#[test]
fn screenshot_base64_returns_png_data_without_writing_file() {
    let server = screenshot_server("eval_result_screenshot.json");
    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let work_dir = unique_temp_dir("screenshot_base64");

    let mut args = base_args(port);
    args.extend(["screenshot".to_owned(), "--base64".to_owned()]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .current_dir(&work_dir)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout must be valid JSON");

    assert_eq!(json["total"], 1);
    assert_eq!(json["results"]["width"], 1);
    assert_eq!(json["results"]["height"], 1);
    assert!(json["results"]["bytes"].as_u64().unwrap_or(0) > 0);

    // results.base64 must be present and contain valid base64-encoded PNG data.
    let b64_str = json["results"]["base64"]
        .as_str()
        .expect("results.base64 should be a string");
    assert!(!b64_str.is_empty(), "base64 string should not be empty");

    // Decode and verify PNG magic bytes.
    let png_bytes = base64::engine::general_purpose::STANDARD
        .decode(b64_str)
        .expect("results.base64 must be valid base64");
    assert_eq!(&png_bytes[..4], b"\x89PNG", "decoded data should be a PNG");

    // No file should have been written into the working directory.
    let files_in_dir: Vec<_> = std::fs::read_dir(&work_dir)
        .expect("read work_dir")
        .filter_map(Result::ok)
        .collect();
    assert!(
        files_in_dir.is_empty(),
        "no file should be written when --base64 is used, found: {:?}",
        files_in_dir
            .iter()
            .map(std::fs::DirEntry::path)
            .collect::<Vec<_>>()
    );

    // The path field must NOT be present in the output.
    assert!(
        json["results"]["path"].is_null(),
        "path should not appear in --base64 output"
    );

    let _ = std::fs::remove_dir_all(&work_dir);
}

#[test]
fn screenshot_base64_handles_longstring_data_url() {
    let server = MockRdpServer::new()
        .on("listTabs", load_fixture("list_tabs_response.json"))
        .on("getTarget", load_fixture("get_target_response.json"))
        .on_with_followup(
            "evaluateJSAsync",
            load_fixture("eval_immediate_response.json"),
            load_fixture("eval_result_screenshot_longstring.json"),
        )
        .on(
            "substring",
            load_fixture("substring_screenshot_response.json"),
        );

    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let work_dir = unique_temp_dir("screenshot_base64_longstring");

    let mut args = base_args(port);
    args.extend(["screenshot".to_owned(), "--base64".to_owned()]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .current_dir(&work_dir)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout must be valid JSON");

    assert_eq!(json["total"], 1);
    assert_eq!(json["results"]["width"], 1);
    assert_eq!(json["results"]["height"], 1);

    let b64_str = json["results"]["base64"]
        .as_str()
        .expect("results.base64 should be a string");
    let png_bytes = base64::engine::general_purpose::STANDARD
        .decode(b64_str)
        .expect("results.base64 must be valid base64");
    assert_eq!(&png_bytes[..4], b"\x89PNG", "decoded data should be a PNG");

    // No file should have been written into the working directory.
    let files_in_dir: Vec<_> = std::fs::read_dir(&work_dir)
        .expect("read work_dir")
        .filter_map(Result::ok)
        .collect();
    assert!(
        files_in_dir.is_empty(),
        "no file should be written when --base64 is used, found: {:?}",
        files_in_dir
            .iter()
            .map(std::fs::DirEntry::path)
            .collect::<Vec<_>>()
    );

    let _ = std::fs::remove_dir_all(&work_dir);
}

// ---------------------------------------------------------------------------
// Firefox 149+ two-step screenshot protocol fallback
// ---------------------------------------------------------------------------

#[test]
fn screenshot_falls_back_to_two_step_protocol_on_firefox_149() {
    // The 1x1 PNG data URL used throughout these tests.
    let png_data_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4//8/AAX+Av4N70a4AAAAAElFTkSuQmCC";

    // The screenshotContentActor in the fixture is:
    //   server1.conn0.child2/screenshotContentActor15
    // and browsingContextID is 16.

    let unrecognized_err = serde_json::json!({
        "from": "server1.conn0.child2/screenshotContentActor15",
        "error": "unrecognizedPacketType",
        "message": "Actor does not recognize the packet type 'captureScreenshot'"
    });

    let prepare_capture_response = serde_json::json!({
        "from": "server1.conn0.child2/screenshotContentActor15",
        "value": {
            "rect": null,
            "messages": [],
            "windowDpr": 1.0,
            "windowZoom": 1.0
        }
    });

    let get_root_response = serde_json::json!({
        "from": "root",
        "screenshotActor": "server1.conn0.screenshotActor7",
        "preferenceActor": "server1.conn0.preferenceActor1",
        "addonsActor": "server1.conn0.addonsActor2"
    });

    let capture_response = serde_json::json!({
        "from": "server1.conn0.screenshotActor7",
        "value": {
            "data": png_data_url,
            "filename": "screenshot.png",
            "messages": []
        }
    });

    let server = MockRdpServer::new()
        .on("listTabs", load_fixture("list_tabs_response.json"))
        .on("getTarget", load_fixture("get_target_response.json"))
        .on_with_followup(
            "evaluateJSAsync",
            load_fixture("eval_immediate_response.json"),
            load_fixture("eval_result_screenshot_null.json"),
        )
        // Legacy captureScreenshot and screenshot methods are unrecognized:
        .on("captureScreenshot", unrecognized_err.clone())
        .on("screenshot", unrecognized_err.clone())
        // "capture" is called twice: once by the legacy path (unrecognized),
        // then once by the two-step screenshotActor path (success).
        .on_sequence(
            "capture",
            vec![(unrecognized_err, vec![]), (capture_response, vec![])],
        )
        // Two-step protocol steps:
        .on("prepareCapture", prepare_capture_response)
        .on("getRoot", get_root_response);

    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let out_dir = unique_temp_dir("screenshot_two_step");
    let out_path = out_dir.join("twostep.png");

    let mut args = base_args(port);
    args.extend([
        "screenshot".to_owned(),
        "--output".to_owned(),
        out_path.to_string_lossy().into_owned(),
    ]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success via Firefox 149+ two-step screenshot, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    assert!(out_path.exists(), "PNG file should have been written");
    let png_bytes = std::fs::read(&out_path).expect("read png");
    assert_eq!(&png_bytes[..4], b"\x89PNG", "file should be a PNG");

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout must be valid JSON");
    assert_eq!(json["total"], 1);
    assert_eq!(json["results"]["width"], 1);
    assert_eq!(json["results"]["height"], 1);
    assert!(json["results"]["bytes"].as_u64().unwrap_or(0) > 0);

    let _ = std::fs::remove_dir_all(&out_dir);
}

// ---------------------------------------------------------------------------
// iter-53: graceful version-mismatch error when the screenshot actor module
// cannot be loaded (Firefox-internal "Unable to load actor module" failure).
//
// Regression: previously the raw Firefox stack trace bubbled out, telling
// users to "relaunch with --headless" — incorrect for this failure mode.  The
// fix surfaces a clean one-liner that names `doctor`.
// ---------------------------------------------------------------------------

#[test]
fn screenshot_module_load_failure_surfaces_clean_version_mismatch_message() {
    // Firefox's actual error shape for the missing screenshot ESM:
    //   error="unknownError" message="Error occurred while creating actor' …
    //   Error: Unable to load actor module 'devtools/server/actors/screenshot' …"
    let module_load_err = serde_json::json!({
        "from": "server1.conn0.child2/screenshotContentActor15",
        "error": "unknownError",
        "message": "Error occurred while creating actor' server1.conn0.child2/screenshotContentActor15: \
                    Error: Unable to load actor module 'devtools/server/actors/screenshot' \
                    ChromeUtils.importESModule: global option is required in DevTools distinct global"
    });

    let server = MockRdpServer::new()
        .on("listTabs", load_fixture("list_tabs_response.json"))
        .on("getTarget", load_fixture("get_target_response.json"))
        .on_with_followup(
            "evaluateJSAsync",
            load_fixture("eval_immediate_response.json"),
            load_fixture("eval_result_screenshot_null.json"),
        )
        // Legacy single-step capture fails with the module-load error.
        .on("captureScreenshot", module_load_err);

    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let mut args = base_args(port);
    args.push("screenshot".to_owned());

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        !output.status.success(),
        "expected non-zero exit when screenshot actor module fails to load"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("screenshot actor unavailable on Firefox"),
        "stderr should include the version-mismatch one-liner: {stderr}"
    );
    assert!(
        stderr.contains("ff-rdp doctor"),
        "stderr should reference `ff-rdp doctor`: {stderr}"
    );
    // Importantly: the misleading "headless" hint must NOT be emitted for
    // this failure mode — that hint is for genuinely-headless capture
    // failures, not for the missing-actor-module case.
    assert!(
        !stderr.contains("headless"),
        "stderr must not nudge users to --headless on a module-load failure: {stderr}"
    );
    // The raw Firefox stack trace must not be echoed — that's exactly the
    // noise we're filtering out.
    assert!(
        !stderr.contains("Unable to load actor module"),
        "stderr must not echo the raw Firefox stack: {stderr}"
    );
}

#[test]
fn screenshot_module_load_failure_in_two_step_protocol_surfaces_clean_message() {
    // Same failure, but raised by the Firefox-149+ two-step path's
    // `prepareCapture` step.  We force the legacy `captureScreenshot` to
    // return `unrecognizedPacketType` so the CLI advances to the two-step
    // path, then `prepareCapture` returns the module-load error.
    let unrecognized_err = serde_json::json!({
        "from": "server1.conn0.child2/screenshotContentActor15",
        "error": "unrecognizedPacketType",
        "message": "Actor does not recognize the packet type 'captureScreenshot'"
    });

    let module_load_err = serde_json::json!({
        "from": "server1.conn0.child2/screenshotContentActor15",
        "error": "unknownError",
        "message": "Error occurred while creating actor' …: Error: Unable to load actor module 'devtools/server/actors/screenshot'"
    });

    let server = MockRdpServer::new()
        .on("listTabs", load_fixture("list_tabs_response.json"))
        .on("getTarget", load_fixture("get_target_response.json"))
        .on_with_followup(
            "evaluateJSAsync",
            load_fixture("eval_immediate_response.json"),
            load_fixture("eval_result_screenshot_null.json"),
        )
        // ScreenshotContentActor::capture tries each name in
        // CAPTURE_METHODS = [captureScreenshot, screenshot, capture] in turn,
        // advancing on `unrecognizedPacketType`.  Wire each one to the same
        // unrecognized error so the CLI falls through to the two-step path.
        .on("captureScreenshot", unrecognized_err.clone())
        .on("screenshot", unrecognized_err.clone())
        .on("capture", unrecognized_err)
        .on("prepareCapture", module_load_err);

    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let mut args = base_args(port);
    args.push("screenshot".to_owned());

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        !output.status.success(),
        "expected non-zero exit when prepareCapture fails with module-load error"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("screenshot actor unavailable on Firefox"),
        "stderr should include the version-mismatch one-liner: {stderr}"
    );
    assert!(
        stderr.contains("ff-rdp doctor"),
        "stderr should reference `ff-rdp doctor`: {stderr}"
    );
}

// ---------------------------------------------------------------------------
// jq filter on success output
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// iter-43: --full-page / --viewport-height
// ---------------------------------------------------------------------------

#[test]
fn screenshot_full_page_and_viewport_height_conflict() {
    // Providing both flags is a user error — clap rejects it before connecting.
    let output = std::process::Command::new(ff_rdp_bin())
        .args(["screenshot", "--full-page", "--viewport-height", "1000"])
        .output()
        .expect("failed to spawn ff-rdp");

    assert!(
        !output.status.success(),
        "expected failure when both --full-page and --viewport-height are given"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("full-page")
            || stderr.contains("viewport-height")
            || stderr.contains("cannot be used with"),
        "expected conflict error, got: {stderr}"
    );
}

#[test]
fn screenshot_full_page_flag_accepted() {
    // With the mock server returning a fixed 1x1 PNG we can't verify the actual
    // rendered height, but we *can* verify that --full-page does not break the
    // normal flow and that the JS generator picks the scrollHeight path.
    let server = screenshot_server("eval_result_screenshot.json");
    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let out_dir = unique_temp_dir("screenshot_full_page");
    let out_path = out_dir.join("full.png");

    let mut args = base_args(port);
    args.extend([
        "screenshot".to_owned(),
        "--full-page".to_owned(),
        "--output".to_owned(),
        out_path.to_string_lossy().into_owned(),
    ]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(out_path.exists());

    let _ = std::fs::remove_dir_all(&out_dir);
}

#[test]
fn screenshot_viewport_height_flag_accepted() {
    let server = screenshot_server("eval_result_screenshot.json");
    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let out_dir = unique_temp_dir("screenshot_viewport_height");
    let out_path = out_dir.join("vh.png");

    let mut args = base_args(port);
    args.extend([
        "screenshot".to_owned(),
        "--viewport-height".to_owned(),
        "2500".to_owned(),
        "--output".to_owned(),
        out_path.to_string_lossy().into_owned(),
    ]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(out_path.exists(), "PNG file should have been written");

    let _ = std::fs::remove_dir_all(&out_dir);
}

#[test]
fn screenshot_with_jq_filter_extracts_path() {
    let server = screenshot_server("eval_result_screenshot.json");
    let port = server.port();
    let handle = std::thread::spawn(move || server.serve_one());

    let out_dir = unique_temp_dir("screenshot_jq");
    let out_path = out_dir.join("jq_test.png");

    let mut args = base_args(port);
    args.extend([
        "--jq".to_owned(),
        ".results.path".to_owned(),
        "screenshot".to_owned(),
        "--output".to_owned(),
        out_path.to_string_lossy().into_owned(),
    ]);

    let output = std::process::Command::new(ff_rdp_bin())
        .args(&args)
        .output()
        .expect("failed to spawn ff-rdp");

    handle.join().unwrap();

    assert!(
        output.status.success(),
        "expected success, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.trim().ends_with("jq_test.png\""),
        "jq filter should return the path string: {stdout}"
    );

    let _ = std::fs::remove_dir_all(&out_dir);
}