Skip to content

The headless browser for AI agents and web scraping

228 KB
Raw Blame
use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::net::SocketAddr;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;

use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use futures_util::{SinkExt, StreamExt};
use serde_json::json;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::sync::Notify;
use tokio_tungstenite::tungstenite::Message;
use tracing::{error, info, warn};

use crate::dispatch::{self, CdpContext};

// PR #36 comment 4341743194: the deferral queue in `process_with_interception`
// must be bounded so a stalled navigation cannot OOM the process. When the cap
// is reached we return an explicit error response rather than silently dropping.
const MAX_DEFERRED_MESSAGES: usize = 256;

struct PendingRuntimeReply {
    id: u64,
    session_id: Option<String>,
    reply_tx: mpsc::UnboundedSender<String>,
    evaluation: crate::domains::runtime::DeferredEvaluation,
}

// The WS-stream forwarding channel must also be bounded: if the LocalSet
// (CDP processor + nav tasks) stalls, the accept thread keeps pushing
// `std::net::TcpStream`s into the queue. An unbounded channel would let
// that queue grow without limit and OOM the process. With a bounded
// capacity, when the LocalSet is saturated the accept thread closes the
// new connection on the spot instead of buffering it — the kernel TCP
// backlog still absorbs short-term spikes, but a long-term stall now
// fails loudly at accept time rather than silently piling up FDs.
const MAX_PENDING_WS_HANDOFFS: usize = 128;

// Cap on *live* CDP connections, each of which costs one OS thread and its own
// V8 isolates. `MAX_PENDING_WS_HANDOFFS` above bounds only the handoff queue —
// connections that have already been handed off are unbounded without this.
//
// 128 matches the handoff bound and is well above normal client fan-out
// (Playwright/Puppeteer use one connection per browser). This also bounds
// per-connection native stack reservations and V8 isolates. Stack address
// space is reserved rather than committed. Override with --max-connections.
pub const DEFAULT_MAX_CONNECTIONS: usize = 128;

// Match the CLI's native stack so supported deep parser trees cannot abort
// every connection during recursive layout, paint, or serialization.
const CDP_CONN_STACK_BYTES: usize = 512 * 1024 * 1024;

// How long shutdown waits for connection threads to finish before persisting
// the cookie jar. Well under the 10s `docker stop` gives us before SIGKILL.
const SHUTDOWN_DRAIN_MS: u64 = 3_000;

// Sent to a client that arrives while the server is at `max_connections`, in
// place of dropping the socket unexplained. The client sees a refusal it can
// retry rather than a bare connection reset.
const CONNECTION_LIMIT_RESPONSE: &str = "HTTP/1.1 503 Service Unavailable\r\n\
    Content-Length: 0\r\nConnection: close\r\n\
    X-Obscura-Reason: max-connections\r\n\r\n";

fn control_token_from_env() -> anyhow::Result<Option<String>> {
    let token = std::env::var("OBSCURA_CDP_TOKEN")
        .ok()
        .filter(|value| !value.is_empty());
    if token.as_ref().is_some_and(|value| value.len() < 32) {
        anyhow::bail!("OBSCURA_CDP_TOKEN must be at least 32 bytes");
    }
    Ok(token)
}

fn constant_time_eq(left: &str, right: &str) -> bool {
    if left.len() != right.len() {
        return false;
    }
    left.bytes()
        .zip(right.bytes())
        .fold(0u8, |difference, (left, right)| difference | (left ^ right))
        == 0
}

fn header_value<'a>(head: &'a str, name: &str) -> Option<&'a str> {
    head.split("\r\n")
        .skip(1)
        .take_while(|line| !line.is_empty())
        .filter_map(|line| line.split_once(':'))
        .find(|(header, _)| header.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.trim())
}

fn bearer_authorized(head: &str, expected: Option<&str>) -> bool {
    match expected {
        None => true,
        Some(expected) => header_value(head, "authorization")
            .and_then(|value| value.strip_prefix("Bearer "))
            .is_some_and(|provided| constant_time_eq(provided, expected)),
    }
}

fn host_matches_bind(
    host_header: &str,
    bind_ip: std::net::IpAddr,
    port: u16,
    forwarded: Option<(std::net::IpAddr, u16)>,
) -> bool {
    let Ok(url) = url::Url::parse(&format!("http://{host_header}/")) else {
        return false;
    };
    fn host_matches_ip(url: &url::Url, bind_ip: std::net::IpAddr) -> bool {
        if bind_ip.is_unspecified() {
            return true;
        }
        match (url.host(), bind_ip) {
            (Some(url::Host::Ipv4(address)), std::net::IpAddr::V4(bind)) => {
                address == bind || (bind.is_loopback() && address.is_loopback())
            }
            (Some(url::Host::Ipv6(address)), std::net::IpAddr::V6(bind)) => {
                address == bind || (bind.is_loopback() && address.is_loopback())
            }
            (Some(url::Host::Ipv4(address)), std::net::IpAddr::V6(bind)) => {
                bind.is_loopback() && address.is_loopback()
            }
            (Some(url::Host::Ipv6(address)), std::net::IpAddr::V4(bind)) => {
                bind.is_loopback() && address.is_loopback()
            }
            (Some(url::Host::Domain(domain)), _) => {
                bind_ip.is_loopback() && domain.eq_ignore_ascii_case("localhost")
            }
            (None, _) => false,
        }
    }
    (url.port_or_known_default() == Some(port) && host_matches_ip(&url, bind_ip))
        || forwarded.is_some_and(|(forwarded_ip, forwarded_port)| {
            url.port_or_known_default() == Some(forwarded_port)
                && host_matches_ip(&url, forwarded_ip)
        })
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum ControlRefusal {
    BrowserOrigin(String),
    ForeignHost,
    Unauthorized,
    OversizedHead,
}

/// Origin allowlist for CDP callers, read from `OBSCURA_CDP_ALLOWED_ORIGINS`
/// (comma-separated, `*` allows every origin). Unset accepts only the
/// endpoint's own HTTP origin.
fn allowed_origins_env() -> Option<String> {
    std::env::var("OBSCURA_CDP_ALLOWED_ORIGINS")
        .ok()
        .filter(|s| !s.trim().is_empty())
}

// The request authority can name the public listener instead of its worker.
// Host validation and authentication still apply after the origin check.
fn origin_accepted(
    origin: &str,
    request_host: Option<&str>,
    allowed_origins: Option<&str>,
) -> bool {
    let origin = origin.trim();
    if let Some(list) = allowed_origins {
        if list
            .split(',')
            .map(str::trim)
            .any(|entry| entry == "*" || entry.eq_ignore_ascii_case(origin))
        {
            return true;
        }
    }
    let Ok(parsed) = url::Url::parse(origin) else {
        return false;
    };
    if parsed.scheme() != "http"
        || !origin.contains("://")
        || !parsed.username().is_empty()
        || parsed.password().is_some()
        || parsed.path() != "/"
        || parsed.query().is_some()
        || parsed.fragment().is_some()
    {
        return false;
    }
    let Some(request_host) = request_host else {
        return false;
    };
    let Ok(server) = url::Url::parse(&format!("http://{request_host}/")) else {
        return false;
    };
    parsed.origin() == server.origin()
}

fn control_refusal(
    head: &str,
    bind_ip: std::net::IpAddr,
    port: u16,
    forwarded: Option<(std::net::IpAddr, u16)>,
    auth_token: Option<&str>,
    allowed_origins: Option<&str>,
) -> Option<ControlRefusal> {
    if let Some(origin) = header_value(head, "origin") {
        if !origin_accepted(origin, header_value(head, "host"), allowed_origins) {
            return Some(ControlRefusal::BrowserOrigin(origin.to_owned()));
        }
    }
    if !header_value(head, "host")
        .is_some_and(|host| host_matches_bind(host, bind_ip, port, forwarded))
    {
        return Some(ControlRefusal::ForeignHost);
    }
    if !bearer_authorized(head, auth_token) {
        return Some(ControlRefusal::Unauthorized);
    }
    None
}

fn refuse_control_connection(mut stream: std::net::TcpStream, refusal: ControlRefusal) {
    use std::io::Write;
    let (status, reason) = match &refusal {
        ControlRefusal::Unauthorized => ("401 Unauthorized", "authentication required"),
        ControlRefusal::OversizedHead => (
            "431 Request Header Fields Too Large",
            "request head too large",
        ),
        ControlRefusal::BrowserOrigin(_) | ControlRefusal::ForeignHost => {
            ("403 Forbidden", "request refused")
        }
    };
    let body = match &refusal {
        ControlRefusal::BrowserOrigin(origin) => json!({
            "error": reason,
            "detail": format!(
                "Rejected a CDP control request from the '{origin}' origin. \
                 Set OBSCURA_CDP_ALLOWED_ORIGINS={origin} to allow connections from this \
                 origin or OBSCURA_CDP_ALLOWED_ORIGINS=* to allow all origins."
            ),
        })
        .to_string(),
        _ => format!("{{\"error\":\"{reason}\"}}"),
    };
    let response = format!(
        "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    let _ = stream.write_all(response.as_bytes());
    let _ = stream.flush();
}
use crate::types::CdpRequest;

struct CdpMessage {
    text: String,
    reply_tx: mpsc::UnboundedSender<String>,
}

enum ServerMessage {
    Cdp(CdpMessage),
    NewConnection {
        reply_tx: mpsc::UnboundedSender<String>,
    },
}

pub async fn start(port: u16) -> anyhow::Result<()> {
    start_with_options(port, None, false).await
}

pub async fn start_with_options(
    port: u16,
    proxy: Option<String>,
    stealth: bool,
) -> anyhow::Result<()> {
    start_with_full_options(port, proxy, stealth, None, None).await
}

pub async fn start_with_full_options(
    port: u16,
    proxy: Option<String>,
    stealth: bool,
    user_agent: Option<String>,
    storage_dir: Option<std::path::PathBuf>,
) -> anyhow::Result<()> {
    start_with_host(port, "127.0.0.1", proxy, stealth, user_agent, storage_dir).await
}

pub async fn start_with_host(
    port: u16,
    host: &str,
    proxy: Option<String>,
    stealth: bool,
    user_agent: Option<String>,
    storage_dir: Option<std::path::PathBuf>,
) -> anyhow::Result<()> {
    start_with_host_and_security(port, host, proxy, stealth, user_agent, false, storage_dir).await
}

pub async fn start_with_host_and_security(
    port: u16,
    host: &str,
    proxy: Option<String>,
    stealth: bool,
    user_agent: Option<String>,
    allow_file_access: bool,
    storage_dir: Option<std::path::PathBuf>,
) -> anyhow::Result<()> {
    start_with_full_serve_options(
        port, host, proxy, stealth, user_agent, allow_file_access, storage_dir, false,
    )
    .await
}

pub async fn start_with_host_security_and_storage(
    port: u16,
    host: &str,
    proxy: Option<String>,
    stealth: bool,
    user_agent: Option<String>,
    allow_file_access: bool,
    storage_dir: Option<std::path::PathBuf>,
) -> anyhow::Result<()> {
    start_with_full_serve_options(
        port, host, proxy, stealth, user_agent, allow_file_access, storage_dir, false,
    )
    .await
}

/// Full serve entry point that also accepts `allow_private_network` (issue
/// #33). Older entry points default it to `false` so existing callers and
/// public API consumers are unaffected.
pub async fn start_with_full_serve_options(
    port: u16,
    host: &str,
    proxy: Option<String>,
    stealth: bool,
    user_agent: Option<String>,
    allow_file_access: bool,
    storage_dir: Option<std::path::PathBuf>,
    allow_private_network: bool,
) -> anyhow::Result<()> {
    start_with_serve_options_and_limit(
        port,
        host,
        proxy,
        stealth,
        user_agent,
        allow_file_access,
        storage_dir,
        allow_private_network,
        DEFAULT_MAX_CONNECTIONS,
    )
    .await
}

/// As `start_with_full_serve_options`, with an explicit cap on live CDP
/// connections. Each connection owns an OS thread and its pages' V8 isolates,
/// so this is what bounds the server's thread and memory footprint.
#[allow(clippy::too_many_arguments)]
pub async fn start_with_serve_options_and_limit(
    port: u16,
    host: &str,
    proxy: Option<String>,
    stealth: bool,
    user_agent: Option<String>,
    allow_file_access: bool,
    storage_dir: Option<std::path::PathBuf>,
    allow_private_network: bool,
    max_connections: usize,
) -> anyhow::Result<()> {
    start_with_serve_options_limit_and_ready_file(
        port,
        host,
        proxy,
        stealth,
        user_agent,
        allow_file_access,
        storage_dir,
        allow_private_network,
        max_connections,
        None,
    )
    .await
}

/// Full serve entry point with optional atomic startup notification.
#[allow(clippy::too_many_arguments)]
pub async fn start_with_serve_options_limit_and_ready_file(
    port: u16,
    host: &str,
    proxy: Option<String>,
    stealth: bool,
    user_agent: Option<String>,
    allow_file_access: bool,
    storage_dir: Option<std::path::PathBuf>,
    allow_private_network: bool,
    max_connections: usize,
    ready_file: Option<&Path>,
) -> anyhow::Result<()> {
    let ip: std::net::IpAddr = host
        .parse()
        .map_err(|e| anyhow::anyhow!("invalid --host '{}': {}", host, e))?;
    let addr = SocketAddr::new(ip, port);
    let auth_token = control_token_from_env()?;
    let forwarded_host = std::env::var("OBSCURA_CDP_FORWARDED_HOST").ok();
    let forwarded_port = std::env::var("OBSCURA_CDP_FORWARDED_PORT").ok();
    let forwarded = match (forwarded_host, forwarded_port) {
        (None, None) => None,
        (Some(host), Some(port)) => Some((
            host.parse::<std::net::IpAddr>().map_err(|error| {
                anyhow::anyhow!("invalid OBSCURA_CDP_FORWARDED_HOST '{}': {}", host, error)
            })?,
            port.parse::<u16>().map_err(|error| {
                anyhow::anyhow!("invalid OBSCURA_CDP_FORWARDED_PORT '{}': {}", port, error)
            })?,
        )),
        _ => anyhow::bail!(
            "OBSCURA_CDP_FORWARDED_HOST and OBSCURA_CDP_FORWARDED_PORT must be set together"
        ),
    };
    if forwarded.is_some() && !ip.is_loopback() {
        anyhow::bail!("forwarded CDP authority is only valid for loopback workers");
    }
    let publicly_reachable = !ip.is_loopback()
        || forwarded.is_some_and(|(forwarded_ip, _)| !forwarded_ip.is_loopback());
    if publicly_reachable && auth_token.is_none() {
        anyhow::bail!(
            "refusing to expose CDP without authentication; set OBSCURA_CDP_TOKEN to at least 32 bytes"
        );
    }

    // Issue #62: the HTTP control plane (/json/version, /json) must remain
    // reachable even while V8 JS evaluation blocks the tokio LocalSet thread.
    //
    // We use a dedicated OS thread with a blocking std::net::TcpListener so
    // the kernel's accept backlog is always drained promptly. HTTP endpoints
    // are served directly via blocking I/O; WebSocket connections are
    // forwarded to the existing LocalSet for CDP processing.
    let std_listener = std::net::TcpListener::bind(addr)
        .map_err(|e| anyhow::anyhow!("bind {}:{}: {}", host, port, e))?;
    // Non-blocking so the accept thread can alternate between draining the
    // backlog and re-polling parked connections (see the accept thread below).
    std_listener
        .set_nonblocking(true)
        .map_err(|e| anyhow::anyhow!("set_nonblocking: {}", e))?;
    let bound_addr = std_listener
        .local_addr()
        .map_err(|e| anyhow::anyhow!("read bound address: {}", e))?;
    let port = bound_addr.port();

    info!("Obscura CDP server listening on ws://{}", bound_addr);
    info!(
        "DevTools endpoint: ws://{}:{}/devtools/browser",
        host, port
    );
    if allow_file_access {
        info!("file:// navigation enabled (--allow-file-access). Do not expose this port to untrusted networks.");
    }
    if auth_token.is_some() {
        info!("CDP bearer authentication enabled");
    }

    // Initialize V8 before announcing readiness. The accept thread starts
    // afterwards, so a publication error can still terminate startup cleanly.
    drop(obscura_js::runtime::ObscuraJsRuntime::new());
    cap_malloc_arenas();
    if let Some(path) = ready_file {
        publish_ready_file(path, bound_addr)?;
    }

    let (ws_tx, mut ws_rx) = mpsc::channel::<std::net::TcpStream>(MAX_PENDING_WS_HANDOFFS);

    // Ctrl-C / graceful shutdown coordination.
    let shutdown_flag = Arc::new(AtomicBool::new(false));
    let shutdown_notify = Arc::new(Notify::new());

    // Dedicated accept thread: drains the kernel backlog immediately and
    // handles HTTP endpoints (/json/version, /json, /json/protocol) with
    // blocking I/O so they never contend with the LocalSet's V8 work.
    //
    // A connection that is accepted but never sends its request head
    // (speculative browser preconnects, port probes, slow-loris clients)
    // must not be able to park this single thread in a blocking read: every
    // later connection, including CDP clients like Playwright's
    // connectOverCDP, would then sit in the kernel backlog unanswered until
    // its own connect timeout (issue #715). The thread therefore never
    // blocks on a *stream* — undecided connections are parked and re-polled
    // every ACCEPT_POLL_INTERVAL, and dropped once they outlive
    // SILENT_CONNECTION_TTL without sending a request head.
    //
    // While nothing is parked the thread blocks in accept() itself, the
    // pre-#715 fast path: zero added latency for the next connection and no
    // CPU while idle. Blocking on the listener is safe — it waits for the
    // kernel, not for client bytes. While something is parked, the listener
    // is drained without blocking at least once per 1 ms poll round, far
    // above any real connect rate, so the kernel backlog cannot overflow
    // under a connection burst.
    let accept_flag = shutdown_flag.clone();
    let accept_auth_token = auth_token.clone();
    let accept_allowed_origins = allowed_origins_env();
    std::thread::Builder::new()
        .name("obscura-cdp-accept".into())
        .spawn(move || {
            let mut pending: Vec<(std::net::TcpStream, std::time::Instant)> = Vec::new();
            while !accept_flag.load(Ordering::Relaxed) {
                if pending.is_empty() {
                    // Fast path: nothing parked, block until a connection
                    // arrives, then classify it in the sweep below.
                    let _ = std_listener.set_nonblocking(false);
                    match std_listener.accept() {
                        Ok((stream, _)) => {
                            let _ = stream.set_nonblocking(true);
                            pending.push((stream, std::time::Instant::now()));
                        }
                        Err(e) => {
                            error!("Accept error: {}", e);
                            // A persistent error (e.g. EMFILE) must not turn
                            // into a log flood while the thread idles.
                            std::thread::sleep(ACCEPT_POLL_INTERVAL);
                        }
                    }
                    let _ = std_listener.set_nonblocking(true);
                } else {
                    // Drain everything the kernel has already queued for us.
                    loop {
                        match std_listener.accept() {
                            Ok((stream, _)) => {
                                let _ = stream.set_nonblocking(true);
                                if pending.len() < MAX_SILENT_PENDING {
                                    pending.push((stream, std::time::Instant::now()));
                                } else {
                                    warn!(
                                        "dropping connection: {} connections parked without a request head",
                                        MAX_SILENT_PENDING
                                    );
                                }
                            }
                            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
                            Err(e) => {
                                error!("Accept error: {}", e);
                                break;
                            }
                        }
                    }
                }
                // Give every parked connection a chance to speak; keep the
                // ones still silent and inside the TTL, dispatch the ones
                // with a request head. Dropping a stream closes its socket.
                for (stream, since) in std::mem::take(&mut pending) {
                    if since.elapsed() >= SILENT_CONNECTION_TTL {
                        continue;
                    }
                    match peek_request_head(&stream) {
                        PeekStatus::NotReady => pending.push((stream, since)),
                        PeekStatus::Closed => {}
                        PeekStatus::Oversized => {
                            refuse_control_connection(stream, ControlRefusal::OversizedHead);
                        }
                        PeekStatus::Head(head) => {
                            if let Err(e) = accept_dispatch(
                                stream,
                                ip,
                                port,
                                forwarded,
                                accept_auth_token.as_deref(),
                                accept_allowed_origins.as_deref(),
                                &ws_tx,
                                &head,
                            ) {
                                if !format!("{}", e).contains("close") {
                                    error!("Accept dispatch error: {}", e);
                                }
                            }
                        }
                    }
                }
                if !pending.is_empty() {
                    std::thread::sleep(ACCEPT_POLL_INTERVAL);
                }
            }
        })?;

    // This context is a configuration and persistence template. Each WebSocket
    // gets an isolated copy with its own cookie jar and HTTP client (#449),
    // while the thread-per-connection layout from #430 still confines that
    // connection's V8 isolates to one OS thread.
    let mut bctx = obscura_browser::BrowserContext::with_storage_and_network(
        "default".to_string(),
        proxy,
        stealth,
        user_agent,
        storage_dir,
        allow_private_network,
    );
    bctx.set_allow_file_access(allow_file_access);
    let shared_ctx = Arc::new(bctx);
    // Persistence is deliberately separate from the connection template.
    // Cookie and localStorage deltas are merged here, but new connections clone the
    // immutable startup snapshot and can never inherit another live client's
    // session state.
    let mut persistence = shared_ctx.connection_copy("persistence".to_string());
    persistence.storage_dir = shared_ctx.storage_dir.clone();
    let persistence_ctx = Arc::new(persistence);
    let persistence_lock = Arc::new(std::sync::Mutex::new(()));

    // One graceful-shutdown watcher for the whole server. It flips the accept
    // flag (stopping the accept thread) and wakes every connection processor via
    // `notify_waiters()`. On its own thread so it needs no LocalSet and cannot be
    // starved by a connection's V8 work. Watches SIGTERM as well as Ctrl-C so
    // `docker stop` / `kill` also flush cookies (issue #333).
    {
        let sf = shutdown_flag.clone();
        let sn = shutdown_notify.clone();
        std::thread::Builder::new()
            .name("obscura-cdp-signal".into())
            .spawn(move || {
                if let Ok(rt) = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                {
                    rt.block_on(async {
                        #[cfg(unix)]
                        {
                            use tokio::signal::unix::{signal, SignalKind};
                            match signal(SignalKind::terminate()) {
                                Ok(mut term) => {
                                    tokio::select! {
                                        _ = tokio::signal::ctrl_c() => {}
                                        _ = term.recv() => {}
                                    }
                                }
                                Err(_) => {
                                    let _ = tokio::signal::ctrl_c().await;
                                }
                            }
                        }
                        #[cfg(not(unix))]
                        {
                            let _ = tokio::signal::ctrl_c().await;
                        }
                    });
                }
                sf.store(true, Ordering::Relaxed);
                sn.notify_waiters();
            })
            .ok();
    }

    // Live CDP connections, incremented on accept and decremented when a
    // connection thread exits (see `run_connection`).
    let live_connections = Arc::new(AtomicUsize::new(0));
    info!("Connection limit: {}", max_connections);

    // Accept loop: hand each WebSocket connection to its own OS thread so its
    // pages' isolates live on a dedicated thread.
    loop {
        let stream = tokio::select! {
            stream = ws_rx.recv() => stream,
            _ = shutdown_notify.notified() => None,
        };
        let stream = match stream {
            Some(s) => s,
            None => break,
        };
        // Nagle off + nonblocking on the std socket before it moves to the
        // connection thread. CDP exchanges many small (~100-byte) frames during
        // newPage()/navigate; with Nagle on, each small write waits on an ACK or
        // the 40ms delayed-ACK timer (~90ms on newPage, ~30ms on goto).
        stream
            .set_nonblocking(true)
            .map_err(|e| error!("set_nonblocking on WS stream: {}", e))
            .ok();
        stream
            .set_nodelay(true)
            .map_err(|e| error!("set_nodelay on WS stream: {}", e))
            .ok();
        // Reserve a slot before spawning. `fetch_update` (rather than a load
        // then a store) keeps the check atomic against the accept thread
        // handing off the next stream concurrently.
        // Retain the established API for compiler compatibility.
        #[allow(deprecated)]
        let reserved = live_connections
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| {
                (n < max_connections).then_some(n + 1)
            })
            .is_ok();
        if !reserved {
            warn!(
                "refusing CDP connection: at --max-connections ({})",
                max_connections
            );
            refuse_connection(stream);
            continue;
        }
        run_connection(
            stream,
            shared_ctx.clone(),
            persistence_ctx.clone(),
            persistence_lock.clone(),
            shutdown_notify.clone(),
            live_connections.clone(),
        );
    }

    // Server is shutting down. Connection threads are detached, so saving the
    // jar right here would race them: a connection still writing a Set-Cookie
    // loses it, and the process then exits and kills the thread mid-flight.
    // Before the per-connection move, the single processor saved on its own way
    // out, ordered against all connection work on one LocalSet -- draining here
    // is what restores that ordering. `notify_waiters` above has already woken
    // every processor, so this is bounded in practice; the deadline only covers
    // a connection wedged in V8, where its own command watchdog is the backstop.
    let drain_deadline =
        tokio::time::Instant::now() + tokio::time::Duration::from_millis(SHUTDOWN_DRAIN_MS);
    loop {
        let live = live_connections.load(Ordering::Acquire);
        if live == 0 {
            break;
        }
        if tokio::time::Instant::now() >= drain_deadline {
            warn!(
                "shutting down with {} connection(s) still live after {}ms; \
                 cookies they write from here are lost",
                live, SHUTDOWN_DRAIN_MS
            );
            break;
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }
    persistence_ctx.save_storage();
    Ok(())
}

#[derive(serde::Serialize)]
struct ReadyRecord {
    pid: u32,
    host: String,
    port: u16,
    websocket_path: &'static str,
}

fn publish_ready_file(path: &Path, address: SocketAddr) -> anyhow::Result<()> {
    let record = serde_json::to_vec(&ReadyRecord {
        pid: std::process::id(),
        host: address.ip().to_string(),
        port: address.port(),
        websocket_path: "/devtools/browser",
    })?;
    let temporary = path.with_file_name(format!(
        ".obscura-ready-{}.tmp",
        uuid::Uuid::new_v4()
    ));
    let result = (|| -> std::io::Result<()> {
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        options.mode(0o600);
        let mut file = options.open(&temporary)?;
        file.write_all(&record)?;
        file.sync_all()?;
        std::fs::rename(&temporary, path)
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(&temporary);
    }
    result.map_err(|e| anyhow::anyhow!("publish ready file {}: {}", path.display(), e))
}

/// Cap the number of per-thread malloc arenas glibc will create.
///
/// glibc hands each new thread its own 64 MiB arena (up to 8x cores). With one
/// thread per connection that is the dominant per-connection memory term:
/// measured with `reliability/conn-scale.py`, 100 connections each running JS
/// reserve 90.0 GiB of address space uncapped and 83.5 GiB capped, and 100 idle
/// connections go from 65 MiB of reserved address space per connection to
/// 2.0 MiB.
///
/// For scale: at the same 100-connection JS workload `main` (one shared
/// isolate) reserves 83.6 GiB, so with the cap this server is level with it on
/// address space. Most of that total is V8's process-wide sandbox, which `main`
/// pays too as soon as it runs any JS at all.
///
/// The resident-set effect matters more than the reservation: freed chunks stay
/// in their arena rather than returning to the OS, so RSS tracks the *peak*
/// number of concurrent connections and never comes back down, which reads as a
/// leak. Measured in the container image against Google Maps, four concurrent
/// connections per round: 350 / 619 / 826 MiB over three rounds uncapped and
/// still climbing linearly, versus 166 / 235 / 269 MiB capped, on a
/// decelerating curve.
///
/// Two arenas cost no measurable throughput here (8 concurrent connections x 12
/// navigations: 1.53s uncapped, 1.50s capped): V8 allocates the JS heap through
/// its own allocator, and the Rust side is dominated by network I/O rather than
/// malloc traffic. Only `serve` calls this, and it owns the process. Respects a
/// caller-set `MALLOC_ARENA_MAX`.
fn cap_malloc_arenas() {
    #[cfg(target_env = "gnu")]
    {
        // Pin the mmap threshold. glibc otherwise raises it (up to 32 MiB) each
        // time a large mmapped block is freed, so later large buffers (response
        // bodies, render surfaces, V8 backing stores) land in the arena and
        // fragment it. Skipped when the operator tuned it.
        if std::env::var_os("MALLOC_MMAP_THRESHOLD_").is_none() {
            const M_MMAP_THRESHOLD: libc::c_int = -3;
            // SAFETY: mallopt is thread-safe; called once here before any
            // connection thread exists.
            unsafe { libc::mallopt(M_MMAP_THRESHOLD, 1 << 20) };
        }
        if std::env::var_os("MALLOC_ARENA_MAX").is_some() {
            return;
        }
        // M_ARENA_MAX is not exported by the libc crate.
        const M_ARENA_MAX: libc::c_int = -8;
        // SAFETY: as above.
        if unsafe { libc::mallopt(M_ARENA_MAX, 2) } != 1 {
            warn!("mallopt(M_ARENA_MAX) failed; memory will scale with peak concurrency");
        }
    }
}

/// Return free glibc heap pages after the last CDP connection tears down.
///
/// A connection owns its pages, DOMs, render buffers, and V8 isolates. Dropping
/// those objects releases the allocations, but glibc normally keeps the freed
/// pages mapped for reuse, so a server that becomes idle can retain its peak RSS
/// indefinitely (#873). Trimming is a process-wide allocator pause, so callers
/// go through `release_connection_memory`, which rate-limits it while other
/// connections are live.
fn release_idle_connection_memory() {
    #[cfg(target_env = "gnu")]
    {
        // SAFETY: malloc_trim is process-wide and thread-safe. The caller has
        // already dropped this connection's LocalSet and Tokio runtime.
        unsafe {
            libc::malloc_trim(0);
        }
    }
}

/// Trim after a connection closes: always when it was the last one, otherwise
/// at most every `BUSY_TRIM_INTERVAL_MS` so a busy worker (which never reaches
/// zero connections) still returns the closed connection's free heap pages
/// instead of holding its peak RSS for days.
fn release_connection_memory(idle: bool) {
    static LAST_TRIM_MS: AtomicU64 = AtomicU64::new(0);
    static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
    let now = START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + 1;
    if claim_connection_memory_trim(&LAST_TRIM_MS, now, idle) {
        release_idle_connection_memory();
    }
}

#[allow(deprecated)]
fn claim_connection_memory_trim(last_trim: &AtomicU64, now: u64, idle: bool) -> bool {
    const BUSY_TRIM_INTERVAL_MS: u64 = 5_000;
    // Claim the interval atomically; a delayed closer cannot roll its timestamp back.
    last_trim.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |last| {
        if idle || last == 0 || now.saturating_sub(last) >= BUSY_TRIM_INTERVAL_MS {
            Some(now.max(last))
        } else {
            None
        }
    }).is_ok()
}

/// Run each connection's `cdp_processor` (with its own `CdpContext` and pages)
/// on a dedicated `current_thread` Tokio runtime and `LocalSet`. A second thread
/// handles WebSocket I/O independently. Confining a connection's pages
/// to one thread is what removes the #430 abort; the interception handshake and
/// the nav `spawn_local` all stay on this one thread, so no cross-thread V8
/// plumbing is needed.
fn run_connection(
    std_stream: std::net::TcpStream,
    context_template: Arc<obscura_browser::BrowserContext>,
    persistence_context: Arc<obscura_browser::BrowserContext>,
    persistence_lock: Arc<std::sync::Mutex<()>>,
    shutdown_notify: Arc<Notify>,
    live_connections: Arc<AtomicUsize>,
) {
    // Releases the slot reserved by the accept loop when the thread unwinds,
    // however it exits — clean close, error return, or panic. A plain
    // decrement at the end of the closure would leak slots on the early
    // returns below until the cap wedged the server shut.
    struct SlotGuard(Option<Arc<AtomicUsize>>);
    impl SlotGuard {
        fn release(&mut self) -> Option<usize> {
            self.0
                .take()
                .map(|counter| counter.fetch_sub(1, Ordering::AcqRel).saturating_sub(1))
        }
    }
    impl Drop for SlotGuard {
        fn drop(&mut self) {
            self.release();
        }
    }

    let slot = live_connections.clone();
    let spawned = std::thread::Builder::new()
        .name("obscura-cdp-conn".into())
        .stack_size(CDP_CONN_STACK_BYTES)
        .spawn(move || {
            let mut slot_guard = SlotGuard(Some(slot));
            let default_context = Arc::new(
                context_template.connection_copy("default".to_string()),
            );
            let initial_cookies = default_context.cookie_jar.get_all_cookies();
            let initial_local_storage = default_context.local_storage.isolated_snapshot();
            let persisted_context = default_context.clone();
            let rt = match tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
            {
                Ok(r) => r,
                Err(e) => {
                    error!("connection runtime build failed: {}", e);
                    return;
                }
            };
            // Socket I/O must not share the renderer's LocalSet: a synchronous
            // V8/layout task otherwise delays even replies already queued by a
            // completed navigation. Keep all page/isolate work on this thread,
            // and move only Send protocol strings and the socket to an I/O thread.
            let (msg_tx, msg_rx) = mpsc::unbounded_channel::<ServerMessage>();
            let (io_stop_tx, io_stop_rx) = tokio::sync::oneshot::channel::<()>();
            let (io_done_tx, io_done_rx) = tokio::sync::oneshot::channel::<()>();
            let io_thread = match std::thread::Builder::new()
                .name("obscura-cdp-io".into())
                .spawn(move || {
                    // Dropping this sender also signals early setup failures.
                    let _io_done = io_done_tx;
                    let io_rt = match tokio::runtime::Builder::new_current_thread()
                        .enable_all().build()
                    {
                        Ok(runtime) => runtime,
                        Err(error) => {
                            error!("connection I/O runtime build failed: {error}");
                            return;
                        }
                    };
                    let io_local = tokio::task::LocalSet::new();
                    io_local.block_on(&io_rt, async move {
                        let stream = match TcpStream::from_std(std_stream) {
                            Ok(stream) => stream,
                            Err(error) => {
                                error!("TcpStream::from_std failed: {error}");
                                return;
                            }
                        };
                        tokio::select! {
                            result = handle_connection_ws(stream, msg_tx) => {
                                if let Err(error) = result {
                                    error!("WebSocket connection error: {error}");
                                }
                            }
                            _ = io_stop_rx => {}
                        }
                    });
                })
            {
                Ok(thread) => thread,
                Err(error) => {
                    error!("connection I/O thread spawn failed: {error}");
                    return;
                }
            };
            let local = tokio::task::LocalSet::new();
            local.block_on(&rt, async move {
                // Run the processor in the connection future. A self-waking
                // LocalSet task can run 61 times before Tokio services I/O,
                // starving fetch under a continuously ready page scheduler.
                let processor = cdp_processor(
                    msg_rx, default_context, shutdown_notify,
                );
                tokio::pin!(processor);
                tokio::select! {
                    _ = &mut processor => {}
                    // Dropping the processor cancels an in-flight command.
                    // Detached navigation tasks are dropped with the LocalSet.
                    _ = io_done_rx => {}
                }
            });
            let _ = io_stop_tx.send(());
            let _ = io_thread.join();

            // `LocalSet` owns any detached local navigation tasks, and the
            // runtime owns their scheduler allocations. Drop both before the
            // idle trim so every page allocation is eligible to be returned.
            drop(local);
            drop(rt);

            // Apply only this connection's cookie changes to the persistence
            // template. Unchanged cookies cannot overwrite another connection's
            // updates, while explicit deletes and replacements still persist.
            if persistence_context.storage_dir.is_some() {
                let _guard = persistence_lock.lock().unwrap_or_else(|e| e.into_inner());
                merge_cookie_delta(
                    &persistence_context.cookie_jar,
                    &initial_cookies,
                    &persisted_context.cookie_jar.get_all_cookies(),
                );
                merge_local_storage_delta(
                    &persistence_context.local_storage,
                    &initial_local_storage,
                    &persisted_context.local_storage,
                );
                persistence_context.save_storage();
            }

            drop(persisted_context);
            let idle = slot_guard.release() == Some(0);
            release_connection_memory(idle);
        });

    // The closure never ran, so its `SlotGuard` never existed: release the
    // reserved slot here or the cap drifts down on every failed spawn.
    if let Err(e) = spawned {
        error!("connection thread spawn failed: {}", e);
        live_connections.fetch_sub(1, Ordering::AcqRel);
    }
}

fn merge_local_storage_delta(destination: &obscura_js::ops::OriginStorage,
    initial: &obscura_js::ops::OriginStorage, current: &obscura_js::ops::OriginStorage) {
    if !destination.merge_changes(initial, current) {
        tracing::warn!("localStorage changes exceeded the persistent profile storage budget");
    }
}

fn cookie_key(cookie: &obscura_net::CookieInfo) -> (String, String, String) {
    (
        cookie.domain.clone(),
        cookie.name.clone(),
        cookie.path.clone(),
    )
}

fn cookie_values_match(
    left: &obscura_net::CookieInfo,
    right: &obscura_net::CookieInfo,
) -> bool {
    left.value == right.value
        && left.secure == right.secure
        && left.http_only == right.http_only
        && left.same_site == right.same_site
        && left.expires == right.expires
}

fn merge_cookie_delta(
    destination: &obscura_net::CookieJar,
    initial: &[obscura_net::CookieInfo],
    current: &[obscura_net::CookieInfo],
) {
    let initial: HashMap<_, _> = initial.iter().map(|cookie| (cookie_key(cookie), cookie)).collect();
    let current: HashMap<_, _> = current.iter().map(|cookie| (cookie_key(cookie), cookie)).collect();

    for (key, cookie) in &initial {
        if !current.contains_key(key) {
            destination.delete_cookies_filtered(
                &cookie.name,
                &cookie.domain,
                Some(&cookie.path),
            );
        }
    }

    let changed: Vec<_> = current
        .iter()
        .filter_map(|(key, cookie)| match initial.get(key) {
            Some(previous) if cookie_values_match(previous, cookie) => None,
            _ => Some((*cookie).clone()),
        })
        .collect();
    destination.set_cookies_from_cdp(changed);
}

/// Turn away a connection that arrived while the server was at its limit.
///
/// Best-effort: the socket is going away either way, so a failed write just
/// means the client sees a reset instead of the 503.
fn refuse_connection(stream: std::net::TcpStream) {
    use std::io::{Read, Write};
    let mut stream = stream;
    let _ = stream.set_nonblocking(false);

    // The accept thread only peeked at the WebSocket handshake. Consume its
    // bounded HTTP header before closing: Windows resets a socket closed with
    // unread receive data, which can discard the queued 503 response.
    let _ = stream.set_read_timeout(Some(std::time::Duration::from_millis(100)));
    let mut request = [0u8; HTTP_PEEK_BUF];
    let mut received = 0;
    while received < request.len() {
        match stream.read(&mut request[received..]) {
            Ok(0) => break,
            Ok(n) => {
                received += n;
                if request[..received].windows(4).any(|end| end == b"\r\n\r\n") {
                    break;
                }
            }
            Err(_) => break,
        }
    }
    let _ = stream.write_all(CONNECTION_LIMIT_RESPONSE.as_bytes());
    let _ = stream.flush();
    let _ = stream.shutdown(std::net::Shutdown::Write);
}

const HTTP_PEEK_BUF: usize = 4096;

/// How long a freshly accepted connection may sit without sending a request
/// head before the accept thread drops it. Real clients send their handshake
/// immediately after connecting; only probes and preconnects linger.
const SILENT_CONNECTION_TTL: std::time::Duration = std::time::Duration::from_secs(10);

/// How often the accept thread re-polls parked connections that have not sent
/// a request head yet. Also the retry delay on a persistent accept error, so
/// it cannot become a log flood. Only paid while something is actually
/// parked; an idle server blocks in accept() and polls nothing.
const ACCEPT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1);

/// Cap on connections parked without a request head. Bounds the accept
/// thread's polling work and the server's fd usage under probe floods.
const MAX_SILENT_PENDING: usize = 256;

/// Result of polling a freshly accepted connection for its request head.
enum PeekStatus {
    /// No classifiable request head yet; poll again next accept round.
    NotReady,
    /// Peer went away without sending a full head.
    Closed,
    /// The header terminator did not fit in the bounded peek buffer. Refuse it;
    /// security-sensitive headers could otherwise be hidden beyond the cap.
    Oversized,
    /// A classifiable request head.
    Head(String),
}

/// Peek — without consuming — at a freshly accepted connection's request
/// head. `GET` requests are only classified once the terminating blank line
/// has arrived, so `/json` route matching never sees a truncated head;
/// anything that cannot be a `GET` is handed over immediately so non-HTTP
/// garbage still gets tungstenite's prompt rejection instead of waiting out
/// the silent-connection TTL.
fn peek_request_head(stream: &std::net::TcpStream) -> PeekStatus {
    let mut buf = [0u8; HTTP_PEEK_BUF];
    let n = match stream.peek(&mut buf) {
        Ok(0) => return PeekStatus::Closed,
        Ok(n) => n,
        Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return PeekStatus::NotReady,
        Err(_) => return PeekStatus::Closed,
    };
    let head = &buf[..n];
    if n >= 4 && head[..4] != *b"GET " {
        return PeekStatus::Head(String::from_utf8_lossy(head).into_owned());
    }
    let complete = head.windows(4).any(|w| w == b"\r\n\r\n");
    if !complete {
        return if n == HTTP_PEEK_BUF {
            PeekStatus::Oversized
        } else {
            PeekStatus::NotReady
        };
    }
    PeekStatus::Head(String::from_utf8_lossy(head).into_owned())
}

/// Dispatch a freshly-accepted TCP connection on the dedicated accept thread.
///
/// The connection's request head has already been peeked by the accept loop
/// (`peek_request_head`) and is passed in as `head`:
/// - HTTP (`GET /json/*`): serve synchronously via blocking I/O so the
///   response is never stalled by the LocalSet.
/// - WebSocket: forward to the LocalSet for CDP processing.
fn accept_dispatch(
    stream: std::net::TcpStream,
    bind_ip: std::net::IpAddr,
    port: u16,
    forwarded: Option<(std::net::IpAddr, u16)>,
    auth_token: Option<&str>,
    allowed_origins: Option<&str>,
    ws_tx: &mpsc::Sender<std::net::TcpStream>,
    head: &str,
) -> anyhow::Result<()> {
    if let Some(refusal) = control_refusal(head, bind_ip, port, forwarded, auth_token, allowed_origins) {
        refuse_control_connection(stream, refusal);
        return Ok(());
    }
    let target = head.lines().next().and_then(|line| line.split_whitespace().nth(1));
    let absolute = target.filter(|target| !target.starts_with('/'))
        .and_then(|target| url::Url::parse(target).ok());
    let path = absolute.as_ref().map(url::Url::path).or(target);
    let endpoint = match path.map(|path| path.split('?').next().unwrap_or(path)) {
        Some("/json/version" | "/json/version/") => Some("version"),
        Some("/json" | "/json/" | "/json/list" | "/json/list/") => Some("list"),
        Some("/json/protocol" | "/json/protocol/") => Some("protocol"),
        _ => None,
    };

    if let Some(ep) = endpoint {
        // The request head is already sitting in the kernel receive buffer;
        // switch back to blocking mode for the synchronous /json serve.
        let _ = stream.set_nonblocking(false);
        return handle_http_json_blocking(stream, port, ep, head);
    }
    // Fall through: GET request that isn't a /json endpoint → treat as
    // WebSocket upgrade (Chromium DevTools clients issue GET with
    // Upgrade: websocket).

    // Try to hand off the WS stream to the LocalSet. If the bounded channel
    // is full the LocalSet is saturated — drop the connection cleanly
    // rather than blocking the accept thread (which would freeze the HTTP
    // control plane that this whole rework exists to keep alive). The
    // dropped `stream` closes itself; the client will see ECONNRESET and
    // can retry.
    ws_tx
        .try_send(stream)
        .map_err(|e| match e {
            mpsc::error::TrySendError::Full(_) => {
                warn!("WS handoff channel full ({}); dropping new WebSocket connection", MAX_PENDING_WS_HANDOFFS);
                anyhow::anyhow!("ws handoff channel full")
            }
            mpsc::error::TrySendError::Closed(_) => anyhow::anyhow!("accept channel closed"),
        })
}

/// Serve an HTTP `/json/*` endpoint with blocking I/O on the accept thread.
fn handle_http_json_blocking(
    mut stream: std::net::TcpStream,
    port: u16,
    endpoint: &str,
    request_head: &str,
) -> anyhow::Result<()> {
    use std::io::{Read, Write};

    let mut buf = vec![0u8; 4096];
    let _ = stream.read(&mut buf)?;
    let authority = websocket_authority(request_head, port);

    let body = match endpoint {
        "version" => serde_json::to_string_pretty(&json!({
            "Browser": "Chrome/145.0.0.0",
            "Protocol-Version": "1.3",
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
            "V8-Version": "14.5.0.0",
            "WebKit-Version": "537.36",
            "webSocketDebuggerUrl": format!("ws://{}/devtools/browser", authority),
        }))?,
        "list" => serde_json::to_string_pretty(&json!([{
            "description": "",
            "devtoolsFrontendUrl": "",
            "id": "page-1",
            "title": "",
            "type": "page",
            "url": "about:blank",
            "webSocketDebuggerUrl": format!("ws://{}/devtools/page/page-1", authority),
        }]))?,
        "protocol" => {
            serde_json::to_string_pretty(&json!({ "version": { "major": "1", "minor": "3" } }))?
        }
        _ => "{}".to_string(),
    };

    let resp = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
        body.len(), body,
    );
    stream.write_all(resp.as_bytes())?;
    stream.flush()?;
    Ok(())
}

fn websocket_authority(request_head: &str, port: u16) -> String {
    request_head
        .lines()
        .filter_map(|line| line.split_once(':'))
        .find(|(name, _)| name.eq_ignore_ascii_case("host"))
        .map(|(_, value)| value.trim())
        .filter(|value| {
            let Ok(url) = url::Url::parse(&format!("http://{value}/")) else {
                return false;
            };
            url.host_str().is_some()
                && url.username().is_empty()
                && url.password().is_none()
                && url.path() == "/"
                && url.query().is_none()
                && url.fragment().is_none()
        })
        .map(str::to_owned)
        .unwrap_or_else(|| format!("127.0.0.1:{port}"))
}

/// Per-connection CDP processor. Each connection runs its own processor (with
/// its own `CdpContext` and pages) on its own OS thread, so every page's V8
/// isolate is confined to a single thread. This removes the #430 abort by
/// construction: V8's `heap->isolate() == Isolate::TryGetCurrent()` invariant is
/// per-thread, so two connections' isolates can never collide. All processors
/// own isolated `BrowserContext` (cookie jar and HTTP client). Cookie deltas are
/// merged into the persistence template when the connection thread exits.
async fn cdp_processor(
    mut rx: mpsc::UnboundedReceiver<ServerMessage>,
    default_context: Arc<obscura_browser::BrowserContext>,
    shutdown_notify: Arc<Notify>,
) {
    let mut ctx = CdpContext::new_with_shared_context(default_context);
    let (itx, irx) = mpsc::unbounded_channel::<obscura_js::ops::InterceptedRequest>();
    ctx.intercept_tx = Some(itx);
    let mut intercept_rx: Option<mpsc::UnboundedReceiver<obscura_js::ops::InterceptedRequest>> = Some(irx);
    let mut intercepted_paused: HashMap<String, PausedIntercept> = HashMap::new();

    // Issue #19 follow-up: messages deferred from inside
    // `process_with_interception` because routing them through
    // `process_cdp_message → dispatch` while a nav was in flight would have
    // tripped V8's TryGetCurrent invariant. Drained at the top of each
    // outer iteration so they get processed sequentially with no other nav
    // in flight.
    let mut deferred: std::collections::VecDeque<ServerMessage> =
        std::collections::VecDeque::new();

    // Graceful shutdown: one signal watcher on the accept side flips the flag
    // and calls `notify_waiters()`. Polled once here (via the select! below) it
    // registers and stays registered across iterations, so a later
    // `notify_waiters()` wakes this processor even while it is mid-dispatch.
    let mut shutdown = Box::pin(shutdown_notify.notified());
    // Chromium's PageHandler receives compositor video frames continuously.
    // Obscura has no separate compositor thread yet, so active screencasts get
    // a bounded 30 Hz opportunity on this connection's owning LocalSet.
    let mut screencast_tick = tokio::time::interval(tokio::time::Duration::from_millis(33));
    screencast_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    let mut connection_reply_tx: Option<mpsc::UnboundedSender<String>> = None;
    // A real browser renderer continues servicing timers, networking, posted
    // tasks, and animation callbacks while its DevTools client is silent. Keep
    // one wake-driven deno_core turn armed after work may have been scheduled;
    // the future parks on the runtime's own waker and is cancelled whenever a
    // higher-priority protocol command arrives. Full idle disarms it until the
    // next command/navigation, so static pages consume no polling budget.
    let mut runtime_pump_armed = false;
    let mut runtime_pump_error_streak = 0_u8;
    let mut idle_pages = HashSet::new();
    let mut pending_runtime = Vec::<PendingRuntimeReply>::new();

    loop {
        let mut index = 0;
        while index < pending_runtime.len() {
            if !pending_runtime[index].evaluation.ready(&mut ctx) { index += 1; continue; }
            let pending = pending_runtime.remove(index);
            let _guard = ctx.v8_lock.clone().lock_owned().await;
            let result = pending.evaluation.finish(&mut ctx, &pending.session_id).await;
            idle_pages.clear();
            runtime_pump_armed = ctx.pages.iter().any(|page| page.has_js());
            dispatch::drain_runtime_events(&mut ctx);
            dispatch::drain_binding_calls(&mut ctx);
            dispatch::drain_frame_events(&mut ctx);
            forward_pending_events(&mut ctx, Some(&pending.reply_tx));
            let response = match result {
                Ok(value) => crate::types::CdpResponse::success(pending.id, value, pending.session_id),
                Err(error) => crate::types::CdpResponse::error(pending.id, -32000, error, pending.session_id),
            };
            if let Ok(json) = serde_json::to_string(&response) { let _ = pending.reply_tx.send(json); }
        }
        // Drain any deferred messages from the previous interception window
        // before pulling new ones off the wire. Each is processed with no
        // nav-task spawn_local in flight, so this connection's only entered
        // Isolate is the one dispatch is about to touch.
        let msg = if let Some(d) = deferred.pop_front() {
            Some(d)
        } else {
            let screencast_active = has_active_screencast(&ctx);
            let has_intercept_rx = intercept_rx.is_some();
            let evaluation_deadline = pending_runtime.iter().map(|pending| pending.evaluation.deadline).min();
            tokio::select! {
                biased;
                msg = rx.recv() => match msg {
                    Some(m) => Some(m),
                    None => break,
                },
                _ = &mut shutdown => {
                    tracing::info!("Shutdown signal received (connection processor)");
                    break;
                },
                _ = async {
                    match evaluation_deadline {
                        Some(deadline) => tokio::time::sleep_until(deadline).await,
                        None => std::future::pending().await,
                    }
                } => None,
                pump_result = pump_live_page_event_loop(&mut ctx, &mut idle_pages), if runtime_pump_armed => {
                    match pump_result {
                        Ok(reached_idle) => {
                            runtime_pump_error_streak = 0;
                            runtime_pump_armed = !reached_idle;
                        }
                        Err(error) => {
                            runtime_pump_error_streak = runtime_pump_error_streak.saturating_add(1);
                            runtime_pump_armed = runtime_pump_error_streak <= 3
                                && ctx.pages.iter().any(|page| page.has_js());
                            tracing::warn!("autonomous page task failed: {error}");
                        }
                    }
                    service_live_page_render_resources(&mut ctx);
                    sync_live_page_background_events(&mut ctx);
                    dispatch::drain_runtime_events(&mut ctx);
                    dispatch::drain_binding_calls(&mut ctx);
                    dispatch::drain_frame_events(&mut ctx);
                    forward_pending_events(&mut ctx, connection_reply_tx.as_ref());
                    if let (Some(reply_tx), Some((session_id, url, method, body))) = (
                        connection_reply_tx.as_ref(),
                        take_live_pending_navigation(&ctx),
                    ) {
                        let navigation = json!({
                            "id": 0,
                            "method": "Page.navigate",
                            "params": {"url": url, "__method": method, "__body": body},
                            "sessionId": session_id,
                        })
                        .to_string();
                        process_with_interception(
                            &navigation,
                            &mut ctx,
                            reply_tx,
                            &mut rx,
                            &mut intercept_rx,
                            &mut intercepted_paused,
                            &mut deferred,
                            false,
                        )
                        .await;
                        idle_pages.clear();
                        runtime_pump_armed = ctx.pages.iter().any(|page| page.has_js());
                    }
                    // Ready page tasks must not keep this root future running
                    // indefinitely while Tokio's network tasks wait to run.
                    tokio::task::yield_now().await;
                    None
                },
                Some(intercepted) = async {
                    if let Some(ref mut receiver) = intercept_rx {
                        receiver.recv().await
                    } else {
                        std::future::pending().await
                    }
                }, if has_intercept_rx => {
                    if let Some(reply_tx) = connection_reply_tx.as_ref() {
                        let route = pending_runtime.iter()
                            .find(|pending| pending.evaluation.page_id == intercepted.page_id)
                            .and_then(|pending| ctx.pages.iter().find(|page| page.id == intercepted.page_id)
                                .map(|page| (page.id.as_str(), page.frame_id.as_str(), pending.session_id.clone())));
                        emit_intercepted_request(
                            intercepted,
                            &ctx,
                            route,
                            reply_tx,
                            &mut intercepted_paused,
                        );
                    } else {
                        let _ = intercepted.resolver.send(
                            obscura_js::ops::InterceptResolution::Fail {
                                reason: "Aborted".into(),
                            },
                        );
                    }
                    None
                },
                _ = screencast_tick.tick(), if screencast_active => {
                    pump_and_forward_screencast_frames(
                        &mut ctx,
                        connection_reply_tx.as_ref(),
                    ).await;
                    idle_pages.clear();
                    runtime_pump_armed = ctx.pages.iter().any(|page| page.has_js());
                    None
                }
            }
        };

        let Some(msg) = msg else {
            continue;
        };

        match msg {
            ServerMessage::NewConnection { reply_tx } => {
                connection_reply_tx = Some(reply_tx.clone());
                let _ = reply_tx.send(
                    json!({"__init": true})
                        .to_string(),
                );
            }
            ServerMessage::Cdp(cdp_msg) => {
                // Route navigation and reload through the spawn-and-defer path,
                // not just intercepted ones. Holding the V8 lock across a
                // multi-second navigate inside the regular dispatch wedges the
                // entire processor (40-site sweep: 39/40 timeouts). Spawning
                // navigation lets `cdp_processor` keep multiplexing other CDP
                // messages via the `process_with_interception` select loop;
                // unrelated requests get deferred only briefly and are drained
                // as soon as the nav settles.
                let is_navigation = is_navigate_method(&cdp_msg.text);

                if is_navigation {
                    process_with_interception(
                        &cdp_msg.text, &mut ctx, &cdp_msg.reply_tx, &mut rx,
                        &mut intercept_rx, &mut intercepted_paused,
                        &mut deferred, true,
                    ).await;
                } else {
                    let fetch_was_resolved = cdp_msg.text.contains("Fetch.")
                        && handle_fetch_resolution(
                            &cdp_msg.text,
                            &cdp_msg.reply_tx,
                            &mut intercepted_paused,
                        );
                    if !fetch_was_resolved {
                        process_cdp_message_with_pending(&cdp_msg.text, &mut ctx, &cdp_msg.reply_tx, Some(&mut pending_runtime)).await;
                    }
                }
            }
        }

        if let (Some(reply_tx), Some((session_id, url, method, body))) = (
            connection_reply_tx.as_ref(),
            take_live_pending_navigation(&ctx),
        ) {
            let navigation = json!({
                "id": 0,
                "method": "Page.navigate",
                "params": {"url": url, "__method": method, "__body": body},
                "sessionId": session_id,
            }).to_string();
            process_with_interception(
                &navigation, &mut ctx, reply_tx, &mut rx,
                &mut intercept_rx, &mut intercepted_paused, &mut deferred, false,
            ).await;
        }

        // Dispatch may have created pages or scheduled work on an idle page.
        // Recheck after commands, then park on the runtimes' own wakers.
        idle_pages.clear();
        runtime_pump_armed = ctx.pages.iter().any(|page| page.has_js());
        runtime_pump_error_streak = 0;

    }

    // The connection thread merges this context's cookie delta into the
    // persistence template after the processor stops.
    let _ = &ctx;
}

struct PausedIntercept {
    resolver: tokio::sync::oneshot::Sender<obscura_js::ops::InterceptResolution>,
    main_document: bool,
}

// Native document requests use Page's page-id.counter namespace. Frame documents
// fetched by JavaScript use fetch-N and must not become the top-level loader.
fn is_main_document_intercept(request: &obscura_js::ops::InterceptedRequest, page_id: &str) -> bool {
    request.page_id == page_id && request.resource_type == "Document"
        && request.request_id.strip_prefix(page_id).is_some_and(|suffix| suffix.starts_with('.'))
}

fn emit_intercepted_request(
    intercepted: obscura_js::ops::InterceptedRequest,
    ctx: &CdpContext,
    navigating_page: Option<(&str, &str, Option<String>)>,
    reply_tx: &mpsc::UnboundedSender<String>,
    intercepted_paused: &mut HashMap<String, PausedIntercept>,
) {
    // Navigation temporarily removes its Page from ctx. Other pages can still
    // have requests queued on the same channel, so never infer their owner.
    let loader = navigating_page.as_ref()
        .filter(|(page_id, _, _)| is_main_document_intercept(&intercepted, page_id))
        .map(|_| intercepted.request_id.clone());
    let route = navigating_page
        .filter(|(page_id, _, _)| *page_id == intercepted.page_id)
        .map(|(_, frame_id, session_id)| (frame_id, session_id))
        .or_else(|| {
            let page = ctx.pages.iter().find(|page| page.id == intercepted.page_id)?;
            let (session_id, _) = ctx.sessions.iter().find(|(_, page_id)| **page_id == page.id)?;
            Some((page.frame_id.as_str(), Some(session_id.clone())))
        });
    let observers = route.as_ref().map_or_else(Vec::new, |(_, session_id)| {
        crate::domains::page::network_observer_sessions(ctx, &intercepted.page_id, session_id)
    });
    emit_routed_intercepted_request(intercepted, route, loader.as_deref(), &observers, reply_tx, intercepted_paused);
}

fn emit_routed_intercepted_request(
    intercepted: obscura_js::ops::InterceptedRequest,
    route: Option<(&str, Option<String>)>,
    loader: Option<&str>,
    observers: &[String],
    reply_tx: &mpsc::UnboundedSender<String>,
    intercepted_paused: &mut HashMap<String, PausedIntercept>,
) {
    let Some((frame_id, session_id)) = route else {
        let _ = intercepted.resolver.send(obscura_js::ops::InterceptResolution::Fail {
            reason: "Aborted".into(),
        });
        return;
    };
    tracing::info!(
        "INTERCEPTION: requestPaused for {} {} (sending to client)",
        intercepted.method,
        intercepted.url
    );
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs_f64();
    let request = json!({
        "url": intercepted.url,
        "method": intercepted.method,
        "headers": intercepted.headers,
        "initialPriority": "High",
        "referrerPolicy": "strict-origin-when-cross-origin",
    });
    let request_will_be_sent = json!({
        "method": "Network.requestWillBeSent",
        "params": {
            "requestId": intercepted.request_id,
            "loaderId": loader.unwrap_or(""),
            "documentURL": if loader.is_some() { intercepted.url.as_str() } else { "" },
            "request": request,
            "timestamp": now,
            "wallTime": now,
            "initiator": {"type": "script"},
            "type": intercepted.resource_type,
            "frameId": frame_id,
        },
        "sessionId": session_id,
    });
    let _ = reply_tx.send(request_will_be_sent.to_string());
    for observer in observers {
        let mut event = request_will_be_sent.clone();
        event["sessionId"] = json!(observer);
        let _ = reply_tx.send(event.to_string());
    }

    let request_paused = json!({
        "method": "Fetch.requestPaused",
        "params": {
            "requestId": intercepted.request_id,
            "request": request,
            "frameId": frame_id,
            "resourceType": intercepted.resource_type,
            "networkId": intercepted.request_id,
            "responseErrorReason": null,
            "responseStatusCode": null,
            "responseHeaders": null,
        },
        "sessionId": session_id,
    });
    let _ = reply_tx.send(request_paused.to_string());
    intercepted_paused.insert(intercepted.request_id, PausedIntercept {resolver: intercepted.resolver, main_document: loader.is_some()});
}

async fn pump_live_page_event_loop(
    ctx: &mut CdpContext,
    idle_pages: &mut HashSet<String>,
) -> Result<bool, String> {
    pump_page_event_loops(ctx.pages.iter_mut(), idle_pages).await
}

pub(crate) async fn pump_page_event_loops<'a>(
    pages: impl Iterator<Item = &'a mut obscura_browser::Page>,
    idle_pages: &mut HashSet<String>,
) -> Result<bool, String> {
    use std::future::Future;
    use std::task::Poll;

    // Register every page's waker before parking. Awaiting pages in order lets
    // a distant timer on the first page hold up ready work on all its peers.
    // A completed turn can emit events even when it leaves its page idle.
    // Publish it now, then omit idle pages until a command schedules new work;
    // otherwise an idle peer would keep a waiting connection spinning.
    let mut turns: Vec<_> = pages.filter_map(|page| {
            if page.has_pending_indexed_db_notifications() { idle_pages.remove(&page.id); }
            if !page.has_js() || idle_pages.contains(&page.id) { return None; }
            Some((page.id.clone(), Box::pin(page.run_autonomous_event_loop_turn())))
        })
        .collect();
    std::future::poll_fn(|cx| {
        let mut all_idle = true;
        let mut progressed = false;
        for (page_id, future) in &mut turns {
            match future.as_mut().poll(cx) {
                Poll::Ready(Ok(idle)) => {
                    all_idle &= idle;
                    progressed = true;
                    if idle { idle_pages.insert(page_id.clone()); }
                }
                Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
                Poll::Pending => all_idle = false,
            }
        }
        if all_idle || progressed {
            Poll::Ready(Ok(all_idle))
        } else {
            Poll::Pending
        }
    }).await
}

/// Apply finished background render-resource loads and start loads for
/// resources the last layout/paint missed, for every live page. Runs before a
/// command (so it observes bytes that landed while the client was silent),
/// after a command (so its layout misses start loading immediately) and after
/// each autonomous pump turn.
fn service_live_page_render_resources(ctx: &mut CdpContext) {
    for page in ctx.pages.iter_mut().filter(|page| page.has_js()) {
        page.queue_pending_render_resources();
    }
}

fn sync_live_page_background_events(ctx: &mut CdpContext) {
    // Emit script-initiated network/history events for every live page, attributed
    // to its own session/frame — not just the first live page (#872).
    let live_ids: Vec<String> = ctx
        .pages
        .iter()
        .filter(|page| page.has_js())
        .map(|page| page.id.clone())
        .collect();
    for page_id in live_ids {
        let Some(session_id) = ctx
            .sessions
            .iter()
            .find(|(_, pid)| *pid == &page_id)
            .map(|(session_id, _)| Some(session_id.clone()))
        else {
            continue;
        };
        let (frame_id, page_url, network_events, same_document_navigation) = {
            let Some(page) = ctx.get_page_mut(&page_id) else {
                continue;
            };
            page.sync_js_network_events();
            // Timer-driven history changes need the same notification as
            // Runtime.evaluate, even when the client is only waiting for an
            // event. Leave document navigations to the interception loop.
            let same_document_navigation = !page.has_pending_navigation() && page.sync_virtual_url();
            (
                page.frame_id.clone(),
                page.url_string(),
                page.network_events.drain(..).collect::<Vec<_>>(),
                same_document_navigation,
            )
        };
        if same_document_navigation {
            crate::domains::page::emit_same_document_navigation(
                ctx, &session_id, &frame_id, &page_url,
            );
        }
        if network_events.is_empty() {
            continue;
        }
        crate::domains::page::emit_runtime_network_events(
            ctx,
            &session_id,
            &frame_id,
            &page_url,
            &page_id,
            &network_events,
        );
    }
}

fn take_live_pending_navigation(
    ctx: &CdpContext,
) -> Option<(String, String, String, String)> {
    // With several live pages, a pending navigation may belong to any of them,
    // not just the first live page — scan until one yields a navigation (#872).
    for page in ctx.pages.iter().filter(|page| page.has_js()) {
        let Some(session_id) = ctx
            .sessions
            .iter()
            .find(|(_, page_id)| *page_id == &page.id)
            .map(|(session_id, _)| session_id.clone())
        else {
            continue;
        };
        if let Some((url, method, body)) = page.take_pending_navigation() {
            return Some((session_id, url, method, body));
        }
    }
    None
}

fn forward_pending_events(
    ctx: &mut CdpContext,
    reply_tx: Option<&mpsc::UnboundedSender<String>>,
) {
    let Some(reply_tx) = reply_tx else {
        return;
    };
    for event in ctx.pending_events.drain(..) {
        if let Ok(json) = serde_json::to_string(&event) {
            let _ = reply_tx.send(json);
        }
    }
}

fn has_active_screencast(ctx: &CdpContext) -> bool {
    #[cfg(feature = "render")]
    {
        !ctx.screencasts.is_empty()
    }
    #[cfg(not(feature = "render"))]
    {
        let _ = ctx;
        false
    }
}

async fn pump_and_forward_screencast_frames(
    ctx: &mut CdpContext,
    reply_tx: Option<&mpsc::UnboundedSender<String>>,
) {
    #[cfg(feature = "render")]
    crate::domains::page::pump_screencast_frames(ctx).await;
    #[cfg(not(feature = "render"))]
    let _ = ctx;

    forward_pending_events(ctx, reply_tx);
}

// Whether a raw CDP frame is a navigate/reload call, and so should take
// the spawn-and-defer navigation path. Matching on the parsed method rather than
// a `contains("Page.navigate")` substring avoids catching
// `Page.navigateToHistoryEntry` (goBack / goForward), which has no `url` param
// and belongs to its own handler, or any other frame that merely embeds the
// literal text (e.g. a `Runtime.evaluate` expression). See issue #363.
fn is_navigate_method(text: &str) -> bool {
    serde_json::from_str::<CdpRequest>(text)
        .map(|req| matches!(req.method.as_str(), "Page.navigate" | "Page.reload"))
        .unwrap_or(false)
}

// Parse a CDP header list (`[{"name":..,"value":..}, ..]`, as used by
// Fetch.continueRequest / fulfillRequest) into a map. Returns None when the
// `headers` field is absent, so the caller can leave the request's headers
// untouched rather than clearing them.
pub(crate) fn parse_cdp_headers(params: &serde_json::Value) -> Option<HashMap<String, String>> {
    let arr = params.get("headers")?.as_array()?;
    Some(
        arr.iter()
            .filter_map(|h| {
                Some((
                    h.get("name")?.as_str()?.to_string(),
                    h.get("value")?.as_str()?.to_string(),
                ))
            })
            .collect(),
    )
}

fn handle_fetch_resolution(
    text: &str,
    reply_tx: &mpsc::UnboundedSender<String>,
    intercepted_paused: &mut HashMap<String, PausedIntercept>,
) -> bool {
    if let Ok(req) = serde_json::from_str::<CdpRequest>(text) {
        let method = req.method.as_str();
        if !matches!(method, "Fetch.continueRequest" | "Fetch.fulfillRequest" | "Fetch.failRequest") {
            return false;
        }
        let request_id = req.params.get("requestId").and_then(|v| v.as_str()).unwrap_or("");
        tracing::info!("INTERCEPTION resolution: {} for {}, paused_count={}", method, request_id, intercepted_paused.len());

        if intercepted_paused.contains_key(request_id) {
            tracing::info!("INTERCEPTION resolved: {}", request_id);
            // Build the resolution before taking the pause. A malformed command
            // is answered with an error and the request stays paused, so a
            // corrected answer on the same requestId still drives the fetch --
            // taking the pause first would wedge the request on a client typo.
            let resolution = match method {
                "Fetch.continueRequest" => {
                    // Honor the client's overrides (Playwright route.continue,
                    // Puppeteer request.continue). op_fetch_url applies each and
                    // re-validates a rewritten URL through the SSRF gate. Leaving
                    // these None silently sent the request unmodified (issue #365).
                    match decode_optional_binary(&req.params, "postData", "continueRequest postData") {
                        Ok(body) => Ok(obscura_js::ops::InterceptResolution::Continue {
                            url: req.params.get("url").and_then(|v| v.as_str()).map(|s| s.to_string()),
                            method: req.params.get("method").and_then(|v| v.as_str()).map(|s| s.to_string()),
                            headers: parse_cdp_headers(&req.params),
                            body,
                        }),
                        Err(message) => Err(message),
                    }
                }
                "Fetch.fulfillRequest" => {
                    let status = req.params.get("responseCode").and_then(|v| v.as_u64()).unwrap_or(200) as u16;
                    let raw_body = req.params.get("body").and_then(|v| v.as_str()).unwrap_or("");
                    let mut headers = HashMap::new();
                    if let Some(arr) = req.params.get("responseHeaders").and_then(|value| value.as_array()) {
                        for header in arr {
                            let (Some(name), Some(value)) = (header.get("name").and_then(|v| v.as_str()), header.get("value").and_then(|v| v.as_str())) else { continue; };
                            if name.eq_ignore_ascii_case("set-cookie") {
                                headers.entry("set-cookie".into()).and_modify(|cookies: &mut String| {
                                    cookies.push('\n'); cookies.push_str(value);
                                }).or_insert_with(|| value.to_string());
                            } else { headers.insert(name.to_string(), value.to_string()); }
                        }
                    }
                    // Validate before consuming the pause; keep exact bytes for JS.
                    match decode_optional_binary(&req.params, "body", "fulfillRequest body") {
                        Ok(bytes) => Ok(obscura_js::ops::InterceptResolution::Fulfill {
                            status,
                            headers,
                            body: String::from_utf8_lossy(&bytes.unwrap_or_default()).to_string(),
                            body_base64: raw_body.to_string(),
                        }),
                        Err(message) => Err(message),
                    }
                }
                "Fetch.failRequest" => {
                    let reason = req.params.get("errorReason").and_then(|v| v.as_str()).unwrap_or("Failed").to_string();
                    Ok(obscura_js::ops::InterceptResolution::Fail { reason })
                }
                _ => return false,
            };
            let resp = match resolution {
                Ok(resolution) => {
                    let resolver = intercepted_paused
                        .remove(request_id)
                        .expect("the pause was present a few lines above and nothing else can take it");
                    let main_document = resolver.main_document;
                    if resolver.resolver.send(resolution).is_ok() && method == "Fetch.failRequest" && !main_document {
                        let reason = req.params.get("errorReason").and_then(|v| v.as_str()).unwrap_or("Failed");
                        let mut error_text = String::from("net::ERR_");
                        for (index, ch) in reason.chars().enumerate() {
                            if index > 0 && ch.is_ascii_uppercase() { error_text.push('_'); }
                            error_text.push(ch.to_ascii_uppercase());
                        }
                        let _ = reply_tx.send(json!({
                            "method": "Network.loadingFailed", "sessionId": req.session_id,
                            "params": {"requestId": request_id, "type": "Fetch", "errorText": error_text,
                                "canceled": reason == "Aborted",
                                "timestamp": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)
                                    .unwrap_or_default().as_secs_f64()},
                        }).to_string());
                    }
                    crate::types::CdpResponse::success(req.id, json!({}), req.session_id)
                }
                // -32602 is the invalid-params code; the pause is deliberately left
                // in place so the client can answer this requestId again.
                Err(message) => crate::types::CdpResponse::error(req.id, -32602, message, req.session_id),
            };
            if let Ok(json) = serde_json::to_string(&resp) {
                let _ = reply_tx.send(json);
            }
            return true;
        }
    }
    false
}

async fn process_with_interception(
    text: &str,
    ctx: &mut CdpContext,
    reply_tx: &mpsc::UnboundedSender<String>,
    rx: &mut mpsc::UnboundedReceiver<ServerMessage>,
    intercept_rx: &mut Option<mpsc::UnboundedReceiver<obscura_js::ops::InterceptedRequest>>,
    intercepted_paused: &mut HashMap<String, PausedIntercept>,
    deferred: &mut std::collections::VecDeque<ServerMessage>,
    send_command_response: bool,
) {
    let req: CdpRequest = match serde_json::from_str(text) {
        Ok(r) => r,
        Err(e) => {
            warn!("Invalid CDP: {}", e);
            return;
        }
    };

    tracing::info!("INTERCEPTION navigate: {} (id={})", req.method, req.id);

    let session_id = &req.session_id;
    let page_id = session_id
        .as_ref()
        .and_then(|sid| ctx.sessions.get(sid))
        .cloned();

    let page_id = match page_id {
        Some(id) => id,
        None => {
            process_cdp_message(text, ctx, reply_tx).await;
            return;
        }
    };

    let page_index = ctx.pages.iter().position(|p| p.id == page_id);
    let mut page = match page_index {
        Some(idx) => ctx.pages.remove(idx),
        None => {
            process_cdp_message(text, ctx, reply_tx).await;
            return;
        }
    };

    // V8 allows only ONE *entered* isolate per OS thread, but many *live*
    // ones. Since #756 every op enters its isolate only transiently (never
    // across an `.await`) and construction leaves the entry stack empty, so a
    // nav task's `init_js` can build a new isolate while other pages' isolates
    // are live without tripping `Context::Exit`'s
    // `heap->isolate() == Isolate::TryGetCurrent()` check. The old defensive
    // `suspend_js` of every other page here (which tore their heaps down and
    // was never resumed once the dispatch-path resume was removed in #872) is
    // therefore no longer needed and would strand concurrent pages.

    let is_reload = req.method == "Page.reload";
    let url_owned = if is_reload {
        page.url_string()
    } else {
        req.params.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string()
    };
    if !send_command_response && page.reject_page_initiated_file_navigation(&url_owned) {
        ctx.pages.push(page);
        return;
    }
    // Preserve the regular handler's file-access gate on this async path.
    if crate::util::url_is_file_scheme(&url_owned) && !page.context.allow_file_access {
        ctx.pages.push(page);
        process_cdp_message(text, ctx, reply_tx).await;
        return;
    }
    let wait_until = crate::domains::page::parse_wait_until(&req.params);
    let nav_method = req.params.get("__method").and_then(|v| v.as_str()).unwrap_or("GET").to_string();
    let nav_body = req.params.get("__body").and_then(|v| v.as_str()).unwrap_or("").to_string();

    let preload_scripts = ctx.preload_sources_for_page(&page_id);

    if let Some(tx) = &ctx.intercept_tx {
        page.set_intercept_tx(tx.clone());
    }

    let session_for_events = req.session_id.clone();
    let frame_id = page.frame_id.clone();
    let initial_loader_id = format!("loader-{}", uuid::Uuid::new_v4());
    let mut loader_id = initial_loader_id.clone();
    let mut document_request_started = false;

    let previous_url = page.url.clone();
    let previous_lifecycle = page.lifecycle;
    let navigation_url = url_owned.clone();
    let navigation_method = nav_method.clone();
    let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();
    let mut cancel_tx = Some(cancel_tx);
    let (nav_done_tx, mut nav_done_rx) = mpsc::channel::<(obscura_browser::Page, Result<(), String>, bool)>(1);
    let nav_v8_lock = ctx.v8_lock.clone();

    tokio::task::spawn_local(async move {
        // Issue #19: serialize this connection's V8 work across its pages. This
        // nav task runs while the connection's processor keeps pumping other CDP
        // messages via `dispatch` (which takes the same per-connection lock), so
        // both sides coordinate on one page's isolate at a time on this thread.
        // The lock is per-connection, so other connections are unaffected (#430).
        let _v8_guard = nav_v8_lock.lock_owned().await;
        // Preloads (addBinding shims, addScriptToEvaluateOnNewDocument sources)
        // must run BEFORE the page's own scripts (CDP contract). Hand them
        // to the page so navigate_single can inject them at the right point.
        page.set_preload_scripts(preload_scripts);
        let (result, cancelled) = tokio::select! {
            result = async {
                if !send_command_response {
                    page.navigate_from_document(&url_owned, &nav_method, &nav_body).await
                } else if nav_method == "POST" && !nav_body.is_empty() {
                    page.navigate_with_wait_post(&url_owned, wait_until, &nav_method, &nav_body).await
                } else {
                    page.navigate_with_wait(&url_owned, wait_until).await
                }
            } => (result.map_err(|e| e.to_string()), false),
            _ = cancel_rx => (Err("net::ERR_ABORTED".into()), true),
        };
        drop(_v8_guard);
        let _ = nav_done_tx.send((page, result, cancelled)).await;
    });

    let navigate_result: Result<(), String>;
    let page_back: Option<obscura_browser::Page>;
    let cancelled: bool;

    // Issue #19 follow-up (PR #36 maintainer's fetch-intercept repro):
    // While the spawned nav task is executing V8 (potentially parked on
    // `op_fetch_url`'s `resolve_rx.await` *with Isolate-N still entered*),
    // we must NOT let the parent's `select!` route foreign Cdp messages
    // through `process_cdp_message → dispatch → page handlers`, because
    // those handlers call `get_session_page_mut` which `suspend_js`'es
    // OTHER pages (drops their `JsRuntime`, which calls
    // `JsRealmInner::destroy`). That trips V8's
    // `heap->isolate() == Isolate::TryGetCurrent()` invariant and aborts
    // the process via `V8_Fatal`.
    //
    // This connection's `ctx.v8_lock` doesn't save us here: it's a
    // `tokio::sync::Mutex` that is released around `.await`s inside V8
    // ops, so it doesn't actually keep the V8 enter/exit pair contiguous
    // on the thread.
    //
    // Park foreign Cdp messages into the outer deferred queue so the
    // outer `cdp_processor` loop processes them after this nav fully
    // completes (and its JsRuntime is no longer in flight on the
    // LocalSet).
    loop {
        let has_irx = intercept_rx.is_some();

        tokio::select! {
            Some((returned_page, result, was_cancelled)) = nav_done_rx.recv() => {
                page_back = Some(returned_page);
                navigate_result = result;
                cancelled = was_cancelled;
                break;
            }
            Some(intercepted) = async {
                if let Some(ref mut irx) = intercept_rx {
                    irx.recv().await
                } else {
                    std::future::pending().await
                }
            }, if has_irx => {
                if is_main_document_intercept(&intercepted, &page_id) {
                    loader_id = intercepted.request_id.clone();
                    document_request_started = true;
                }
                emit_intercepted_request(
                    intercepted,
                    ctx,
                    Some((&page_id, &frame_id, session_for_events.clone())),
                    reply_tx,
                    intercepted_paused,
                );
            }
            Some(msg) = rx.recv() => {
                tracing::info!("INTERCEPTION select: received CDP message during navigation");
                match msg {
                    ServerMessage::NewConnection { reply_tx: new_tx } => {
                        // Safe: no V8 enter, just bookkeeping.
                        let pid = ctx.create_page();
                        let sid = format!("{}-session", pid);
                        ctx.sessions.insert(sid.clone(), pid.clone());
                        let _ = new_tx.send(json!({"__init": true, "pageId": pid, "sessionId": sid}).to_string());
                    }
                    ServerMessage::Cdp(msg) => {
                        if let Ok(command) = serde_json::from_str::<CdpRequest>(&msg.text) {
                            let same_page = command.session_id.as_ref()
                                .and_then(|session| ctx.sessions.get(session)) == Some(&page_id);
                            let stop = command.method == "Page.stopLoading" && same_page;
                            let close = (command.method == "Page.close" && same_page)
                                || (command.method == "Target.closeTarget"
                                    && command.params.get("targetId").and_then(|id| id.as_str()) == Some(page_id.as_str()));
                            if stop || close {
                                if let Some(cancel) = cancel_tx.take() { let _ = cancel.send(()); }
                                if stop {
                                    let response = crate::types::CdpResponse::success(command.id, json!({}), command.session_id);
                                    if let Ok(json) = serde_json::to_string(&response) { let _ = msg.reply_tx.send(json); }
                                    continue;
                                }
                            }
                        }
                        if msg.text.contains("Fetch.continueRequest")
                            || msg.text.contains("Fetch.fulfillRequest")
                            || msg.text.contains("Fetch.failRequest")
                        {
                            // Safe: only flips a oneshot to resume the parked
                            // op inside the spawned nav task. No V8 enter on
                            // this side; the actual V8 work happens back on
                            // the nav task's thread.
                            handle_fetch_resolution(&msg.text, &msg.reply_tx, intercepted_paused);
                        } else {
                            // UNSAFE during nav: would route through dispatch,
                            // which can `suspend_js` other pages and trip the
                            // V8 invariant. Defer until nav completes —
                            // pushed to the outer `cdp_processor` queue so
                            // it's processed sequentially with no nav task
                            // in flight.
                            if deferred.len() >= MAX_DEFERRED_MESSAGES {
                                tracing::warn!("INTERCEPTION: deferred queue full ({}), returning error to client", MAX_DEFERRED_MESSAGES);
                                if let Ok(req) = serde_json::from_str::<CdpRequest>(&msg.text) {
                                    let resp = crate::types::CdpResponse::error(
                                        req.id,
                                        -32000,
                                        "Server busy: navigation in progress, try again later".to_string(),
                                        req.session_id,
                                    );
                                    if let Ok(json) = serde_json::to_string(&resp) {
                                        let _ = msg.reply_tx.send(json);
                                    }
                                }
                            } else {
                                tracing::info!("INTERCEPTION: deferring CDP message until nav completes");
                                deferred.push_back(ServerMessage::Cdp(msg));
                            }
                        }
                    }
                }
            }
        }
    }

    // Deferred messages are handled by the outer `cdp_processor` loop
    // (it drains `deferred` before pulling the next message off `rx`).

    let mut page = page_back.expect("navigation task should return the page");
    let committed = page.network_events.iter().any(|event| event.resource_type == "Document")
        || page.js.as_ref().is_some_and(|js| previous_url.as_ref().is_some_and(|url| js.document_url() != url.as_str()));
    if cancelled {
        page.stop_loading();
        if committed {
            page.lifecycle = obscura_browser::LifecycleState::Failed;
            page.push_history(page.url_string());
        } else {
            page.url = previous_url;
            page.lifecycle = previous_lifecycle;
        }
        intercepted_paused.retain(|_, paused| !paused.resolver.is_closed());
    }

    // Fold in network events for script-initiated requests (fetch/XHR/dynamic
    // resource) so they emit as Network.requestWillBeSent / responseReceived
    // alongside the static navigation subresources (#406).
    page.sync_js_network_events();
    let network_events: Vec<_> = page.network_events.drain(..).collect();
    let failed_document = if document_request_started && navigate_result.is_err()
        && !network_events.iter().any(|event| event.request_id == loader_id && event.resource_type == "Document") {
        Some(loader_id.clone())
    } else { None };
    let navigation_error = navigate_result.as_ref().err().cloned();
    let page_url = page.url_string();
    loader_id = network_events.iter().rev().find(|event| event.resource_type == "Document" && event.url == page_url
        && event.request_id.strip_prefix(&page_id).is_some_and(|suffix| suffix.starts_with('.')))
        .map(|event| if event.intercepted { event.request_id.clone() } else { initial_loader_id.clone() })
        .unwrap_or_else(|| failed_document.clone().unwrap_or(initial_loader_id));
    let page_id_for_events = page.id.clone();
    let reached_network_idle = page.lifecycle.is_network_idle();

    ctx.pages.push(page);

    let response = if cancelled {
        crate::types::CdpResponse::success(req.id,
            if is_reload { json!({}) } else if committed { json!({"frameId": frame_id, "loaderId": loader_id}) }
            else { json!({"frameId": frame_id, "loaderId": loader_id, "errorText": "net::ERR_ABORTED"}) },
            req.session_id.clone())
    } else { match navigate_result {
        Ok(()) => crate::types::CdpResponse::success(
            req.id,
            if is_reload { json!({}) } else { json!({"frameId": frame_id, "loaderId": loader_id}) },
            req.session_id.clone(),
        ),
        Err(e) => crate::types::CdpResponse::error(req.id, -32000, e, req.session_id.clone()),
    }};

    if send_command_response {
        if let Ok(json) = serde_json::to_string(&response) {
            let _ = reply_tx.send(json);
        }
    }

    // Shared event emission: includes the post-#190 Network.requestWillBeSent
    // -before-frameNavigated ordering, the #189 requestId=loaderId trick that
    // makes `page.goto()` resolve to a Response, and the #192 per-isolated-
    // world fresh context ids. Pushes to `ctx.pending_events`; we then drain
    // to the WS reply channel.
    if !(cancelled && !committed) {
        if let (Some(request_id), Some(error)) = (&failed_document, &navigation_error) {
            let error = error.strip_prefix("Network error: ").unwrap_or(error);
            let error_text = if error.starts_with("net::ERR_") { error } else { "net::ERR_FAILED" };
            crate::domains::page::emit_navigation_failure(ctx, &session_for_events, request_id, &page_id_for_events, error_text);
        }
    }
    if cancelled && !committed {
        crate::domains::page::emit_aborted_navigation(ctx, &session_for_events, &frame_id,
            &loader_id, &navigation_url, &navigation_method, &page_id_for_events, document_request_started);
    } else {
        crate::domains::page::emit_navigation_events(
            ctx,
            &session_for_events,
            &frame_id,
            &loader_id,
            &page_url,
            &page_id_for_events,
            &network_events,
            wait_until,
            reached_network_idle,
        );
    }
    for event in ctx.pending_events.drain(..) {
        if let Ok(json) = serde_json::to_string(&event) {
            let _ = reply_tx.send(json);
        }
    }
}

async fn process_cdp_message(
    text: &str,
    ctx: &mut CdpContext,
    reply_tx: &mpsc::UnboundedSender<String>,
) {
    process_cdp_message_with_pending(text, ctx, reply_tx, None).await;
}

async fn process_cdp_message_with_pending(
    text: &str,
    ctx: &mut CdpContext,
    reply_tx: &mpsc::UnboundedSender<String>,
    pending_runtime: Option<&mut Vec<PendingRuntimeReply>>,
) {
    let req: CdpRequest = match serde_json::from_str(text) {
        Ok(r) => r,
        Err(e) => {
            warn!("Invalid CDP: {}: {}", e, crate::util::truncate_on_char_boundary(text, 200));
            return;
        }
    };

    tracing::debug!("CDP: {} (id={}, s={:?})", req.method, req.id, req.session_id);

    service_live_page_render_resources(ctx);
    let mut evaluation = None;
    let is_awaited = matches!(req.method.as_str(), "Runtime.evaluate" | "Runtime.callFunctionOn")
        && req.params.get("awaitPromise").and_then(|value| value.as_bool()) == Some(true);
    let response = if pending_runtime.as_ref().is_some_and(|pending| pending.len() >= MAX_DEFERRED_MESSAGES) && is_awaited {
        crate::types::CdpResponse::error(req.id, -32000, "Too many pending evaluations".into(), req.session_id.clone())
    } else if pending_runtime.is_some() {
        dispatch::dispatch_with_deferred(&req, ctx, Some(&mut evaluation)).await
    } else {
        dispatch::dispatch(&req, ctx).await
    };
    service_live_page_render_resources(ctx);

    // Chromium CDP semantics: events emitted as a side-effect of a command
    // (e.g. Target.targetCreated + Target.attachedToTarget from
    // Target.createTarget) MUST arrive BEFORE the command's response.
    // Playwright awaits the response and immediately reads state wired up
    // by those events; if the response lands first, accessing
    // Target._page errors with "Cannot read properties of undefined".
    for event in ctx.pending_events.drain(..) {
        if let Ok(json) = serde_json::to_string(&event) {
            let _ = reply_tx.send(json);
        }
    }

    if let (Some(evaluation), Some(pending)) = (evaluation, pending_runtime) {
        pending.push(PendingRuntimeReply {
            id: req.id, session_id: req.session_id, reply_tx: reply_tx.clone(), evaluation,
        });
    } else {
        if let Ok(json) = serde_json::to_string(&response) { let _ = reply_tx.send(json); }
    }

}

/// Lossy text view of a base64 CDP field, for the two callers that serve it
/// as a string. `decode_base64_bytes` is the decoder; this only flattens its
/// result the way those call sites already expect.
pub(crate) fn decode_base64(input: &str) -> String {
    String::from_utf8_lossy(&decode_base64_bytes(input).unwrap_or_default()).to_string()
}

/// Read an optional CDP `binary` parameter as the bytes it encodes.
///
/// `Ok(None)` means the field was absent, which is "leave this alone" rather
/// than "make it empty". An unparseable value is an error rather than a
/// best-effort decode: base64 that is not base64 is a client mistake, and
/// answering it silently is what let a raw-text `postData` reach the wire as
/// mangled bytes with nothing anywhere saying so.
pub(crate) fn decode_optional_binary(
    params: &serde_json::Value,
    field: &str,
    what: &str,
) -> Result<Option<Vec<u8>>, String> {
    let Some(value) = params.get(field) else {
        return Ok(None);
    };
    let raw = value.as_str().ok_or_else(|| format!("{what} must be a base64 string"))?;
    match decode_base64_bytes(raw) {
        Ok(bytes) => Ok(Some(bytes)),
        Err(why) => Err(format!("{what} is not valid base64: {why}")),
    }
}

fn decode_base64_bytes(input: &str) -> Result<Vec<u8>, String> {
    BASE64.decode(input).map_err(|error| error.to_string())
}

fn fast_path_response(text: &str) -> Option<String> {
    let req: CdpRequest = serde_json::from_str(text).ok()?;

    let result = match req.method.as_str() {
        "Network.enable" | "Network.setCacheDisabled" | "Network.setRequestInterception" |
        "Page.setInterceptFileChooserDialog" |
        "Runtime.runIfWaitingForDebugger" | "Runtime.discardConsoleEntries" |
        "Performance.enable" | "Log.enable" | "Security.enable" |
        "Emulation.setTouchEmulationEnabled" |
        "CSS.enable" | "Accessibility.enable" | "ServiceWorker.enable" |
        "Inspector.enable" | "Debugger.enable" | "Profiler.enable" |
        "HeapProfiler.enable" | "Overlay.enable" | "Storage.enable" |
        "Target.setAutoAttach" => {
            Some(json!({}))
        }
        "Browser.getVersion" => {
            Some(json!({
                "protocolVersion": "1.3",
                "product": "Chrome/145.0.0.0",
                "revision": "@0000000000000000000000000000000000000000",
                "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
                "jsVersion": "14.5.0.0",
            }))
        }
        "Browser.setDownloadBehavior" | "Browser.getWindowBounds" => {
            Some(json!({}))
        }
        _ => None,
    };

    if let Some(value) = result {
        let resp = crate::types::CdpResponse::success(req.id, value, req.session_id);
        serde_json::to_string(&resp).ok()
    } else {
        None
    }
}

async fn handle_connection_ws(
    stream: TcpStream,
    msg_tx: mpsc::UnboundedSender<ServerMessage>,
) -> anyhow::Result<()> {
    // tokio_tungstenite wraps the stream in a 128 KiB write BufWriter by
    // default. CDP traffic is many small (~100-byte) frames, and that buffer
    // adds extra latency per frame. write_buffer_size=0 makes every WS write
    // hit the socket directly. Combined with set_nodelay(true) above, gets
    // per-frame latency on localhost down toward ideal.
    use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
    let mut cfg = WebSocketConfig::default();
    cfg.write_buffer_size = 0;
    cfg.max_write_buffer_size = 64 << 20;
    let ws_stream = tokio_tungstenite::accept_async_with_config(stream, Some(cfg)).await?;
    info!("WebSocket connected");
    let (mut ws_sender, mut ws_receiver) = ws_stream.split();

    let (reply_tx, mut reply_rx) = mpsc::unbounded_channel::<String>();

    let _ = msg_tx.send(ServerMessage::NewConnection {
        reply_tx: reply_tx.clone(),
    });
    if let Some(init_msg) = reply_rx.recv().await {
        tracing::debug!("Connection init: {}", &init_msg[..init_msg.len().min(100)]);
    }

    let send_task = tokio::task::spawn_local(async move {
        while let Some(msg) = reply_rx.recv().await {
            if msg.contains("\"__init\"") {
                continue;
            }
            if ws_sender.send(Message::Text(msg.into())).await.is_err() {
                break;
            }
        }
    });

    while let Some(msg) = ws_receiver.next().await {
        let msg = match msg {
            Ok(m) => m,
            Err(e) => {
                warn!("WS read error: {}", e);
                break;
            }
        };

        match msg {
            Message::Text(text) => {
                if text.contains("\"Browser.close\"") {
                    if let Ok(req) = serde_json::from_str::<CdpRequest>(&text) {
                        let resp = crate::types::CdpResponse::success(req.id, json!({}), None);
                        if let Ok(json) = serde_json::to_string(&resp) {
                            let _ = reply_tx.send(json);
                        }
                    }
                    break;
                }

                if let Some(resp) = fast_path_response(&text) {
                    let _ = reply_tx.send(resp);
                } else {
                    let _ = msg_tx.send(ServerMessage::Cdp(CdpMessage {
                        text: text.to_string(),
                        reply_tx: reply_tx.clone(),
                    }));
                }
            }
            Message::Close(_) => {
                info!("WS closed by client");
                break;
            }
            _ => {}
        }
    }

    send_task.abort();
    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    fn local_storage_delta_does_not_discard_existing_values_when_profile_is_full() {
        use obscura_js::ops::OriginStorage;
        let origin = "https://app.test";
        let initial = OriginStorage::default();
        let current = initial.isolated_snapshot();
        assert!(current.set(origin, "new".into(), "value".into()));
        let destination = OriginStorage::default();
        assert!(destination.load(origin, vec![("k".into(), "x".repeat(5 * 1024 * 1024 - 1))]));
        super::merge_local_storage_delta(&destination, &initial, &current);
        assert_eq!(destination.len(origin), 1);
        assert_eq!(destination.key(origin, 0).as_deref(), Some("k"));
        assert!(!destination.is_dirty());
    }

    #[test]
    fn local_storage_delta_preserves_other_clients_values_and_key_order() {
        use obscura_js::ops::OriginStorage;
        let origin = "https://app.test";
        let initial = OriginStorage::default();
        assert!(initial.load(origin, vec![("sid".into(), "old".into()), ("gone".into(), "x".into())]));
        let current = initial.isolated_snapshot();
        current.remove(origin, "gone");
        assert!(current.set(origin, "first".into(), "1".into()));
        assert!(current.set(origin, "second".into(), "2".into()));
        let destination = OriginStorage::default();
        assert!(destination.load(origin, vec![("a".into(), "A".into()),
            ("sid".into(), "newer".into()), ("gone".into(), "x".into())]));
        super::merge_local_storage_delta(&destination, &initial, &current);
        assert_eq!(destination.snapshot(origin), vec![("a".into(), "A".into()),
            ("sid".into(), "newer".into()), ("first".into(), "1".into()), ("second".into(), "2".into())]);
        super::merge_local_storage_delta(&destination, &initial, &initial);
        assert_eq!(destination.get(origin, "sid").as_deref(), Some("newer"));
    }

    use super::{
        bearer_authorized, control_refusal, handle_fetch_resolution, is_navigate_method,
        merge_cookie_delta, parse_cdp_headers, pump_live_page_event_loop,
        websocket_authority, ControlRefusal,
    };
    #[cfg(feature = "render")]
    use super::pump_and_forward_screencast_frames;
    use obscura_net::{CookieInfo, CookieJar};
    use serde_json::json;
    use std::collections::HashMap;

    #[test]
    fn connection_memory_trim_preserves_interval_and_idle_behavior() {
        use std::sync::atomic::{AtomicU64, Ordering};
        let last = AtomicU64::new(0);
        for (now, idle, expected, timestamp) in [
            (100, false, true, 100),
            (100, false, false, 100),
            (5_099, false, false, 100),
            (5_100, false, true, 5_100),
            (5_101, true, true, 5_101),
            (100, true, true, 5_101),
            (5_102, false, false, 5_101),
        ] {
            assert_eq!(super::claim_connection_memory_trim(&last, now, idle), expected);
            assert_eq!(last.load(Ordering::Relaxed), timestamp);
        }
    }

    #[test]
    fn busy_connection_memory_trim_has_one_winner_per_interval() {
        use std::sync::{atomic::{AtomicU64, AtomicUsize, Ordering}, Barrier};
        let last = AtomicU64::new(0);
        let winners = AtomicUsize::new(0);
        let barrier = Barrier::new(16);
        std::thread::scope(|scope| {
            for _ in 0..16 {
                scope.spawn(|| {
                    for round in 1..=2_000 {
                        barrier.wait();
                        if super::claim_connection_memory_trim(&last, round * 5_000, false) {
                            winners.fetch_add(1, Ordering::Relaxed);
                        }
                        barrier.wait();
                    }
                });
            }
        });
        assert_eq!(winners.load(Ordering::Relaxed), 2_000);
    }

    #[test]
    fn intercepted_request_is_observable_without_sharing_fetch_control() {
        let mut ctx = crate::dispatch::CdpContext::new();
        let page = ctx.create_page();
        let other = ctx.create_page();
        ctx.sessions.insert("driver".into(), page.clone());
        ctx.sessions.insert("observer".into(), page.clone());
        ctx.sessions.insert("unrelated".into(), other);
        let (resolver, _resolution) = tokio::sync::oneshot::channel();
        let intercepted = obscura_js::ops::InterceptedRequest {
            request_id: "fetch-1".into(), page_id: page.clone(), url: "https://example.test/data".into(),
            method: "GET".into(), headers: Default::default(), resource_type: "Fetch".into(), resolver,
        };
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut paused = HashMap::new();
        super::emit_intercepted_request(intercepted, &ctx, Some((&page, "frame-1", Some("driver".into()))), &tx, &mut paused);
        let driver: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
        let observer: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
        let pause: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
        assert_eq!(driver["method"], "Network.requestWillBeSent");
        assert_eq!(observer["method"], driver["method"]);
        assert_eq!(observer["params"], driver["params"]);
        assert_eq!(observer["sessionId"], "observer");
        assert_eq!(pause["method"], "Fetch.requestPaused");
        assert_eq!(pause["sessionId"], "driver");
        assert_eq!(paused.len(), 1);
        assert!(paused.contains_key("fetch-1"));
        assert!(rx.try_recv().is_err());
    }

    #[test]
    fn intercepted_documents_keep_their_own_loader_and_page_identity() {
        let mut ctx = crate::dispatch::CdpContext::new();
        let navigating = ctx.create_page();
        let other = ctx.create_page();
        ctx.sessions.insert("driver".into(), navigating.clone());
        ctx.sessions.insert("other-driver".into(), other.clone());
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut paused = HashMap::new();
        let navigation_id = format!("{navigating}.1");
        let other_id = format!("{other}.1");
        for (page, request_id, expected_loader) in [(&navigating, navigation_id.as_str(), navigation_id.as_str()),
            (&other, other_id.as_str(), ""), (&navigating, "fetch-iframe", "")] {
            let (resolver, _resolution) = tokio::sync::oneshot::channel();
            let intercepted = obscura_js::ops::InterceptedRequest {
                request_id: request_id.into(), page_id: page.clone(), url: "http://example.test/".into(),
                method: "GET".into(), headers: Default::default(), resource_type: "Document".into(), resolver,
            };
            super::emit_intercepted_request(intercepted, &ctx,
                Some((&navigating, "frame-nav", Some("driver".into()))), &tx, &mut paused);
            let request: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
            let pause: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
            assert_eq!(request["params"]["requestId"], request_id);
            assert_eq!(request["params"]["loaderId"], expected_loader);
            assert_eq!(pause["params"]["networkId"], request_id);
        }
        assert_eq!(paused.len(), 3);
    }

    #[test]
    fn lifecycle_subscription_commands_reach_the_stateful_dispatcher() {
        for enabled in [true, false] {
            let request = json!({
                "id": 1,
                "method": "Page.setLifecycleEventsEnabled",
                "params": {"enabled": enabled},
                "sessionId": "page-session",
            });
            assert!(super::fast_path_response(&request.to_string()).is_none(),
                "lifecycle subscriptions must not be acknowledged without updating state");
        }
    }

    fn native_head(host: &str) -> String {
        format!(
            "GET /devtools/browser HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"
        )
    }

    #[test]
    fn control_endpoints_only_match_the_request_target() {
        use std::io::{Read, Write};
        for (target, extra, endpoint) in [
            ("/json/version", "", Some("Browser")),
            ("/json/version?client=test", "", Some("Browser")),
            ("/json/version/", "", Some("Browser")),
            ("/json/version/?client=test", "", Some("Browser")),
            ("/json/list/", "", Some("webSocketDebuggerUrl")),
            ("/json/", "", Some("webSocketDebuggerUrl")),
            ("/json/protocol/", "", Some("version")),
            ("/json/list", "", Some("webSocketDebuggerUrl")),
            ("/json", "", Some("webSocketDebuggerUrl")),
            ("/json/protocol", "", Some("version")),
            ("/devtools/browser", "X-Route: /json/list\r\n", None),
            ("/devtools/browser?next=/json/version", "", None),
            ("/json/versionify", "", None),
            ("/json/list-extra", "", None),
            ("/json/version/extra", "", None),
            ("/json/list/extra", "", None),
            ("http://{authority}/json/version/?client=test", "", Some("Browser")),
            ("http://{authority}/json/version", "", Some("Browser")),
            ("http://{authority}/json/list?client=test", "", Some("webSocketDebuggerUrl")),
            ("http://{authority}/devtools/browser?next=/json/version", "", None),
        ] {
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            let address = listener.local_addr().unwrap();
            let mut client = std::net::TcpStream::connect(address).unwrap();
            client.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap();
            let (server, _) = listener.accept().unwrap();
            let target = target.replace("{authority}", &address.to_string());
            let head = format!("GET {target} HTTP/1.1\r\nHost: {address}\r\n{extra}\r\n");
            client.write_all(head.as_bytes()).unwrap();
            let (tx, mut rx) = tokio::sync::mpsc::channel(1);
            super::accept_dispatch(server, address.ip(), address.port(), None, None, None, &tx, &head).unwrap();
            if let Some(key) = endpoint {
                assert!(rx.try_recv().is_err(), "HTTP endpoint must not be forwarded: {target}");
                let mut response = String::new();
                client.read_to_string(&mut response).unwrap();
                assert!(response.starts_with("HTTP/1.1 200"), "{response}");
                assert!(response.contains(key), "{target}: {response}");
            } else {
                assert!(rx.try_recv().is_ok(), "WebSocket request must not match a header or partial endpoint: {target}");
            }
        }
    }

    #[test]
    fn native_loopback_cdp_request_is_allowed() {
        let head = native_head("127.0.0.1:9222");
        assert_eq!(
            control_refusal(&head, "127.0.0.1".parse().unwrap(), 9222, None, None, None),
            None
        );
    }

    #[test]
    fn browser_origin_and_rebound_host_are_refused() {
        let with_origin = native_head("127.0.0.1:9222").replace(
            "Upgrade: websocket",
            "Origin: https://evil.example\r\nUpgrade: websocket",
        );
        assert_eq!(
            control_refusal(
                &with_origin,
                "127.0.0.1".parse().unwrap(),
                9222,
                None,
                None,
                None,
            ),
            Some(ControlRefusal::BrowserOrigin("https://evil.example".to_owned()))
        );
        assert_eq!(
            control_refusal(
                &native_head("rebind.example:9222"),
                "127.0.0.1".parse().unwrap(),
                9222,
                None,
                None,
                None,
            ),
            Some(ControlRefusal::ForeignHost)
        );
    }

    #[test]
    fn loopback_worker_accepts_only_its_forwarded_public_port() {
        let bind = "127.0.0.1".parse().unwrap();
        let forwarded = Some((bind, 9222));
        assert_eq!(
            control_refusal(&native_head("127.0.0.1:9222"), bind, 9223, forwarded, None, None),
            None
        );
        assert_eq!(
            control_refusal(
                &native_head("rebind.example:9222"),
                bind,
                9223,
                forwarded,
                None,
                None,
            ),
            Some(ControlRefusal::ForeignHost)
        );
        assert_eq!(
            control_refusal(&native_head("127.0.0.1:9444"), bind, 9223, forwarded, None, None),
            Some(ControlRefusal::ForeignHost)
        );
    }

    #[test]
    fn public_worker_authority_still_requires_authentication() {
        let bind = "127.0.0.1".parse().unwrap();
        let public = Some(("0.0.0.0".parse().unwrap(), 9222));
        let head = native_head("cdp.example.test:9222");
        assert_eq!(
            control_refusal(&head, bind, 9223, public, Some("secret"), None),
            Some(ControlRefusal::Unauthorized)
        );
    }

    #[test]
    fn endpoint_origins_are_accepted_without_configuration() {
        for (origin, host) in [
            ("http://127.0.0.1:9222", "127.0.0.1:9222"),
            ("HTTP://LOCALHOST:9222", "localhost:9222"),
            ("http://[::1]:9222", "[::1]:9222"),
            ("http://192.168.1.10:9333", "192.168.1.10:9333"),
            ("http://localhost", "localhost:80"),
            ("http://cdp.example.test:9222", "cdp.example.test:9222"),
        ] {
            assert!(super::origin_accepted(origin, Some(host), None), "{origin}");
        }
    }

    #[test]
    fn foreign_and_malformed_origins_stay_refused_without_configuration() {
        for origin in [
            "https://evil.example",
            "http://evil.example:8080",
            "http://rebind.example:9222",
            "http://127.0.0.1:7777",
            "http://localhost:9222",
            "https://127.0.0.1:9222",
            "http://[email protected]:9222",
            "http://user:[email protected]:9222",
            "http://127.0.0.1:9222/path",
            "http://127.0.0.1:9222/?query",
            "http://127.0.0.1:9222/#fragment",
            "http:127.0.0.1:9222",
            "null",
            "",
        ] {
            assert!(!super::origin_accepted(origin, Some("127.0.0.1:9222"), None), "{origin}");
        }
        assert!(!super::origin_accepted("http://127.0.0.1:9222", None, None));
    }

    #[test]
    fn allowed_origins_list_overrides_the_default_policy() {
        let host = Some("127.0.0.1:9222");
        let list = Some("http://dev.example:4173, https://tunnel.example");
        assert!(super::origin_accepted("http://dev.example:4173", host, list));
        assert!(super::origin_accepted("https://tunnel.example", host, list));
        assert!(super::origin_accepted("  https://tunnel.example ", host, list));
        assert!(!super::origin_accepted("http://other.example", host, list));
        assert!(super::origin_accepted("http://anything.example", host, Some("*")));
        assert!(super::origin_accepted("null", host, Some("null")));
        assert!(super::origin_accepted("HTTP://DEV.EXAMPLE:4173", host, list));
    }

    #[test]
    fn allowed_origins_preserve_forwarded_host_and_authentication_checks() {
        let bind = "127.0.0.1".parse().unwrap();
        let forwarded = Some((bind, 9222));
        let token = "01234567890123456789012345678901";
        let with_origin = |host, origin| native_head(host).replace(
            "Upgrade: websocket", &format!("Origin: {origin}\r\nUpgrade: websocket"),
        );
        assert_eq!(control_refusal(
            &with_origin("127.0.0.1:9222", "http://127.0.0.1:9222"),
            bind, 9223, forwarded, None, None,
        ), None);
        assert_eq!(control_refusal(
            &with_origin("rebind.example:9222", "http://rebind.example:9222"),
            bind, 9223, forwarded, None, Some("*"),
        ), Some(ControlRefusal::ForeignHost));
        assert_eq!(control_refusal(
            &with_origin("127.0.0.1:9222", "https://allowed.example"),
            bind, 9223, forwarded, Some(token), Some("https://allowed.example"),
        ), Some(ControlRefusal::Unauthorized));
        let authenticated = with_origin("cdp.example.test:9222", "http://cdp.example.test:9222")
            .replace("Upgrade: websocket", &format!("Authorization: Bearer {token}\r\nUpgrade: websocket"));
        assert_eq!(control_refusal(
            &authenticated, bind, 9223, Some(("0.0.0.0".parse().unwrap(), 9222)),
            Some(token), None,
        ), None);
    }

    #[test]
    fn configured_cdp_token_is_mandatory() {
        let token = "01234567890123456789012345678901";
        let mut head = native_head("127.0.0.1:9222");
        assert!(!bearer_authorized(&head, Some(token)));
        head = head.replace(
            "Upgrade: websocket",
            &format!("Authorization: Bearer {token}\r\nUpgrade: websocket"),
        );
        assert!(bearer_authorized(&head, Some(token)));
    }

    #[test]
    fn discovery_uses_the_client_facing_http_authority() {
        let request = "GET /json/version HTTP/1.1\r\nhOsT: cdp.example.test:9222\r\n\r\n";
        assert_eq!(
            websocket_authority(request, 9223),
            "cdp.example.test:9222"
        );

        let malformed = "GET /json/version HTTP/1.1\r\nHost: attacker.test/path\r\n\r\n";
        assert_eq!(websocket_authority(malformed, 9223), "127.0.0.1:9223");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn websocket_replies_are_not_blocked_by_renderer_tasks() {
        use futures_util::{SinkExt, StreamExt};
        use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
        use std::time::{Duration, Instant};
        use tokio_tungstenite::tungstenite::Message;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let live = Arc::new(AtomicUsize::new(1));
        let live_server = live.clone();
        let accept = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            stream.set_nodelay(true).unwrap();
            let context = crate::dispatch::CdpContext::new().default_context;
            super::run_connection(stream.into_std().unwrap(), context.clone(), context,
                Arc::new(std::sync::Mutex::new(())), Arc::new(tokio::sync::Notify::new()), live_server);
        });
        let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{address}/devtools/browser")).await.unwrap();
        accept.await.unwrap();
        ws.send(Message::Text(json!({"id":1,"method":"Target.createTarget","params":{"url":"about:blank"}}).to_string().into())).await.unwrap();
        let mut session = None;
        loop {
            let msg = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();
            if let Message::Text(text) = msg {
                let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                if let Some(sid) = value["params"]["sessionId"].as_str() { session = Some(sid.to_string()); }
                if value["id"] == 1 { break; }
            }
        }
        let started = Instant::now();
        ws.send(Message::Text(json!({"id":2,"method":"Runtime.evaluate","sessionId":session.as_ref().unwrap(),
            "params":{"expression":"setTimeout(() => { const end=Date.now()+600; while(Date.now()<end){} },0); { const end=Date.now()+30; while(Date.now()<end){} }; 'armed'","returnByValue":true}}).to_string().into())).await.unwrap();
        loop {
            let msg = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();
            if let Message::Text(text) = msg {
                let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                if value["id"] == 2 {
                    assert!(value.get("error").is_none(), "{value}");
                    break;
                }
            }
        }
        assert!(started.elapsed() < Duration::from_millis(300),
            "a completed reply was trapped behind unrelated renderer work: {:?}", started.elapsed());
        tokio::time::sleep(Duration::from_millis(650)).await;
        ws.send(Message::Text(json!({"id":3,"method":"Runtime.evaluate","sessionId":session.as_ref().unwrap(),
            "params":{"expression":"new Promise(() => {})","awaitPromise":true}}).to_string().into())).await.unwrap();
        tokio::time::sleep(Duration::from_millis(25)).await;
        ws.close(None).await.unwrap();
        tokio::time::timeout(Duration::from_secs(5), async {
            while live.load(Ordering::Acquire) != 0 {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        }).await.expect("connection and I/O threads must stop on socket close");
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn connection_survives_deep_parser_and_scripted_layouts() {
        use futures_util::{SinkExt, StreamExt};
        use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
        use std::time::Duration;
        use tokio::sync::Notify;
        use tokio_tungstenite::tungstenite::Message;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let live = Arc::new(AtomicUsize::new(1));
        let live_server = live.clone();
        let accept = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let context = crate::dispatch::CdpContext::new().default_context;
            super::run_connection(stream.into_std().unwrap(), context.clone(), context,
                Arc::new(std::sync::Mutex::new(())), Arc::new(Notify::new()), live_server);
        });
        let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{address}/devtools/browser")).await.unwrap();
        accept.await.unwrap();
        ws.send(Message::Text(json!({"id":1,"method":"Target.createTarget",
            "params":{"url":"about:blank"}}).to_string().into())).await.unwrap();
        let target_id = loop {
            let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();
            if let Message::Text(text) = message {
                let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                if value["id"] == 1 {
                    break value["result"]["targetId"].as_str().unwrap().to_string();
                }
            }
        };
        let session = format!("{target_id}-session");
        let scripted = "(function(){document.body.textContent='';let parent=document.body;for(let i=0;i<1500;i++){const child=document.createElement('div');parent.appendChild(child);parent=child}parent.textContent='content';const r=document.body.getBoundingClientRect();return {height:r.height,nodes:document.querySelectorAll('div').length}})()";
        for (index, (count, with_mutations)) in [(400, false), (10000, false), (1500, true)].into_iter().enumerate() {
            let expression = if with_mutations {
                scripted.to_string()
            } else {
                format!("(function(){{document.body.innerHTML='<div>'.repeat({count})+'content';const r=document.body.getBoundingClientRect();return {{height:r.height,nodes:document.querySelectorAll('div').length}}}})()")
            };
            let id = index + 2;
            ws.send(Message::Text(json!({"id":id,"method":"Runtime.evaluate","sessionId":session,
                "params":{"expression":expression,"returnByValue":true}}).to_string().into())).await.unwrap();
            loop {
                let message = tokio::time::timeout(Duration::from_secs(20), ws.next()).await.unwrap().unwrap().unwrap();
                if let Message::Text(text) = message {
                    let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                    if value["id"] == id {
                        assert!(value["error"].is_null(), "{value}");
                        assert!(value["result"]["exceptionDetails"].is_null(), "{value}");
                        assert_eq!(value["result"]["result"]["value"]["nodes"].as_u64(), Some(count), "{value}");
                        assert!(value["result"]["result"]["value"]["height"].as_f64().unwrap() > 0.0, "{value}");
                        break;
                    }
                }
            }
        }
        ws.close(None).await.unwrap();
        tokio::time::timeout(Duration::from_secs(5), async {
            while live.load(Ordering::Acquire) != 0 {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        }).await.expect("deep-document connection must release its slot");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn busy_page_tcp_resets_release_every_connection() {
        use futures_util::{SinkExt, StreamExt};
        use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
        use std::time::Duration;
        use tokio_tungstenite::{MaybeTlsStream, tungstenite::Message};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let live = Arc::new(AtomicUsize::new(0));
        let live_server = live.clone();
        let accept = tokio::spawn(async move {
            let context = crate::dispatch::CdpContext::new().default_context;
            for _ in 0..8 {
                let (stream, _) = listener.accept().await.unwrap();
                live_server.fetch_add(1, Ordering::AcqRel);
                super::run_connection(stream.into_std().unwrap(), context.clone(), context.clone(),
                    Arc::new(std::sync::Mutex::new(())), Arc::new(tokio::sync::Notify::new()), live_server.clone());
            }
        });
        for _ in 0..8 {
            let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{address}/devtools/browser")).await.unwrap();
            ws.send(Message::Text(json!({"id":1,"method":"Target.createTarget",
                "params":{"url":"about:blank"}}).to_string().into())).await.unwrap();
            let target_id = loop {
                let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();
                if let Message::Text(text) = message {
                    let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                    if value["id"] == 1 {
                        break value["result"]["targetId"].as_str().unwrap().to_string();
                    }
                }
            };
            ws.send(Message::Text(json!({"id":2,"method":"Runtime.evaluate",
                "sessionId":format!("{target_id}-session"),
                "params":{"expression":"requestAnimationFrame(function busy(){requestAnimationFrame(busy)});const channel=new MessageChannel();channel.port1.onmessage=()=>channel.port2.postMessage(null);channel.port2.postMessage(null);'armed'","returnByValue":true}})
                .to_string().into())).await.unwrap();
            loop {
                let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();
                if let Message::Text(text) = message {
                    let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                    if value["id"] == 2 {
                        assert_eq!(value["result"]["result"]["value"], "armed", "{value}");
                        break;
                    }
                }
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
            // Zero linger sends an RST without a WebSocket close handshake.
            #[allow(deprecated)]
            match ws.get_mut() {
                MaybeTlsStream::Plain(stream) => stream.set_linger(Some(Duration::ZERO)).unwrap(),
                _ => panic!("local ws connection unexpectedly used TLS"),
            }
            drop(ws);
            tokio::time::timeout(Duration::from_secs(5), async {
                while live.load(Ordering::Acquire) != 0 {
                    tokio::time::sleep(Duration::from_millis(10)).await;
                }
            }).await.expect("busy disconnected page must release its connection");
        }
        accept.await.unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn connection_fetch_progresses_during_continuously_ready_page_tasks() {
        use futures_util::{SinkExt, StreamExt};
        use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
        use std::time::{Duration, Instant};
        use tokio_tungstenite::tungstenite::Message;

        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let http = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}/hydrate", http.local_addr().unwrap());
        std::thread::spawn(move || {
            use std::io::{Read, Write};
            for _ in 0..3 {
                let (mut stream, _) = http.accept().unwrap();
                let mut request = [0u8; 2048];
                stream.read(&mut request).unwrap();
                std::thread::sleep(Duration::from_millis(20));
                stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\nhydrated").unwrap();
            }
        });
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let live = Arc::new(AtomicUsize::new(1));
        let live_server = live.clone();
        let accept = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            stream.set_nodelay(true).unwrap();
            let context = crate::dispatch::CdpContext::new().default_context;
            super::run_connection(stream.into_std().unwrap(), context.clone(), context,
                Arc::new(std::sync::Mutex::new(())), Arc::new(tokio::sync::Notify::new()), live_server);
        });
        let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{address}/devtools/browser")).await.unwrap();
        accept.await.unwrap();
        ws.send(Message::Text(json!({"id":1,"method":"Target.createTarget","params":{"url":"about:blank"}}).to_string().into())).await.unwrap();
        let mut session = None;
        loop {
            let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();
            if let Message::Text(text) = message {
                let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                if let Some(id) = value["params"]["sessionId"].as_str() { session = Some(id.to_string()); }
                if value["id"] == 1 { break; }
            }
        }
        let body = format!(r#"
            const channel = new MessageChannel();
            const deadline = Date.now() + 5000;
            let turns = 0;
            channel.port1.onmessage = () => {{
                turns++;
                const taskEnd = Date.now() + 60;
                while (Date.now() < taskEnd) {{}}
                if (Date.now() < deadline) channel.port2.postMessage(null);
            }};
            channel.port2.postMessage(null);
            const text = await (await fetch({url:?})).text();
            channel.port1.close(); channel.port2.close();
            return {{text, turns}};
        "#);
        for (id, method, params) in [
            (2, "Runtime.evaluate", json!({"expression":format!("(async()=>{{{body}}})()"),"awaitPromise":true,"returnByValue":true})),
            (3, "Runtime.callFunctionOn", json!({"functionDeclaration":format!("async function(){{{body}}}"),"awaitPromise":true,"returnByValue":true})),
        ] {
            let started = Instant::now();
            ws.send(Message::Text(json!({"id":id,"method":method,"sessionId":session,"params":params}).to_string().into())).await.unwrap();
            loop {
                let message = tokio::time::timeout(Duration::from_secs(8), ws.next()).await.unwrap().unwrap().unwrap();
                if let Message::Text(text) = message {
                    let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                    if value["id"] == id {
                        assert_eq!(value["result"]["result"]["value"]["text"], "hydrated", "{value}");
                        assert!(value["result"]["result"]["value"]["turns"].as_f64().unwrap() > 0.0);
                        break;
                    }
                }
            }
            assert!(started.elapsed() < Duration::from_secs(2),
                "{method} starved network work behind ready page tasks: {:?}", started.elapsed());
        }
        ws.send(Message::Text(json!({"id":4,"method":"Runtime.evaluate","sessionId":session,
            "params":{"expression":format!("(async()=>{{{body}}})().then(value => globalThis.__autonomousFetch = value); 'armed'"),"returnByValue":true}}).to_string().into())).await.unwrap();
        loop {
            let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();
            if let Message::Text(text) = message {
                let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                if value["id"] == 4 {
                    assert_eq!(value["result"]["result"]["value"], "armed", "{value}");
                    break;
                }
            }
        }
        // No awaited command drives this fetch: the idle browser pump must
        // share the owning Tokio runtime with the network tasks too.
        tokio::time::sleep(Duration::from_millis(1200)).await;
        ws.send(Message::Text(json!({"id":5,"method":"Runtime.evaluate","sessionId":session,
            "params":{"expression":"globalThis.__autonomousFetch","returnByValue":true}}).to_string().into())).await.unwrap();
        loop {
            let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();
            if let Message::Text(text) = message {
                let value: serde_json::Value = serde_json::from_str(&text).unwrap();
                if value["id"] == 5 {
                    assert_eq!(value["result"]["result"]["value"]["text"], "hydrated",
                        "autonomous page tasks starved background networking: {value}");
                    break;
                }
            }
        }
        ws.close(None).await.unwrap();
        tokio::time::timeout(Duration::from_secs(5), async {
            while live.load(Ordering::Acquire) != 0 { tokio::time::sleep(Duration::from_millis(10)).await; }
        }).await.expect("connection must release its slot");
    }

    fn cookie(name: &str, value: &str) -> CookieInfo {
        CookieInfo {
            name: name.to_string(),
            value: value.to_string(),
            domain: "example.com".to_string(),
            path: "/".to_string(),
            secure: false,
            http_only: false,
            same_site: "Lax".to_string(),
            expires: None,
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn page_runtime_advances_while_cdp_client_is_silent() {
        tokio::task::LocalSet::new()
            .run_until(async {
                let (server_tx, server_rx) = tokio::sync::mpsc::unbounded_channel();
                let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
                let shutdown = std::sync::Arc::new(tokio::sync::Notify::new());
                let default_context = crate::dispatch::CdpContext::new().default_context;
                let processor = tokio::task::spawn_local(super::cdp_processor(
                    server_rx,
                    default_context,
                    shutdown,
                ));

                server_tx
                    .send(super::ServerMessage::NewConnection {
                        reply_tx: reply_tx.clone(),
                    })
                    .unwrap();
                let init = reply_rx.recv().await.expect("processor init");
                assert!(init.contains("__init"));

                let send = |value: serde_json::Value| {
                    server_tx
                        .send(super::ServerMessage::Cdp(super::CdpMessage {
                            text: value.to_string(),
                            reply_tx: reply_tx.clone(),
                        }))
                        .unwrap();
                };
                send(json!({
                    "id": 1,
                    "method": "Target.createTarget",
                    "params": {"url": "about:blank"},
                }));

                let mut session_id = None;
                loop {
                    let value: serde_json::Value = serde_json::from_str(
                        &tokio::time::timeout(
                            std::time::Duration::from_secs(2),
                            reply_rx.recv(),
                        )
                        .await
                        .expect("create target response timeout")
                        .expect("create target response channel"),
                    )
                    .unwrap();
                    if session_id.is_none() {
                        session_id = value["params"]["sessionId"]
                            .as_str()
                            .map(str::to_string);
                    }
                    if value["id"] == 1 {
                        break;
                    }
                }
                let session_id = session_id.expect("attached page session");

                send(json!({
                    "id": 2,
                    "method": "Runtime.evaluate",
                    "sessionId": session_id,
                    "params": {
                        "expression": "(() => { setTimeout(() => { globalThis.__autonomousDone = 'yes'; history.replaceState({}, '', '#silent'); }, 40); return 'armed'; })()",
                        "returnByValue": true,
                    },
                }));
                loop {
                    let value: serde_json::Value = serde_json::from_str(
                        &tokio::time::timeout(
                            std::time::Duration::from_secs(2),
                            reply_rx.recv(),
                        )
                        .await
                        .expect("timer arm response timeout")
                        .expect("timer arm response channel"),
                    )
                    .unwrap();
                    if value["id"] == 2 {
                        break;
                    }
                }

                // This is deliberately host/client time. No CDP message is sent
                // while the timeout becomes due; Chrome's renderer still runs,
                // and Obscura's connection-owned page pump must do the same.
                loop {
                    let value: serde_json::Value = serde_json::from_str(
                        &tokio::time::timeout(
                            std::time::Duration::from_secs(2), reply_rx.recv(),
                        ).await.expect("silent history navigation event timeout")
                            .expect("navigation event channel"),
                    ).unwrap();
                    if value["method"] == "Page.navigatedWithinDocument" {
                        assert_eq!(value["sessionId"], session_id);
                        assert_eq!(value["params"]["url"], "about:blank#silent");
                        assert_eq!(value["params"]["navigationType"], "historyApi");
                        break;
                    }
                }

                send(json!({
                    "id": 3,
                    "method": "Runtime.evaluate",
                    "sessionId": session_id,
                    "params": {
                        "expression": "globalThis.__autonomousDone || 'missing'",
                        "returnByValue": true,
                    },
                }));
                loop {
                    let value: serde_json::Value = serde_json::from_str(
                        &tokio::time::timeout(
                            std::time::Duration::from_secs(2),
                            reply_rx.recv(),
                        )
                        .await
                        .expect("timer observation response timeout")
                        .expect("timer observation response channel"),
                    )
                    .unwrap();
                    if value["id"] == 3 {
                        assert_eq!(value["result"]["result"]["value"], "yes");
                        break;
                    }
                }

                drop(server_tx);
                tokio::time::timeout(std::time::Duration::from_secs(2), processor)
                    .await
                    .expect("processor shutdown timeout")
                    .expect("processor task");
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn click_navigation_acknowledges_input_before_navigation_events() {
        tokio::task::LocalSet::new()
            .run_until(async {
                let (server_tx, server_rx) = tokio::sync::mpsc::unbounded_channel();
                let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
                let shutdown = std::sync::Arc::new(tokio::sync::Notify::new());
                let default_context = crate::dispatch::CdpContext::new().default_context;
                let processor = tokio::task::spawn_local(super::cdp_processor(
                    server_rx,
                    default_context,
                    shutdown,
                ));

                server_tx
                    .send(super::ServerMessage::NewConnection {
                        reply_tx: reply_tx.clone(),
                    })
                    .unwrap();
                reply_rx.recv().await.expect("processor init");

                let send = |value: serde_json::Value| {
                    server_tx
                        .send(super::ServerMessage::Cdp(super::CdpMessage {
                            text: value.to_string(),
                            reply_tx: reply_tx.clone(),
                        }))
                        .unwrap();
                };
                send(json!({
                    "id": 1,
                    "method": "Target.createTarget",
                    "params": {"url": "about:blank"},
                }));

                let mut session_id = None;
                loop {
                    let value: serde_json::Value = serde_json::from_str(
                        &tokio::time::timeout(std::time::Duration::from_secs(2), reply_rx.recv())
                            .await
                            .expect("create target timeout")
                            .expect("create target response"),
                    )
                    .unwrap();
                    if session_id.is_none() {
                        session_id = value["params"]["sessionId"].as_str().map(str::to_string);
                    }
                    if value["id"] == 1 {
                        break;
                    }
                }
                let session_id = session_id.expect("attached page session");

                send(json!({
                    "id": 2,
                    "method": "Runtime.evaluate",
                    "sessionId": session_id,
                    "params": {"expression": "document.body.innerHTML='<a id=route href=\"data:text/html,navigated\">go</a>';document.elementFromPoint=()=>route"},
                }));
                loop {
                    let value: serde_json::Value = serde_json::from_str(
                        &tokio::time::timeout(std::time::Duration::from_secs(2), reply_rx.recv())
                            .await
                            .expect("setup timeout")
                            .expect("setup response"),
                    )
                    .unwrap();
                    if value["id"] == 2 {
                        break;
                    }
                }

                for (id, event_type) in [(3, "mousePressed"), (4, "mouseReleased")] {
                    send(json!({
                        "id": id,
                        "method": "Input.dispatchMouseEvent",
                        "sessionId": session_id,
                        "params": {"type": event_type, "x": 0, "y": 0, "button": "left"},
                    }));
                    if id == 3 {
                        loop {
                            let value: serde_json::Value = serde_json::from_str(
                                &tokio::time::timeout(
                                    std::time::Duration::from_secs(2),
                                    reply_rx.recv(),
                                )
                                .await
                                .expect("mouse press timeout")
                                .expect("mouse press response"),
                            )
                            .unwrap();
                            if value["id"] == 3 {
                                break;
                            }
                        }
                    }
                }

                let mut input_acknowledged = false;
                loop {
                    let value: serde_json::Value = serde_json::from_str(
                        &tokio::time::timeout(std::time::Duration::from_secs(2), reply_rx.recv())
                            .await
                            .expect("click navigation timeout")
                            .expect("click navigation response"),
                    )
                    .unwrap();
                    if value["id"] == 4 {
                        input_acknowledged = true;
                    }
                    if value["method"] == "Page.frameNavigated"
                        && value["params"]["frame"]["url"]
                            .as_str()
                            .is_some_and(|url| url.starts_with("data:text/html,navigated"))
                    {
                        assert!(
                            input_acknowledged,
                            "Input.dispatchMouseEvent must be acknowledged before click navigation events"
                        );
                        break;
                    }
                }

                drop(server_tx);
                tokio::time::timeout(std::time::Duration::from_secs(2), processor)
                    .await
                    .expect("processor shutdown timeout")
                    .expect("processor task");
            })
            .await;
    }

    #[test]
    fn cookie_delta_merges_changes_without_reverting_other_connections() {
        let destination = CookieJar::new();
        destination.set_cookies_from_cdp(vec![cookie("sid", "newer"), cookie("other", "kept")]);
        let initial = vec![cookie("sid", "old"), cookie("removed", "old")];
        let current = vec![cookie("sid", "old"), cookie("added", "value")];

        merge_cookie_delta(&destination, &initial, &current);

        let cookies = destination.get_all_cookies();
        assert!(cookies.iter().any(|c| c.name == "sid" && c.value == "newer"));
        assert!(cookies.iter().any(|c| c.name == "other"));
        assert!(cookies.iter().any(|c| c.name == "added"));
        assert!(!cookies.iter().any(|c| c.name == "removed"));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn recorded_navigation_emits_new_document_frame_before_load_completion() {
        use base64::Engine as _;
        tokio::task::LocalSet::new().run_until(async {
            let mut ctx = crate::dispatch::CdpContext::new();
            let page_id = ctx.create_page();
            let session = Some(format!("{page_id}-session"));
            ctx.sessions.insert(session.clone().unwrap(), page_id);
            crate::domains::page::handle("navigate", &json!({
                "url":"data:text/html,<body style='background:white'>", "waitUntil":"load"
            }), &mut ctx, &session).await.unwrap();
            crate::domains::page::handle("startScreencast", &json!({
                "format":"png", "maxWidth":8, "maxHeight":8
            }), &mut ctx, &session).await.unwrap();
            let stream_id = ctx.screencasts[session.as_ref().unwrap()].session_id;
            crate::domains::page::handle("screencastFrameAck", &json!({"sessionId":stream_id}),
                &mut ctx, &session).await.unwrap();
            ctx.pending_events.clear();

            let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
            let (_server_tx, mut server_rx) = tokio::sync::mpsc::unbounded_channel();
            let mut intercept_rx = None;
            let mut paused = HashMap::new();
            let mut deferred = std::collections::VecDeque::new();
            super::process_with_interception(&json!({
                "id":1, "method":"Page.navigate", "sessionId":session,
                "params":{"url":"data:text/html,<body style='background:rgb(0,0,255)'>", "waitUntil":"load"}
            }).to_string(), &mut ctx, &reply_tx, &mut server_rx,
                &mut intercept_rx, &mut paused, &mut deferred, true).await;
            let mut events = Vec::new();
            while let Ok(text) = reply_rx.try_recv() {
                events.push(serde_json::from_str::<serde_json::Value>(&text).unwrap());
            }
            let frame = events.iter().position(|event| event["method"] == "Page.screencastFrame")
                .expect("recorded navigation must not wait for a later compositor tick");
            let loaded = events.iter().position(|event| event["method"] == "Page.loadEventFired")
                .expect("load completion");
            assert!(frame < loaded, "a client can stop recording immediately after load");
            assert_eq!(events[frame]["sessionId"], json!(session));
            let bytes = base64::engine::general_purpose::STANDARD
                .decode(events[frame]["params"]["data"].as_str().unwrap()).unwrap();
            let image = image::load_from_memory(&bytes).unwrap().to_rgba8();
            assert_eq!(image.get_pixel(image.width()/2, image.height()/2).0, [0,0,255,255]);
        }).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn intercepted_request_bursts_and_script_navigation_keep_servicing_replies() {
        use std::time::Duration;
        use serde_json::Value;
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        tokio::task::LocalSet::new().run_until(async {
            let (server_tx, server_rx) = tokio::sync::mpsc::unbounded_channel();
            let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
            let context = crate::dispatch::CdpContext::new().default_context;
            let processor = tokio::task::spawn_local(super::cdp_processor(
                server_rx, context, std::sync::Arc::new(tokio::sync::Notify::new()),
            ));
            server_tx.send(super::ServerMessage::NewConnection {
                reply_tx: reply_tx.clone(),
            }).unwrap();
            reply_rx.recv().await.unwrap();
            let send = |value: Value| {
                server_tx.send(super::ServerMessage::Cdp(super::CdpMessage {
                    text: value.to_string(), reply_tx: reply_tx.clone(),
                })).unwrap();
            };
            send(json!({"id": 1, "method": "Target.createTarget", "params": {"url": "about:blank"}}));
            let mut session = None;
            loop {
                let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                if let Some(id) = value["params"]["sessionId"].as_str() {
                    session = Some(id.to_string());
                }
                if value["id"] == 1 { break; }
            }
            let session = session.expect("attached session");
            send(json!({"id": 2, "method": "Fetch.enable", "sessionId": session,
                "params": {"patterns": [{"urlPattern": "http://127.0.0.1:9/*"}]}}));
            loop {
                let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                if value["id"] == 2 { break; }
            }
            // No network dependency: each fetch is fulfilled by this client.
            // Keep servicing replies even if navigation finishes before fetches.
            let url = "data:text/html,<button style='position:fixed;left:0;top:0;width:100px;height:40px' onclick='location.reload()'>Reload</button><script type='module'>window.count=(await Promise.all(Array.from({length:64},(_,i)=>fetch('http://127.0.0.1:9/'+i).then(r=>r.text())))).filter(s=>s==='ok').length</script>";
            let mut resolution_id = 100;
            let mut commands = vec![
                (3, "Page.navigate", json!({"url": url, "waitUntil": "networkidle0"})),
                (4, "Page.reload", json!({"waitUntil": "networkidle0"})),
                (5, "Runtime.evaluate", json!({"expression": "location.reload()"})),
                (6, "Runtime.callFunctionOn", json!({"functionDeclaration": "function(){ location.reload(); }"})),
            ];
            if cfg!(feature = "render") {
                commands.push((7, "Input.dispatchMouseEvent", json!({
                    "type": "mouseReleased", "button": "left", "x": 10, "y": 10,
                })));
            }
            for (id, method, params) in commands {
                if id == 7 {
                    send(json!({"id": 50, "method": "Input.dispatchMouseEvent", "sessionId": session,
                        "params": {"type": "mousePressed", "button": "left", "x": 10, "y": 10}}));
                    loop {
                        let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                        if value["id"] == 50 { break; }
                    }
                }
                send(json!({"id": id, "method": method, "sessionId": session, "params": params}));
                let mut pauses = 0;
                let mut acknowledged = false;
                let mut navigated = false;
                tokio::time::timeout(Duration::from_secs(3), async {
                    loop {
                        let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                        if value["method"] == "Fetch.requestPaused"
                            && value["params"]["request"]["url"].as_str()
                                .is_some_and(|url| url.starts_with("http://127.0.0.1:9/"))
                        {
                            pauses += 1;
                            resolution_id += 1;
                            send(json!({"id": resolution_id, "method": "Fetch.fulfillRequest",
                                "sessionId": session, "params": {"requestId": value["params"]["requestId"],
                                    "responseCode": 200, "body": "b2s=",
                                    "responseHeaders": [{"name": "access-control-allow-origin", "value": "*"}]}}));
                        }
                        if value["id"] == id {
                            assert!(value.get("error").is_none(), "{method}: {value}");
                            acknowledged = true;
                        }
                        if value["method"] == "Page.frameNavigated" {
                            navigated = true;
                        }
                        if acknowledged && navigated && pauses == 64 { break; }
                    }
                }).await.unwrap_or_else(|_| panic!("{method} stalled after {pauses} intercepted requests"));
                assert_eq!(pauses, 64, "{method} must service every paused request");
            }
            drop(server_tx);
            tokio::time::timeout(Duration::from_secs(2), processor).await.unwrap().unwrap();
        }).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn pending_runtime_evaluations_do_not_block_their_resolver() {
        use super::{cdp_processor, CdpContext, CdpMessage, ServerMessage};
        use serde_json::Value;
        use std::time::Duration;
        use tokio::sync::mpsc;
        tokio::task::LocalSet::new().run_until(async {
            let (server_tx, server_rx) = mpsc::unbounded_channel();
            let (reply_tx, mut reply_rx) = mpsc::unbounded_channel();
            let processor = tokio::task::spawn_local(cdp_processor(
                server_rx, CdpContext::new().default_context,
                std::sync::Arc::new(tokio::sync::Notify::new()),
            ));
            server_tx.send(ServerMessage::NewConnection { reply_tx: reply_tx.clone() }).unwrap();
            reply_rx.recv().await.unwrap();
            let send = |value: Value| {
                server_tx.send(ServerMessage::Cdp(CdpMessage {
                    text: value.to_string(), reply_tx: reply_tx.clone(),
                })).unwrap();
            };
            send(json!({"id": 1, "method": "Target.createTarget", "params": {"url": "about:blank"}}));
            let mut session = None;
            loop {
                let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                if let Some(id) = value["params"]["sessionId"].as_str() { session = Some(id.to_string()); }
                if value["id"] == 1 { break; }
            }
            let session = session.expect("attached session");
            for (id, method, params) in [
                (2, "Runtime.evaluate", json!({"expression": "new Promise(resolve => globalThis.releasePending = resolve)", "awaitPromise": true, "returnByValue": true})),
                (3, "Runtime.callFunctionOn", json!({"functionDeclaration": "function(){ return new Promise(resolve => globalThis.releasePending = resolve) }", "awaitPromise": true, "returnByValue": true})),
            ] {
                send(json!({"id": id, "method": method, "sessionId": session, "params": params}));
                send(json!({"id": id + 10, "method": "Runtime.evaluate", "sessionId": session,
                    "params": {"expression": "releasePending(42); 'released'", "returnByValue": true}}));
                let mut resolved = false;
                let mut released = false;
                tokio::time::timeout(Duration::from_secs(2), async {
                    while !resolved || !released {
                        let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                        if value["id"] == id {
                            assert!(value.get("error").is_none(), "{value}");
                            assert_eq!(value["result"]["result"]["value"].as_f64(), Some(42.0));
                            resolved = true;
                        } else if value["id"] == id + 10 {
                            assert_eq!(value["result"]["result"]["value"], "released", "{value}");
                            released = true;
                        }
                    }
                }).await.expect("a pending promise must not block the command that resolves it");
            }
            send(json!({"id": 100, "method": "Runtime.evaluate", "sessionId": session,
                "params": {"expression": "location.href='data:text/html,<title>next</title>'; 42", "awaitPromise": true, "returnByValue": true}}));
            tokio::time::timeout(Duration::from_secs(2), async {
                loop {
                    let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                    if value["id"] == 100 {
                        assert!(value.get("error").is_none(), "plain return must precede navigation: {value}");
                        assert_eq!(value["result"]["result"]["value"].as_f64(), Some(42.0));
                        break;
                    }
                }
            }).await.expect("script-initiated navigation must not discard a settled reply");
            std::env::set_var("OBSCURA_CDP_COMMAND_TIMEOUT_MS", "50");
            send(json!({"id": 200, "method": "Runtime.evaluate", "sessionId": session,
                "params": {"expression": "new Promise(resolve => setTimeout(() => resolve({get trap(){while(true){}}}), 10))", "awaitPromise": true, "returnByValue": true}}));
            tokio::time::timeout(Duration::from_secs(2), async {
                loop {
                    let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                    if value["id"] == 200 {
                        assert!(value.get("error").is_some(), "a deferred result getter must remain watchdog-bounded: {value}");
                        break;
                    }
                }
            }).await.expect("deferred result serialization must not hang the worker");
            send(json!({"id": 201, "method": "Runtime.evaluate", "sessionId": session,
                "params": {"expression": "21*2", "returnByValue": true}}));
            tokio::time::timeout(Duration::from_secs(2), async {
                loop {
                    let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                    if value["id"] == 201 {
                        assert_eq!(value["result"]["result"]["value"].as_f64(), Some(42.0), "{value}");
                        break;
                    }
                }
            }).await.expect("the page must remain usable after a result getter is terminated");
            drop(server_tx);
            tokio::time::timeout(Duration::from_secs(2), processor).await.unwrap().unwrap();
        }).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn awaited_runtime_requests_keep_servicing_route_replies() {
        use super::{cdp_processor, CdpContext, CdpMessage, ServerMessage};
        use serde_json::Value;
        use std::time::Duration;
        use tokio::sync::mpsc;
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        tokio::task::LocalSet::new().run_until(async {
            let (server_tx, server_rx) = mpsc::unbounded_channel();
            let (reply_tx, mut reply_rx) = mpsc::unbounded_channel();
            let context = CdpContext::new().default_context;
            let processor = tokio::task::spawn_local(cdp_processor(
                server_rx, context, std::sync::Arc::new(tokio::sync::Notify::new()),
            ));
            server_tx.send(ServerMessage::NewConnection { reply_tx: reply_tx.clone() }).unwrap();
            reply_rx.recv().await.unwrap();
            let send = |value: Value| {
                server_tx.send(ServerMessage::Cdp(CdpMessage {
                    text: value.to_string(), reply_tx: reply_tx.clone(),
                })).unwrap();
            };
            send(json!({"id": 1, "method": "Target.createTarget", "params": {"url": "about:blank"}}));
            let mut session = None;
            loop {
                let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                if let Some(id) = value["params"]["sessionId"].as_str() { session = Some(id.to_string()); }
                if value["id"] == 1 { break; }
            }
            let session = session.expect("attached session");
            send(json!({"id": 2, "method": "Fetch.enable", "sessionId": session,
                "params": {"patterns": [{"urlPattern": "http://127.0.0.1:9/*"}]}}));
            loop {
                let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                if value["id"] == 2 { break; }
            }
            let target_id = session.strip_suffix("-session").unwrap();
            send(json!({"id": 50, "method": "Target.attachToTarget",
                "params": {"targetId": target_id, "flatten": true}}));
            let observer = loop {
                let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                if value["id"] == 50 { break value["result"]["sessionId"].as_str().unwrap().to_string(); }
            };
            let body = "let result=''; for(let i=0;i<2;i++) result+=await (await fetch('http://127.0.0.1:9/'+i)).text(); return result";
            for (id, method, params) in [
                (3, "Runtime.evaluate", json!({"expression": format!("(async()=>{{{body}}})()"), "awaitPromise": true, "returnByValue": true})),
                (4, "Runtime.callFunctionOn", json!({"functionDeclaration": format!("async function(){{{body}}}"), "awaitPromise": true, "returnByValue": true})),
            ] {
                send(json!({"id": id, "method": method, "sessionId": session, "params": params}));
                send(json!({"id": 10 + id, "method": "Runtime.evaluate", "sessionId": session,
                    "params": {"expression": "21*2", "returnByValue": true}}));
                let mut pauses = 0;
                let mut completed = false;
                let mut finished = 0;
                let mut deferred_completed = false;
                let mut driver_requests = Vec::new();
                let mut observer_requests = Vec::new();
                tokio::time::timeout(Duration::from_secs(3), async {
                    loop {
                        let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                        if value["method"] == "Network.requestWillBeSent" {
                            if value["sessionId"] == session {
                                driver_requests.push(value["params"].clone());
                            } else if value["sessionId"] == observer {
                                observer_requests.push(value["params"].clone());
                            }
                        }
                        if value["method"] == "Fetch.requestPaused" {
                            assert_eq!(value["sessionId"], session);
                            pauses += 1;
                            send(json!({"id": 100 + pauses, "method": "Fetch.fulfillRequest", "sessionId": session,
                                "params": {"requestId": value["params"]["requestId"], "responseCode": 200,
                                    "body": "b2s=", "responseHeaders": [{"name": "access-control-allow-origin", "value": "*"}]}}));
                        }
                        if value["id"] == id {
                            assert_eq!(value["result"]["result"]["value"], "okok", "{value}");
                            assert_eq!(pauses, 2);
                            completed = true;
                        }
                        if value["method"] == "Network.loadingFinished" && value["sessionId"] == session { finished += 1; }
                        if value["id"] == 10 + id {
                            assert_eq!(value["result"]["result"]["value"].as_f64(), Some(42.0));
                            deferred_completed = true;
                        }
                        if completed && deferred_completed && finished == 2 && observer_requests.len() == 2 { break; }
                    }
                }).await.expect("awaited evaluation must service route replies");
                assert_eq!(driver_requests.len(), 2);
                assert_eq!(observer_requests, driver_requests);
            }
            drop(server_tx);
            tokio::time::timeout(Duration::from_secs(2), processor).await.unwrap().unwrap();
        }).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn intercepted_requests_keep_their_page_and_unique_identity() {
        use serde_json::Value;
        use std::time::Duration;
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        tokio::task::LocalSet::new().run_until(async {
            let (server_tx, server_rx) = tokio::sync::mpsc::unbounded_channel();
            let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
            let context = crate::dispatch::CdpContext::new().default_context;
            let processor = tokio::task::spawn_local(super::cdp_processor(
                server_rx, context, std::sync::Arc::new(tokio::sync::Notify::new()),
            ));
            server_tx.send(super::ServerMessage::NewConnection { reply_tx: reply_tx.clone() }).unwrap();
            reply_rx.recv().await.unwrap();
            let send = |value: Value| {
                server_tx.send(super::ServerMessage::Cdp(super::CdpMessage {
                    text: value.to_string(), reply_tx: reply_tx.clone(),
                })).unwrap();
            };
            let mut sessions = Vec::new();
            for index in 0..2 {
                send(json!({"id": 1, "method": "Target.createTarget", "params": {"url": "about:blank"}}));
                loop {
                    let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                    if let Some(session) = value["params"]["sessionId"].as_str() {
                        sessions.push(session.to_string());
                    }
                    if value["id"] == 1 { break; }
                }
                for (method, params) in [
                    ("Page.navigate", json!({"url": "data:text/html,<title>owner</title>"})),
                    ("Fetch.enable", json!({"patterns": [{"urlPattern": "*"}]})),
                ] {
                    send(json!({"id": 2, "method": method, "params": params, "sessionId": sessions[index]}));
                    loop {
                        let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                        if value["id"] == 2 {
                            assert!(value.get("error").is_none(), "{value}");
                            break;
                        }
                    }
                }
            }
            for (index, session) in sessions.iter().enumerate() {
                send(json!({"id": 10 + index, "method": "Runtime.evaluate", "sessionId": session,
                    "params": {"expression": format!("void fetch('http://127.0.0.1:9/{index}').then(r=>r.text()).then(s=>window.answer=s)")}}));
            }
            let mut requests = Vec::new();
            tokio::time::timeout(Duration::from_secs(3), async {
                while requests.len() < 2 {
                    let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                    if value["method"] == "Fetch.requestPaused" {
                        requests.push(value);
                    }
                }
            }).await.expect("both pages must pause independently");
            assert_ne!(requests[0]["params"]["requestId"], requests[1]["params"]["requestId"],
                "shared resolver map requires unique request IDs across pages");
            for (index, request) in requests.iter().enumerate() {
                let owner = request["params"]["request"]["url"].as_str().unwrap().rsplit('/').next().unwrap().parse::<usize>().unwrap();
                assert_eq!(request["sessionId"], sessions[owner], "request belongs to its initiating page");
                send(json!({"id": 20 + index, "method": "Fetch.fulfillRequest", "sessionId": sessions[owner],
                    "params": {"requestId": request["params"]["requestId"], "responseCode": 200,
                        "body": "b2s=", "responseHeaders": [{"name": "access-control-allow-origin", "value": "*"}]}}));
            }
            for session in &sessions {
                send(json!({"id": 30, "method": "Runtime.evaluate", "sessionId": session,
                    "params": {"expression": "new Promise(resolve => {let t=setInterval(()=>{if(window.answer){clearInterval(t);resolve(window.answer)}},1)})", "awaitPromise": true, "returnByValue": true}}));
                tokio::time::timeout(Duration::from_secs(3), async {
                    loop {
                        let value: Value = serde_json::from_str(&reply_rx.recv().await.unwrap()).unwrap();
                        if value["id"] == 30 {
                            assert_eq!(value["result"]["result"]["value"], "ok");
                            break;
                        }
                    }
                }).await.expect("both resolvers complete");
            }
            drop(server_tx);
            tokio::time::timeout(Duration::from_secs(2), processor).await.unwrap().unwrap();
        }).await;
    }

    // Issue #363: only exact navigate/reload methods take the spawn-and-defer
    // navigation path. A substring match also caught Page.navigateToHistoryEntry
    // (goBack / goForward), which has no `url` param, so it was misrouted into
    // the raw-navigate path and failed with "Invalid URL" instead of reaching
    // its real handler.
    #[test]
    fn only_exact_page_navigate_and_reload_route_as_navigation() {
        assert!(is_navigate_method(
            r#"{"id":1,"method":"Page.navigate","params":{"url":"https://example.com"}}"#
        ));
        assert!(is_navigate_method(
            r#"{"id":3,"method":"Page.reload","params":{}}"#
        ));
        assert!(!is_navigate_method(
            r#"{"id":2,"method":"Page.navigateToHistoryEntry","params":{"entryId":0}}"#
        ));
    }

    // A Runtime.evaluate whose expression merely contains the literal
    // "Page.navigate" must not be misrouted, and malformed input is not a
    // navigation.
    #[test]
    fn unrelated_methods_do_not_route_as_navigation() {
        assert!(!is_navigate_method(
            r#"{"id":3,"method":"Runtime.evaluate","params":{"expression":"'Page.navigate'"}}"#
        ));
        assert!(!is_navigate_method("not json"));
    }

    // Issue #365: Fetch.continueRequest header overrides must be parsed from the
    // CDP `[{name, value}]` list so they can be applied to the outgoing request.
    #[test]
    fn parse_cdp_headers_reads_name_value_pairs() {
        let params = json!({
            "headers": [
                {"name": "X-A", "value": "1"},
                {"name": "X-B", "value": "2"},
            ]
        });
        let headers = parse_cdp_headers(&params).expect("headers present");
        assert_eq!(headers.get("X-A").map(String::as_str), Some("1"));
        assert_eq!(headers.get("X-B").map(String::as_str), Some("2"));
    }

    // No `headers` field means "leave the request's headers untouched", which is
    // None, not an empty map that would clear them.
    #[test]
    fn parse_cdp_headers_absent_is_none() {
        assert!(parse_cdp_headers(&json!({"url": "https://example.com"})).is_none());
    }

    async fn assert_navigation_intercept_reply_without_timer(method: &str) {
        use super::{process_with_interception, CdpMessage, ServerMessage, MAX_DEFERRED_MESSAGES};
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use obscura_js::ops::{InterceptedRequest, InterceptResolution};

        tokio::task::LocalSet::new().run_until(async {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let address = listener.local_addr().unwrap();
            let (requested_tx, requested_rx) = tokio::sync::oneshot::channel();
            let (release_tx, release_rx) = tokio::sync::oneshot::channel();
            let fixture = tokio::task::spawn_local(async move {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut request = Vec::new();
                let mut buffer = [0u8; 1024];
                while !request.windows(4).any(|part| part == b"\r\n\r\n") {
                    let count = stream.read(&mut buffer).await.unwrap();
                    assert!(count > 0);
                    request.extend_from_slice(&buffer[..count]);
                }
                requested_tx.send(()).unwrap();
                release_rx.await.unwrap();
                let body = b"<!doctype html><title>Finished</title><h1>Finished</h1>";
                let head = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
                stream.write_all(head.as_bytes()).await.unwrap();
                stream.write_all(body).await.unwrap();
            });

            let context = obscura_browser::context::BrowserContext::with_storage_and_network(
                "interception-test".into(), None, false, None, None, true,
            );
            let mut ctx = crate::dispatch::CdpContext::new_with_shared_context(std::sync::Arc::new(context));
            let page_id = ctx.create_page();
            let session_id = format!("{page_id}-session");
            ctx.sessions.insert(session_id.clone(), page_id.clone());
            let (server_tx, mut server_rx) = tokio::sync::mpsc::unbounded_channel();
            let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
            let (intercept_tx, intercept_rx) = tokio::sync::mpsc::unbounded_channel();
            ctx.intercept_tx = Some(intercept_tx.clone());
            let command = json!({"id": 1, "method": "Page.navigate", "sessionId": session_id,
                "params": {"url": format!("http://{address}/"), "waitUntil": "load"}}).to_string();
            let navigation_reply = reply_tx.clone();
            let navigation = tokio::task::spawn_local(async move {
                let mut intercept_rx = Some(intercept_rx);
                let mut paused = HashMap::new();
                let mut deferred = std::collections::VecDeque::new();
                process_with_interception(&command, &mut ctx, &navigation_reply,
                    &mut server_rx, &mut intercept_rx, &mut paused, &mut deferred, true).await;
                (ctx, paused, deferred)
            });
            tokio::time::timeout(std::time::Duration::from_secs(5), requested_rx)
                .await.expect("navigation must reach the held response").unwrap();

            // The real socket is already connected and its response is gated.
            // Only the channel handshake below runs with a paused clock. An
            // unconditional timer auto-advances it, independent of host load.
            tokio::time::pause();
            let started = tokio::time::Instant::now();
            let (resolution_tx, resolution_rx) = tokio::sync::oneshot::channel();
            intercept_tx.send(InterceptedRequest {
                page_id: page_id.clone(),
                request_id: "pending-test".into(), url: format!("http://{address}/pending"),
                method: "GET".into(), headers: HashMap::new(), resource_type: "Fetch".into(),
                resolver: resolution_tx,
            }).unwrap();
            loop {
                let value: serde_json::Value = serde_json::from_str(
                    &tokio::time::timeout(std::time::Duration::from_secs(1), reply_rx.recv())
                        .await.expect("paused notification").unwrap()).unwrap();
                assert_ne!(value["id"], 1, "navigation must wait for its response");
                if value["method"] == "Fetch.requestPaused" {
                    assert_eq!(value["params"]["requestId"], "pending-test");
                    break;
                }
            }
            let send = |value: serde_json::Value| {
                server_tx.send(ServerMessage::Cdp(CdpMessage {
                    text: value.to_string(), reply_tx: reply_tx.clone(),
                })).unwrap();
            };
            let foreign_count = if method == "failRequest" { MAX_DEFERRED_MESSAGES + 1 } else { 1 };
            for index in 0..foreign_count {
                send(json!({"id": 100 + index, "method": "Runtime.evaluate",
                    "sessionId": session_id, "params": {"expression": "globalThis.foreignRan=true"}}));
            }
            let mut params = json!({"requestId": "pending-test"});
            match method {
                "continueRequest" => {
                    params["url"] = json!("https://example.com/rewritten");
                    params["method"] = json!("POST");
                    params["headers"] = json!([{"name": "X-Check", "value": "kept"}]);
                    params["postData"] = json!("cGF5bG9hZA==");
                }
                "fulfillRequest" => {
                    params["responseCode"] = json!(201);
                    params["responseHeaders"] = json!([{"name": "X-Check", "value": "kept"}]);
                    params["body"] = json!("aGVsbG8=");
                }
                "failRequest" => params["errorReason"] = json!("Aborted"),
                _ => unreachable!(),
            }
            send(json!({"id": 10, "method": format!("Fetch.{method}"),
                "sessionId": session_id, "params": params}));
            let mut overflow_responses = 0;
            loop {
                let value: serde_json::Value = serde_json::from_str(
                    &tokio::time::timeout(std::time::Duration::from_secs(1), reply_rx.recv())
                        .await.expect("Fetch resolution reply").unwrap()).unwrap();
                assert_ne!(value["id"], 1, "must not acknowledge unfinished navigation");
                if value["id"] == 10 {
                    assert!(value.get("error").is_none(), "{value}");
                    break;
                }
                if value.get("id").is_some() {
                    assert_eq!(value["id"], 100 + MAX_DEFERRED_MESSAGES);
                    assert_eq!(value["error"]["code"], -32000);
                    overflow_responses += 1;
                }
            }
            let elapsed = started.elapsed();
            match (method, resolution_rx.await.unwrap()) {
                ("continueRequest", InterceptResolution::Continue { url, method, headers, body }) => {
                    assert_eq!(url.as_deref(), Some("https://example.com/rewritten"));
                    assert_eq!(method.as_deref(), Some("POST"));
                    assert_eq!(headers.unwrap().get("X-Check").map(String::as_str), Some("kept"));
                    assert_eq!(body.as_deref(), Some(b"payload".as_slice()));
                }
                ("fulfillRequest", InterceptResolution::Fulfill { status, headers, body, body_base64 }) => {
                    assert_eq!(status, 201);
                    assert_eq!(headers.get("X-Check").map(String::as_str), Some("kept"));
                    assert_eq!(body, "hello");
                    assert_eq!(body_base64, "aGVsbG8=");
                }
                ("failRequest", InterceptResolution::Fail { reason }) => assert_eq!(reason, "Aborted"),
                _ => panic!("resolution kind changed"),
            }
            tokio::time::resume();
            release_tx.send(()).unwrap();
            let (ctx, paused, deferred) = tokio::time::timeout(std::time::Duration::from_secs(5), navigation)
                .await.expect("navigation completion").unwrap();
            fixture.await.unwrap();
            assert_eq!(ctx.pages.len(), 1);
            assert_eq!(ctx.pages[0].url_string(), format!("http://{address}/"));
            assert!(paused.is_empty());
            assert_eq!(deferred.len(), foreign_count.min(MAX_DEFERRED_MESSAGES));
            assert_eq!(overflow_responses, usize::from(foreign_count > MAX_DEFERRED_MESSAGES));
            let replies: Vec<serde_json::Value> = std::iter::from_fn(|| reply_rx.try_recv().ok())
                .map(|text| serde_json::from_str(&text).unwrap()).collect();
            assert_eq!(replies.iter().filter(|reply| reply["id"] == 1).count(), 1);
            let navigation_reply = replies.iter().find(|reply| reply["id"] == 1).unwrap();
            assert!(navigation_reply.get("error").is_none(), "{navigation_reply}");
            assert!(!replies.iter().any(|reply| reply["id"] == 10), "no duplicate resolution reply");
            assert_eq!(elapsed, std::time::Duration::ZERO, "ready replies must not wait for a timer");
        }).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_intercept_continue_has_no_timer_delay() {
        assert_navigation_intercept_reply_without_timer("continueRequest").await;
    }

    async fn assert_stop_loading_cancels_navigation(script: bool, method: &str) {
        use super::{process_cdp_message, process_with_interception, CdpMessage, ServerMessage};
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        tokio::task::LocalSet::new().run_until(async {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let address = listener.local_addr().unwrap();
            let (requested_tx, requested_rx) = tokio::sync::oneshot::channel();
            let fixture = tokio::task::spawn_local(async move {
                if script {
                    let (mut stream, _) = listener.accept().await.unwrap();
                    let mut buffer = [0; 2048];
                    stream.read(&mut buffer).await.unwrap();
                    let body = "<!doctype html><title>Partial</title><script src='/held.js'></script>";
                    let response = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
                    stream.write_all(response.as_bytes()).await.unwrap();
                }
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut buffer = [0; 2048];
                assert!(stream.read(&mut buffer).await.unwrap() > 0);
                requested_tx.send(()).unwrap();
                // No response: cancellation must drop the pending HTTP request.
                assert_eq!(stream.read(&mut buffer).await.unwrap(), 0);
            });
            let context = obscura_browser::context::BrowserContext::with_storage_and_network(
                "stop-loading-test".into(), None, false, None, None, true,
            );
            let mut ctx = crate::dispatch::CdpContext::new_with_shared_context(std::sync::Arc::new(context));
            let page_id = ctx.create_page();
            let other_page = ctx.create_page();
            let session = format!("{page_id}-session");
            ctx.sessions.insert(session.clone(), page_id.clone());
            ctx.sessions.insert("raw-session".into(), page_id.clone());
            ctx.sessions.insert("other-session".into(), other_page.clone());
            ctx.get_page_mut(&page_id).unwrap().resume_js();
            let original_url = ctx.pages[0].url_string();
            let (server_tx, mut server_rx) = tokio::sync::mpsc::unbounded_channel();
            let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
            let navigation_reply = reply_tx.clone();
            let url = format!("http://{address}/");
            let command = json!({"id": 1, "method": "Page.navigate", "sessionId": session,
                "params": {"url": url, "waitUntil": "load"}}).to_string();
            let navigation = tokio::task::spawn_local(async move {
                let mut paused = HashMap::new();
                let mut deferred = std::collections::VecDeque::new();
                process_with_interception(&command, &mut ctx, &navigation_reply,
                    &mut server_rx, &mut None, &mut paused, &mut deferred, true).await;
                (ctx, paused, deferred)
            });
            tokio::time::timeout(std::time::Duration::from_secs(5), requested_rx)
                .await.expect("fixture request").unwrap();
            for (id, session) in [(2, "other-session"), (3, "raw-session")] {
                server_tx.send(ServerMessage::Cdp(CdpMessage {
                    text: json!({"id": id, "method": if id == 2 { "Page.stopLoading" } else { method },
                        "sessionId": session, "params": {"targetId": page_id}}).to_string(),
                    reply_tx: reply_tx.clone(),
                })).unwrap();
            }
            let (mut ctx, paused, deferred) = tokio::time::timeout(std::time::Duration::from_secs(2), navigation)
                .await.expect("Page.stopLoading must cancel without waiting for the HTTP timeout").unwrap();
            tokio::time::timeout(std::time::Duration::from_secs(2), fixture)
                .await.expect("pending request socket must close").unwrap();
            assert!(paused.is_empty());
            assert_eq!(deferred.len(), if method == "Page.stopLoading" { 1 } else { 2 },
                "another target's stop must not cancel this navigation");
            for message in deferred {
                if let ServerMessage::Cdp(message) = message {
                    process_cdp_message(&message.text, &mut ctx, &message.reply_tx).await;
                }
            }
            let replies: Vec<serde_json::Value> = std::iter::from_fn(|| reply_rx.try_recv().ok())
                .map(|text| serde_json::from_str(&text).unwrap()).collect();
            assert_eq!(replies.iter().filter(|reply| reply["id"] == 3).count(), 1);
            let stopped = replies.iter().find(|reply| reply["id"] == 3).unwrap();
            assert!(stopped.get("error").is_none(), "{stopped}");
            let aborted = replies.iter().find(|reply| reply["id"] == 1).unwrap();
            assert!(aborted.get("error").is_none(), "{aborted}");
            if !script {
                assert_eq!(aborted["result"]["errorText"], "net::ERR_ABORTED", "{aborted}");
            }
            assert!(!replies.iter().any(|reply| reply["method"] == "Page.loadEventFired"));
            assert!(replies.iter().any(|reply| reply["method"] == "Page.frameStoppedLoading"));
            assert!(ctx.get_page(&other_page).is_some());
            if method != "Page.stopLoading" {
                assert!(ctx.get_page(&page_id).is_none());
                assert_eq!(replies.iter().filter(|reply| reply["method"] == "Target.targetDestroyed").count(), 1);
                return;
            }
            assert_eq!(ctx.get_page(&page_id).unwrap().url_string(), if script { url } else { original_url });
            assert_eq!(ctx.get_page_mut(&page_id).unwrap().evaluate("1 + 2").as_f64(), Some(3.0));
            process_cdp_message(&json!({"id": 4, "method": "Page.navigate", "sessionId": session,
                "params": {"url": "about:blank"}}).to_string(), &mut ctx, &reply_tx).await;
            assert_eq!(ctx.get_page(&page_id).unwrap().url_string(), "about:blank");
        }).await;
    }

    async fn routed_document_events(scenario: &str) -> Vec<serde_json::Value> {
        tokio::task::LocalSet::new().run_until(async {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let url = format!("http://{}/start", listener.local_addr().unwrap());
            drop(listener);
            let context = obscura_browser::context::BrowserContext::with_storage_and_network(
                "routed-lifecycle".into(), None, false, None, None, true,
            );
            let mut ctx = crate::dispatch::CdpContext::new_with_shared_context(std::sync::Arc::new(context));
            let page_id = ctx.create_page();
            let session = format!("{page_id}-session");
            ctx.sessions.insert(session.clone(), page_id.clone());
            let mut intercept_rx = Some(ctx.get_page_mut(&page_id).unwrap().enable_interception());
            let (server_tx, mut server_rx) = tokio::sync::mpsc::unbounded_channel();
            let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
            let (done_tx, mut done_rx) = tokio::sync::oneshot::channel();
            let command = json!({"id": 1, "method": "Page.navigate", "sessionId": session,
                "params": {"url": url}}).to_string();
            let mut paused = HashMap::new();
            let mut deferred = std::collections::VecDeque::new();
            let navigation = async {
                super::process_with_interception(&command, &mut ctx, &reply_tx,
                    &mut server_rx, &mut intercept_rx, &mut paused, &mut deferred, true).await;
                let _ = done_tx.send(());
            };
            let client = async {
                use base64::Engine as _;
                let mut events = Vec::new();
                let mut pauses = 0;
                loop {
                    tokio::select! {
                        biased;
                        Some(text) = reply_rx.recv() => {
                            let event: serde_json::Value = serde_json::from_str(&text).unwrap();
                            if event["method"] == "Fetch.requestPaused" {
                                pauses += 1;
                                let request_id = &event["params"]["requestId"];
                                let stop = scenario == "chain-stop" && pauses == 2;
                                let method = if stop { "Page.stopLoading" }
                                    else if scenario == "abort" { "Fetch.failRequest" }
                                    else if scenario == "transport" || (scenario == "chain-fail" && pauses == 2) { "Fetch.continueRequest" }
                                    else { "Fetch.fulfillRequest" };
                                let body = if pauses == 1 && scenario.starts_with("chain") {
                                    "<script>location.replace('/finish')</script>"
                                } else if pauses == 1 && scenario == "repeat" {
                                    "<script>location.reload()</script>"
                                } else { "<title>Finished</title>" };
                                server_tx.send(super::ServerMessage::Cdp(super::CdpMessage {
                                    text: json!({"id": pauses + 1, "method": method, "sessionId": session,
                                        "params": {"requestId": request_id, "errorReason": "Aborted", "responseCode": 200,
                                            "responseHeaders": [{"name": "Content-Type", "value": "text/html"}],
                                            "body": base64::engine::general_purpose::STANDARD.encode(body)}}).to_string(),
                                    reply_tx: reply_tx.clone(),
                                })).unwrap();
                            }
                            events.push(event);
                        }
                        _ = &mut done_rx => break,
                    }
                }
                events
            };
            let (_, events) = tokio::time::timeout(std::time::Duration::from_secs(5), async {
                tokio::join!(navigation, client)
            }).await.expect("routed navigation must finish");
            events
        }).await
    }

    fn assert_routed_completions(events: &[serde_json::Value], finished: usize, failed: usize) {
        let requests: Vec<_> = events.iter().filter(|event| event["method"] == "Network.requestWillBeSent").collect();
        let completed: Vec<_> = events.iter().filter(|event| event["method"] == "Network.loadingFinished").collect();
        let errors: Vec<_> = events.iter().filter(|event| event["method"] == "Network.loadingFailed").collect();
        assert_eq!(requests.len(), finished + failed, "{events:?}");
        assert_eq!(completed.len(), finished, "{events:?}");
        assert_eq!(errors.len(), failed, "{events:?}");
        for request in requests {
            let id = &request["params"]["requestId"];
            assert_eq!(completed.iter().chain(errors.iter()).filter(|event| &event["params"]["requestId"] == id).count(), 1,
                "each published request must finish exactly once: {events:?}");
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn routed_document_transport_failure_finishes_its_request() {
        assert_routed_completions(&routed_document_events("transport").await, 0, 1);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn routed_document_abort_finishes_once_with_canonical_error() {
        let events = routed_document_events("abort").await;
        assert_routed_completions(&events, 0, 1);
        let error = events.iter().find(|event| event["method"] == "Network.loadingFailed").unwrap();
        assert_eq!(error["params"]["errorText"], "net::ERR_ABORTED");
        assert_eq!(error["params"]["canceled"], true);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn routed_document_script_navigation_preserves_both_completions() {
        assert_routed_completions(&routed_document_events("chain").await, 2, 0);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn routed_document_reload_preserves_both_completions() {
        assert_routed_completions(&routed_document_events("repeat").await, 2, 0);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn routed_document_script_navigation_failure_finishes_both_requests() {
        assert_routed_completions(&routed_document_events("chain-fail").await, 1, 1);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn routed_document_script_navigation_stop_finishes_both_requests() {
        assert_routed_completions(&routed_document_events("chain-stop").await, 1, 1);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn stop_loading_finishes_the_intercepted_document_request() {
        tokio::task::LocalSet::new().run_until(async {
            let mut ctx = crate::dispatch::CdpContext::new();
            let page_id = ctx.create_page();
            let session = format!("{page_id}-session");
            ctx.sessions.insert(session.clone(), page_id.clone());
            let mut intercept_rx = Some(ctx.get_page_mut(&page_id).unwrap().enable_interception());
            let (server_tx, mut server_rx) = tokio::sync::mpsc::unbounded_channel();
            let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
            let command = json!({"id": 1, "method": "Page.navigate", "sessionId": session,
                "params": {"url": "http://127.0.0.1:9/paused"}}).to_string();
            let mut paused = HashMap::new();
            let mut deferred = std::collections::VecDeque::new();
            let client = async {
                let mut network_id = None;
                let mut request_events = 0;
                while let Some(text) = reply_rx.recv().await {
                    let event: serde_json::Value = serde_json::from_str(&text).unwrap();
                    if event["method"] == "Network.requestWillBeSent" { request_events += 1; }
                    if event["method"] == "Fetch.requestPaused" {
                        network_id = Some(event["params"]["networkId"].clone());
                        server_tx.send(super::ServerMessage::Cdp(super::CdpMessage {
                            text: json!({"id": 2, "method": "Page.stopLoading", "sessionId": session}).to_string(),
                            reply_tx: reply_tx.clone(),
                        })).unwrap();
                    }
                    if event["method"] == "Network.loadingFailed" {
                        assert_eq!(Some(event["params"]["requestId"].clone()), network_id,
                            "cancellation must finish the request that was paused");
                        assert_eq!(request_events, 1, "a paused request must not be published twice");
                        break;
                    }
                }
            };
            tokio::time::timeout(std::time::Duration::from_secs(5), async {
                tokio::join!(super::process_with_interception(&command, &mut ctx, &reply_tx,
                    &mut server_rx, &mut intercept_rx, &mut paused, &mut deferred, true), client);
            }).await.unwrap();
        }).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn stop_loading_cancels_a_held_document_request() {
        assert_stop_loading_cancels_navigation(false, "Page.stopLoading").await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn stop_loading_cancels_a_held_parser_script_request() {
        assert_stop_loading_cancels_navigation(true, "Page.stopLoading").await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn stop_loading_cancels_for_page_close() {
        assert_stop_loading_cancels_navigation(false, "Page.close").await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn stop_loading_cancels_for_target_close() {
        assert_stop_loading_cancels_navigation(false, "Target.closeTarget").await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_intercept_fulfill_has_no_timer_delay() {
        assert_navigation_intercept_reply_without_timer("fulfillRequest").await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_intercept_fail_keeps_deferral_bounded_without_delay() {
        assert_navigation_intercept_reply_without_timer("failRequest").await;
    }

    #[test]
    fn fetch_resolution_is_handled_once_by_the_outer_processor() {
        let (resolution_tx, mut resolution_rx) = tokio::sync::oneshot::channel();
        let mut paused = HashMap::from([("request-1".to_string(), super::PausedIntercept {resolver: resolution_tx, main_document: false})]);
        let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
        assert!(!handle_fetch_resolution(
            r#"{"id":16,"method":"Network.getResponseBody","params":{"requestId":"request-1"}}"#,
            &reply_tx,
            &mut paused,
        ));
        assert!(paused.contains_key("request-1"), "unrelated commands must not consume the resolver");
        assert!(handle_fetch_resolution(
            r#"{"id":17,"method":"Fetch.continueRequest","params":{"requestId":"request-1"}}"#,
            &reply_tx,
            &mut paused,
        ));
        assert!(matches!(
            resolution_rx.try_recv(),
            Ok(obscura_js::ops::InterceptResolution::Continue { .. })
        ));
        let response: serde_json::Value =
            serde_json::from_str(&reply_rx.try_recv().expect("one command response")).unwrap();
        assert_eq!(response["id"], 17);
        assert!(reply_rx.try_recv().is_err(), "must not emit a duplicate response");

        let (resolution_tx, mut resolution_rx) = tokio::sync::oneshot::channel();
        paused.insert("request-2".into(), super::PausedIntercept {resolver: resolution_tx, main_document: false});
        assert!(handle_fetch_resolution(
            r#"{"id":18,"method":"Fetch.failRequest","sessionId":"page-session","params":{"requestId":"request-2","errorReason":"Aborted"}}"#,
            &reply_tx, &mut paused,
        ));
        assert!(matches!(resolution_rx.try_recv(), Ok(obscura_js::ops::InterceptResolution::Fail { reason }) if reason == "Aborted"));
        let event: serde_json::Value = serde_json::from_str(&reply_rx.try_recv().unwrap()).unwrap();
        assert_eq!(event["method"], "Network.loadingFailed");
        assert_eq!(event["sessionId"], "page-session");
        assert_eq!(event["params"]["requestId"], "request-2");
        assert_eq!(event["params"]["errorText"], "net::ERR_ABORTED");
        assert_eq!(event["params"]["canceled"], true);
        let response: serde_json::Value = serde_json::from_str(&reply_rx.try_recv().unwrap()).unwrap();
        assert_eq!(response["id"], 18);
        assert!(reply_rx.try_recv().is_err(), "abort emits one failure and one response");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn indexeddb_versionchange_rearms_an_idle_page_until_its_delayed_close() {
        let mut ctx = crate::dispatch::CdpContext::new();
        let mut ids = Vec::new();
        for _ in 0..2 {
            let id = ctx.create_page();
            let session = Some(format!("{id}-session"));
            ctx.sessions.insert(session.clone().unwrap(),id.clone());
            crate::domains::page::handle("navigate", &json!({"url":"data:text/html,<body>idb</body>"}), &mut ctx, &session).await.unwrap();
            ctx.get_page_mut(&id).unwrap().js.as_mut().unwrap().set_url("https://idb.test/");
            ids.push(id);
        }
        let mut idle = Default::default();
        ctx.get_page_mut(&ids[0]).unwrap().evaluate(r#"(() => {
            const r = indexedDB.open('idle-upgrade',1);
            globalThis.opened = false;
            r.onsuccess = () => {globalThis.opened = true;
                r.result.onversionchange = () => setTimeout(() => r.result.close(),10);};
        })()"#);
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while !pump_live_page_event_loop(&mut ctx,&mut idle).await.unwrap() {}
        }).await.unwrap();
        assert!(idle.contains(&ids[0]));
        assert_eq!(ctx.get_page_mut(&ids[0]).unwrap().evaluate("opened"),json!(true));
        ctx.get_page_mut(&ids[1]).unwrap().evaluate(r#"(() => {
            globalThis.upgraded = false;
            setTimeout(() => {const r = indexedDB.open('idle-upgrade',2);
                r.onsuccess = () => globalThis.upgraded = r.result.version === 2;},10);
        })()"#);
        idle.remove(&ids[1]);
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            loop {
                pump_live_page_event_loop(&mut ctx,&mut idle).await.unwrap();
                if ctx.get_page_mut(&ids[1]).unwrap().evaluate("upgraded") == json!(true) {break;}
            }
        }).await.expect("versionchange must wake the idle page and retain its delayed-close work");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn autonomous_pages_do_not_wait_for_another_pages_distant_timer() {
        let mut ctx = crate::dispatch::CdpContext::new();
        let mut idle_pages = Default::default();
        let mut pages = Vec::new();
        for _ in 0..3 {
            let id = ctx.create_page();
            let session = Some(format!("{id}-session"));
            ctx.sessions.insert(session.clone().unwrap(), id.clone());
            crate::domains::page::handle(
                "navigate", &json!({"url": "data:text/html,<body>timer</body>"}),
                &mut ctx, &session,
            ).await.unwrap();
            pages.push(id);
        }
        ctx.get_page_mut(&pages[0]).unwrap().evaluate(
            "globalThis.slow = setTimeout(() => {}, 60000)",
        );
        for id in &pages[1..] {
            assert_eq!(ctx.get_page_mut(id).unwrap().evaluate(
                "(() => { globalThis.done = false; setTimeout(() => { globalThis.done = true; }, 20); return globalThis.done; })()",
            ), json!(false));
        }
        let started = std::time::Instant::now();
        let completed = tokio::time::timeout(std::time::Duration::from_secs(1), async {
            loop {
                pump_live_page_event_loop(&mut ctx, &mut idle_pages).await.unwrap();
                if pages[1..].iter().all(|id| {
                    ctx.get_page_mut(id).unwrap().evaluate("globalThis.done") == json!(true)
                }) {
                    break;
                }
            }
        }).await;
        assert!(completed.is_ok(), "a parked page must not prevent other pages' timers from running");
        assert!(started.elapsed() < std::time::Duration::from_millis(500),
            "ready timers must not need the outer timeout's wake: {:?}", started.elapsed());
        ctx.get_page_mut(&pages[2]).unwrap().evaluate(
            "setTimeout(() => { globalThis.finalTurn = true; }, 0)",
        );
        idle_pages.clear(); // A new command rearms previously idle pages.
        // This turn can do work and become idle in the same poll. Its result
        // must still be published while the first page remains parked.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        let started = std::time::Instant::now();
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            loop {
                pump_live_page_event_loop(&mut ctx, &mut idle_pages).await.unwrap();
                if ctx.get_page_mut(&pages[2]).unwrap().evaluate("globalThis.finalTurn") == json!(true) {
                    break;
                }
            }
        }).await.expect("the last completed task must not remain buffered");
        assert!(started.elapsed() < std::time::Duration::from_millis(500),
            "a task becoming idle must still publish progress: {:?}", started.elapsed());
        let parked = tokio::time::timeout(std::time::Duration::from_millis(50), async {
            for _ in 0..8 {
                pump_live_page_event_loop(&mut ctx, &mut idle_pages).await.unwrap();
            }
        }).await;
        assert!(parked.is_err(), "idle peers must not repeatedly wake a parked connection");
        ctx.get_page_mut(&pages[0]).unwrap().evaluate("clearTimeout(globalThis.slow)");
        idle_pages.clear();
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while !pump_live_page_event_loop(&mut ctx, &mut idle_pages).await.unwrap() {}
        }).await.expect("all idle pages must disarm the pump instead of spinning");
    }

    // #569 / #365 — postData is declared `binary` in the CDP domain, so a
    // client sends it base64-encoded. Passing the encoded text straight through
    // made the request body the base64 itself, which a server reads as neither
    // the JSON nor the form the page meant to send.
    #[test]
    fn continue_request_decodes_a_base64_post_data() {
        let (resolution_tx, mut resolution_rx) = tokio::sync::oneshot::channel();
        let mut paused = HashMap::from([("request-1".to_string(), super::PausedIntercept {resolver: resolution_tx, main_document: false})]);
        let (reply_tx, _reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();

        // base64 of {"a":1}
        assert!(handle_fetch_resolution(
            r#"{"id":1,"method":"Fetch.continueRequest","params":{"requestId":"request-1","postData":"eyJhIjoxfQ=="}}"#,
            &reply_tx,
            &mut paused,
        ));

        let Ok(obscura_js::ops::InterceptResolution::Continue { body, .. }) = resolution_rx.try_recv() else {
            panic!("continueRequest must resolve as Continue");
        };
        assert_eq!(
            body.as_deref(),
            Some(br#"{"a":1}"#.as_slice()),
            "the request body must be the bytes the client encoded, not the base64 text"
        );
    }

    // The body a client rewrites is not always text -- a protobuf, a gzip
    // stream, a multipart file part. Carrying it through `String` replaced
    // every non-UTF-8 sequence with U+FFFD before it reached the wire.
    #[test]
    fn continue_request_keeps_a_non_utf8_post_data_intact() {
        let (resolution_tx, mut resolution_rx) = tokio::sync::oneshot::channel();
        let mut paused = HashMap::from([("request-1".to_string(), super::PausedIntercept {resolver: resolution_tx, main_document: false})]);
        let (reply_tx, _reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();

        // base64 of the three bytes 00 FF FE, which are not valid UTF-8
        assert!(handle_fetch_resolution(
            r#"{"id":1,"method":"Fetch.continueRequest","params":{"requestId":"request-1","postData":"AP/+"}}"#,
            &reply_tx,
            &mut paused,
        ));

        let Ok(obscura_js::ops::InterceptResolution::Continue { body, .. }) = resolution_rx.try_recv() else {
            panic!("continueRequest must resolve as Continue");
        };
        assert_eq!(
            body.as_deref(),
            Some([0x00u8, 0xFF, 0xFE].as_slice()),
            "a binary body must reach the wire byte for byte"
        );
    }

    // Base64 that is not base64 is a client mistake. Answering it silently is
    // how raw text reached the wire as mangled bytes; answering it with an
    // error while keeping the pause lets the client correct itself.
    #[test]
    fn continue_request_rejects_post_data_that_is_not_base64_without_wedging_it() {
        let (resolution_tx, mut resolution_rx) = tokio::sync::oneshot::channel();
        let mut paused = HashMap::from([("request-1".to_string(), super::PausedIntercept {resolver: resolution_tx, main_document: false})]);
        let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();

        assert!(handle_fetch_resolution(
            r#"{"id":9,"method":"Fetch.continueRequest","params":{"requestId":"request-1","postData":"!!!not-base64"}}"#,
            &reply_tx,
            &mut paused,
        ));

        let rejected: serde_json::Value =
            serde_json::from_str(&reply_rx.try_recv().expect("one command response")).unwrap();
        assert_eq!(rejected["id"], 9);
        assert_eq!(rejected["error"]["code"], -32602);
        assert!(
            rejected["error"]["message"]
                .as_str()
                .unwrap_or_default()
                .starts_with("continueRequest postData is not valid base64"),
            "the error must name the field, got {:?}",
            rejected["error"]["message"]
        );
        assert!(
            resolution_rx.try_recv().is_err(),
            "a rejected command must not resolve the pause"
        );
        assert!(
            paused.contains_key("request-1"),
            "a rejected command must leave the request paused so it can be answered again"
        );

        // the same requestId, answered correctly, still drives the fetch
        assert!(handle_fetch_resolution(
            r#"{"id":10,"method":"Fetch.continueRequest","params":{"requestId":"request-1","postData":"eyJhIjoxfQ=="}}"#,
            &reply_tx,
            &mut paused,
        ));
        let Ok(obscura_js::ops::InterceptResolution::Continue { body, .. }) = resolution_rx.try_recv() else {
            panic!("the corrected continueRequest must resolve as Continue");
        };
        assert_eq!(body.as_deref(), Some(br#"{"a":1}"#.as_slice()));
    }

    // The same strictness on the other arm carrying a CDP `binary` field.
    #[test]
    fn fulfill_request_preserves_repeated_set_cookie_headers() {
        let (tx, mut rx) = tokio::sync::oneshot::channel();
        let mut paused = HashMap::from([("document-1".into(), super::PausedIntercept { resolver: tx, main_document: true })]);
        let (reply_tx, _) = tokio::sync::mpsc::unbounded_channel();
        assert!(handle_fetch_resolution(r#"{"id":1,"method":"Fetch.fulfillRequest","params":{"requestId":"document-1","responseCode":200,"responseHeaders":[{"name":"Set-Cookie","value":"first=1; Path=/"},{"name":"Set-Cookie","value":"second=2; Path=/"},{"name":"set-cookie","value":"third=3; Path=/"},{"name":"Content-Type","value":"text/html"}]}}"#,
            &reply_tx, &mut paused));
        let Ok(obscura_js::ops::InterceptResolution::Fulfill { headers, .. }) = rx.try_recv() else {
            panic!("fulfillment must resolve the paused document");
        };
        assert_eq!(headers.get("set-cookie").unwrap(), "first=1; Path=/\nsecond=2; Path=/\nthird=3; Path=/");
        assert_eq!(headers.get("Content-Type").unwrap(), "text/html");
    }

    #[test]
    fn fulfill_request_rejects_a_body_that_is_not_base64() {
        let (resolution_tx, _resolution_rx) = tokio::sync::oneshot::channel();
        let mut paused = HashMap::from([("request-1".to_string(), super::PausedIntercept {resolver: resolution_tx, main_document: false})]);
        let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();

        assert!(handle_fetch_resolution(
            r#"{"id":11,"method":"Fetch.fulfillRequest","params":{"requestId":"request-1","responseCode":200,"body":"<html>"}}"#,
            &reply_tx,
            &mut paused,
        ));

        let rejected: serde_json::Value =
            serde_json::from_str(&reply_rx.try_recv().expect("one command response")).unwrap();
        assert_eq!(rejected["error"]["code"], -32602);
        assert!(
            rejected["error"]["message"]
                .as_str()
                .unwrap_or_default()
                .starts_with("fulfillRequest body is not valid base64")
        );
        assert!(paused.contains_key("request-1"), "the request must stay paused");
    }

    #[test]
    fn continue_request_rejects_invalid_binary_values_and_allows_retry() {
        for value in [json!(null), json!(42), json!("AA="), json!("AB=="), json!("====")] {
            let (tx, mut rx) = tokio::sync::oneshot::channel();
            let mut paused = HashMap::from([("request-1".to_string(), super::PausedIntercept { resolver: tx, main_document: false })]);
            let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
            let command = json!({"id": 1, "method": "Fetch.continueRequest",
                "params": {"requestId": "request-1", "postData": value}}).to_string();
            assert!(handle_fetch_resolution(&command, &reply_tx, &mut paused));
            let reply: serde_json::Value = serde_json::from_str(&reply_rx.try_recv().unwrap()).unwrap();
            assert_eq!(reply["error"]["code"], -32602, "accepted invalid postData: {value}");
            assert!(matches!(rx.try_recv(), Err(tokio::sync::oneshot::error::TryRecvError::Empty)));
            assert!(paused.contains_key("request-1"));
            assert!(handle_fetch_resolution(
                r#"{"id":2,"method":"Fetch.continueRequest","params":{"requestId":"request-1","postData":""}}"#,
                &reply_tx, &mut paused,
            ));
            assert!(matches!(rx.try_recv(), Ok(obscura_js::ops::InterceptResolution::Continue { body: Some(body), .. }) if body.is_empty()));
            let reply: serde_json::Value = serde_json::from_str(&reply_rx.try_recv().unwrap()).unwrap();
            assert!(reply.get("error").is_none());
        }
    }

    // An absent postData still means "leave the body alone", not "send empty".
    #[test]
    fn continue_request_without_post_data_leaves_the_body_alone() {
        let (resolution_tx, mut resolution_rx) = tokio::sync::oneshot::channel();
        let mut paused = HashMap::from([("request-1".to_string(), super::PausedIntercept {resolver: resolution_tx, main_document: false})]);
        let (reply_tx, _reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();

        assert!(handle_fetch_resolution(
            r#"{"id":1,"method":"Fetch.continueRequest","params":{"requestId":"request-1"}}"#,
            &reply_tx,
            &mut paused,
        ));

        let Ok(obscura_js::ops::InterceptResolution::Continue { body, .. }) = resolution_rx.try_recv() else {
            panic!("continueRequest must resolve as Continue");
        };
        assert!(body.is_none(), "an absent postData must not become an empty body");
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn autonomous_screencast_pumps_timers_and_retains_backpressured_damage() {
        let mut ctx = crate::dispatch::CdpContext::new();
        let page_id = ctx.create_page();
        let session_id = format!("{page_id}-session");
        ctx.sessions.insert(session_id.clone(), page_id);
        let session = Some(session_id.clone());
        ctx.get_session_page_mut(&session)
            .expect("page")
            .set_viewport((96.0, 64.0));
        crate::domains::page::handle(
            "navigate",
            &json!({
                "url": "data:text/html,<html style='margin:0'><body style='margin:0;width:96px;height:64px;background:red'></body></html>",
                "waitUntil": "load",
            }),
            &mut ctx,
            &session,
        )
        .await
        .expect("navigate screencast fixture");
        ctx.pending_events.clear();
        crate::domains::page::handle(
            "startScreencast",
            &json!({}),
            &mut ctx,
            &session,
        )
        .await
        .expect("start screencast");
        let stream_id = ctx
            .pending_events
            .iter()
            .find(|event| event.method == "Page.screencastFrame")
            .and_then(|event| event.params["sessionId"].as_i64())
            .expect("initial stream id");
        ctx.pending_events.clear();

        let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();
        ctx.get_session_page_mut(&session)
            .expect("page")
            .evaluate(
                "setTimeout(() => document.body.setAttribute('style', 'margin:0;width:96px;height:64px;background:green'), 0)",
            );
        pump_live_page_event_loop(&mut ctx, &mut Default::default()).await.unwrap();
        pump_and_forward_screencast_frames(&mut ctx, Some(&reply_tx)).await;
        let first_update: serde_json::Value = serde_json::from_str(
            &reply_rx.try_recv().expect("timer mutation should emit a frame"),
        )
        .unwrap();
        assert_eq!(first_update["method"], "Page.screencastFrame");
        assert_eq!(first_update["params"]["sessionId"], stream_id);
        assert!(reply_rx.try_recv().is_err());
        assert_eq!(ctx.screencasts[&session_id].frames_in_flight, 2);

        // The second mutation is pumped while the two-frame acknowledgement
        // window is full. It must not emit yet, but its damage must remain
        // pending and appear immediately after capacity is returned.
        ctx.get_session_page_mut(&session)
            .expect("page")
            .evaluate(
                "setTimeout(() => document.body.setAttribute('style', 'margin:0;width:96px;height:64px;background:blue'), 0)",
            );
        pump_live_page_event_loop(&mut ctx, &mut Default::default()).await.unwrap();
        pump_and_forward_screencast_frames(&mut ctx, Some(&reply_tx)).await;
        assert!(reply_rx.try_recv().is_err());
        assert!(ctx.screencasts[&session_id].autonomous_frame_pending);

        crate::domains::page::handle(
            "screencastFrameAck",
            &json!({"sessionId": stream_id}),
            &mut ctx,
            &session,
        )
        .await
        .expect("ack current frame");
        pump_and_forward_screencast_frames(&mut ctx, Some(&reply_tx)).await;
        let after_ack: serde_json::Value = serde_json::from_str(
            &reply_rx
                .try_recv()
                .expect("backpressured damage should emit after ack"),
        )
        .unwrap();
        assert_eq!(after_ack["method"], "Page.screencastFrame");
        assert_eq!(after_ack["params"]["sessionId"], stream_id);
        assert!(!ctx.screencasts[&session_id].autonomous_frame_pending);
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn autonomous_screencast_observes_raf_visual_mutations() {
        let mut ctx = crate::dispatch::CdpContext::new();
        let page_id = ctx.create_page();
        let session_id = format!("{page_id}-session");
        ctx.sessions.insert(session_id.clone(), page_id);
        let session = Some(session_id.clone());
        ctx.get_session_page_mut(&session)
            .expect("page")
            .set_viewport((96.0, 64.0));
        crate::domains::page::handle(
            "navigate",
            &json!({
                "url": "data:text/html,<html style='margin:0'><body style='margin:0;width:96px;height:64px;background:red'></body></html>",
                "waitUntil": "load",
            }),
            &mut ctx,
            &session,
        )
        .await
        .expect("navigate visual-damage fixture");
        ctx.pending_events.clear();
        crate::domains::page::handle(
            "startScreencast",
            &json!({}),
            &mut ctx,
            &session,
        )
        .await
        .expect("start screencast");
        let initial = ctx
            .pending_events
            .iter()
            .find(|event| event.method == "Page.screencastFrame")
            .expect("initial frame");
        let stream_id = initial.params["sessionId"].as_i64().unwrap();
        let initial_data = initial.params["data"].as_str().unwrap().to_string();
        ctx.pending_events.clear();
        crate::domains::page::handle(
            "screencastFrameAck",
            &json!({"sessionId": stream_id}),
            &mut ctx,
            &session,
        )
        .await
        .expect("ack initial frame");

        // Bypass CDP dispatch after scheduling the callback. The only path
        // which can deliver and capture this update is the active stream's
        // periodic event-loop/render pump.
        ctx.get_session_page_mut(&session)
            .expect("page")
            .evaluate(
                "requestAnimationFrame(() => document.body.setAttribute('style','margin:0;width:96px;height:64px;background:lime'))",
            );
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        pump_live_page_event_loop(&mut ctx, &mut Default::default()).await.unwrap();
        pump_and_forward_screencast_frames(&mut ctx, None).await;
        let raf_frame = ctx
            .pending_events
            .iter()
            .find(|event| event.method == "Page.screencastFrame")
            .expect("RAF visual mutation must autonomously emit a frame");
        assert_ne!(
            raf_frame.params["data"].as_str().unwrap(),
            initial_data,
            "RAF-driven paint must capture the updated visible state"
        );
    }
}