agent-first-http 0.12.0

Give your AI agent its own private browser — so it reads the real page, past logins and bot walls, without ever touching yours.
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
//! Display-takeover routing and capability tests. Most tests use a tiny fake
//! KasmVNC upstream so the proxy/token/path behavior stays deterministic; the
//! real KasmVNC launch smoke is ignored and run by `tests/test.sh takeover`.

#![cfg(feature = "host")]
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::disallowed_methods,
    clippy::disallowed_macros,
    clippy::err_expect,
    clippy::print_stdout,
    clippy::useless_conversion
)]

mod support;

use std::sync::Arc;
use std::time::Duration;

use agent_first_http::host::bootstrap::{
    BrowserChoice, DisplayMode, HealthPublic, HostArgs, ProfileChoice, Takeover,
    TakeoverProviderKind,
};
use agent_first_http::host::browser::BrowserHandle;
use agent_first_http::host::listener::{AppState, router_for_tests, test_state};
use agent_first_http::shared::error::ErrorCode;
use futures::{SinkExt, StreamExt};
use serde_json::json;
use tokio::net::TcpListener;

use support::takeover_host::{
    handoff_secret_of, mint_panel_url as takeover_handoff_url,
    spawn_fake_provider as spawn_fake_kasm, spawn_host as spawn_display_router,
    spawn_host_with_state as spawn_display_router_with_state,
};

/// A host with no display provider at all — the one shape the shared helper
/// deliberately cannot build, because every other test needs a provider.
async fn spawn_screencast_only_router(token: Option<&str>) -> String {
    support::ensure_rustls_provider();
    let state = test_state(token, HealthPublic::Off);
    let app = router_for_tests(state);
    let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind host");
    let addr = listener.local_addr().expect("addr");
    tokio::spawn(async move {
        let _ = axum::serve(listener, app).await;
    });
    tokio::time::sleep(Duration::from_millis(20)).await;
    format!("http://{addr}")
}

#[tokio::test]
async fn display_route_is_provider_neutral_and_unavailable_without_provider() {
    let base = spawn_screencast_only_router(None).await;
    let resp = reqwest::Client::new()
        .get(format!("{base}/takeover/panel"))
        .send()
        .await
        .expect("send");
    assert_eq!(resp.status(), reqwest::StatusCode::SERVICE_UNAVAILABLE);
}

#[tokio::test]
async fn takeover_handoff_is_unavailable_without_display_provider() {
    let base = spawn_screencast_only_router(Some("secret")).await;
    let resp = reqwest::Client::new()
        .post(format!("{base}/takeover/handoff"))
        .bearer_auth("secret")
        .json(&json!({}))
        .send()
        .await
        .expect("send");
    assert_eq!(resp.status(), reqwest::StatusCode::SERVICE_UNAVAILABLE);
    let body = resp.json::<serde_json::Value>().await.expect("json");
    agent_first_data::validate_protocol_event(&body, true).expect("strict AFDATA event");
    assert_eq!(body["error"]["code"], "backend_unsupported");
}

#[tokio::test]
async fn display_proxy_rewrites_paths_strips_auth_and_accepts_takeover_cookie() {
    let upstream_port = spawn_fake_kasm().await;
    let base = spawn_display_router(Some("secret"), upstream_port).await;
    let no_redirect = reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .expect("client");
    let takeover_url = takeover_handoff_url(&base, "secret").await;

    let landing = no_redirect
        .get(&takeover_url)
        .send()
        .await
        .expect("landing");
    assert_eq!(landing.status(), reqwest::StatusCode::OK);
    let cookie = landing
        .headers()
        .get(reqwest::header::SET_COOKIE)
        .and_then(|v| v.to_str().ok())
        .expect("set-cookie")
        .split(';')
        .next()
        .expect("cookie pair")
        .to_string();
    assert!(cookie.starts_with("afhttp_handoff="));
    let bootstrap = landing.text().await.expect("landing body");
    // The landing page seeds noVNC's `resize` and quality settings and drops
    // the one-time handoff query, having just set the takeover cookie.
    assert!(
        bootstrap.contains("&resize=scale"),
        "missing resize setting: {bootstrap}"
    );
    assert!(
        bootstrap.contains("&max_video_resolution_x="),
        "missing quality params: {bootstrap}"
    );
    assert!(
        !bootstrap.contains("handoff_secret=") && !bootstrap.contains("handoff="),
        "handoff capability leaked: {bootstrap}"
    );
    // noVNC roots its WebSocket URL at the origin, so `path` must name wherever
    // this panel is publicly served from — and that is the one thing the
    // listener cannot know, because a proxy framing the panel elsewhere
    // forwards nothing that says so. It is derived in the browser instead, and
    // an absolute panel path baked in here is exactly the regression that made
    // the canvas unreachable through `afui session serve`.
    assert!(
        bootstrap.contains("location.pathname"),
        "the websocket path must be derived from where the browser is: {bootstrap}"
    );
    assert!(
        !bootstrap.contains("path=takeover/panel/websockify"),
        "the websocket path must not be hardcoded to this listener's own prefix: {bootstrap}"
    );

    let through_cookie = reqwest::Client::new()
        .get(format!("{base}/takeover/panel/echo?x=1"))
        .header(reqwest::header::COOKIE, cookie)
        .send()
        .await
        .expect("cookie auth")
        .json::<serde_json::Value>()
        .await
        .expect("json");
    assert_eq!(through_cookie["path_and_query"], "/echo?x=1");
    assert_eq!(through_cookie["saw_cookie"], false);
    assert_eq!(through_cookie["saw_authorization"], false);

    let handoff = handoff_secret_of(&takeover_url);
    let stripped_query = reqwest::Client::new()
        .get(format!(
            "{base}/takeover/panel/echo?handoff_secret={handoff}&x=2"
        ))
        .send()
        .await
        .expect("query auth")
        .json::<serde_json::Value>()
        .await
        .expect("json");
    assert_eq!(stripped_query["path_and_query"], "/echo?x=2");
}

/// A panel framed somewhere else is served, not corrected.
///
/// Once the browser has answered "here is where I am", the listener has no
/// opinion about it: a `path` naming a prefix that is not this listener's own
/// is passed to the display client unchanged, and the landing page is not
/// bootstrapped a second time. Bootstrapping again would loop, and rewriting
/// `path` would put the canvas back on a prefix only the direct delivery has.
#[tokio::test]
async fn a_panel_framed_under_a_foreign_prefix_keeps_the_prefix_the_browser_reported() {
    let upstream_port = spawn_fake_kasm().await;
    let base = spawn_display_router(Some("secret"), upstream_port).await;
    let handoff = handoff_secret_of(&takeover_handoff_url(&base, "secret").await);
    // What `afui session serve` produces: the browser is at `/s/<credential>/`,
    // so that is the prefix it reports, and the framing listener adds the
    // announced credential back on to every upstream request.
    let framed = "s%2F0123456789abcdef%2Fwebsockify";

    let landed = reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .expect("client")
        .get(format!(
            "{base}/takeover/panel/?handoff_secret={handoff}&path={framed}&resize=scale"
        ))
        .send()
        .await
        .expect("send");
    assert_eq!(
        landed.status(),
        reqwest::StatusCode::OK,
        "a settled landing page must be served, not bootstrapped again"
    );
    let seen = landed.json::<serde_json::Value>().await.expect("json");
    assert_eq!(
        seen["path_and_query"],
        format!("/?path={framed}&resize=scale"),
        "the client's own prefix must reach the display unchanged"
    );
}

/// Revocation, which the handoff map this replaced had no way to express: the
/// only way to end a live panel used to be shutting the whole host down. A
/// profile switch tore the browser out from under a panel someone still had
/// open, and every credential minted for it kept authorizing.
#[tokio::test]
async fn revoking_takeover_credentials_ends_a_panel_that_is_still_open() {
    let upstream_port = spawn_fake_kasm().await;
    let (base, state) = spawn_display_router_with_state(Some("secret"), upstream_port).await;
    let takeover_url = takeover_handoff_url(&base, "secret").await;
    let secret = handoff_secret_of(&takeover_url);
    let panel = format!("{base}/takeover/panel/echo?handoff_secret={secret}");

    let live = reqwest::Client::new()
        .get(&panel)
        .send()
        .await
        .expect("before revoke");
    assert_eq!(live.status(), reqwest::StatusCode::OK);
    let cookie = live
        .headers()
        .get(reqwest::header::SET_COOKIE)
        .and_then(|v| v.to_str().ok())
        .expect("set-cookie")
        .split(';')
        .next()
        .expect("cookie pair")
        .to_string();

    // What `ensure_profile` and host shutdown call.
    assert_eq!(state.revoke_takeover_handoffs(), 1);

    let by_query = reqwest::Client::new()
        .get(&panel)
        .send()
        .await
        .expect("after revoke");
    assert_eq!(by_query.status(), reqwest::StatusCode::UNAUTHORIZED);

    // The cookie the browser already holds is the same credential, so it dies
    // with it — otherwise the panel's own asset requests would outlive revoke.
    let by_cookie = reqwest::Client::new()
        .get(format!("{base}/takeover/panel/echo"))
        .header(reqwest::header::COOKIE, cookie)
        .send()
        .await
        .expect("after revoke, by cookie");
    assert_eq!(by_cookie.status(), reqwest::StatusCode::UNAUTHORIZED);

    // A credential minted after the switch works: revoke ends the live ones, it
    // does not disable the route.
    let reminted = takeover_handoff_url(&base, "secret").await;
    let again = reqwest::Client::new()
        .get(format!(
            "{base}/takeover/panel/echo?handoff_secret={}",
            handoff_secret_of(&reminted)
        ))
        .send()
        .await
        .expect("after remint");
    assert_eq!(again.status(), reqwest::StatusCode::OK);
}

/// A credential is only ever accepted by the host that minted it, and only in
/// its exact form. The map this replaced compared secrets with a hash lookup;
/// `UiAccessToken::authorize` compares them in constant time, and a wrong
/// secret of the right length must still be rejected.
#[tokio::test]
async fn a_near_miss_credential_is_rejected() {
    let upstream_port = spawn_fake_kasm().await;
    let base = spawn_display_router(Some("secret"), upstream_port).await;
    let secret = handoff_secret_of(&takeover_handoff_url(&base, "secret").await);

    // Flip the last character to something else in the same alphabet: same
    // length, same shape, one byte different.
    let mut near_miss = secret.clone();
    let last = near_miss.pop().expect("non-empty secret");
    near_miss.push(if last == '0' { '1' } else { '0' });
    assert_ne!(near_miss, secret);

    let resp = reqwest::Client::new()
        .get(format!(
            "{base}/takeover/panel/echo?handoff_secret={near_miss}"
        ))
        .send()
        .await
        .expect("send");
    assert_eq!(resp.status(), reqwest::StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn display_proxy_rejects_long_lived_token_query() {
    let upstream_port = spawn_fake_kasm().await;
    let base = spawn_display_router(Some("secret"), upstream_port).await;
    let resp = reqwest::Client::new()
        .get(format!("{base}/takeover/panel?token_secret=secret"))
        .send()
        .await
        .expect("send");
    assert_eq!(resp.status(), reqwest::StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn display_proxy_forwards_websocket_upgrades_behind_token() {
    let upstream_port = spawn_fake_kasm().await;
    let base = spawn_display_router(Some("secret"), upstream_port).await;
    let takeover_url = takeover_handoff_url(&base, "secret").await;
    let handoff = handoff_secret_of(&takeover_url);
    let ws_url = base.replacen("http://", "ws://", 1).to_string()
        + &format!("/takeover/panel/ws?handoff_secret={handoff}");

    let (mut socket, _resp) = tokio_tungstenite::connect_async(&ws_url)
        .await
        .expect("connect display ws");
    socket
        .send(tokio_tungstenite::tungstenite::Message::Text(
            "hello".into(),
        ))
        .await
        .expect("send");
    let msg = socket.next().await.expect("next").expect("message");
    assert_eq!(msg.into_text().expect("text"), "echo:hello");
}

#[test]
fn capabilities_advertise_display_takeover_by_backend_family() {
    let tmp = tempfile::tempdir().expect("tmp");

    let mut chromium = BrowserHandle::synthetic(tmp.path().join("chromium"));
    chromium.family = "chromium".to_string();
    let chromium_state =
        test_state(None, HealthPublic::Off).with_default_browser(Arc::new(chromium));
    assert!(
        agent_first_http::host::listener::capabilities::build(&chromium_state)
            .takeover
            .backend_capable
    );

    let mut camoufox = BrowserHandle::synthetic(tmp.path().join("camoufox"));
    camoufox.family = "camoufox".to_string();
    let camoufox_state =
        test_state(None, HealthPublic::Off).with_default_browser(Arc::new(camoufox));
    assert!(
        agent_first_http::host::listener::capabilities::build(&camoufox_state)
            .takeover
            .backend_capable
    );

    let mut lightpanda = BrowserHandle::synthetic(tmp.path().join("lightpanda"));
    lightpanda.family = "lightpanda".to_string();
    let lightpanda_state =
        test_state(None, HealthPublic::Off).with_default_browser(Arc::new(lightpanda));
    assert!(
        !agent_first_http::host::listener::capabilities::build(&lightpanda_state)
            .takeover
            .backend_capable
    );
}

#[test]
fn capabilities_include_provider_neutral_display_fields() {
    let state = test_state(None, HealthPublic::Off).with_takeover_for_tests(5900);
    let caps = agent_first_http::host::listener::capabilities::build(&state);
    assert!(caps.takeover.supported);
    assert_eq!(caps.takeover.panel_url.as_deref(), Some("/takeover/panel"));
    assert_eq!(caps.takeover.provider.as_deref(), Some("kasmvnc"));
}

#[tokio::test]
async fn lightpanda_rejects_kasmvnc_takeover_before_launch() {
    let args = HostArgs {
        listen: "tcp:127.0.0.1:0".into(),
        profile: ProfileChoice::Ephemeral,
        display: DisplayMode::Headful,
        takeover: Takeover::On {
            provider: TakeoverProviderKind::KasmVnc,
        },
        display_quality: 100,
        browser: BrowserChoice::Lightpanda,
        browser_bin: None,
        token: None,
        takeover_enabled: true,
        health_enabled: true,
        health_public: HealthPublic::Off,
        engine_envs: Vec::new(),
        browser_args: Vec::new(),
        proxy: None,
        recent_requests_cap: 0,
    };
    let err = AppState::launch(&args).await.err().expect("expected error");
    assert_eq!(err.error_code, ErrorCode::BackendUnsupported);
}

#[tokio::test]
#[ignore]
async fn kasmvnc_process_launches_when_binary_available() {
    support::ensure_rustls_provider();
    let Some(bin) = support::env::discover_kasmvnc() else {
        println!("(skipping: no KasmVNC Xvnc binary; set AFHTTP_TEST_KASMVNC_BIN)");
        return;
    };
    // SAFETY: this ignored hardware integration test is run in isolation, so
    // no other thread reads or mutates the process environment concurrently.
    unsafe { std::env::set_var("AFHTTP_KASMVNC_BIN", bin) };
    let handle = agent_first_http::host::takeover::launch_kasmvnc_provider()
        .await
        .expect("launch kasmvnc");
    assert!(handle.display.starts_with(':'));
    let resp = reqwest::Client::new()
        .get(format!("http://127.0.0.1:{}/", handle.web_port))
        .send()
        .await
        .expect("kasm web request");
    assert!(resp.status().is_success());
}

/// The `--disable-gpu` regression, pinned where it actually reproduces.
///
/// The host used to pass `--disable-gpu` unconditionally, which switched the
/// GPU process off and took WebGL with it: a takeover browser reported
/// `webgl: false`, `webgl2: false` and zero extensions. No real browser looks
/// like that, and anti-bot scorers read it as automation — the takeover host
/// was advertising itself as a bot on the one path built to get past walls.
///
/// This has to run headful on a real X display. Under `--headless=new`,
/// Chromium serves WebGL whether or not `--disable-gpu` is passed, so the same
/// assertion in a headless test passes with the fix reverted and guards
/// nothing. Ignored and driven by `tests/test.sh takeover`, alongside the other
/// tests that need a live KasmVNC display.
#[tokio::test]
#[ignore]
async fn takeover_browsers_expose_webgl_on_a_real_display() {
    use agent_first_http::sdk::Client;
    use agent_first_http::sdk::fetch::{RenderMode, Wait};
    use agent_first_http::shared::artifacts::Artifact;

    support::ensure_rustls_provider();
    let Some(kasm) = support::env::discover_kasmvnc() else {
        panic!("KasmVNC is required for the takeover gate; set AFHTTP_TEST_KASMVNC_BIN");
    };
    // SAFETY: the takeover gate runs these ignored display tests with
    // --test-threads=1, so no other thread touches the environment here.
    unsafe { std::env::set_var("AFHTTP_KASMVNC_BIN", kasm) };
    let provider = agent_first_http::host::takeover::launch_kasmvnc_provider()
        .await
        .expect("launch kasmvnc");

    // Writes the verdict into the DOM: evaluate_after_wait runs JS but returns
    // nothing to the caller, so the page has to carry the answer out.
    const PROBE: &str = r#"(() => {
      const one = document.createElement('canvas').getContext('webgl');
      const two = document.createElement('canvas').getContext('webgl2');
      const out = document.createElement('div');
      out.id = 'afhttp-webgl-probe';
      out.textContent = JSON.stringify({
        webgl: !!one,
        webgl2: !!two,
        extensions: one ? one.getSupportedExtensions().length : 0,
      });
      document.body.appendChild(out);
    })()"#;

    let fixture = support::fixture_server::spawn().await;

    for (choice, label, bin) in [
        (
            BrowserChoice::Brave,
            "brave",
            support::env::discover_brave(),
        ),
        (
            BrowserChoice::Chrome,
            "chrome",
            support::env::discover_chrome(),
        ),
    ] {
        let bin = bin.unwrap_or_else(|| {
            panic!("{label} is a takeover backend and must be present in the test image")
        });
        let args = HostArgs {
            listen: "tcp:127.0.0.1:0".into(),
            profile: ProfileChoice::Ephemeral,
            display: DisplayMode::Headful,
            takeover: Takeover::On {
                provider: TakeoverProviderKind::KasmVnc,
            },
            display_quality: 100,
            browser: choice,
            browser_bin: Some(bin),
            token: None,
            takeover_enabled: true,
            health_enabled: true,
            health_public: HealthPublic::Off,
            engine_envs: vec![("DISPLAY".to_string(), provider.display.clone())],
            browser_args: Vec::new(),
            proxy: None,
            recent_requests_cap: 0,
        };
        let handle = agent_first_http::host::browser::launch(&args)
            .await
            .unwrap_or_else(|e| panic!("{label} headful launch: {e:?}"));

        let state = test_state(None, HealthPublic::Off).with_default_browser(Arc::new(handle));
        let app = router_for_tests(state);
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
        let addr = listener.local_addr().expect("local_addr");
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });
        tokio::time::sleep(Duration::from_millis(50)).await;

        let tmp = tempfile::tempdir().expect("tmpdir");
        let client = Client::connect(&format!("ws://{addr}")).expect("client");
        let result = client
            .fetch(format!("{}/identity.html", fixture.base_url()))
            .render(RenderMode::Always)
            .wait(Wait::Load)
            .timeout(Duration::from_secs(30))
            .evaluate_after_wait(PROBE)
            .want([Artifact::RenderedHtml])
            .out_dir(tmp.path().to_path_buf())
            .send()
            .await
            .unwrap_or_else(|e| panic!("{label} fetch: {e:?}"));

        let rendered = std::fs::read_to_string(
            result
                .rendered_html_file
                .as_ref()
                .expect("rendered_html_file"),
        )
        .expect("read rendered html");

        assert!(
            rendered.contains("\"webgl\":true") && rendered.contains("\"webgl2\":true"),
            "{label} lost WebGL on a real display — that is the --disable-gpu regression: {rendered}"
        );
        assert!(
            !rendered.contains("\"extensions\":0"),
            "{label} exposed a WebGL context with no extensions: {rendered}"
        );
    }
}

/// The takeover download regression, pinned where it actually reproduces.
///
/// A download started on the takeover display used to stop on a native GTK
/// "wants to save" dialog aimed at `~/Downloads`. Nothing reached
/// `download_dir`, and the dialog blocked the display until a human clicked it.
///
/// The host did issue `Browser.setDownloadBehavior` at launch, which looked
/// like it covered this — but on a connection it closed immediately, and
/// Chromium scopes that override to the client that set it. Nothing survived to
/// the moment anything downloaded. The profile prefs written by
/// `preseed_chromium_profile` are what actually carry it now.
///
/// It must run headful on a real display: `--headless=new` never shows a save
/// dialog, so the same assertion passes headless with the fix reverted.
///
/// It must also NOT go through `Client::fetch`. That pipeline sets its own
/// `Browser.setDownloadBehavior` on its own live connection, so a fetch-driven
/// download succeeds even with this bug fully present. Driving a bare CDP
/// session — like the human whose click is not a CDP client at all — is the
/// only way this fails when regressed.
#[tokio::test]
#[ignore]
async fn takeover_download_lands_in_profile_without_a_save_dialog() {
    use agent_first_http::sdk::cdp::ws_client::Connection;

    support::ensure_rustls_provider();
    let Some(kasm) = support::env::discover_kasmvnc() else {
        panic!("KasmVNC is required for the takeover gate; set AFHTTP_TEST_KASMVNC_BIN");
    };
    // SAFETY: the takeover gate runs these ignored display tests with
    // --test-threads=1, so no other thread touches the environment here.
    unsafe { std::env::set_var("AFHTTP_KASMVNC_BIN", kasm) };
    let provider = agent_first_http::host::takeover::launch_kasmvnc_provider()
        .await
        .expect("launch kasmvnc");

    let fixture = support::fixture_server::spawn().await;
    let bin = support::env::discover_brave()
        .expect("brave is a takeover backend and must be present in the test image");

    let args = HostArgs {
        listen: "tcp:127.0.0.1:0".into(),
        profile: ProfileChoice::Ephemeral,
        display: DisplayMode::Headful,
        takeover: Takeover::On {
            provider: TakeoverProviderKind::KasmVnc,
        },
        display_quality: 100,
        browser: BrowserChoice::Brave,
        browser_bin: Some(bin),
        token: None,
        takeover_enabled: true,
        health_enabled: true,
        health_public: HealthPublic::Off,
        engine_envs: vec![("DISPLAY".to_string(), provider.display.clone())],
        browser_args: Vec::new(),
        proxy: None,
        recent_requests_cap: 0,
    };
    let handle = agent_first_http::host::browser::launch(&args)
        .await
        .unwrap_or_else(|e| panic!("brave headful launch: {e:?}"));
    let download_dir = handle.download_dir.clone();

    let conn = Connection::connect(&handle.ws_url, None)
        .await
        .expect("connect to browser");
    let targets = conn
        .send("Target.getTargets", &serde_json::json!({}), None)
        .await
        .expect("Target.getTargets");
    let target_id = targets["targetInfos"]
        .as_array()
        .and_then(|list| {
            list.iter()
                .find(|t| t["type"] == "page")
                .and_then(|t| t["targetId"].as_str())
        })
        .expect("a page target")
        .to_string();
    let attached = conn
        .send(
            "Target.attachToTarget",
            &serde_json::json!({"targetId": target_id, "flatten": true}),
            None,
        )
        .await
        .expect("Target.attachToTarget");
    let session_id = attached["sessionId"]
        .as_str()
        .expect("sessionId")
        .to_string();

    // Navigating to an attachment is what a human clicking a download link
    // does. The navigation itself aborts with ERR_ABORTED by design — the
    // download, not the page load, is the outcome under test.
    let _ = conn
        .send(
            "Page.navigate",
            &serde_json::json!({"url": format!("{}/download.bin", fixture.base_url())}),
            Some(&session_id),
        )
        .await;

    let deadline = std::time::Instant::now() + Duration::from_secs(30);
    let mut landed = Vec::new();
    while std::time::Instant::now() < deadline {
        landed = std::fs::read_dir(&download_dir)
            .map(|rd| {
                rd.filter_map(Result::ok)
                    .map(|e| e.file_name().to_string_lossy().to_string())
                    // Chromium writes .crdownload while a transfer is in flight.
                    .filter(|n| !n.ends_with(".crdownload"))
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        if !landed.is_empty() {
            break;
        }
        tokio::time::sleep(Duration::from_millis(250)).await;
    }

    assert!(
        !landed.is_empty(),
        "takeover download never reached {}: a save dialog is blocking the display, \
         which is the regression this pins",
        download_dir.display()
    );
}