Skip to content

The headless browser for AI agents and web scraping

520 KB
Raw Blame
use std::sync::Arc;

use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use obscura_dom::{parse_html, DomTree};
use obscura_js::frame::FrameRealm;
use obscura_js::ops::{OriginStorage, max_live_frames, NavigationTiming};
use obscura_js::runtime::{HistoryUpdate, ObscuraJsRuntime};
use obscura_net::{
    CallbackRegistry, ObscuraHttpClient, ObscuraNetError, RequestCallback, ResourceRequest,
    ResourceType, Response, ResponseCallback,
};
use url::Url;

use crate::context::BrowserContext;
use crate::lifecycle::LifecycleState;

/// Parse `OBSCURA_GEOLOCATION="lat,lon"` for the navigator.geolocation shim.
/// Returns None when unset or malformed, leaving the built-in default in place.
/// Lets a deployment align the reported coordinates with the region its exit IP
/// resolves to, so timezone and location stay consistent (issue #228).
fn env_geolocation() -> Option<(f64, f64)> {
    let raw = std::env::var("OBSCURA_GEOLOCATION").ok()?;
    let (lat, lon) = raw.split_once(',')?;
    let lat: f64 = lat.trim().parse().ok()?;
    let lon: f64 = lon.trim().parse().ok()?;
    let valid = lat.is_finite()
        && lon.is_finite()
        && (-90.0..=90.0).contains(&lat)
        && (-180.0..=180.0).contains(&lon);
    valid.then_some((lat, lon))
}

fn decode_data_uri(uri: &str) -> Option<Vec<u8>> {
    let rest = uri.strip_prefix("data:")?;
    let comma = rest.find(',')?;
    let meta = &rest[..comma];
    let payload = &rest[comma + 1..];
    if meta.split(';').any(|t| t.eq_ignore_ascii_case("base64")) {
        let cleaned: String = payload.chars().filter(|c| !c.is_whitespace()).collect();
        BASE64.decode(cleaned).ok()
    } else {
        Some(percent_decode(payload))
    }
}

fn percent_decode(s: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(s.len());
    let b = s.as_bytes();
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' && i + 2 < b.len() {
            let hi = hex_val(b[i + 1]);
            let lo = hex_val(b[i + 2]);
            if let (Some(h), Some(l)) = (hi, lo) {
                out.push((h << 4) | l);
                i += 3;
                continue;
            }
        }
        out.push(b[i]);
        i += 1;
    }
    out
}

fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// Truncate `s` to at most `max` bytes without splitting a UTF-8 character.
/// `&s[..max]` panics if `max` lands inside a multi-byte char; the evaluated
/// expression logged below is caller-controlled, so slice it safely.
/// (`str::floor_char_boundary` would do this but is still unstable.)
fn truncate_on_char_boundary(s: &str, max: usize) -> &str {
    if s.len() <= max {
        return s;
    }
    let mut end = max;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

#[cfg(feature = "render")]
fn remaining_settle_resource_warmup_ms(
    max_ms: u64,
    elapsed: std::time::Duration,
    configured_ms: u64,
) -> u64 {
    std::time::Duration::from_millis(max_ms)
        .checked_sub(elapsed)
        .map(|remaining| {
            (remaining.as_millis().min(u128::from(u64::MAX)) as u64).min(configured_ms)
        })
        .unwrap_or(0)
}

#[cfg(feature = "stealth")]
use obscura_net::StealthHttpClient;

/// Returns true when a JS-initiated navigation would step from a
/// non-file scheme into a file: URL. We treat that move as an SOP
/// violation because the existing realm survives the navigation and
/// can read the new document's body.
pub(crate) fn cross_scheme_to_file(from: &str, to: &str) -> bool {
    let to_is_file = Url::parse(to)
        .map(|u| u.scheme().eq_ignore_ascii_case("file"))
        .unwrap_or(false);
    if !to_is_file {
        return false;
    }
    Url::parse(from)
        .map(|u| !u.scheme().eq_ignore_ascii_case("file"))
        .unwrap_or(true)
}

/// Whether a navigation target is a local file, including spellings the URL
/// parser rejects (a bare `file:` prefix) so they cannot slip past the gate.
fn url_is_file_scheme(raw: &str) -> bool {
    Url::parse(raw)
        .map(|u| u.scheme().eq_ignore_ascii_case("file"))
        .unwrap_or_else(|_| raw.trim_start().to_ascii_lowercase().starts_with("file:"))
}

/// Sub-resource fetch policy. http(s) is always fine; data: is allowed
/// because the bytes are inline in the URI (no network fetch, no SSRF);
/// file: is only allowed when the page itself was loaded from file:;
/// everything else (javascript:, chrome:, etc) is blocked.
/// Real Chrome allows data: subresources by default; Instagram and most
/// Meta properties depend on this for their inline bootstrap scripts.
fn subresource_allowed(page_url: Option<&Url>, resource: &str) -> bool {
    let Ok(target) = Url::parse(resource) else {
        return false;
    };
    let scheme = target.scheme().to_ascii_lowercase();
    match scheme.as_str() {
        "http" | "https" | "data" => true,
        "file" => page_url
            .map(|u| u.scheme().eq_ignore_ascii_case("file"))
            .unwrap_or(false),
        _ => false,
    }
}

/// Compute the default `strict-origin-when-cross-origin` referrer value used
/// for a document-initiated navigation. Direct navigations bypass this helper
/// and use an empty referrer. Referrer-Policy overrides are not yet plumbed
/// through the navigation request.
fn navigation_referrer(source: &Url, target: &Url) -> String {
    if !matches!(source.scheme(), "http" | "https")
        || !matches!(target.scheme(), "http" | "https")
        || (source.scheme() == "https" && target.scheme() == "http")
    {
        return String::new();
    }

    if source.origin() == target.origin() {
        let mut sanitized = source.clone();
        sanitized.set_fragment(None);
        let _ = sanitized.set_username("");
        let _ = sanitized.set_password(None);
        return sanitized.to_string();
    }

    let mut origin = source.origin().ascii_serialization();
    origin.push('/');
    origin
}

#[derive(Debug, Clone)]
pub struct NetworkEvent {
    pub request_id: String,
    /// The live interception channel already emitted the request start.
    pub intercepted: bool,
    pub url: String,
    pub method: String,
    pub resource_type: String,
    pub status: u16,
    pub headers: std::collections::HashMap<String, String>,
    pub response_headers: Arc<std::collections::HashMap<String, String>>,
    pub body_size: usize,
    pub timestamp: f64,
    pub error_text: Option<String>,
}

#[derive(Debug, Clone)]
pub struct StoredResponseBody {
    /// Raw response bytes. The CDP wire form (lossy text or base64, per
    /// `base64_encoded`) is produced on read by `cdp_body`, so the common
    /// case — a body that no CDP client ever asks for — pays no decode at
    /// store time and holds one copy instead of two.
    pub body: Vec<u8>,
    pub base64_encoded: bool,
}

impl StoredResponseBody {
    /// The body as CDP `Network.getResponseBody` reports it.
    pub fn cdp_body(&self) -> String {
        if self.base64_encoded {
            BASE64.encode(&self.body)
        } else {
            String::from_utf8_lossy(&self.body).into_owned()
        }
    }
}

#[derive(Clone, Copy)]
struct DeviceMetricsBaseline {
    viewport: (f32, f32),
    device_scale_factor: f32,
}

enum PendingFrameWork {
    Unattached(obscura_js::ops::PendingFrame),
    Attached {
        frame_id: u32,
        parent_frame_id: u32,
        frame_url: String,
        urls: Vec<String>,
        next_url: usize,
        sources: std::collections::HashMap<String, String>,
    },
}

impl PendingFrameWork {
    fn frame_id(&self) -> u32 {
        match self {
            Self::Unattached(frame) => frame.frame_id,
            Self::Attached { frame_id, .. } => *frame_id,
        }
    }

    fn parent_frame_id(&self) -> u32 {
        match self {
            Self::Unattached(frame) => frame.parent_frame_id,
            Self::Attached { parent_frame_id, .. } => *parent_frame_id,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PendingNavigationOutcome {
    None,
    Document,
    SameDocument,
}

pub struct Page {
    pub id: String,
    pub frame_id: String,
    pub url: Option<Url>,
    pub dom: Option<DomTree>,
    /// Live child frame realms, in creation order. Declared before `js` on
    /// purpose: a realm holds a V8 handle into that isolate, and fields drop in
    /// declaration order, so the frames must go first.
    pub frames: Vec<FrameRealm>,
    pub js: Option<ObscuraJsRuntime>,
    pub lifecycle: LifecycleState,
    pub http_client: Arc<ObscuraHttpClient>,
    pub context: Arc<BrowserContext>,
    /// `sessionStorage` backing store, keyed by origin. Owned by the Page rather
    /// than by the realm: `init_js` runs on every navigation and on CDP target
    /// switching, but a session entry must survive both while never leaving the
    /// tab (issue #678).
    session_storage: Arc<OriginStorage>,
    pub title: String,
    /// Source document URL for the current document. This is deliberately
    /// separate from `url`: direct automation navigations have no referrer,
    /// while a navigation requested by page script uses the previous document.
    pub referrer: String,
    /// CSS viewport used by responsive page JavaScript and CDP screenshots.
    /// The physical `screen` fingerprint remains independent.
    pub viewport: (f32, f32),
    /// Optional CDP physical-screen override. This is separate from the CSS
    /// viewport and survives navigation, matching device-metrics emulation.
    screen_size_override: Option<(f32, f32)>,
    screen_metrics_emulated: bool,
    locale_override: Option<String>,
    /// Metrics captured when CDP device emulation is first enabled. Chromium
    /// keeps this baseline across subsequent override calls and restores it
    /// only when the override is cleared.
    device_metrics_baseline: Option<DeviceMetricsBaseline>,
    reduced_motion: bool,
    dark_color_scheme: bool,
    /// Output device pixels per CSS pixel for CDP surface capture. Layout and
    /// CSSOM stay in CSS pixels; Emulation.setDeviceMetricsOverride owns this
    /// independent raster scale.
    pub device_scale_factor: f32,
    /// DevTools override for the compositor's base surface. It is page-owned,
    /// so it survives document navigation without leaking to other targets.
    default_background_color_override: Option<[u8; 4]>,
    /// WHATWG canonical name of the current document's character encoding
    /// (e.g. "UTF-8", "EUC-JP"), detected when the response body is decoded.
    /// Exposed to JS as `document.characterSet` and used for the URL query
    /// encoding override on `<a>`/`<area>` hrefs in legacy-charset documents.
    pub encoding: String,
    /// MIME type of the current document's main resource, lowercased and
    /// without parameters, or empty when no type was supplied.
    /// Exposed to JS as `document.contentType`.
    pub content_type: String,
    /// Monotonic origin for the current document's CSS animation timeline.
    /// It is reset once author styles are installed, so stylesheet download
    /// latency does not incorrectly advance newly-created animations.
    document_timeline_origin: std::time::Instant,
    navigation_timing: NavigationTiming,
    /// Optional page-scoped ceiling for an end-to-end navigation. Automation
    /// frontends set this from their request timeout so a caller asking for a
    /// 50-second navigation is not silently cut off by the process default.
    /// Pages without an override retain the environment-configurable default.
    navigation_timeout: Option<std::time::Duration>,
    /// Optional per-page cap. Pages without a value keep the default.
    navigation_chain_limit: Option<usize>,
    /// Navigation history for Page.getNavigationHistory / navigateToHistoryEntry.
    /// Entries are URLs in visit order; `history_index` is the current position.
    /// Pushed on every successful navigation; truncated on goBack -> new nav.
    pub history: Vec<String>,
    pub history_index: usize,
    /// Index of the current document's first history entry. Entries after it
    /// up to `history_index` are its same-document (pushState) URLs.
    document_history_start: usize,
    /// Entry a page-initiated `history.go()` is traversing to, taken with the
    /// pending navigation that loads it. Committing that load moves the cursor
    /// to the entry instead of appending a new one.
    pending_history_traversal: std::sync::Mutex<Option<usize>>,
    pub network_events: Vec<NetworkEvent>,
    response_bodies: std::collections::HashMap<String, StoredResponseBody>,
    response_body_order: std::collections::VecDeque<String>,
    network_event_counter: u32,
    pub intercept_enabled: bool,
    pub intercept_block_patterns: Vec<String>,
    pub blocked_url_patterns: Vec<String>,
    intercept_tx: Option<tokio::sync::mpsc::UnboundedSender<obscura_js::ops::InterceptedRequest>>,
    // Scripts to execute in the page's JS context BEFORE any of the page's
    // own scripts run — the CDP `Page.addScriptToEvaluateOnNewDocument`
    // contract. Includes `Runtime.addBinding` shims so puppeteer's
    // `exposeFunction` bindings exist before inline `<script>` tags execute.
    preload_scripts: Vec<String>,
    /// Whether at least one attached CDP session enabled the Runtime domain.
    /// Page-owned so the subscription survives replacement of the JS runtime
    /// during navigation.
    runtime_events_enabled: std::cell::Cell<bool>,
    console_messages_enabled: std::cell::Cell<bool>,
    pending_frame_work: std::collections::VecDeque<PendingFrameWork>,
    /// Document-owned HTML script preparation flags saved while the V8 realm
    /// is suspended for CDP/MCP tab switching.  These are restored only when
    /// the same surviving DomTree is resumed; navigation clears them.
    suspended_started_script_ids: Vec<u32>,
    /// Re-creatable CDP handles retained while tab switching replaces this
    /// page's V8 runtime. Chromium keeps these handles alive with the target;
    /// preserving them avoids order-dependent failures in concurrent clients.
    suspended_cdp_object_state: obscura_js::runtime::CdpObjectState,
    /// Console messages drained from the runtime when the page is suspended for
    /// tab switching, so they are not lost when the runtime is dropped (#971).
    /// Retrieved (and cleared) alongside the live messages by
    /// `take_pending_console_messages`.
    suspended_console_messages: Vec<String>,
    /// Passive on_request/on_response callbacks, scoped to this page (issue
    /// #408): they fire only for requests this page drives and die with it.
    /// Arc because the JS runtime state holds a second handle for fetch()/XHR.
    callbacks: Arc<CallbackRegistry>,
    #[cfg(feature = "stealth")]
    pub stealth_client: Option<Arc<StealthHttpClient>>,
}

const MAX_STYLESHEET_IMPORT_DEPTH: u8 = 4;
const MAX_STYLESHEET_RESOURCES: usize = 128;
const DEFAULT_NAVIGATION_TIMEOUT_MS: u64 = 30_000;

/// The first navigation counts. The low default stops a page that resets
/// `location` on every load.
const DEFAULT_NAVIGATION_CHAIN_LIMIT: usize = 10;

fn default_navigation_timeout() -> std::time::Duration {
    navigation_timeout_from_env_value(std::env::var("OBSCURA_NAV_TIMEOUT_MS").ok().as_deref())
}

fn navigation_timeout_from_env_value(value: Option<&str>) -> std::time::Duration {
    let milliseconds = value
        .and_then(|value| value.parse().ok())
        .unwrap_or(DEFAULT_NAVIGATION_TIMEOUT_MS);
    std::time::Duration::from_millis(milliseconds)
}

fn default_navigation_chain_limit() -> usize {
    navigation_chain_limit_from_env_value(std::env::var("OBSCURA_NAV_CHAIN_LIMIT").ok().as_deref())
}

fn navigation_chain_limit_from_env_value(value: Option<&str>) -> usize {
    // Only an unreadable value falls back to the default, so
    // `OBSCURA_NAV_CHAIN_LIMIT=0` and `set_navigation_chain_limit(0)` agree.
    value
        .and_then(|value| value.parse::<usize>().ok())
        .map(|limit| limit.max(1))
        .unwrap_or(DEFAULT_NAVIGATION_CHAIN_LIMIT)
}

fn duration_millis_u64(duration: std::time::Duration) -> u64 {
    duration.as_millis().min(u128::from(u64::MAX)) as u64
}

#[derive(Clone)]
struct LoadedStylesheet {
    response_url: Url,
    imports: Vec<StylesheetImport>,
    rules: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct StylesheetImport {
    url: String,
    media: Option<String>,
}

#[derive(Clone, Copy)]
enum AuthorStylesheetTarget {
    Linked(usize),
    InlineImport(usize),
}

fn canonical_stylesheet_url(mut url: Url) -> (String, Url) {
    url.set_fragment(None);
    (url.to_string(), url)
}

/// Expand a cached stylesheet graph in CSS cascade order. Network deduplication
/// is separate from expansion: a shared import is downloaded once but expanded
/// at each import position, while the active stack cuts cycles.
fn materialize_stylesheet_graph(
    key: &str,
    sheets: &std::collections::HashMap<String, LoadedStylesheet>,
    aliases: &std::collections::HashMap<String, String>,
    active: &mut std::collections::HashSet<String>,
) -> Option<String> {
    let actual_key = aliases.get(key).map(String::as_str).unwrap_or(key);
    if !active.insert(actual_key.to_string()) {
        return None;
    }
    let Some(sheet) = sheets.get(actual_key).cloned() else {
        active.remove(actual_key);
        return None;
    };

    let mut output = String::new();
    for import in &sheet.imports {
        let Ok(import_url) = sheet.response_url.join(&import.url) else {
            continue;
        };
        let (import_key, _) = canonical_stylesheet_url(import_url);
        if let Some(imported) = materialize_stylesheet_graph(&import_key, sheets, aliases, active) {
            if let Some(media) = import.media.as_deref() {
                output.push_str("@media ");
                output.push_str(media);
                output.push_str(" {\n");
                output.push_str(&imported);
                output.push_str("\n}\n");
            } else {
                output.push_str(&imported);
                output.push('\n');
            }
        }
    }
    output.push_str(&rebase_css_urls(&sheet.rules, &sheet.response_url));
    active.remove(actual_key);
    Some(output)
}

fn stylesheet_graph_is_origin_clean(
    key: &str,
    sheets: &std::collections::HashMap<String, LoadedStylesheet>,
    aliases: &std::collections::HashMap<String, String>,
    active: &mut std::collections::HashSet<String>,
    document_url: &Url,
) -> bool {
    let actual_key = aliases.get(key).map(String::as_str).unwrap_or(key);
    if !active.insert(actual_key.to_string()) {
        return true;
    }
    let Some(sheet) = sheets.get(actual_key) else {
        active.remove(actual_key);
        return true;
    };
    let clean = sheet.response_url.origin() == document_url.origin()
        && sheet.imports.iter().all(|import| {
            let Ok(import_url) = sheet.response_url.join(&import.url) else {
                return true;
            };
            let (import_key, _) = canonical_stylesheet_url(import_url);
            stylesheet_graph_is_origin_clean(&import_key, sheets, aliases, active, document_url)
        });
    active.remove(actual_key);
    clean
}

/// Preserve the URL base of a fetched stylesheet after it is materialized as
/// inline CSS. Relative `url(...)` values resolve against the stylesheet's
/// URL in browsers, not the document URL; failing to rebase them drops common
/// background, mask, cursor, and font assets from nested theme directories.
fn rebase_css_urls(css: &str, base: &url::Url) -> String {
    let mut out = String::with_capacity(css.len());
    let mut index = 0usize;
    while index < css.len() {
        let rest = &css[index..];
        if rest.starts_with("/*") {
            if let Some(end) = rest[2..].find("*/") {
                let length = end + 4;
                out.push_str(&rest[..length]);
                index += length;
            } else {
                out.push_str(rest);
                break;
            }
            continue;
        }
        let Some(first) = rest.chars().next() else {
            break;
        };
        if first == '"' || first == '\'' {
            let quote = first;
            let mut escaped = false;
            let mut length = quote.len_utf8();
            for ch in rest[quote.len_utf8()..].chars() {
                length += ch.len_utf8();
                if escaped {
                    escaped = false;
                } else if ch == '\\' {
                    escaped = true;
                } else if ch == quote {
                    break;
                }
            }
            out.push_str(&rest[..length]);
            index += length;
            continue;
        }
        let is_url = rest
            .get(..4)
            .map_or(false, |prefix| prefix.eq_ignore_ascii_case("url("));
        if !is_url {
            out.push(first);
            index += first.len_utf8();
            continue;
        }

        let mut quote = None;
        let mut escaped = false;
        let mut end = None;
        for (offset, ch) in rest[4..].char_indices() {
            if escaped {
                escaped = false;
                continue;
            }
            if ch == '\\' {
                escaped = true;
                continue;
            }
            match quote {
                Some(open) if ch == open => quote = None,
                Some(_) => {}
                None if ch == '"' || ch == '\'' => quote = Some(ch),
                None if ch == ')' => {
                    end = Some(4 + offset);
                    break;
                }
                None => {}
            }
        }
        let Some(end) = end else {
            out.push_str(rest);
            break;
        };
        let raw = rest[4..end].trim();
        let value = if raw.len() >= 2
            && ((raw.starts_with('"') && raw.ends_with('"'))
                || (raw.starts_with('\'') && raw.ends_with('\'')))
        {
            &raw[1..raw.len() - 1]
        } else {
            raw
        };
        let resolved = if value.is_empty()
            || value.starts_with('#')
            || value.contains("var(")
            || url::Url::parse(value).is_ok()
        {
            None
        } else {
            base.join(value).ok().map(|url| url.to_string())
        };
        if let Some(resolved) = resolved {
            out.push_str("url(\"");
            for ch in resolved.chars() {
                if ch == '\\' || ch == '"' {
                    out.push('\\');
                }
                out.push(ch);
            }
            out.push_str("\")");
        } else {
            out.push_str(&rest[..=end]);
        }
        index += end + 1;
    }
    out
}

/// Extract network-backed `url(...)` assets while respecting CSS comments and
/// strings. Linked sheets have already been rebased before materialization;
/// inline declarations are resolved against the document base here.
#[cfg(any(feature = "render", test))]
fn css_resource_urls(css: &str, base: &url::Url) -> Vec<String> {
    let mut urls = Vec::new();
    let mut index = 0usize;
    while index < css.len() {
        let rest = &css[index..];
        if rest.starts_with("/*") {
            if let Some(end) = rest[2..].find("*/") {
                index += end + 4;
            } else {
                break;
            }
            continue;
        }
        // `@import url(...)` is a stylesheet dependency, not a paint asset.
        // It is fetched by the bounded stylesheet graph above. Letting the
        // generic image/font warmup rediscover it issues a second request with
        // the wrong ResourceType::Image classification.
        if let Some(length) = css_import_rule_len(rest) {
            index += length;
            continue;
        }
        // A `@font-face` `src` list is a priority order, not a set of
        // resources. Scanning it generically warms every entry of every
        // descriptor; the renderer considers far fewer. `css_font_face_rule`
        // collects the ones it will consider and reports the whole block as
        // consumed, the same shape as the `@import` skip above.
        if let Some((length, sources)) = css_font_face_rule(rest, base) {
            urls.extend(sources);
            index += length;
            continue;
        }
        let Some(first) = rest.chars().next() else {
            break;
        };
        if first == '"' || first == '\'' {
            let quote = first;
            let mut escaped = false;
            let mut length = quote.len_utf8();
            for ch in rest[quote.len_utf8()..].chars() {
                length += ch.len_utf8();
                if escaped {
                    escaped = false;
                } else if ch == '\\' {
                    escaped = true;
                } else if ch == quote {
                    break;
                }
            }
            index += length;
            continue;
        }
        if !rest
            .get(..4)
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case("url("))
        {
            index += first.len_utf8();
            continue;
        }
        let mut quote = None;
        let mut escaped = false;
        let mut end = None;
        for (offset, ch) in rest[4..].char_indices() {
            if escaped {
                escaped = false;
                continue;
            }
            if ch == '\\' {
                escaped = true;
                continue;
            }
            match quote {
                Some(open) if ch == open => quote = None,
                Some(_) => {}
                None if ch == '"' || ch == '\'' => quote = Some(ch),
                None if ch == ')' => {
                    end = Some(4 + offset);
                    break;
                }
                None => {}
            }
        }
        let Some(end) = end else { break };
        push_css_url(&rest[4..end], base, &mut urls);
        index += end + 1;
    }
    urls
}

/// Record one `url(...)` value when it names a network resource.
///
/// Shared by the generic scan and the `@font-face` path so the two cannot
/// disagree about quoting, fragments, `data:` or an unresolved `var()`.
#[cfg(any(feature = "render", test))]
fn push_css_url(raw: &str, base: &url::Url, urls: &mut Vec<String>) {
    let raw = raw.trim();
    let value = if raw.len() >= 2
        && ((raw.starts_with('"') && raw.ends_with('"'))
            || (raw.starts_with('\'') && raw.ends_with('\'')))
    {
        &raw[1..raw.len() - 1]
    } else {
        raw
    };
    if value.is_empty()
        || value.starts_with('#')
        || value.starts_with("data:")
        || value.contains("var(")
    {
        return;
    }
    if let Ok(mut url) = base.join(value) {
        url.set_fragment(None);
        if matches!(url.scheme(), "http" | "https") {
            urls.push(url.to_string());
        }
    }
}

/// Return the byte length of a leading `@font-face` block, together with the
/// sources the renderer will actually consider, in source order.
///
/// A `src` list is a priority order, not a set. Both rules here are taken from
/// the layer this warms, `obscura-render`: `font_face_declaration` ends in
/// `.last()`, so a rule carrying several `src` descriptors uses the final one,
/// which is the cascade and what the `src: url(.eot); src: url(...)` idiom
/// relies on; and `font_source_may_be_supported` drops `.eot` and `.svg` after
/// stripping the query and fragment. Warming anything else fetches bytes the
/// renderer has already ruled out.
///
/// A malformed block is left to the normal scanner, so this cannot swallow the
/// rules that follow it.
#[cfg(any(feature = "render", test))]
fn css_font_face_rule(css: &str, base: &url::Url) -> Option<(usize, Vec<String>)> {
    if !css.get(..10)?.eq_ignore_ascii_case("@font-face") {
        return None;
    }
    let open_relative = css[10..].find('{')?;
    if !css[10..10 + open_relative].trim().is_empty() {
        return None;
    }
    let open = 10 + open_relative;
    let close = open + css_block_end(&css[open..])?;

    let mut urls = Vec::new();
    if let Some(src) = css_last_declaration(&css[open + 1..close], "src") {
        for value in css_url_values(src) {
            if font_source_is_decodable(value) {
                push_css_url(value, base, &mut urls);
            }
        }
    }
    Some((close + 1, urls))
}

/// Byte offset of the brace closing the block that `css` opens, or `None` when
/// the block is unterminated. Braces inside strings do not count.
#[cfg(any(feature = "render", test))]
fn css_block_end(css: &str) -> Option<usize> {
    let mut depth = 0usize;
    let mut quote: Option<char> = None;
    let mut escaped = false;
    for (offset, ch) in css.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if ch == '\\' {
            escaped = true;
            continue;
        }
        if let Some(open) = quote {
            if ch == open {
                quote = None;
            }
            continue;
        }
        match ch {
            '"' | '\'' => quote = Some(ch),
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    return Some(offset);
                }
            }
            _ => {}
        }
    }
    None
}

/// Value of the last declaration named `name` in a declaration block. Last
/// rather than first, because that is what the cascade resolves to and what
/// `obscura-render` reads.
#[cfg(any(feature = "render", test))]
fn css_last_declaration<'a>(block: &'a str, name: &str) -> Option<&'a str> {
    let mut found = None;
    let mut start = 0usize;
    let mut depth = 0usize;
    let mut quote: Option<char> = None;
    let mut escaped = false;
    let mut boundaries: Vec<usize> = Vec::new();
    for (offset, ch) in block.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if ch == '\\' {
            escaped = true;
            continue;
        }
        if let Some(open) = quote {
            if ch == open {
                quote = None;
            }
            continue;
        }
        match ch {
            '"' | '\'' => quote = Some(ch),
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            ';' if depth == 0 => boundaries.push(offset),
            _ => {}
        }
    }
    boundaries.push(block.len());
    for end in boundaries {
        let declaration = &block[start..end];
        start = (end + 1).min(block.len());
        let Some((property, value)) = declaration.split_once(':') else {
            continue;
        };
        if property.trim().eq_ignore_ascii_case(name) {
            found = Some(value.trim());
        }
    }
    found
}

/// The `url(...)` values of one declaration, unquoted, in source order.
#[cfg(any(feature = "render", test))]
fn css_url_values(value: &str) -> Vec<&str> {
    let lower = value.to_ascii_lowercase();
    let mut out = Vec::new();
    let mut cursor = 0usize;
    while let Some(relative) = lower[cursor..].find("url(") {
        let start = cursor + relative + 4;
        let Some(end_relative) = value[start..].find(')') else {
            break;
        };
        let end = start + end_relative;
        let raw = value[start..end].trim();
        let unquoted = if raw.len() >= 2
            && ((raw.starts_with('"') && raw.ends_with('"'))
                || (raw.starts_with('\'') && raw.ends_with('\'')))
        {
            &raw[1..raw.len() - 1]
        } else {
            raw
        };
        if !unquoted.is_empty() {
            out.push(unquoted);
        }
        cursor = end + 1;
    }
    out
}

/// Whether the renderer can decode a font source, by the same extension rule
/// `obscura-render` applies before it will even consider one.
#[cfg(any(feature = "render", test))]
fn font_source_is_decodable(src: &str) -> bool {
    let path = src
        .split(['?', '#'])
        .next()
        .unwrap_or(src)
        .to_ascii_lowercase();
    !path.ends_with(".eot") && !path.ends_with(".svg")
}

/// Return the byte length of a leading CSS `@import` rule, including its
/// terminating semicolon. Semicolons inside quoted URLs, comments, or `url()`
/// parentheses do not end the rule. A malformed import is left to the normal
/// scanner so this helper cannot swallow following declarations.
#[cfg(any(feature = "render", test))]
fn css_import_rule_len(css: &str) -> Option<usize> {
    let prefix = css.get(..7)?;
    if !prefix.eq_ignore_ascii_case("@import") {
        return None;
    }
    if css[7..]
        .chars()
        .next()
        .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_')
    {
        return None;
    }

    let bytes = css.as_bytes();
    let mut index = 7usize;
    let mut quote = None;
    let mut escaped = false;
    let mut paren_depth = 0usize;
    while index < bytes.len() {
        let byte = bytes[index];
        if let Some(open) = quote {
            if escaped {
                escaped = false;
            } else if byte == b'\\' {
                escaped = true;
            } else if byte == open {
                quote = None;
            }
            index += 1;
            continue;
        }
        if byte == b'/' && bytes.get(index + 1) == Some(&b'*') {
            let Some(end) = css[index + 2..].find("*/") else {
                return None;
            };
            index += end + 4;
            continue;
        }
        match byte {
            b'\'' | b'"' => quote = Some(byte),
            b'(' => paren_depth += 1,
            b')' => paren_depth = paren_depth.saturating_sub(1),
            b';' if paren_depth == 0 => return Some(index + 1),
            b'{' if paren_depth == 0 => return None,
            _ => {}
        }
        index += 1;
    }
    None
}

#[cfg(any(feature = "render", test))]
fn render_resource_is_font(url: &url::Url) -> bool {
    let path = url.path().to_ascii_lowercase();
    [".woff", ".woff2", ".ttf", ".otf", ".eot"]
        .iter()
        .any(|extension| path.ends_with(extension))
}

/// Pull leading `@import` rules out of a stylesheet. Returns each import target
/// URL with its optional media condition plus the CSS with those `@import`
/// statements removed. Browsers fetch media-gated imports even when they do
/// not match the current screen; preserving the condition lets the same bytes
/// participate in a later PDF print cascade. Handles `@import "x.css";`,
/// `@import url("x.css");`, `@import url(x.css);` and an optional trailing
/// media query.
fn split_css_imports(css: &str) -> (Vec<StylesheetImport>, String) {
    let mut urls = Vec::new();
    let mut stripped = String::with_capacity(css.len());
    let mut rest = css;
    loop {
        let Some(pos) = rest.find("@import") else {
            stripped.push_str(rest);
            break;
        };
        // Real sheets place `@import` at the top (after an optional @charset), so
        // scanning for it anywhere is safe in practice and tolerates minified
        // whitespace. Text before this match carries through unchanged.
        stripped.push_str(&rest[..pos]);
        let after = &rest[pos + "@import".len()..];
        let Some(semi) = after.find(';') else {
            // Malformed; keep the remainder verbatim.
            stripped.push_str(&rest[pos..]);
            break;
        };
        let stmt = &after[..semi];
        if let Some(target) = parse_import_url(stmt) {
            urls.push(target);
        } else {
            // Could not parse a URL; preserve the statement so we don't lose it.
            stripped.push_str("@import");
            stripped.push_str(&after[..=semi]);
        }
        rest = &after[semi + 1..];
    }
    (urls, stripped)
}

/// Extract the URL and optional trailing media query from an `@import`
/// statement body (the text between `@import` and `;`).
fn parse_import_url(stmt: &str) -> Option<StylesheetImport> {
    let s = stmt.trim();
    let is_url_fn = s.get(..4).is_some_and(|head| head.eq_ignore_ascii_case("url("));
    let (url, media) = if is_url_fn {
        let rest = &s[4..];
        let end = rest.find(')')?;
        let inner = rest[..end].trim().trim_matches(|c| c == '"' || c == '\'');
        (inner.to_string(), rest[end + 1..].trim())
    } else {
        let quote = s.chars().next().filter(|c| *c == '"' || *c == '\'')?;
        let rest = &s[1..];
        let end = rest.find(quote)?;
        (rest[..end].to_string(), rest[end + 1..].trim())
    };
    if url.is_empty() {
        return None;
    }
    Some(StylesheetImport {
        url,
        media: (!media.is_empty()).then(|| media.to_string()),
    })
}

/// Attach CSSOM state and dispatch load for a host-fetched linked sheet.
/// Fetched bytes live in native DOM state, never in a synthetic `<style>` that
/// page script could read.
fn register_linked_stylesheet_script(link_nid: usize, response_url: &str) -> String {
    let response_url = serde_json::to_string(response_url).unwrap_or_else(|_| "null".to_string());
    format!(
        r#"(function() {{
            var links = document.querySelectorAll('link[rel~="stylesheet"]');
            var link = null;
            for (var i = 0; i < links.length; i++) {{
                if (links[i]._nid === {link_nid}) {{ link = links[i]; break; }}
            }}
            if (!link) return;
            function syncSheet() {{
                if (Object.prototype.hasOwnProperty.call(link, 'media')) {{
                    var media = String(link.media || '');
                    if (media) link.setAttribute('media', media);
                    else link.removeAttribute('media');
                }}
                if (Object.prototype.hasOwnProperty.call(link, 'disabled')) {{
                    if (link.disabled) link.setAttribute('disabled', '');
                    else link.removeAttribute('disabled');
                }}
            }}

            syncSheet();
            globalThis.__obscura_registerLinkedStylesheet(link, {response_url});
            try {{ link.dispatchEvent(new Event('load')); }}
            finally {{ syncSheet(); }}
        }})()"#
    )
}

/// Discover linked author sheets in document order.
///
/// Media queries control whether a loaded sheet participates in the cascade;
/// they do not suppress its fetch or `load` event. Each request carries the
/// link's node id (not a query-order index) so the materialization script
/// addresses the same node even if a load handler mutates the link list (#1044).
fn linked_stylesheet_requests(dom: &DomTree) -> Vec<(usize, String)> {
    let link_ids = dom
        .query_selector_all("link[rel~=\"stylesheet\"]")
        .unwrap_or_default();
    let mut links = Vec::new();
    for lid in link_ids {
        if let Some(node) = dom.get_node(lid) {
            // Disabled alternate sheets remain dormant until script enables
            // them. Media-gated sheets are different: they still load.
            if node.get_attribute("disabled").is_some() {
                continue;
            }
            if let Some(href) = node.get_attribute("href") {
                links.push((lid.index() as usize, href.to_string()));
            }
        }
    }
    links
}

/// Discover fetchable `@import` rules in inline author sheets.
fn inline_stylesheet_import_requests(dom: &DomTree) -> Vec<(usize, StylesheetImport)> {
    let style_ids = dom.query_selector_all("style").unwrap_or_default();
    let mut imports = Vec::new();
    let mut author_index = 0usize;
    for style_id in style_ids {
        if dom.get_node(style_id).is_none() {
            continue;
        }
        let (style_imports, _) = split_css_imports(&dom.text_content(style_id));
        imports.extend(
            style_imports
                .into_iter()
                .map(|import| (author_index, import)),
        );
        author_index += 1;
    }
    imports
}

impl Page {
    pub fn new(id: String, context: Arc<BrowserContext>) -> Self {
        let http_client = context.http_client.clone();
        // Chromium convention: the main frame's frameId == the targetId.
        // Playwright's frame manager looks up the main frame by targetId
        // (via target._targetInfo.targetId), so any divergence here makes
        // Page.getFrameTree return a frame the client cannot match,
        // triggering a Target.closeTarget and "Frame has been detached".
        let frame_id = id.clone();
        #[cfg(feature = "stealth")]
        let stealth_client = if context.stealth {
            // The wreq client backing StealthHttpClient does not speak SOCKS5.
            // Callers must validate the proxy scheme up front and fail loudly
            // (see obscura-cli) rather than silently rewriting socks5:// to
            // http://, which only works when the upstream happens to be a
            // Clash-style mixed-mode proxy and breaks plain SOCKS5 servers
            // like `ssh -ND` (#160).
            let mut client = StealthHttpClient::with_proxy(
                context.cookie_jar.clone(),
                context.proxy_url.as_deref(),
                context.allow_private_network,
            ).with_user_agent(context.user_agent_override.clone());
            client.allow_file_access = context.allow_file_access;
            Some(Arc::new(client))
        } else {
            None
        };

        Page {
            id,
            frame_id,
            url: None,
            dom: None,
            frames: Vec::new(),
            js: None,
            lifecycle: LifecycleState::Idle,
            http_client,
            context,
            session_storage: Arc::new(OriginStorage::default()),
            title: String::new(),
            referrer: String::new(),
            viewport: (1280.0, 720.0),
            screen_size_override: None,
            screen_metrics_emulated: false,
            locale_override: None,
            device_metrics_baseline: None,
            reduced_motion: false,
            dark_color_scheme: false,
            device_scale_factor: 1.0,
            default_background_color_override: None,
            encoding: "UTF-8".to_string(),
            content_type: String::new(),
            document_timeline_origin: std::time::Instant::now(),
            navigation_timing: NavigationTiming::default(),
            navigation_timeout: None,
            navigation_chain_limit: None,
            history: Vec::new(),
            history_index: 0,
            document_history_start: 0,
            pending_history_traversal: std::sync::Mutex::new(None),
            network_events: Vec::new(),
            response_bodies: std::collections::HashMap::new(),
            response_body_order: std::collections::VecDeque::new(),
            network_event_counter: 0,
            intercept_enabled: false,
            intercept_block_patterns: Vec::new(),
            blocked_url_patterns: Vec::new(),
            intercept_tx: None,
            preload_scripts: Vec::new(),
            runtime_events_enabled: std::cell::Cell::new(false),
            console_messages_enabled: std::cell::Cell::new(false),
            pending_frame_work: std::collections::VecDeque::new(),
            suspended_started_script_ids: Vec::new(),
            suspended_cdp_object_state: obscura_js::runtime::CdpObjectState::default(),
            suspended_console_messages: Vec::new(),
            callbacks: Arc::new(CallbackRegistry::new()),
            #[cfg(feature = "stealth")]
            stealth_client,
        }
    }

    /// Set the end-to-end navigation deadline for this page. This page-scoped
    /// value takes precedence over `OBSCURA_NAV_TIMEOUT_MS`; callers that do
    /// not set it retain the existing environment-configurable 30s default.
    pub fn set_navigation_timeout(&mut self, timeout: std::time::Duration) {
        self.navigation_timeout = Some(timeout);
    }

    /// Return the effective end-to-end navigation deadline for this page.
    pub fn navigation_timeout(&self) -> std::time::Duration {
        self.navigation_timeout
            .unwrap_or_else(default_navigation_timeout)
    }

    /// Takes precedence over `OBSCURA_NAV_CHAIN_LIMIT`. A limit of 0 is
    /// raised to 1, which would otherwise report success having loaded
    /// nothing.
    pub fn set_navigation_chain_limit(&mut self, limit: usize) {
        self.navigation_chain_limit = Some(limit.max(1));
    }

    pub fn navigation_chain_limit(&self) -> usize {
        self.navigation_chain_limit
            .unwrap_or_else(default_navigation_chain_limit)
    }

    fn should_block_url(&self, url: &str) -> bool {
        self.blocked_url_patterns
            .iter()
            .any(|pattern| url_matches_cdp_pattern(pattern, url))
    }

    /// Moves fetched frame documents into Page ownership without doing work
    /// that can be cancelled. Realms are still created one at a time, in the
    /// same sibling order as before this queue existed.
    fn queue_pending_frames(&mut self) -> bool {
        // Keep exactly one bounded batch in Page ownership. Additional frame
        // documents remain in the runtime's existing 64-document/32 MiB queue
        // until this batch finishes, so repeated cancellation cannot multiply
        // the configured retention ceiling.
        if !self.pending_frame_work.is_empty() {
            return false;
        }
        let pending = match self.js.as_ref() {
            Some(js) => js.take_pending_frames(),
            None => return false,
        };
        if pending.is_empty() {
            return false;
        }

        self.pending_frame_work
            .extend(pending.into_iter().map(PendingFrameWork::Unattached));
        true
    }

    /// Creates, fetches, and runs the front frame. The record remains Page-
    /// owned at each await, so cancellation resumes the current URL and leaves
    /// every untouched sibling in order.
    async fn run_next_pending_frame(&mut self) -> bool {
        if matches!(self.pending_frame_work.front(), Some(PendingFrameWork::Unattached(_))) {
            let Some(PendingFrameWork::Unattached(frame)) = self.pending_frame_work.pop_front()
            else {
                return false;
            };
            // A realm is a live v8::Context plus a DOM tree, and the page realm
            // holds its window and document, so nothing here can be collected
            // while the document lives. Frames are released when the document
            // is replaced, so a page that churns iframes would otherwise grow
            // the process without bound. Refuse past the cap rather than let a
            // page decide how much memory to take.
            let cap = max_live_frames();
            if self.frames.len() >= cap {
                tracing::warn!(
                    "refusing a realm for frame {}: already at the {} live frame cap",
                    frame.url,
                    cap,
                );
                self.forget_frame_references(frame.frame_id, frame.parent_frame_id);
                return true;
            }
            let realm = match self.js.as_mut().and_then(|js| {
                FrameRealm::new(js, frame.frame_id, frame.parent_frame_id, &frame.url, &frame.html)
            }) {
                Some(realm) => realm,
                None => {
                    tracing::warn!("could not build a realm for frame {}", frame.url);
                    self.forget_frame_references(frame.frame_id, frame.parent_frame_id);
                    return true;
                }
            };
            // Discover author scripts before preload code can mutate the frame
            // DOM, preserving the existing preparation order.
            let urls = match self.js.as_mut() {
                Some(js) => realm.external_script_urls(js),
                None => Vec::new(),
            };

            if let Some(js) = self.js.as_mut() {
                if let Err(error) = realm.set_viewport(
                    js,
                    frame.viewport_width as f64,
                    frame.viewport_height as f64,
                ) {
                    tracing::debug!("frame {} viewport setup failed: {error}", frame.url);
                }
                // New-document scripts must be installed before the published
                // child context can be observed, including while its external
                // scripts are still loading.
                if frame.url != "about:blank" {
                    for source in &self.preload_scripts {
                        if let Err(error) = realm.execute_script(js, source) {
                            tracing::debug!("frame {} preload failed: {error}", frame.url);
                        }
                    }
                    if !self.preload_scripts.is_empty() {
                        let watchdog = js.arm_watchdog(std::time::Duration::from_secs(5));
                        let result = realm.execute_script(js, "globalThis.__obscura_init_frames();");
                        js.disarm_watchdog(watchdog);
                        if let Err(error) = result { tracing::debug!("frame initialization failed: {error}"); }
                    }
                }
            }
            let frame_id = frame.frame_id;
            let parent_frame_id = frame.parent_frame_id;
            let frame_url = frame.url;
            self.frames.push(realm);
            self.pending_frame_work.push_front(PendingFrameWork::Attached {
                frame_id,
                parent_frame_id,
                frame_url,
                urls,
                next_url: 0,
                sources: std::collections::HashMap::new(),
            });
        }

        while let Some((frame_id, url)) = self.pending_frame_work.front().and_then(|pending| {
            let PendingFrameWork::Attached {
                frame_id,
                urls,
                next_url,
                ..
            } = pending
            else {
                return None;
            };
            urls.get(*next_url).cloned().map(|url| (*frame_id, url))
        }) {
            let source = if self.should_block_url(&url) {
                None
            } else if let Ok(parsed) = Url::parse(&url) {
                match self.do_fetch(&parsed).await {
                    Ok(response) => Some(String::from_utf8_lossy(&response.body).into_owned()),
                    Err(error) => {
                        tracing::warn!("frame script {} failed: {}", url, error);
                        None
                    }
                }
            } else {
                None
            };

            let Some(PendingFrameWork::Attached {
                frame_id: pending_frame_id,
                urls,
                next_url,
                sources,
                ..
            }) = self.pending_frame_work.front_mut()
            else {
                return false;
            };
            if *pending_frame_id != frame_id || urls.get(*next_url) != Some(&url) {
                continue;
            }
            if let Some(source) = source {
                sources.insert(url, source);
            }
            *next_url += 1;
        }

        let Some(PendingFrameWork::Attached {
            frame_id,
            parent_frame_id,
            frame_url,
            sources,
            ..
        }) = self.pending_frame_work.front_mut()
        else {
            return false;
        };
        let frame_id = *frame_id;
        let parent_frame_id = *parent_frame_id;
        let frame_url = frame_url.clone();
        let sources = std::mem::take(sources);
        let Some(index) = self
            .frames
            .iter()
            .position(|frame| frame.frame_id() == frame_id)
        else {
            self.pending_frame_work.pop_front();
            return true;
        };
        // Initial blank documents finish synchronously during insertion.
        if frame_url != "about:blank" {
            if let Some(js) = self.js.as_mut() {
                for problem in self.frames[index]
                    .run_document_scripts(js, |url| sources.get(url).cloned())
                {
                    tracing::debug!("frame {}: {}", frame_url, problem);
                }
                if let Err(error) = self.frames[index].dispatch_load_events(js) {
                    tracing::debug!("frame {} load events failed: {error}", frame_url);
                }
            }
            self.execute_frame_owner_script(parent_frame_id, &format!(
                "(function(){{ const frame = globalThis.__obscura_frameElements[{frame_id}]; \
                 if (frame && frame.isConnected && frame._frameId === {frame_id}) \
                   frame.dispatchEvent(new Event('load')); }})()"
            ));
        }
        self.pending_frame_work.pop_front();
        true
    }

    /// Hands each queued `postMessage` to the realm it was addressed to.
    ///
    /// Reports whether anything was delivered, because a message usually causes
    /// a reply: a widget posts its result, the page answers, and the exchange
    /// only finishes if the caller settles and drains again.
    fn deliver_frame_messages(&mut self) -> bool {
        let pending = match self.js.as_ref() {
            Some(js) => js.take_pending_frame_messages(),
            None => return false,
        };
        if pending.is_empty() {
            return false;
        }

        for message in pending {
            let escaped_data = serde_json::to_string(&message.data_json).unwrap_or_default();
            let escaped_origin = serde_json::to_string(&message.origin).unwrap_or_default();
            let escaped_target_origin =
                serde_json::to_string(&message.target_origin).unwrap_or_default();
            if message.target_frame_id == 0 {
                let Some(js) = self.js.as_mut() else { continue };
                let script = format!(
                    "globalThis.__obscura_deliverMessage({escaped_data}, {escaped_origin}, {}, {escaped_target_origin}, {});",
                    message.source_frame_id,
                    message.source_context_id.map_or(-1i64, i64::from),
                );
                if let Err(error) = js.execute_script("<frame-message>", &script) {
                    tracing::debug!("message to the page failed: {error}");
                }
                continue;
            }

            let Some(index) = self
                .frames
                .iter()
                .position(|frame| frame.frame_id() == message.target_frame_id)
            else {
                // The frame was torn down between the send and the drain.
                tracing::debug!("message for frame {} which is gone", message.target_frame_id);
                continue;
            };
            let Some(js) = self.js.as_mut() else { continue };
            if let Err(error) = self.frames[index].deliver_queued_message(js, &message) {
                tracing::debug!("message to frame {} failed: {error}", message.target_frame_id);
            }
        }
        true
    }

    /// Removes the JS references owned by the iframe's parent realm and by the
    /// page's same-origin frame table. This also covers a frame rejected before
    /// a `FrameRealm` exists, so the normal drop path cannot be skipped.
    fn forget_frame_references(&mut self, frame_id: u32, parent_frame_id: u32) {
        if let Some(js) = self.js.as_mut() {
            js.forget_frame_state(frame_id);
        }
        let script = format!(
            "if (globalThis.__obscura_frameElements[{frame_id}] &&\
             globalThis.__obscura_frameElements[{frame_id}]._frameId === {frame_id}) {{\
               globalThis.__obscura_frameElements[{frame_id}]._frameId = 0;\
               if (globalThis.__obscura_frameElements[{frame_id}]._iframeWin &&\
                   !globalThis.__obscura_frameElements[{frame_id}]._iframeOpaque)\
                 globalThis.__obscura_frameElements[{frame_id}]._iframeWin._frameId = 0;\
             }}\
             delete globalThis.__obscura_frameObjects[{frame_id}];\
             delete globalThis.__obscura_frameWindows[{frame_id}];\
             delete globalThis.__obscura_frameElements[{frame_id}];"
        );
        self.execute_frame_owner_script(parent_frame_id, &script);
        if parent_frame_id != 0 {
            let page_script = format!(
                "delete globalThis.__obscura_frameObjects[{frame_id}];"
            );
            if let Some(js) = self.js.as_mut() {
                if let Err(error) = js.execute_script("<frame-detach>", &page_script) {
                    tracing::debug!("releasing page frame reference failed: {error}");
                }
            }
        }
    }

    /// Executes code in the realm that owns the iframe element. Nested
    /// iframe registries live in their parent frame, not in the page realm.
    fn execute_frame_owner_script(&mut self, parent_frame_id: u32, script: &str) {
        if parent_frame_id == 0 {
            if let Some(js) = self.js.as_mut() {
                if let Err(error) = js.execute_script("<frame-owner>", script) {
                    tracing::debug!("frame owner script failed: {error}");
                }
            }
            return;
        }

        let Some(index) = self
            .frames
            .iter()
            .position(|frame| frame.frame_id() == parent_frame_id)
        else {
            return;
        };
        let Some(js) = self.js.as_mut() else { return };
        if let Err(error) = self.frames[index].execute_script(js, script) {
            tracing::debug!("nested frame owner script failed: {error}");
        }
    }

    /// Discards the realms whose iframe element has left the document.
    ///
    /// A browser discards a child browsing context when its element is
    /// removed: the document and its context are torn down. Nothing here can
    /// be collected on its own, because the page realm holds each frame's
    /// window and document so that `contentWindow` can be the frame's real
    /// object, so a page that replaces an iframe repeatedly would otherwise
    /// accumulate contexts and DOM trees for the life of the document.
    ///
    /// Descendants are discarded in the same pass so none can run after their
    /// owner has left the document.
    fn release_detached_frames(&mut self) {
        if self.frames.is_empty() && self.pending_frame_work.is_empty() {
            return;
        }
        // Each realm reports its own frames whose element is still connected.
        // Liveness is asked of the element rather than of a document query,
        // because an iframe inside a shadow root is absent from
        // `document.querySelectorAll('iframe')` — the shape a challenge widget
        // uses — and treating it as detached tears down a live frame.
        const LIVE_FRAME_IDS: &str = "__obscura_liveFrameIds()";

        let mut live: Vec<u32> = Vec::new();
        let Some(js) = self.js.as_mut() else { return };
        match js.evaluate(LIVE_FRAME_IDS) {
            Ok(value) => live.extend(serde_json::from_value::<Vec<u32>>(value).unwrap_or_default()),
            // A query that did not run says nothing about which frames are
            // gone, and an empty answer here reads as "all of them". Holding
            // them is bounded by the live-frame cap; discarding a live frame
            // is not recoverable, so leave the tree alone.
            Err(error) => {
                tracing::debug!("could not list the page's live frames: {error}");
                return;
            }
        }
        // A frame's own children are in that frame's document, not the page's.
        for index in 0..self.frames.len() {
            let Some(js) = self.js.as_mut() else { return };
            match self.frames[index].evaluate(js, LIVE_FRAME_IDS) {
                Ok(value) => {
                    live.extend(serde_json::from_value::<Vec<u32>>(value).unwrap_or_default())
                }
                Err(error) => {
                    tracing::debug!("could not list a frame's live frames: {error}");
                    return;
                }
            }
        }
        // A synchronously initialized parent may not be in self.frames yet.
        // Its children's native owner chain still proves they are connected.
        if let Some(js) = &self.js {
            for pending in &self.pending_frame_work {
                if js.frame_is_active(pending.frame_id()) { live.push(pending.frame_id()); }
            }
        }
        let mut discarded_ids: std::collections::HashSet<u32> = self
            .frames
            .iter()
            .map(|frame| (frame.frame_id(), frame.parent_frame_id()))
            .filter(|(id, _)| !live.contains(id))
            .map(|(id, _)| id)
            .chain(
                self.pending_frame_work
                    .iter()
                    .filter(|pending| !live.contains(&pending.frame_id()))
                    .map(PendingFrameWork::frame_id),
            )
            .collect();
        loop {
            let before = discarded_ids.len();
            let descendants: Vec<u32> = self
                .frames
                .iter()
                .filter(|frame| discarded_ids.contains(&frame.parent_frame_id()))
                .map(FrameRealm::frame_id)
                .chain(
                    self.pending_frame_work
                        .iter()
                        .filter(|pending| discarded_ids.contains(&pending.parent_frame_id()))
                        .map(PendingFrameWork::frame_id),
                )
                .collect();
            discarded_ids.extend(descendants);
            if discarded_ids.len() == before {
                break;
            }
        }
        if discarded_ids.is_empty() {
            return;
        }

        let discarded: Vec<(u32, u32)> = self
            .frames
            .iter()
            .map(|frame| (frame.frame_id(), frame.parent_frame_id()))
            .chain(
                self.pending_frame_work
                    .iter()
                    .filter_map(|pending| match pending {
                        PendingFrameWork::Unattached(_) => {
                            Some((pending.frame_id(), pending.parent_frame_id()))
                        }
                        PendingFrameWork::Attached { .. } => None,
                    }),
            )
            .filter(|(id, _)| discarded_ids.contains(id))
            .collect();

        // Clean owner realms before dropping any parent. This matters for a
        // nested child whose iframe registry lives in a parent that is also
        // being removed during this pass.
        for &(frame_id, parent_frame_id) in &discarded {
            self.forget_frame_references(frame_id, parent_frame_id);
        }
        self.frames
            .retain(|frame| !discarded_ids.contains(&frame.frame_id()));
        self.pending_frame_work
            .retain(|pending| !discarded_ids.contains(&pending.frame_id()));
        tracing::debug!("discarded {} detached frame realm(s)", discarded.len());
    }

    /// Moves the frame tree forward by one step: give any fetched frame
    /// document a realm, then hand on any message waiting for a realm.
    ///
    /// Reports whether anything happened, so a caller can pump again. A new
    /// frame runs scripts that can post, and a message usually causes a reply,
    /// so neither queue is finished until both are quiet.
    async fn advance_frames(&mut self) -> bool {
        let mut queued_new = self.queue_pending_frames();
        self.release_detached_frames();
        if self.pending_frame_work.is_empty() && self.queue_pending_frames() {
            queued_new = true;
            self.release_detached_frames();
        }
        let queued = self.pending_frame_work.len();
        let mut scripts_ran = false;
        for _ in 0..queued {
            scripts_ran |= self.run_next_pending_frame().await;
        }
        let navigated = self.advance_frame_navigations();
        let delivered = self.deliver_frame_messages();
        self.release_detached_frames();
        queued_new || scripts_ran || delivered || navigated
    }

    fn advance_frame_navigations(&mut self) -> bool {
        if self.frames.is_empty() { return false; }
        let pending = match &self.js { Some(js) => js.take_pending_frame_navigations(), None => return false };
        let changed = !pending.is_empty();
        for (id, url, method, body) in pending {
            let Some(frame) = self.frames.iter().find(|frame| frame.frame_id() == id) else { continue; };
            let owner = frame.parent_frame_id();
            let script = format!("(function(){{const frame=globalThis.__obscura_frameElements[{id}];                if(frame && frame._frameId==={id} && frame.isConnected) frame._loadIframeSrc({},{{method:{},body:{}}});}})()",
                serde_json::to_string(&url).unwrap(), serde_json::to_string(&method).unwrap(), serde_json::to_string(&body).unwrap());
            self.execute_frame_owner_script(owner, &script);
        }
        changed
    }

    /// URLs of the page's live child frames, in creation order.
    pub fn frame_urls(&self) -> Vec<String> {
        self.frames
            .iter()
            .map(|frame| frame.url().to_string())
            .collect()
    }

    /// Evaluates an expression inside one of the page's child frames.
    pub fn evaluate_in_frame(
        &mut self,
        index: usize,
        expression: &str,
    ) -> Result<serde_json::Value, String> {
        let realm = self.frames.get(index).ok_or("no such frame")?;
        let js = self.js.as_mut().ok_or("no runtime")?;
        realm.evaluate(js, expression)
    }

    /// Update the page's CSS viewport. Calling this before navigation makes
    /// responsive scripts observe it from their first instruction; calling it
    /// on a live page mirrors CDP's device-metrics override surfaces.
    pub fn set_viewport(&mut self, viewport: (f32, f32)) {
        if !viewport.0.is_finite()
            || !viewport.1.is_finite()
            || viewport.0 <= 0.0
            || viewport.1 <= 0.0
        {
            return;
        }
        self.viewport = viewport;
        if let Some(js) = &mut self.js {
            js.set_viewport(viewport.0 as f64, viewport.1 as f64);
        }
    }

    /// Set or clear the CDP physical-screen override independently of layout.
    pub fn set_screen_size_override(&mut self, size: Option<(f32, f32)>, emulated: bool) {
        self.screen_size_override = size.filter(|(width, height)| {
            width.is_finite() && height.is_finite() && *width > 0.0 && *height > 0.0
        });
        self.screen_metrics_emulated = emulated;
        if let Some(js) = &mut self.js {
            js.set_screen_size_override(
                self.screen_size_override
                    .map(|(width, height)| (width as f64, height as f64)),
                self.screen_metrics_emulated,
            );
        }
    }

    pub fn set_locale_override(&mut self, locale: Option<String>) {
        self.locale_override = locale.filter(|locale| !locale.is_empty());
        if let Some(js) = &mut self.js {
            js.set_locale(self.locale_override.as_deref().unwrap_or("en-US"));
        }
    }

    /// Apply CDP device metrics relative to the metrics that were active when
    /// emulation was first enabled. A zero protocol dimension/scale is passed
    /// as `None` and therefore restores that axis from the retained baseline.
    pub fn apply_device_metrics_override(
        &mut self,
        width: Option<f32>,
        height: Option<f32>,
        device_scale_factor: Option<f32>,
        screen_size: Option<(f32, f32)>,
        mobile: bool,
    ) {
        let baseline = *self
            .device_metrics_baseline
            .get_or_insert(DeviceMetricsBaseline {
                viewport: self.viewport,
                device_scale_factor: self.device_scale_factor,
            });
        let viewport = (
            width.unwrap_or(baseline.viewport.0),
            height.unwrap_or(baseline.viewport.1),
        );
        self.set_viewport(viewport);

        // Blink uses the effective widget size as the screen size for mobile
        // emulation when no complete explicit screen size was supplied.
        let effective_screen_size = screen_size.or_else(|| mobile.then_some(viewport));
        self.set_screen_size_override(effective_screen_size, true);
        self.set_device_scale_factor(device_scale_factor.unwrap_or(baseline.device_scale_factor));
    }

    /// Disable CDP device metrics and restore the state captured by the first
    /// override. Clearing while emulation is inactive is intentionally a no-op.
    pub fn clear_device_metrics_override(&mut self) {
        let Some(baseline) = self.device_metrics_baseline.take() else {
            return;
        };
        self.set_viewport(baseline.viewport);
        self.set_screen_size_override(None, false);
        self.set_device_scale_factor(baseline.device_scale_factor);
    }

    /// Override reduced-motion and dark color-scheme preferences together.
    /// The pair persists across navigation and is shared with child documents.
    pub fn set_media_preferences(&mut self, reduce: bool, dark: bool) {
        self.reduced_motion = reduce;
        self.dark_color_scheme = dark;
        if let Some(js) = &mut self.js {
            js.set_media_preferences(reduce, dark);
        }
    }

    pub fn set_reduced_motion(&mut self, reduce: bool) {
        self.reduced_motion = reduce;
        if let Some(js) = &mut self.js {
            js.set_reduced_motion(reduce);
        }
    }

    /// Set the screenshot surface density without changing CSS layout. CDP
    /// uses zero to disable its override, which restores the native 1x surface
    /// in Obscura's headless-only model.
    pub fn set_device_scale_factor(&mut self, device_scale_factor: f32) {
        if !device_scale_factor.is_finite() || device_scale_factor < 0.0 {
            return;
        }
        self.device_scale_factor = if device_scale_factor == 0.0 {
            1.0
        } else {
            device_scale_factor
        };
        if let Some(js) = &mut self.js {
            let _ = js.execute_script(
                "<device-metrics>",
                &format!("globalThis.devicePixelRatio={};", self.device_scale_factor),
            );
        }
    }

    pub fn set_default_background_color_override(&mut self, color: Option<[u8; 4]>) {
        self.default_background_color_override = color;
    }

    #[cfg(feature = "render")]
    fn capture_surface_color(&self) -> [u8; 4] {
        self.default_background_color_override
            .unwrap_or([255, 255, 255, 255])
    }

    async fn intercept_navigation(&self, url: &Url, method: &str, body: &str, initiator: Option<&Url>) -> Result<Option<Response>, PageError> {
        use obscura_js::ops::{InterceptedRequest, InterceptResolution};
        if !self.intercept_enabled || !matches!(url.scheme(), "http" | "https")
            || (!self.intercept_block_patterns.is_empty() && !self.intercept_block_patterns.iter().any(|pattern| url_matches_cdp_pattern(pattern, url.as_str()))) {
            return Ok(None);
        }
        let Some(tx) = &self.intercept_tx else { return Ok(None); };
        let request_headers = self.http_client.extra_headers.read().await.clone();
        let (resolver, resolution) = tokio::sync::oneshot::channel();
        let request = InterceptedRequest {request_id: format!("{}.{}", self.id, self.network_event_counter + 1),
            page_id: self.id.clone(), url: url.to_string(), method: method.into(), headers: request_headers.clone(),
            resource_type: "Document".into(), resolver};
        if tx.send(request).is_err() { return Ok(None); }
        let response = match resolution.await {
            Ok(InterceptResolution::Fulfill {status, headers: supplied, body, body_base64}) => {
                let bytes = if body_base64.is_empty() { body.into_bytes() } else {
                    BASE64.decode(body_base64).map_err(|error| PageError::NetworkError(error.to_string()))?
                };
                if bytes.len() > ResourceRequest::navigation().max_response_bytes {
                    return Err(PageError::NetworkError("Fulfilled document exceeds the response body limit".into()));
                }
                let mut headers = std::collections::HashMap::new();
                for (name, value) in supplied {
                    let name = name.to_ascii_lowercase();
                    if name == "set-cookie" {
                        headers.entry(name).and_modify(|cookies: &mut String| {
                            cookies.push('\n'); cookies.push_str(&value);
                        }).or_insert(value);
                    } else { headers.insert(name, value); }
                }
                if let Some(cookies) = headers.get("set-cookie") {
                    for cookie in cookies.lines() { self.context.cookie_jar.set_cookie(cookie, url); }
                }
                let response = Response {url: url.clone(), status, headers, body: bytes, redirected_from: Vec::new()};
                let request = obscura_net::RequestInfo {url: url.clone(), method: method.into(), headers: request_headers,
                    resource_type: ResourceType::Document};
                self.callbacks.fire_request(&request).await;
                self.callbacks.fire_response(&request, &response).await;
                response
            }
            Ok(InterceptResolution::Continue {url: rewrite, method: changed_method, headers, body: changed_body}) => {
                let target = match rewrite { Some(value) => Url::parse(&value).map_err(|error| PageError::InvalidUrl(error.to_string()))?, None => url.clone() };
                if target.scheme() != url.scheme() {
                    return Err(PageError::NetworkError("Interception cannot change a navigation's URL scheme".into()));
                }
                let method = changed_method.as_deref().unwrap_or(method);
                let body = changed_body.or_else(|| (method == "POST" || !body.is_empty()).then(|| body.as_bytes().to_vec()));
                self.fetch_navigation_from_document(&target, method, body, headers, initiator).await
                    .map_err(|error| PageError::NetworkError(error.to_string()))?
            }
            Ok(InterceptResolution::Fail {reason}) => {
                let mut error = String::from("net::ERR_");
                for (index, ch) in reason.chars().enumerate() {
                    if index > 0 && ch.is_ascii_uppercase() { error.push('_'); }
                    error.push(ch.to_ascii_uppercase());
                }
                return Err(PageError::NetworkError(error));
            }
            Err(_) => return Err(PageError::NetworkError("net::ERR_ABORTED".into())),
        };
        Ok(Some(response))
    }

    async fn fetch_navigation_from_document(
        &self, url: &Url, method: &str, body: Option<Vec<u8>>,
        headers: Option<std::collections::HashMap<String, String>>, initiator: Option<&Url>,
    ) -> Result<Response, ObscuraNetError> {
        #[cfg(feature = "stealth")]
        if let Some(client) = &self.stealth_client {
            return client.fetch_navigation_request_from_document(url, method, body, headers, initiator, Some(&self.callbacks)).await;
        }
        self.http_client.fetch_navigation_request_from_document(url, method, body, headers, initiator, Some(&self.callbacks)).await
    }

    async fn do_fetch(&self, url: &Url) -> Result<Response, ObscuraNetError> {
        #[cfg(feature = "stealth")]
        if let Some(ref stealth) = self.stealth_client {
            // Pass the page callbacks so CDP Network events and
            // page.on('request'/'response') observers fire for stealth-mode
            // navigations too, matching the non-stealth path below.
            return stealth
                .fetch_with_callbacks(url, Some(&self.callbacks))
                .await;
        }
        self.http_client
            .fetch_with_callbacks(url, Some(&self.callbacks))
            .await
    }
    fn init_js(&mut self) {
        // init_js is also the new-document path.  Only resume_js explicitly
        // takes these IDs out before entering here and restores them after the
        // same DomTree is installed; a navigation must never inherit IDs from
        // a suspended prior document whose allocator may reuse them.
        self.suspended_started_script_ids.clear();
        self.suspended_cdp_object_state = obscura_js::runtime::CdpObjectState::default();
        // Drop any existing runtime so the JS realm starts clean on
        // every navigation. The old code reused the V8 isolate and
        // only re-bound `globalThis.document`, leaving window.onload,
        // custom window properties and event handlers from the prior
        // page in place. That made it possible for a page to set
        // attacker-controlled state, trigger a navigation, and then
        // run code in the next document's context.
        self.pending_frame_work.clear();
        if self.js.is_some() {
            // Every frame realm holds a V8 handle into this isolate, so the
            // frames of the outgoing document must go before the runtime does.
            self.frames.clear();
            let _ = self.js.take();
        }

        // Thread the BrowserContext's proxy through to the ES-module loader
        // and op_fetch_url so dynamic imports and JS fetch() honour the
        // configured upstream proxy (#139). When proxy_url is None this is
        // equivalent to with_base_url() (direct connection).
        let mut rt = ObscuraJsRuntime::with_base_url_and_proxy(
            &self.url_string(),
            self.context.proxy_url.clone(),
        );
        rt.set_url(&self.url_string());
        rt.set_encoding(&self.encoding);
        rt.set_content_type(&self.content_type);
        rt.set_title(&self.title);
        rt.set_referrer(&self.referrer);
        let (session_history, session_index) = self.predicted_session_history();
        rt.set_session_history(session_history, session_index, session_index);

        #[cfg(feature = "stealth")]
        if self.stealth_client.is_some() {
            rt.set_stealth(true);
            rt.set_user_agent(self.context.user_agent_override.as_deref().unwrap_or(obscura_net::STEALTH_USER_AGENT));
            rt.set_platform(
                obscura_net::STEALTH_NAVIGATOR_PLATFORM,
                obscura_net::STEALTH_UA_PLATFORM,
                obscura_net::STEALTH_UA_PLATFORM_VERSION,
            );
        } else {
            if let Ok(ua) = self.http_client.user_agent.try_read() {
                rt.set_user_agent(&ua);
            }
            rt.set_platform(
                &self.context.platform,
                &self.context.ua_platform,
                &self.context.ua_platform_version,
            );
        }
        #[cfg(not(feature = "stealth"))]
        {
            if let Ok(ua) = self.http_client.user_agent.try_read() {
                rt.set_user_agent(&ua);
            }
            rt.set_platform(
                &self.context.platform,
                &self.context.ua_platform,
                &self.context.ua_platform_version,
            );
        }
        if let Some(locale) = &self.locale_override {
            rt.set_locale(locale);
        }
        if let Some((lat, lon)) = env_geolocation() {
            rt.set_geolocation(lat, lon);
        }
        rt.set_viewport(self.viewport.0 as f64, self.viewport.1 as f64);
        rt.set_screen_size_override(
            self.screen_size_override
                .map(|(width, height)| (width as f64, height as f64)),
            self.screen_metrics_emulated,
        );

        rt.set_cookie_jar(self.context.cookie_jar.clone());
        // Web Storage lives outside the realm so a navigation cannot drop it.
        rt.set_local_storage(self.context.local_storage.clone());
        rt.set_indexed_db(self.context.indexed_db.clone());
        rt.set_session_storage(self.session_storage.clone());
        rt.set_http_client(self.http_client.clone());
        rt.set_callbacks(self.callbacks.clone());
        rt.set_blocked_urls(self.blocked_url_patterns.clone());
        #[cfg(feature = "stealth")]
        if let Some(ref stealth) = self.stealth_client {
            rt.set_stealth_client(stealth.clone());
        }

        rt.set_intercept_page_id(&self.id);
        if let Some(tx) = &self.intercept_tx {
            rt.set_intercept_tx(tx.clone());
        }
        // Re-apply intercept_enabled: enable_interception()/enable_intercept()
        // called before the first navigation sets this on the Page while the
        // runtime does not exist yet, so the new runtime would otherwise start
        // with interception disabled and op_fetch_url would never intercept.
        rt.set_intercept_enabled(self.intercept_enabled);
        rt.set_intercept_url_patterns(self.intercept_block_patterns.clone());
        #[cfg(feature = "render")]
        rt.set_intercept_block_patterns(self.intercept_block_patterns.clone());
        rt.set_runtime_events_enabled(self.runtime_events_enabled.get());
        rt.set_console_messages_enabled(self.console_messages_enabled.get());

        if let Some(dom) = self.dom.take() {
            rt.set_dom(dom);
        }

        rt.set_navigation_timing(self.navigation_timing.clone());
        rt.set_frame_preload_scripts(&self.preload_scripts);
        rt.run_page_init();
        rt.set_media_preferences(self.reduced_motion, self.dark_color_scheme);
        let _ = rt.execute_script(
            "<device-metrics>",
            &format!("globalThis.devicePixelRatio={};", self.device_scale_factor),
        );

        self.js = Some(rt);
    }

    /// Resolve the document base URL per HTML spec:
    /// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#document-base-url
    /// Falls back to self.url when no <base href> exists.
    fn resolve_base_url(&self) -> Option<url::Url> {
        let doc_url = self.url.as_ref()?;
        let base_href: Option<String> = self.js.as_ref().and_then(|js| {
            js.with_dom(|dom| match dom.query_selector("base[href]") {
                Ok(Some(nid)) => dom
                    .get_node(nid)
                    .and_then(|n| n.get_attribute("href").map(|s| s.to_string())),
                _ => None,
            })
            .flatten()
        });
        match base_href {
            Some(href) => doc_url.join(&href).ok(),
            None => Some(doc_url.clone()),
        }
    }

    async fn fetch_stylesheets(&mut self) -> Vec<(AuthorStylesheetTarget, String, bool, String)> {
        let (all_links, inline_imports) = match &self.js {
            Some(js) => js
                .with_dom(|dom| {
                    (
                        linked_stylesheet_requests(dom),
                        inline_stylesheet_import_requests(dom),
                    )
                })
                .unwrap_or_default(),
            None => {
                tracing::info!("fetch_stylesheets: no js runtime");
                return Vec::new();
            }
        };

        tracing::info!(
            "fetch_stylesheets: found {} stylesheet links and {} inline imports",
            all_links.len(),
            inline_imports.len()
        );

        let Some(document_url) = self.url.clone() else {
            return Vec::new();
        };
        let document_base = self
            .resolve_base_url()
            .unwrap_or_else(|| document_url.clone());
        let mut roots = Vec::new();
        let mut scheduled = std::collections::HashSet::new();
        let mut pending = Vec::new();
        for (link_index, href) in all_links {
            let Ok(resolved) = document_base.join(&href) else {
                continue;
            };
            let (key, resolved) = canonical_stylesheet_url(resolved);
            if !subresource_allowed(Some(&document_url), resolved.as_str()) {
                tracing::warn!(
                    "blocking cross-scheme <link rel=stylesheet href>: page={} href={}",
                    self.url_string(),
                    resolved,
                );
                continue;
            }
            if self.should_block_url(resolved.as_str()) {
                tracing::info!("Blocked stylesheet by interception: {}", resolved);
                continue;
            }
            roots.push((AuthorStylesheetTarget::Linked(link_index), key.clone(), None));
            if scheduled.insert(key.clone()) {
                if scheduled.len() <= MAX_STYLESHEET_RESOURCES {
                    pending.push((key, resolved, 0u8));
                }
            }
        }
        for (style_index, import) in inline_imports {
            let Ok(resolved) = document_base.join(&import.url) else {
                continue;
            };
            let (key, resolved) = canonical_stylesheet_url(resolved);
            if !subresource_allowed(Some(&document_url), resolved.as_str())
                || self.should_block_url(resolved.as_str())
            {
                tracing::info!("Blocked inline stylesheet import: {}", resolved);
                continue;
            }
            roots.push((
                AuthorStylesheetTarget::InlineImport(style_index),
                key.clone(),
                import.media,
            ));
            if scheduled.insert(key.clone()) && scheduled.len() <= MAX_STYLESHEET_RESOURCES {
                pending.push((key, resolved, 1u8));
            }
        }

        let mut sheets = std::collections::HashMap::new();
        let mut aliases = std::collections::HashMap::new();
        while !pending.is_empty() {
            let batch = std::mem::take(&mut pending);
            let client = self.http_client.clone();
            #[cfg(feature = "stealth")]
            let stealth_client = self.stealth_client.clone();
            let callbacks = self.callbacks.clone();
            let initiator = document_url.clone();
            use futures::StreamExt as _;
            let results: Vec<_> =
                futures::stream::iter(batch.into_iter().map(|(key, requested_url, depth)| {
                    let client = client.clone();
                    #[cfg(feature = "stealth")]
                    let stealth_client = stealth_client.clone();
                    let callbacks = callbacks.clone();
                    let initiator = initiator.clone();
                    async move {
                        let request =
                            ResourceRequest::subresource(ResourceType::Stylesheet, &initiator);
                        #[cfg(feature = "stealth")]
                        let result = if let Some(stealth_client) = stealth_client {
                            stealth_client
                                .fetch_resource_with_callbacks(
                                    &requested_url,
                                    request,
                                    Some(&callbacks),
                                )
                                .await
                        } else {
                            client
                                .fetch_resource_with_callbacks(
                                    &requested_url,
                                    request,
                                    Some(&callbacks),
                                )
                                .await
                        };
                        #[cfg(not(feature = "stealth"))]
                        let result = client
                            .fetch_resource_with_callbacks(
                                &requested_url,
                                request,
                                Some(&callbacks),
                            )
                            .await;
                        (key, requested_url, depth, result)
                    }
                }))
                .buffered(16)
                .collect()
                .await;

            for (key, requested_url, depth, result) in results {
                let response = match result {
                    Ok(response) => response,
                    Err(error) => {
                        tracing::debug!("Failed to fetch stylesheet {}: {}", requested_url, error);
                        continue;
                    }
                };
                let response_url = response.url.clone();
                self.record_network_event_with_body(
                    response_url.as_str(),
                    "GET",
                    "Stylesheet",
                    response.status,
                    &response.headers,
                    &response.body,
                    false,
                );

                let (response_key, response_url) = canonical_stylesheet_url(response_url);
                if let Some(existing) = aliases.get(&response_key).cloned() {
                    aliases.insert(key, existing);
                    continue;
                }
                let css = obscura_net::decode_non_html(&response.body, response.content_type());
                let (imports, rules) = split_css_imports(&css);
                let imports = if depth < MAX_STYLESHEET_IMPORT_DEPTH {
                    imports
                } else {
                    Vec::new()
                };
                aliases.insert(key.clone(), key.clone());
                aliases.insert(response_key, key.clone());
                sheets.insert(
                    key,
                    LoadedStylesheet {
                        response_url: response_url.clone(),
                        imports: imports.clone(),
                        rules,
                    },
                );

                if depth >= MAX_STYLESHEET_IMPORT_DEPTH {
                    continue;
                }
                for import in imports {
                    let Ok(import_url) = response_url.join(&import.url) else {
                        continue;
                    };
                    let (import_key, import_url) = canonical_stylesheet_url(import_url);
                    if aliases.contains_key(&import_key) || scheduled.contains(&import_key) {
                        continue;
                    }
                    if scheduled.len() >= MAX_STYLESHEET_RESOURCES {
                        tracing::warn!(
                            "stylesheet resource cap reached at {} resources",
                            MAX_STYLESHEET_RESOURCES
                        );
                        continue;
                    }
                    if !subresource_allowed(Some(&document_url), import_url.as_str())
                        || self.should_block_url(import_url.as_str())
                    {
                        tracing::info!("Blocked stylesheet import: {}", import_url);
                        continue;
                    }
                    scheduled.insert(import_key.clone());
                    pending.push((import_key, import_url, depth + 1));
                }
            }
        }

        roots
            .into_iter()
            .filter_map(|(target, key, media)| {
                let actual_key = aliases.get(&key).map(String::as_str).unwrap_or(&key);
                let response_url = sheets.get(actual_key)?.response_url.to_string();
                let origin_clean = stylesheet_graph_is_origin_clean(
                    &key,
                    &sheets,
                    &aliases,
                    &mut std::collections::HashSet::new(),
                    &document_url,
                );
                materialize_stylesheet_graph(
                    &key,
                    &sheets,
                    &aliases,
                    &mut std::collections::HashSet::new(),
                )
                .map(|css| {
                    let css = match media {
                        Some(media) => format!("@media {media} {{\n{css}\n}}\n"),
                        None => css,
                    };
                    (target, css, origin_clean, response_url)
                })
            })
            .collect()
    }

    async fn execute_scripts(&mut self) {
        self.execute_scripts_with_module_budget(None).await;
    }

    /// Drive a selected script queue until it empties or the shared parser
    /// deadline expires. The caller chooses the queue so parser blockers and
    /// load-delaying dynamic scripts keep their distinct lifecycle semantics.
    async fn drive_pending_scripts(
        js: &mut ObscuraJsRuntime,
        deadline: tokio::time::Instant,
        pending: fn(&mut ObscuraJsRuntime) -> bool,
        label: &str,
    ) -> bool {
        while pending(js) {
            let Some(remaining) = deadline.checked_duration_since(tokio::time::Instant::now())
            else {
                return false;
            };
            if remaining.is_zero() {
                return false;
            }
            let poll_budget = remaining.min(tokio::time::Duration::from_millis(25));
            match tokio::time::timeout(
                poll_budget,
                js.run_load_delaying_event_loop_tick(),
            )
            .await
            {
                Ok(Ok(_idle)) => {
                    if pending(js) {
                        tokio::task::yield_now().await;
                    }
                }
                Ok(Err(error)) => {
                    if obscura_js::runtime::is_fatal_event_loop_error(&error) {
                        tracing::warn!("{label} script event loop failed: {error}");
                        return false;
                    }
                    // A load-delaying script threw or left an unhandled
                    // rejection. Chrome reports the error and runs the rest;
                    // killing the pump would strand every still-pending script
                    // (#699). The absolute deadline above bounds a page that
                    // errors on every turn.
                    tracing::warn!("{label} script task error, continuing: {error}");
                    tokio::task::yield_now().await;
                }
                Err(_) => {
                    // This timeout only cancels a parked event-loop poll. The
                    // shared absolute deadline above remains authoritative.
                }
            }
        }
        true
    }

    async fn drive_load_delaying_scripts(
        js: &mut ObscuraJsRuntime,
        deadline: tokio::time::Instant,
    ) -> bool {
        Self::drive_pending_scripts(
            js,
            deadline,
            ObscuraJsRuntime::has_pending_load_delaying_scripts,
            "load-delaying",
        )
        .await
    }

    async fn drive_parser_blocking_scripts(
        js: &mut ObscuraJsRuntime,
        deadline: tokio::time::Instant,
    ) -> bool {
        Self::drive_pending_scripts(
            js,
            deadline,
            ObscuraJsRuntime::has_pending_parser_blocking_scripts,
            "parser-blocking",
        )
        .await
    }

    async fn execute_scripts_with_module_budget(&mut self, module_budget_override: Option<u64>) {
        let scripts_started = std::time::Instant::now();
        tracing::info!(
            "execute_scripts called, js runtime exists: {}",
            self.js.is_some()
        );
        // Soft deadline on the entire script-execution phase. Heavy SPAs
        // (GitHub, Linear, CodeSandbox) ship 50+ scripts and our serial
        // fetch + execute loop can blow past a Puppeteer/Playwright goto
        // timeout. The old 10s default was too tight: a heavy React/Vue/Angular
        // SPA had its remaining scripts skipped before the app booted, so it
        // never fired its XHR/fetch calls and page.on('response') saw nothing
        // (issue #361). Only pages that actually run past the deadline are
        // affected; fast pages finish and return well before it, so a larger
        // budget costs them nothing. 30s gives an app room to initialize while
        // the per-phase watchdog (armed at this + 1s) still bounds a real
        // synchronous hang. Raise it further with OBSCURA_SCRIPT_DEADLINE_MS=<ms>
        // for very heavy SPAs on slow networks (pair it with a matching client
        // navigation timeout).
        let script_deadline_ms: u64 = std::env::var("OBSCURA_SCRIPT_DEADLINE_MS")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(30_000);
        let script_deadline =
            tokio::time::Instant::now() + tokio::time::Duration::from_millis(script_deadline_ms);

        // Hard backstop over the WHOLE script-execution phase. Inline scripts
        // run back-to-back with no await between them, so neither the soft
        // deadline above (only checked between scripts) nor the per-script guard
        // can interrupt a page that burns the budget across many synchronous
        // scripts (the real-world SPA / anti-bot busy-loop hang). This watchdog
        // terminates the isolate if cumulative synchronous script work overruns.
        let exec_wd = self
            .js
            .as_mut()
            .map(|js| js.arm_watchdog(std::time::Duration::from_millis(script_deadline_ms + 1000)));

        #[derive(Debug, Clone, Copy)]
        enum ScriptKind {
            Classic,
            Module,
            ImportMap,
        }

        #[derive(Debug)]
        struct ScriptInfo {
            src: Option<String>,
            inline: String,
            is_defer: bool,
            is_async: bool,
            kind: ScriptKind,
            nid: u32,
            /// Document base URL at this element's parser encounter point.
            base_url: String,
        }

        let all_scripts = match &self.js {
            Some(js) => {
                let document_url = self.url_string();
                js.with_dom(|dom| {
                    let script_ids = dom.query_selector_all("script").unwrap_or_default();
                    let mut bases_at_script = std::collections::HashMap::new();
                    let mut active_base = url::Url::parse(&document_url).ok();
                    let mut found_base = false;
                    for nid in dom.descendants(dom.document()) {
                        let Some(node) = dom.get_node(nid) else {
                            continue;
                        };
                        let Some(name) = node.as_element() else {
                            continue;
                        };
                        if name.local.as_ref() == "base" && !found_base {
                            if let Some(href) = node.get_attribute("href") {
                                found_base = true;
                                if let Some(resolved) =
                                    active_base.as_ref().and_then(|base| base.join(href).ok())
                                {
                                    active_base = Some(resolved);
                                }
                            }
                        } else if name.local.as_ref() == "script" {
                            bases_at_script.insert(
                                nid.raw(),
                                active_base
                                    .as_ref()
                                    .map(ToString::to_string)
                                    .unwrap_or_else(|| document_url.clone()),
                            );
                        }
                    }
                    let mut scripts = Vec::new();

                    for sid in script_ids {
                        if let Some(node) = dom.get_node(sid) {
                            let src = node.get_attribute("src").map(|s| s.to_string());
                            let script_type = node
                                .get_attribute("type")
                                .unwrap_or("")
                                .trim()
                                .to_ascii_lowercase();
                            let is_defer = node.get_attribute("defer").is_some();
                            let is_async = node.get_attribute("async").is_some();
                            let kind = match script_type.as_str() {
                                "module" => ScriptKind::Module,
                                "importmap" => ScriptKind::ImportMap,
                                "" | "text/javascript" | "application/javascript" => {
                                    ScriptKind::Classic
                                }
                                _ => continue,
                            };
                            // HTML "prepare the script element": a classic
                            // script with `nomodule` does not run in a browser
                            // that supports module scripts. Sites ship a modern
                            // module build beside a nomodule legacy build;
                            // running both mixes their webpack runtimes.
                            if matches!(kind, ScriptKind::Classic)
                                && node.get_attribute("nomodule").is_some()
                            {
                                continue;
                            }

                            let inline_code = if src.is_none() {
                                dom.text_content(sid)
                            } else {
                                String::new()
                            };

                            if matches!(kind, ScriptKind::ImportMap)
                                || src.is_some()
                                || !inline_code.trim().is_empty()
                            {
                                scripts.push(ScriptInfo {
                                    src,
                                    inline: inline_code,
                                    is_defer,
                                    is_async,
                                    kind,
                                    nid: sid.raw(),
                                    base_url: bases_at_script
                                        .get(&sid.raw())
                                        .cloned()
                                        .unwrap_or_else(|| document_url.clone()),
                                });
                            }
                        }
                    }
                    scripts
                })
                .unwrap_or_default()
            }
            None => return,
        };

        // HTML scripts have an "already started" flag. Mark every
        // parser-discovered script before running page code so React/Next
        // hydration can move or hoist those nodes without appendChild
        // executing them a second time.
        if let Some(js) = &mut self.js {
            let ids = all_scripts
                .iter()
                .map(|script| script.nid.to_string())
                .collect::<Vec<_>>()
                .join(",");
            let _ = js.execute_script(
                "<parser-scripts>",
                &format!("globalThis.__markParserScripts([{}]);", ids),
            );
        }

        tracing::info!("Found {} parser-discovered scripts", all_scripts.len());
        let mut fetch_tasks: Vec<(usize, String)> = Vec::new();

        for (i, script) in all_scripts.iter().enumerate() {
            if !matches!(script.kind, ScriptKind::Classic) {
                continue;
            }
            if let Some(src_url) = &script.src {
                let full_url = if src_url.starts_with("http://") || src_url.starts_with("https://")
                {
                    src_url.clone()
                } else {
                    url::Url::parse(&script.base_url)
                        .ok()
                        .and_then(|base| base.join(src_url).ok())
                        .map(|url| url.to_string())
                        .unwrap_or_else(|| src_url.clone())
                };

                if !subresource_allowed(self.url.as_ref(), &full_url) {
                    // Block file://, data:, javascript:, and other
                    // off-origin schemes from being injected as a
                    // <script src>. Without this an http page can
                    // include <script src="file:///etc/passwd"> and
                    // see the body parsed as JS source.
                    tracing::warn!(
                        "blocking cross-scheme <script src>: page={} src={}",
                        self.url_string(),
                        full_url,
                    );
                    continue;
                }
                if self.should_block_url(&full_url) {
                    tracing::info!("Blocked script by interception: {}", full_url);
                    continue;
                }
                fetch_tasks.push((i, full_url));
            }
        }

        let client = self.http_client.clone();
        let page_callbacks = self.callbacks.clone();
        let script_initiator = self
            .url
            .clone()
            .unwrap_or_else(|| Url::parse("about:blank").unwrap());
        let fetch_futures: Vec<_> = fetch_tasks
            .iter()
            .map(|(idx, url)| {
                let client = client.clone();
                let cbs = page_callbacks.clone();
                let initiator = script_initiator.clone();
                let url = url.clone();
                let idx = *idx;
                async move {
                    let parsed =
                        Url::parse(&url).unwrap_or_else(|_| Url::parse("about:blank").unwrap());
                    if parsed.scheme() == "data" {
                        // data: URIs are inline; decode locally, no network fetch.
                        // Instagram and other Meta properties serve their bootstrap
                        // as <script src="data:application/x-javascript;base64,...">.
                        let body = decode_data_uri(&url).unwrap_or_default();
                        let content_type = url
                            .strip_prefix("data:")
                            .and_then(|s| s.split(',').next())
                            .unwrap_or("application/javascript")
                            .split(';')
                            .next()
                            .unwrap_or("application/javascript")
                            .to_string();
                        let mut headers = std::collections::HashMap::new();
                        headers.insert("content-type".to_string(), content_type);
                        let resp = obscura_net::Response {
                            url: parsed,
                            status: 200,
                            headers,
                            body,
                            redirected_from: Vec::new(),
                        };
                        return Some((idx, url, resp));
                    }
                    let request = ResourceRequest::subresource(ResourceType::Script, &initiator);
                    match client
                        .fetch_resource_with_callbacks(&parsed, request, Some(&cbs))
                        .await
                    {
                        Ok(resp) => Some((idx, url, resp)),
                        Err(e) => {
                            tracing::warn!("Failed to fetch script {}: {}", url, e);
                            None
                        }
                    }
                }
            })
            .collect();

        // Bound concurrency: a page with 100 external scripts would
        // otherwise open 100 sockets at once, exhausting the connection
        // pool / ephemeral ports and triggering OS-level backpressure.
        // 16 is well above the per-host pool ceiling most browsers use
        // and matches what real Chrome does for a given origin.
        use futures::StreamExt as _;
        let fetch_stream = futures::stream::iter(fetch_futures).buffer_unordered(16);
        let fetch_results = match tokio::time::timeout_at(
            script_deadline,
            fetch_stream.collect::<Vec<_>>(),
        )
        .await
        {
            Ok(results) => results,
            Err(_) => {
                tracing::warn!(
                    "execute_scripts: fetch deadline reached, some scripts may not have loaded"
                );
                Vec::new()
            }
        };

        let mut fetched: std::collections::HashMap<usize, (String, String, obscura_net::Response)> =
            std::collections::HashMap::new();
        for result in fetch_results {
            if let Some((idx, url, resp)) = result {
                if !script_response_is_executable(resp.status) {
                    self.record_network_event_with_body(
                        &url,
                        "GET",
                        "Script",
                        resp.status,
                        &resp.headers,
                        &resp.body,
                        false,
                    );
                    tracing::warn!(
                        "Refusing to execute script {} after HTTP {}",
                        url,
                        resp.status
                    );
                    continue;
                }
                // Script bodies: only the HTTP Content-Type charset matters
                // (no in-band meta-charset for JS).
                let code = obscura_net::decode_non_html(&resp.body, resp.content_type());
                fetched.insert(idx, (url, code, resp));
            }
        }

        // Spec: readyState is "loading" while parser-discovered scripts execute.
        // Scripts that check readyState === 'loading' will register DOMContentLoaded
        // listeners instead of calling their callback immediately.
        if let Some(js) = &mut self.js {
            let _ = js.execute_script(
                "<ready-state>",
                "globalThis.__documentReadyState__ = 'loading';",
            );
        }

        // CDP `Page.addScriptToEvaluateOnNewDocument` contract: preload
        // sources must run BEFORE any of the page's own scripts. This is
        // also where puppeteer's `exposeFunction` wrapper installs itself —
        // if preload runs after page scripts, every early binding call
        // hits an undefined function and silently no-ops.
        let preload_sources = self.preload_scripts.clone();
        if let Some(js) = &mut self.js {
            for source in &preload_sources {
                if let Err(e) = js.execute_script_guarded("<preload>", source.as_str()) {
                    tracing::debug!("Preload script error: {}", e);
                }
            }
            if !preload_sources.is_empty() {
                let _ = js.execute_script_with_timeout("<frame-init>", "globalThis.__obscura_init_frames();",
                    std::time::Duration::from_secs(5));
            }
        }

        // Per-module budget. Modules on an already-rendered page are
        // enhancement, not the app: give them a short budget so one slow
        // non-essential module (e.g. YC's bookface, whose top-level eval
        // idle-waits ~10s) cannot block navigation completion. A page whose
        // body is still an empty shell IS the SPA (issue #205), so give it the
        // full script budget and the app module still mounts.
        let module_budget_ms: u64 = {
            let body_nodes = self
                .js
                .as_ref()
                .and_then(|js| {
                    js.with_dom(|dom| {
                        dom.query_selector("body")
                            .ok()
                            .flatten()
                            .map(|b| dom.descendants(b).len())
                            .unwrap_or(0)
                    })
                })
                .unwrap_or(0);
            let short_ms: u64 = module_budget_override.unwrap_or_else(|| {
                std::env::var("OBSCURA_MODULE_BUDGET_MS")
                    .ok()
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(3_000)
            });
            // A rendered body has hundreds of descendants; an unmounted Vite/Next
            // shell is <root> plus maybe a spinner.
            if module_budget_override.is_some() || body_nodes > 50 {
                short_ms
            } else {
                script_deadline_ms
            }
        };
        // V8 can flag an overrun while a synchronous renderer host call is in
        // progress, but it cannot preempt Rust after entering that call. Allow
        // one bounded, finite style/layout flush without weakening the
        // page-wide script deadline. Private test overrides keep zero grace.
        let module_hostcall_grace_ms = if module_budget_override.is_some() {
            0
        } else {
            std::env::var("OBSCURA_MODULE_HOSTCALL_GRACE_MS")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(5_000)
        };

        enum ScheduledScript {
            Classic(usize),
            Module {
                prepared: obscura_js::runtime::PreparedModule,
                url: Option<String>,
                remaining_active_ms: u64,
                graph_elapsed_ms: u64,
                queued_at: std::time::Instant,
            },
        }

        let remaining_budget_ms = |deadline: tokio::time::Instant| -> Option<u64> {
            let remaining = deadline.checked_duration_since(tokio::time::Instant::now())?;
            if remaining.is_zero() {
                return None;
            }
            let millis = remaining
                .as_millis()
                .saturating_add(u128::from(remaining.subsec_nanos() % 1_000_000 != 0));
            Some(millis.min(u128::from(u64::MAX)) as u64)
        };
        let elapsed_ms_ceil = |elapsed: std::time::Duration| -> u64 {
            elapsed
                .as_micros()
                .div_ceil(1_000)
                .max(1)
                .min(u128::from(u64::MAX)) as u64
        };
        let evaluation_budget_ms = |remaining_active_ms: u64| -> Option<u64> {
            let remaining_page_ms = remaining_budget_ms(script_deadline)?;
            let budget = remaining_active_ms
                .saturating_add(module_hostcall_grace_ms)
                .min(remaining_page_ms);
            (budget != 0).then_some(budget)
        };

        let execute_classic =
            |page: &mut Self,
             script: &ScriptInfo,
             fetched_script: Option<(String, String, obscura_net::Response)>| {
                if script.src.is_some() {
                    if let Some((url, code, resp)) = fetched_script {
                        tracing::info!("Executing script ({} bytes): {}", code.len(), url);
                        let execution_url = resp.url.to_string();
                        page.record_network_event_with_body(
                            &url,
                            "GET",
                            "Script",
                            resp.status,
                            &resp.headers,
                            &resp.body,
                            false,
                        );
                        if let Some(js) = &mut page.js {
                            let _ = js.execute_script(
                                "<current-script>",
                                &format!("globalThis.__currentScriptNid={};", script.nid),
                            );
                            if let Err(error) = js.execute_script_guarded(&execution_url, &code) {
                                tracing::warn!("Script error ({}): {}", execution_url, error);
                            }
                            let _ = js.execute_script(
                                "<current-script>",
                                "globalThis.__currentScriptNid=0;",
                            );
                        }
                    }
                } else if !script.inline.is_empty() {
                    if let Some(js) = &mut page.js {
                        let _ = js.execute_script(
                            "<current-script>",
                            &format!("globalThis.__currentScriptNid={};", script.nid),
                        );
                        if let Err(error) =
                            js.execute_script_guarded(&script.base_url, &script.inline)
                        {
                            tracing::warn!("Inline script error: {}", error);
                        }
                        let _ = js
                            .execute_script("<current-script>", "globalThis.__currentScriptNid=0;");
                    }
                }
            };

        let mut post_parse = Vec::new();

        // Process parser-discovered scripts in encounter order. Import maps
        // register at their exact position; module graphs start there too, but
        // evaluation of non-async modules remains post-parse.
        for (index, script) in all_scripts.iter().enumerate() {
            if tokio::time::Instant::now() >= script_deadline {
                tracing::warn!(
                    "execute_scripts: deadline reached, skipping {} remaining scripts",
                    all_scripts.len() - index,
                );
                break;
            }

            match script.kind {
                ScriptKind::ImportMap => {
                    if script.src.is_some() {
                        tracing::warn!("External import maps are not supported");
                        continue;
                    }
                    if let Some(js) = &self.js {
                        if let Err(error) = js.add_import_map(&script.inline, &script.base_url) {
                            tracing::warn!("Ignoring invalid import map: {}", error);
                        }
                    }
                }
                ScriptKind::Classic => {
                    if script.is_defer && !script.is_async && script.src.is_some() {
                        post_parse.push(ScheduledScript::Classic(index));
                    } else {
                        let fetched_script = fetched.remove(&index);
                        execute_classic(self, script, fetched_script);
                        if let Some(js) = &mut self.js {
                            if js.take_document_write_inserted_script()
                                && !Self::drive_parser_blocking_scripts(js, script_deadline).await
                            {
                                tracing::warn!(
                                    "script deadline reached with a parser-blocking document.write script pending"
                                );
                            }
                        }
                    }
                }
                ScriptKind::Module => {
                    // Graph loading and evaluation share one active-work
                    // allowance. Queue time behind other post-parse scripts is
                    // not work performed by this module.
                    let Some(remaining_page_ms) = remaining_budget_ms(script_deadline) else {
                        tracing::warn!("ES module budget exhausted before graph preparation");
                        continue;
                    };
                    let prepare_budget_ms = module_budget_ms.min(remaining_page_ms);
                    let prepare_started = std::time::Instant::now();
                    let (prepared, module_url) = if let Some(src) = &script.src {
                        let full_url = if src.starts_with("http://")
                            || src.starts_with("https://")
                            || src.starts_with("data:")
                        {
                            src.clone()
                        } else {
                            url::Url::parse(&script.base_url)
                                .ok()
                                .and_then(|base| base.join(src).ok())
                                .map(|url| url.to_string())
                                .unwrap_or_else(|| src.clone())
                        };
                        tracing::info!("Preparing ES module graph: {}", full_url);
                        let result = match &mut self.js {
                            Some(js) => js.prepare_module(&full_url, prepare_budget_ms).await,
                            None => continue,
                        };
                        tracing::debug!(
                            phase = "module-graph",
                            module = %full_url,
                            elapsed_ms = prepare_started.elapsed().as_millis(),
                            budget_ms = prepare_budget_ms,
                            success = result.is_ok(),
                            "ES module phase complete",
                        );
                        match result {
                            Ok(prepared) => (prepared, Some(full_url)),
                            Err(error) => {
                                tracing::warn!("ES module error ({}): {}", full_url, error);
                                continue;
                            }
                        }
                    } else {
                        let result = match &mut self.js {
                            Some(js) => {
                                js.prepare_inline_module(
                                    &script.inline,
                                    &script.base_url,
                                    prepare_budget_ms,
                                )
                                .await
                            }
                            None => continue,
                        };
                        tracing::debug!(
                            phase = "module-graph",
                            module = "<inline>",
                            elapsed_ms = prepare_started.elapsed().as_millis(),
                            budget_ms = prepare_budget_ms,
                            success = result.is_ok(),
                            "ES module phase complete",
                        );
                        match result {
                            Ok(prepared) => (prepared, None),
                            Err(error) => {
                                tracing::warn!("Inline ES module error: {}", error);
                                continue;
                            }
                        }
                    };
                    let graph_elapsed_ms = elapsed_ms_ceil(prepare_started.elapsed());
                    let remaining_active_ms = module_budget_ms.saturating_sub(graph_elapsed_ms);
                    if remaining_active_ms == 0 {
                        tracing::warn!(
                            module = module_url.as_deref().unwrap_or("<inline>"),
                            graph_elapsed_ms,
                            active_budget_ms = module_budget_ms,
                            "ES module exhausted its active budget during graph preparation",
                        );
                        continue;
                    }
                    let scheduled = ScheduledScript::Module {
                        prepared,
                        url: module_url,
                        remaining_active_ms,
                        graph_elapsed_ms,
                        queued_at: std::time::Instant::now(),
                    };
                    if script.is_async {
                        let ScheduledScript::Module {
                            prepared,
                            url,
                            remaining_active_ms,
                            graph_elapsed_ms,
                            queued_at,
                        } = scheduled
                        else {
                            unreachable!();
                        };
                        let Some(evaluation_budget_ms) = evaluation_budget_ms(remaining_active_ms)
                        else {
                            tracing::warn!(
                                module = url.as_deref().unwrap_or("<inline>"),
                                graph_elapsed_ms,
                                queue_wait_ms = queued_at.elapsed().as_millis(),
                                "ES module exhausted the page budget before evaluation",
                            );
                            continue;
                        };
                        let queue_wait_ms = queued_at.elapsed().as_millis();
                        let evaluation_started = std::time::Instant::now();
                        let result = match &mut self.js {
                            Some(js) => {
                                js.evaluate_prepared_module(prepared, evaluation_budget_ms)
                                    .await
                            }
                            None => continue,
                        };
                        tracing::debug!(
                            phase = "module-evaluation",
                            module = url.as_deref().unwrap_or("<inline>"),
                            elapsed_ms = evaluation_started.elapsed().as_millis(),
                            graph_elapsed_ms,
                            queue_wait_ms,
                            remaining_active_ms,
                            evaluation_ceiling_ms = evaluation_budget_ms,
                            success = result.is_ok(),
                            "ES module phase complete",
                        );
                        if let Err(error) = result {
                            tracing::warn!("ES module evaluation error: {}", error);
                        } else if let Some(url) = url {
                            tracing::info!("ES module loaded: {}", url);
                        }
                    } else {
                        post_parse.push(scheduled);
                    }
                }
            }
        }

        // Parsing has finished before defer scripts and non-async modules run.
        // They still gate DOMContentLoaded, but observe the browser's
        // `interactive` readyState while they execute.
        if let Some(js) = &mut self.js {
            js.record_navigation_timing("domInteractive");
            let _ = js.execute_script(
                "<ready-state-interactive>",
                "globalThis.__documentReadyState__ = 'interactive';",
            );
        }

        for scheduled in post_parse {
            if tokio::time::Instant::now() >= script_deadline {
                tracing::warn!("execute_scripts: deadline reached during post-parse scripts");
                break;
            }
            match scheduled {
                ScheduledScript::Classic(index) => {
                    let script = &all_scripts[index];
                    let fetched_script = fetched.remove(&index);
                    execute_classic(self, script, fetched_script);
                    if let Some(js) = &mut self.js {
                        if js.take_document_write_inserted_script()
                            && !Self::drive_parser_blocking_scripts(js, script_deadline).await
                        {
                            tracing::warn!(
                                "script deadline reached with a parser-blocking document.write script pending"
                            );
                        }
                    }
                }
                ScheduledScript::Module {
                    prepared,
                    url,
                    remaining_active_ms,
                    graph_elapsed_ms,
                    queued_at,
                } => {
                    let Some(evaluation_budget_ms) = evaluation_budget_ms(remaining_active_ms)
                    else {
                        tracing::warn!(
                            module = url.as_deref().unwrap_or("<inline>"),
                            graph_elapsed_ms,
                            queue_wait_ms = queued_at.elapsed().as_millis(),
                            "ES module exhausted the page budget before post-parse evaluation",
                        );
                        continue;
                    };
                    let queue_wait_ms = queued_at.elapsed().as_millis();
                    let evaluation_started = std::time::Instant::now();
                    let result = match &mut self.js {
                        Some(js) => {
                            js.evaluate_prepared_module(prepared, evaluation_budget_ms)
                                .await
                        }
                        None => continue,
                    };
                    tracing::debug!(
                        phase = "module-evaluation",
                        module = url.as_deref().unwrap_or("<inline>"),
                        elapsed_ms = evaluation_started.elapsed().as_millis(),
                        graph_elapsed_ms,
                        queue_wait_ms,
                        remaining_active_ms,
                        evaluation_ceiling_ms = evaluation_budget_ms,
                        success = result.is_ok(),
                        "ES module phase complete",
                    );
                    if let Err(error) = result {
                        tracing::warn!("ES module evaluation error: {}", error);
                    } else if let Some(url) = url {
                        tracing::info!("ES module loaded: {}", url);
                    }
                }
            }
        }

        if let Some(js) = &mut self.js {
            // DOMContentLoaded follows parser/defer/module work, but async
            // dynamic script elements do not gate it. They do remain in the
            // document's load-event delay set, including scripts inserted by
            // a DOMContentLoaded listener.
            js.record_navigation_timing("domContentLoadedEventStart");
            let completed = js.execute_script(
                "<dom-content-loaded>",
                "try { document.dispatchEvent(new Event('DOMContentLoaded', {bubbles:false,cancelable:false})); } catch(e) {}\n\
                 try { window.dispatchEvent(new Event('DOMContentLoaded', {bubbles:false,cancelable:false})); } catch(e) {}",
            );
            if completed.is_ok() {
                js.record_navigation_timing("domContentLoadedEventEnd");
            }

            let load_blockers_finished =
                Self::drive_load_delaying_scripts(js, script_deadline).await;
            if !load_blockers_finished {
                tracing::warn!(
                    "script deadline reached with load-delaying dynamic scripts still pending"
                );
            }

            // readyState becomes complete before the load event. A script
            // inserted by an onload handler is therefore post-load work and
            // remains pending until an explicit caller settle/wait.
            js.record_navigation_timing("domComplete");
            js.record_navigation_timing("loadEventStart");
            let completed = js.execute_script(
                "<load-event>",
                "globalThis.__documentReadyState__ = 'complete';\n\
                 try {\n\
                   const loadEvent = new Event('load', {bubbles:false,cancelable:false});\n\
                   try { window.dispatchEvent(loadEvent); } catch(e) {}\n\
                 } catch(e) {}",
            );
            if completed.is_ok() {
                js.record_navigation_timing("loadEventEnd");
            }
        }
        if let Some(token) = exec_wd {
            if let Some(js) = self.js.as_mut() {
                js.disarm_watchdog(token);
            }
        }
        tracing::debug!(
            phase = "script-execution-total",
            elapsed_ms = scripts_started.elapsed().as_millis(),
            budget_ms = script_deadline_ms,
            "script execution phase complete",
        );
        self.sync_js_network_events();
    }

    pub async fn navigate(&mut self, url_str: &str) -> Result<(), PageError> {
        self.navigate_with_wait(url_str, crate::lifecycle::WaitUntil::Load)
            .await
    }

    pub async fn navigate_with_wait(
        &mut self,
        url_str: &str,
        wait_until: crate::lifecycle::WaitUntil,
    ) -> Result<(), PageError> {
        self.navigate_with_wait_post(url_str, wait_until, "GET", "")
            .await
    }

    pub async fn navigate_with_wait_post(
        &mut self,
        url_str: &str,
        wait_until: crate::lifecycle::WaitUntil,
        method: &str,
        body: &str,
    ) -> Result<(), PageError> {
        // Hard ceiling on a single end-to-end navigation. Without this a slow
        // primary fetch or a runaway settle loop can hold the V8 lock for
        // arbitrarily long (we've measured 60+ seconds on JS-heavy news
        // sites), wedging every other in-flight CDP request because the
        // dispatcher holds the lock across the entire handler. 30 seconds
        // matches reqwest's default per-request timeout — the worst case is
        // one slow primary GET plus one slow JS-redirect chain step. Override
        // with `OBSCURA_NAV_TIMEOUT_MS=NN`, or set a page-scoped deadline when
        // the automation request already has an explicit timeout.
        let nav_timeout = self.navigation_timeout();
        let nav_timeout_ms = duration_millis_u64(nav_timeout);

        let result = match tokio::time::timeout(
            nav_timeout,
            self.navigate_with_wait_post_inner(url_str, wait_until, method, body, "", None),
        )
        .await
        {
            Ok(r) => r,
            Err(_) => {
                self.lifecycle = crate::lifecycle::LifecycleState::Failed;
                Err(PageError::NetworkError(format!(
                    "navigation exceeded {nav_timeout_ms}ms deadline"
                )))
            }
        };
        if result.is_ok() {
            self.push_history(self.url_string());
        }
        result
    }

    /// Drive the JS event loop after navigation so deferred work can run:
    /// pending timers (setTimeout / setInterval), queued microtasks, in-flight
    /// fetches, and completion callbacks such as testharness's
    /// `add_completion_callback`. Returns as soon as the loop goes idle, or
    /// after `max_ms`. Without this the page is observed exactly as it stood at
    /// the load event, before any async work settles, which silently strands
    /// timer-driven tests and dynamic pages.
    pub async fn settle(&mut self, max_ms: u64) {
        if max_ms == 0 {
            return;
        }
        let settle_started = std::time::Instant::now();
        // Pump, then give any frame document that finished fetching a realm of
        // its own. Attaching one runs its scripts, which can start timers,
        // fetches and further frames, so keep alternating until no new frame
        // appears or the budget is gone (issue #600).
        loop {
            let remaining = max_ms.saturating_sub(settle_started.elapsed().as_millis() as u64);
            if remaining == 0 {
                break;
            }
            if let Some(js) = &mut self.js {
                if std::env::var_os("OBSCURA_STRICT_SETTLE").is_some() {
                    Self::settle_runtime_for_duration(js, remaining).await;
                } else {
                    // A deno_core event loop remains "busy" for any future timer,
                    // including analytics intervals and animation loops which do
                    // not make the page more ready. Require a short window without
                    // observable document/network/script activity instead. The
                    // absolute caller budget and V8 watchdog still bound both
                    // asynchronous work and synchronous microtask storms.
                    let _ = js.run_event_loop_until_quiescent(remaining, 150).await;
                }
            }
            #[cfg(feature = "render")]
            {
                self.queue_pending_render_resources();
            }
            if !self.advance_frames().await {
                break;
            }
        }
        #[cfg(feature = "render")]
        {
            // Timers, fetch completions, and framework commits commonly append
            // images or @font-face rules during settling. Seed those resources
            // here so a following capture remains a fast observation of the
            // retained page rather than initiating its own network phase.
            let warmup_ms = std::env::var("OBSCURA_RENDER_RESOURCE_SETTLE_WARMUP_MS")
                .ok()
                .and_then(|value| value.parse::<u64>().ok())
                .unwrap_or(1_000);
            let remaining_ms = remaining_settle_resource_warmup_ms(
                max_ms,
                settle_started.elapsed(),
                warmup_ms,
            );
            if remaining_ms != 0 {
                let _ = self.prepare_screenshot_resources(remaining_ms).await;
            }
        }
    }

    /// Pump the event loop and retain the full requested wall-clock delay.
    /// The CLI uses this for an explicitly supplied `--wait`; callers asking
    /// for a fixed capture delay should not be silently shortened by adaptive
    /// readiness heuristics.
    pub async fn settle_for_duration(&mut self, duration_ms: u64) {
        if duration_ms == 0 {
            return;
        }
        if let Some(js) = &mut self.js {
            Self::settle_runtime_for_duration(js, duration_ms).await;
        }
        // A fixed wait must retain its full wall clock, so frames get their
        // realms once at the end instead of being interleaved as in `settle`.
        // Their document scripts still run; only their own deferred work is
        // left for a later settle.
        self.advance_frames().await;
    }

    /// Advance one wake-driven browser task for a continuously owned page.
    /// `true` means deno_core reached full idle; `false` means one wake/task was
    /// delivered and the owner should offer another turn after servicing any
    /// higher-priority automation commands.
    #[doc(hidden)]
    pub async fn run_autonomous_event_loop_turn(&mut self) -> Result<bool, String> {
        #[cfg(feature = "render")]
        {
            self.queue_pending_render_resources();
        }
        let reached_idle = match self.js.as_mut() {
            Some(js) => {
                #[cfg(feature = "render")]
                {
                    // A finished transport load is page work too: wake up as
                    // soon as it lands so the next layout, paint or lifecycle
                    // read sees the real bytes instead of waiting for the next
                    // protocol command. The runtime turn is cancel-safe (the
                    // connection processor already races it against commands).
                    // The waiter is registered before the pending check, so a
                    // load finishing in between cannot be missed.
                    let notify = js.render_resource_notify();
                    let notified = notify.notified();
                    tokio::pin!(notified);
                    notified.as_mut().enable();
                    let loads_pending = js.has_pending_render_resources();
                    tokio::select! {
                        biased;
                        turn = js.run_autonomous_event_loop_turn() => turn?,
                        _ = &mut notified, if loads_pending => false,
                    }
                }
                #[cfg(not(feature = "render"))]
                js.run_autonomous_event_loop_turn().await?
            }
            None => true,
        };
        // Dynamic iframe fetches finish on the page event loop, but their
        // realms must be built by Page between turns. Keep the autonomous CDP
        // pump on the same generic frame path as settle(), so a client that
        // stays attached can observe and run child documents as they arrive.
        let frame_work = self.advance_frames().await;
        #[cfg(feature = "render")]
        {
            if reached_idle && !frame_work && self.js.is_some() {
                // The runtime may have nothing to do until a resource lands.
                // Park on the next result instead of reporting "busy" (which
                // would spin the connection pump). `notified` is cancel-safe,
                // so the processor can still preempt this turn with a
                // command. Register the waiter first, then service (a load
                // that finished before this point is applied here; its wake
                // is already past), then decide whether to park.
                let notify = self.js.as_ref().unwrap().render_resource_notify();
                let notified = notify.notified();
                tokio::pin!(notified);
                notified.as_mut().enable();
                self.queue_pending_render_resources();
                if self.has_pending_render_resources() {
                    notified.await;
                    self.drain_render_resource_results();
                    return Ok(false);
                }
                return Ok(true);
            }
            // Geometry this turn produced may have missed resources; start
            // their loads now.
            self.queue_pending_render_resources();
            return Ok(reached_idle && !frame_work);
        }
        #[cfg(not(feature = "render"))]
        Ok(reached_idle && !frame_work)
    }

    async fn settle_runtime_for_duration(js: &mut ObscuraJsRuntime, duration_ms: u64) {
        let started = tokio::time::Instant::now();
        let _ = js.run_event_loop_for_duration(duration_ms).await;
        let requested = tokio::time::Duration::from_millis(duration_ms);
        let elapsed = started.elapsed();
        if elapsed < requested {
            tokio::time::sleep(requested - elapsed).await;
        }
    }

    /// Append the current URL to the history stack, truncating any forward
    /// entries past the cursor (matches real Chrome: navigating after a
    /// goBack clobbers the forward history).
    pub fn push_history(&mut self, url: String) {
        self.push_history_entry(url, true);
    }

    /// Record a URL the current document reached through pushState or
    /// replaceState. It stays part of the same document's entries.
    pub(crate) fn push_same_document_history(&mut self, url: String) {
        self.push_history_entry(url, false);
    }

    pub(crate) fn apply_history_update(&mut self, update: HistoryUpdate) {
        let HistoryUpdate::Entries { start, index, old_length, truncate_forward, first, urls, .. } = update else { return; };
        let Some(end) = first.checked_add(urls.len()) else { return; };
        let length = if truncate_forward { end } else { old_length };
        if first > old_length || index >= length || (!truncate_forward && end > old_length) { return; }
        let current_url = self.url_string();
        if urls.iter().any(|url| cross_scheme_to_file(&current_url, url)) { return; }
        if self.history.is_empty() && start == 0 {
            self.history.push(current_url);
        }
        let Some(document_end) = start.checked_add(old_length).filter(|&end| end <= self.history.len()) else { return; };
        let Some(changed_end) = start.checked_add(end) else { return; };
        self.history.splice(start + first..changed_end.min(document_end), urls);
        self.document_history_start = start;
        self.history_index = start + index;
        if truncate_forward {
            self.history.truncate(start + length);
        }
    }

    /// Traverse an entry belonging to the live document without replacing its runtime.
    pub fn traverse_same_document_history(&mut self, index: usize) -> bool {
        self.sync_history_updates();
        let Some(url) = self.history.get(index) else { return false; };
        let expression = format!("globalThis.__obscuraHistory.traverse({}, {})", index,
            serde_json::to_string(url).unwrap_or_default());
        if self.evaluate(&expression) != serde_json::json!(true) { return false; }
        self.sync_virtual_url();
        true
    }

    fn push_history_entry(&mut self, url: String, new_document: bool) {
        if url.is_empty() {
            return;
        }
        let traversal = if new_document {
            self.pending_history_traversal.lock().ok().and_then(|mut index| index.take())
        } else {
            None
        };
        if let Some(index) = traversal.filter(|&index| self.history.get(index) == Some(&url)) {
            self.history_index = index;
        } else if self.history.get(self.history_index) != Some(&url) {
            // Consecutive duplicates are skipped so Page.reload does not pile up entries.
            if !self.history.is_empty() && self.history_index < self.history.len() - 1 {
                self.history.truncate(self.history_index + 1);
            }
            self.history.push(url);
            self.history_index = self.history.len() - 1;
        }
        if new_document {
            self.document_history_start = self.history_index;
        }
        self.sync_js_session_history();
    }

    /// Replace the history and cursor, treating the current document as the
    /// entry at `index`. Page.navigateToHistoryEntry and
    /// Page.resetNavigationHistory rewrite history through this.
    pub fn set_history(&mut self, history: Vec<String>, index: usize) {
        self.history = history;
        self.history_index = index;
        self.document_history_start = index;
        if self.history.is_empty() {
            let url = self.url_string();
            if let Some(js) = self.js.as_mut() {
                let _ = js.execute_script("<reset-history>", &format!(
                    "globalThis.__obscuraHistory.reset({})", serde_json::to_string(&url).unwrap_or_default()));
            }
        }
        self.sync_js_session_history();
    }

    /// Give the document's `window.history` the page's session history, so
    /// `history.length` and cross-document `history.go()` see every entry.
    pub fn sync_js_session_history(&self) {
        if let Some(js) = &self.js {
            js.set_session_history(
                self.history.clone(),
                self.document_history_start,
                self.history_index,
            );
        }
    }

    /// The session history as it will be once the document being created
    /// commits through `push_history`: the entry a traversal targets, the
    /// current entry on a reload, or a new entry replacing the forward ones.
    fn predicted_session_history(&self) -> (Vec<String>, usize) {
        let url = self.url_string();
        let traversal = self.pending_history_traversal.lock().ok().and_then(|index| *index);
        if let Some(index) = traversal.filter(|&index| self.history.get(index) == Some(&url)) {
            return (self.history.clone(), index);
        }
        if self.history.get(self.history_index) == Some(&url) {
            return (self.history.clone(), self.history_index);
        }
        let mut urls: Vec<String> =
            self.history.iter().take(self.history_index + 1).cloned().collect();
        urls.push(url);
        let index = urls.len() - 1;
        (urls, index)
    }

    /// Move the history cursor without re-navigating; used by
    /// Page.navigateToHistoryEntry which then drives the actual fetch.
    pub fn set_history_index(&mut self, idx: usize) {
        if idx < self.history.len() {
            self.history_index = idx;
        }
    }

    async fn navigate_with_wait_post_inner(
        &mut self,
        url_str: &str,
        wait_until: crate::lifecycle::WaitUntil,
        method: &str,
        body: &str,
        initial_referrer: &str,
        initial_initiator: Option<&Url>,
    ) -> Result<(), PageError> {
        self.sync_history_updates();
        // file:// is a local file read. Every client route (CLI, CDP's
        // Page.navigate/reload/history and Target.createTarget, the MCP
        // tools) ends up here, so the context's opt-in is enforced once
        // instead of being copied into each handler, where a route that
        // missed its copy read local files (#1069).
        if url_is_file_scheme(url_str) && !self.context.allow_file_access {
            return Err(PageError::NetworkError(format!(
                "file:// navigation is disabled for this browser context: {url_str}"
            )));
        }
        let deadline = tokio::time::Instant::now() + self.navigation_timeout();
        self.network_events.clear();
        let mut current_url = url_str.to_string();
        let mut current_method = method.to_string();
        let mut current_body = body.to_string();
        let mut document_referrer = initial_referrer.to_string();
        let mut document_initiator = initial_initiator.cloned();
        let chain_limit = self.navigation_chain_limit();
        for chain in 0..chain_limit {
            self.navigate_single(
                &current_url,
                wait_until,
                &current_method,
                &current_body,
                &document_referrer,
                document_initiator.as_ref(),
                deadline,
            )
            .await?;
            if let Some((next_url, next_method, next_body)) = self.take_pending_navigation() {
                if cross_scheme_to_file(&current_url, &next_url) {
                    // SOP gate. A web page must not be able to drive
                    // a navigation to file:// and then read the loaded
                    // document. Without this an http(s) page sets
                    // window.onload, calls location.href = "file:..."
                    // and harvests document.body from a local file
                    // once the new document loads.
                    tracing::warn!(
                        "blocking JS-initiated cross-scheme navigation to file: {} -> {}",
                        current_url,
                        next_url,
                    );
                    break;
                }
                tracing::info!(
                    "JS-triggered navigation chain: {} {} -> {}",
                    current_method,
                    current_url,
                    next_url
                );
                document_initiator = self.url.clone();
                document_referrer = self
                    .url
                    .as_ref()
                    .and_then(|source| {
                        Url::parse(&next_url)
                            .ok()
                            .map(|target| navigation_referrer(source, &target))
                    })
                    .unwrap_or_default();
                current_url = next_url;
                current_method = next_method;
                current_body = next_body;
                if chain + 1 == chain_limit {
                    // Hit the cap and the page still wants to keep
                    // chaining. Surface that as an error instead of
                    // returning Ok(()) so callers can distinguish a
                    // successful load from a navigation storm.
                    return Err(PageError::TooManyClientNavigations(chain_limit));
                }
                continue;
            }
            break;
        }
        Ok(())
    }

    async fn navigate_single(
        &mut self,
        url_str: &str,
        wait_until: crate::lifecycle::WaitUntil,
        method: &str,
        body: &str,
        referrer: &str,
        initiator: Option<&Url>,
        deadline: tokio::time::Instant,
    ) -> Result<(), PageError> {
        let url = Url::parse(url_str).map_err(|e| PageError::InvalidUrl(e.to_string()))?;
        self.navigation_timing = NavigationTiming::default();

        // The previous document's background loads end with the document.
        self.retire_render_resources();
        self.lifecycle = LifecycleState::Loading;
        self.referrer = referrer.to_string();
        self.url = Some(url.clone());
        let page_id = self.id.as_str();
        self.network_events.retain(|event| event.intercepted && event.resource_type == "Document"
            && event.request_id.strip_prefix(page_id).is_some_and(|suffix| suffix.starts_with('.')));

        if self.context.obey_robots {
            if url.scheme() == "http" || url.scheme() == "https" {
                let origin = url.origin().ascii_serialization();
                if !self.context.robots_cache.contains(&origin) {
                    let mut robots_url = url.clone();
                    robots_url.set_path("/robots.txt");
                    robots_url.set_query(None);
                    robots_url.set_fragment(None);
                    let body = match self
                        .http_client
                        .fetch_with_callbacks(&robots_url, Some(&self.callbacks))
                        .await
                    {
                        Ok(resp) if resp.status == 200 => {
                            String::from_utf8_lossy(&resp.body).into_owned()
                        }
                        _ => String::new(),
                    };
                    self.context.robots_cache.parse_and_store(
                        &origin,
                        &body,
                        &self.context.user_agent,
                    );
                }

                if !self.context.robots_cache.is_allowed(&origin, url.path()) {
                    self.lifecycle = LifecycleState::Failed;
                    return Err(PageError::NetworkError(format!(
                        "Blocked by robots.txt: {}",
                        url
                    )));
                }
            }
        }

        if url.scheme() == "about" {
            self.navigate_blank();
            self.init_js();
            // Preloads (Page.addScriptToEvaluateOnNewDocument, the
            // Runtime.addBinding shim) must run on about:blank too —
            // puppeteer's `browser.newPage()` lands on about:blank and
            // a follow-up `exposeFunction` is unusable otherwise.
            let preload_sources = self.preload_scripts.clone();
            if let Some(js) = &mut self.js {
                for source in &preload_sources {
                    if let Err(e) = js.execute_script_guarded("<preload>", source.as_str()) {
                        tracing::debug!("Preload script error on about:blank: {}", e);
                    }
                }
                if !preload_sources.is_empty() {
                    let _ = js.execute_script_with_timeout("<frame-init>", "globalThis.__obscura_init_frames();",
                        std::time::Duration::from_secs(5));
                }
            }
            return Ok(());
        }

        self.navigation_timing.record("fetchStart");
        let intercepted = self.intercept_navigation(&url, method, body, initiator).await.map_err(|error| {
            self.lifecycle = LifecycleState::Failed; error
        })?;
        let was_intercepted = intercepted.is_some();
        let response = if let Some(response) = intercepted { Ok(response) } else if url.scheme() == "data" {
            let content_type = url_str
                .strip_prefix("data:")
                .and_then(|s| s.split(',').next())
                .unwrap_or("text/html")
                .split(';')
                .next()
                .unwrap_or("text/html")
                .to_string();
            let body_bytes = decode_data_uri(url_str).unwrap_or_default();
            let mut headers = std::collections::HashMap::new();
            headers.insert("content-type".to_string(), content_type);
            Ok(obscura_net::Response {
                url: url.clone(),
                status: 200,
                headers,
                body: body_bytes,
                redirected_from: Vec::new(),
            })
        } else if method == "POST" || initiator.is_some() {
            self.fetch_navigation_from_document(
                &url, if method == "POST" { "POST" } else { "GET" },
                (method == "POST").then(|| body.as_bytes().to_vec()), None, initiator,
            ).await
        } else {
            self.do_fetch(&url).await
        }
        .map_err(|e| {
            self.lifecycle = LifecycleState::Failed;
            PageError::NetworkError(e.to_string())
        })?;
        self.navigation_timing.record("responseEnd");

        // Store binary main resources (images, PDFs, octet-stream) base64 so
        // Network.getResponseBody returns intact bytes. A UTF-8-lossy text store
        // corrupts them (issue #340). Text-like types stay as text.
        let main_is_binary = !is_text_like_content_type(response.content_type());
        self.record_network_event_with_body(
            if was_intercepted && response.redirected_from.is_empty() { url.as_str() } else { response.url.as_str() },
            method,
            "Document",
            response.status,
            &response.headers,
            &response.body,
            main_is_binary,
        );

        if was_intercepted {
            if let Some(event) = self.network_events.last_mut() { event.intercepted = true; }
        }
        if !response.redirected_from.is_empty() {
            self.url = Some(response.url.clone());
        }

        // An HTTP error status with no body at all (a bare 429/403/503 from a
        // rate limiter or WAF) is not a document. Chrome fails that navigation
        // with net::ERR_HTTP_RESPONSE_CODE_FAILURE and shows its own error
        // page, so Page.navigate / page.goto reject. Parsing the empty body
        // instead commits `<html><head></head><body></body></html>` as a
        // successful load and the block looks like an empty site. An error
        // status that carries a body (a real 404 page) still renders.
        if response.status >= 400 && response.body.is_empty() {
            self.lifecycle = LifecycleState::Failed;
            return Err(PageError::NetworkError(format!(
                "net::ERR_HTTP_RESPONSE_CODE_FAILURE: HTTP {} with an empty body for {}",
                response.status, response.url
            )));
        }

        // Honor the response charset: HTTP Content-Type → <meta charset> sniff
        // in the first 1KB → UTF-8 fallback. Without this, every non-UTF-8
        // page (GBK, Big5, Shift-JIS, Windows-125x, EUC-KR, ISO-8859-x)
        // came through as replacement characters.
        let (body_text, encoding_name) =
            obscura_net::decode_response_with_name(&response.body, response.content_type());
        self.encoding = encoding_name.to_string();
        self.navigation_timing.record("domLoading");
        // A non-HTML text response is a plain-text document, not an HTML one
        // that happens to hold text: every `<word>` in a .txt or .md body
        // would otherwise be parsed as an element and its contents dropped
        // from textContent (#1231). Chrome wraps the decoded text in a
        // single <pre> instead.
        let (dom, document_content_type) = match plain_text_document_type(response.content_type())
        {
            Some(mime) => (parse_plain_text_document(&body_text), mime),
            None => (parse_html(&body_text), base_content_type(response.content_type()).unwrap_or_default()),
        };
        self.content_type = document_content_type;

        self.title = dom
            .query_selector("title")
            .ok()
            .flatten()
            .map(|title_id| dom.text_content(title_id))
            .unwrap_or_default();

        self.dom = Some(dom);
        self.init_js();
        let author_stylesheets = self.fetch_stylesheets().await;

        // Install fetched CSS in native DOM state. Cross-origin bytes must not
        // become observable through a synthetic style element or page global.
        if !author_stylesheets.is_empty() {
            if let Some(js) = &mut self.js {
                js.with_dom(|dom| {
                    let styles = dom.query_selector_all("style").unwrap_or_default();
                    for (target, css, origin_clean, _) in &author_stylesheets {
                        // Linked targets carry the link's node id (#1044), so
                        // resolve it directly instead of indexing a query-order
                        // list. InlineImport still uses the style query index.
                        let owner = match target {
                            AuthorStylesheetTarget::Linked(nid) => {
                                let id = obscura_dom::NodeId::new(*nid as u32);
                                dom.get_node(id).map(|_| id)
                            }
                            AuthorStylesheetTarget::InlineImport(index) => {
                                styles.get(*index).copied()
                            }
                        };
                        if let Some(owner) = owner {
                            dom.append_external_stylesheet(owner, css.clone(), *origin_clean);
                        }
                    }
                });
                for (target, _, _, response_url) in &author_stylesheets {
                    if let AuthorStylesheetTarget::Linked(link_index) = target {
                        let _ = js.execute_script(
                            "<fetch_stylesheets>",
                            &register_linked_stylesheet_script(*link_index, response_url),
                        );
                    }
                }
            }
        }
        // Static registration is complete before page script runs. Remove the
        // temporary host bridge even when the document had no initial sheets;
        // dynamic loads use the closure-private function directly.
        if let Some(js) = &mut self.js {
            let _ = js.execute_script(
                "<fetch_stylesheets-cleanup>",
                "delete globalThis.__obscura_registerLinkedStylesheet",
            );
        }
        self.document_timeline_origin = std::time::Instant::now();
        #[cfg(feature = "render")]
        if let Some(js) = &self.js {
            js.reset_animation_timeline();
        }
        if let Some(js) = &mut self.js {
            let _ = js.execute_script("<iframe-load>",
                "(function() { var iframes = document.querySelectorAll('iframe[src]'); for (var i = 0; i < iframes.length; i++) { var src = iframes[i].getAttribute('src'); if (src && src !== 'about:blank') iframes[i]._loadIframeSrc(src); } })()");
        }

        // Scripts can synchronously flush style/layout through
        // getComputedStyle(), geometry, ResizeObserver, or IntersectionObserver.
        // Seed their image/font dependencies concurrently through the page
        // transport first. Otherwise the first CSSOM read falls into the
        // renderer's synchronous resource loader and serial network latency pins
        // V8, making framework startup take many seconds. This is deliberately
        // bounded: navigation should not wait indefinitely for decorative
        // resources.
        #[cfg(feature = "render")]
        {
            let warmup_ms = std::env::var("OBSCURA_RENDER_RESOURCE_WARMUP_MS")
                .ok()
                .and_then(|value| value.parse::<u64>().ok())
                .unwrap_or(1_000);
            let _ = self.prepare_screenshot_resources(warmup_ms).await;
        }

        // Spec: DOMContentLoaded fires AFTER parser-blocking scripts run,
        // not before. Skipping execute_scripts() on the DCL path meant
        // every inline <script> in the page was silently dropped: form
        // listeners never registered, frameworks never bootstrapped,
        // page.click() handlers were no-ops. Now scripts run regardless
        // of waitUntil and DCL means "DOM parsed AND scripts executed".
        self.execute_scripts().await;
        // The document's own scripts are the common source of storage writes,
        // so the profile is flushed once they have run, not before.
        self.context.save_local_storage();

        #[cfg(feature = "render")]
        {
            // Page scripts and their bounded post-script event-loop pass can
            // create responsive images, inline styles, and @font-face rules
            // that did not exist during the parser warmup above. Discover them
            // before navigation becomes capture-ready. Known parser resources
            // are filtered by the render cache, so ordinary pages pay only the
            // inexpensive scan on this second pass.
            let warmup_ms = std::env::var("OBSCURA_RENDER_RESOURCE_POST_SCRIPT_WARMUP_MS")
                .ok()
                .and_then(|value| value.parse::<u64>().ok())
                .unwrap_or(1_000);
            let _ = self.prepare_screenshot_resources(warmup_ms).await;
        }

        self.lifecycle = LifecycleState::DomContentLoaded;

        // Before any `wait_until` can return, because the frames belong to the
        // document rather than to one readiness level. Puppeteer and Playwright
        // send `Page.navigate` with no `waitUntil`, which lands here and returns
        // on the next line, so building frames further down left every real CDP
        // client seeing a page with no frames at all.
        self.build_document_frames().await;

        if wait_until == crate::lifecycle::WaitUntil::DomContentLoaded {
            return Ok(());
        }

        if let Some(js) = &mut self.js {
            if let Ok(new_title) = js.evaluate("document.title") {
                if let Some(t) = new_title.as_str() {
                    self.title = t.to_string();
                }
            }
        }

        self.lifecycle = LifecycleState::Loaded;

        if matches!(
            wait_until,
            crate::lifecycle::WaitUntil::NetworkIdle0 | crate::lifecycle::WaitUntil::NetworkIdle2
        ) {
            let threshold = match wait_until {
                crate::lifecycle::WaitUntil::NetworkIdle0 => 0,
                crate::lifecycle::WaitUntil::NetworkIdle2 => 2,
                _ => 0,
            };

            self.wait_for_network_idle_until(threshold, deadline).await?;
        }

        Ok(())
    }

    #[cfg(test)]
    async fn wait_for_network_idle(&mut self, threshold: u32) -> Result<(), PageError> {
        let deadline = tokio::time::Instant::now() + self.navigation_timeout();
        self.wait_for_network_idle_until(threshold, deadline).await
    }

    async fn wait_for_network_idle_until(&mut self, threshold: u32, deadline: tokio::time::Instant) -> Result<(), PageError> {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        let netidle_wd = self.js.as_mut().map(|js| js.arm_watchdog(remaining));
        let mut idle_since: Option<tokio::time::Instant> = None;

        let reached_idle = loop {
            let active = self.http_client.active_requests();
            #[cfg(feature = "stealth")]
            let active = active + self.stealth_client.as_ref().map_or(0, |client| client.active_requests());
            let now = tokio::time::Instant::now();

            if now >= deadline { break false; }
            if active <= threshold {
                if idle_since.is_none() {
                    idle_since = Some(now);
                }
                if now.duration_since(idle_since.unwrap())
                    >= tokio::time::Duration::from_millis(500)
                {
                    break true;
                }
            } else {
                idle_since = None;
            }

            // An idle runtime can stay parked. Wake at the existing quiet
            // window or hard deadline instead of adding a final full slice.
            let readiness_deadline = idle_since
                .map_or(deadline, |since| since + tokio::time::Duration::from_millis(500))
                .min(deadline);
            if let Some(js) = &mut self.js {
                let next_check = readiness_deadline.min(now + tokio::time::Duration::from_millis(50));
                crate::idle_deadline::wait_for_activity(
                    next_check,
                    next_check == readiness_deadline,
                    js.wait_for_event_loop_activity(),
                )
                .await;
            } else {
                let next_check = readiness_deadline.min(now + tokio::time::Duration::from_millis(100));
                crate::idle_deadline::wait_for_activity(
                    next_check,
                    next_check == readiness_deadline,
                    std::future::pending::<()>(),
                ).await;
            }
        };

        let mut terminated = false;
        if let Some(token) = netidle_wd {
            if let Some(js) = self.js.as_mut() {
                terminated = js.disarm_watchdog(token);
            }
        }
        if reached_idle && !terminated {
            self.lifecycle = LifecycleState::NetworkIdle;
            Ok(())
        } else {
            self.lifecycle = LifecycleState::Failed;
            Err(PageError::NetworkError("network idle exceeded the navigation deadline".into()))
        }
    }

    /// Builds the child frames of the document that just loaded.
    ///
    /// Loading a document includes loading the frames in it, so this belongs to
    /// navigation rather than to `settle`: a CDP client that only navigates
    /// would otherwise be told the page has no frames, because nothing had
    /// given them realms yet.
    ///
    /// A frame's document is fetched by page script, so it arrives from the
    /// event loop rather than being ready the moment parsing ends. Pages
    /// without an iframe skip the pumping entirely and pay one native selector
    /// query.
    async fn build_document_frames(&mut self) {
        // How many rounds of "attach a frame, let it start its own" to follow.
        // A frame can add a frame, so this needs a bound rather than a loop
        // until quiet: a page that adds one on every turn would never finish.
        const ROUNDS: usize = 8;
        const ROUND_MS: u64 = 50;

        let has_iframe = self
            .with_dom(|dom| dom.query_selector("iframe").ok().flatten().is_some())
            .unwrap_or(false);
        if !has_iframe {
            return;
        }

        for _ in 0..ROUNDS {
            if let Some(js) = &mut self.js {
                // A Tokio timeout cannot interrupt synchronous microtasks.
                // Use the same cooperative, watchdog-bounded pump as settling.
                let _ = js.run_event_loop_bounded(ROUND_MS).await;
            }
            if !self.advance_frames().await {
                break;
            }
        }
    }

    pub fn navigate_blank(&mut self) {
        self.navigation_timing = NavigationTiming::default();
        self.retire_render_resources();
        self.pending_frame_work.clear();
        self.frames.clear();
        self.js = None;
        self.url = Some(Url::parse("about:blank").unwrap());
        self.dom = Some(parse_html(
            "<html><head></head><body></body></html>",
        ));
        self.title = String::new();
        self.content_type.clear();
        self.lifecycle = LifecycleState::Loaded;
        self.document_timeline_origin = std::time::Instant::now();
    }

    pub fn url_string(&self) -> String {
        self.url
            .as_ref()
            .map(|u| u.to_string())
            .unwrap_or_else(|| "about:blank".to_string())
    }

    pub fn with_dom<R>(&self, f: impl FnOnce(&DomTree) -> R) -> Option<R> {
        if let Some(js) = &self.js {
            return js.with_dom(f);
        }
        self.dom.as_ref().map(f)
    }

    /// Render resources the retained document references but the renderer
    /// cache does not know yet, found by scanning the light DOM for `<img>`,
    /// `<video poster>`, `<style>`, `style` attributes and `<use>`. This is
    /// only the navigation warmup: everything layout or paint actually asks
    /// for later is reported by the renderer itself (`take_render_resource_requests`).
    /// Blocked or disallowed URLs come back separately so they can be
    /// remembered as missing.
    #[cfg(feature = "render")]
    fn render_resource_candidates(
        &self,
    ) -> (
        Vec<(String, Option<obscura_js::ImageRequestProfile>, bool)>,
        Vec<(String, Option<obscura_js::ImageRequestProfile>, bool)>,
    ) {
        let Some(js) = &self.js else {
            return (Vec::new(), Vec::new());
        };
        let Some(document_url) = self.url.clone() else {
            return (Vec::new(), Vec::new());
        };
        let base_url = self
            .resolve_base_url()
            .unwrap_or_else(|| document_url.clone());
        let mut candidates = std::collections::BTreeSet::new();

        for (raw, profile) in js.pending_render_image_urls() {
            if let Ok(mut url) = url::Url::parse(&raw) {
                url.set_fragment(None);
                candidates.insert((url.to_string(), Some(profile), false));
            }
        }
        let css_sources = js
            .with_dom(|dom| {
                let mut sources = Vec::new();
                for id in dom.descendants(dom.document()) {
                    let Some(node) = dom.get_node(id) else {
                        continue;
                    };
                    if node
                        .as_element()
                        .is_some_and(|element| element.local.as_ref() == "style")
                    {
                        sources.push(dom.text_content(id));
                    }
                    if let Some(style) = node.get_attribute("style") {
                        sources.push(style.to_string());
                    }
                    if node
                        .as_element()
                        .is_some_and(|element| element.local.as_ref() == "use")
                    {
                        if let Some(href) = node
                            .get_attribute("href")
                            .or_else(|| node.get_attribute("xlink:href"))
                        {
                            sources.push(format!("url({href})"));
                        }
                    }
                }
                for sheet in dom.external_stylesheets().values() {
                    sources.extend(sheet.sources.iter().map(ToString::to_string));
                }
                sources
            })
            .unwrap_or_default();
        for css in css_sources {
            for raw in css_resource_urls(&css, &base_url) {
                if let Ok(mut url) = url::Url::parse(&raw) {
                    url.set_fragment(None);
                    let is_font = render_resource_is_font(&url);
                    candidates.insert((url.to_string(), None, is_font));
                }
            }
        }
        candidates.retain(|(url, profile, _)| match profile {
            Some(profile) => !js.render_image_resource_is_known(url, *profile),
            None => !js.render_resource_is_known(url),
        });

        let mut loadable = Vec::new();
        let mut rejected = Vec::new();
        // Preserve the historical warmup bound. Anything beyond this batch
        // is reported again by a later cache-only layout.
        for (url, profile, is_font) in candidates.into_iter().take(MAX_STYLESHEET_RESOURCES) {
            if subresource_allowed(Some(&document_url), &url) && !self.should_block_url(&url) {
                loadable.push((url, profile, is_font));
            } else {
                rejected.push((url, profile, is_font));
            }
        }
        (loadable, rejected)
    }

    /// Abandon every background load of the current document. Navigation, a
    /// blank reset, suspension and teardown call this so a response that
    /// belongs to a previous document can neither seed the next document's
    /// cache nor be mistaken for that document's own request of the same URL
    /// (the runtime also fences results by document generation). Aborting
    /// the tasks drops their in-progress HTTP requests.
    #[cfg(feature = "render")]
    pub fn retire_render_resources(&mut self) {
        if let Some(js) = &self.js {
            js.abandon_render_resources();
        }
    }

    #[cfg(not(feature = "render"))]
    pub fn retire_render_resources(&mut self) {}

    /// Apply every finished background load without waiting and report the
    /// responses as Network events. Returns the number of loads that stored
    /// usable bytes. Successful image and font bytes invalidate the retained
    /// geometry, so the next layout or paint observes the real intrinsic size.
    #[cfg(feature = "render")]
    pub fn drain_render_resource_results(&mut self) -> usize {
        let Some(js) = self.js.as_mut() else {
            return 0;
        };
        let loaded = js.apply_render_resource_results();
        self.record_render_resource_events();
        loaded
    }

    /// Report the responses of applied background loads as Network events
    /// (recording needs the page, not the runtime).
    #[cfg(feature = "render")]
    fn record_render_resource_events(&mut self) {
        let Some(js) = self.js.as_mut() else {
            return;
        };
        let events = js.take_render_resource_events();
        for event in events {
            self.record_network_event_with_body(
                &event.response.url,
                "GET",
                if event.is_font { "Font" } else { "Image" },
                event.response.status,
                &event.response.headers,
                event.response.body.as_ref(),
                true,
            );
        }
    }

    #[cfg(not(feature = "render"))]
    pub fn drain_render_resource_results(&mut self) -> usize {
        0
    }

    /// Apply finished loads and start transport loads for the resources
    /// cache-only layout or paint missed since the last call (the runtime's
    /// own service step, plus the Network events). Returns the number of
    /// loads that stored usable bytes.
    #[cfg(feature = "render")]
    pub fn queue_pending_render_resources(&mut self) -> usize {
        let Some(js) = self.js.as_mut() else {
            return 0;
        };
        let loaded = js.service_render_resources();
        self.record_render_resource_events();
        loaded
    }

    #[cfg(not(feature = "render"))]
    pub fn queue_pending_render_resources(&mut self) -> usize {
        0
    }

    /// Start loads for everything the light-DOM scan finds. Used by the
    /// navigation warmups before any layout has run.
    #[cfg(feature = "render")]
    pub fn spawn_pending_render_resources(&mut self) -> usize {
        if let Some(js) = &self.js {
            // A runtime attached without `init_js` loads through the page
            // transport all the same.
            if !js.has_page_transport() {
                js.set_http_client(self.http_client.clone());
                js.set_callbacks(self.callbacks.clone());
                #[cfg(feature = "stealth")]
                if let Some(stealth) = &self.stealth_client {
                    js.set_stealth_client(stealth.clone());
                }
            }
        }
        let (loadable, rejected) = self.render_resource_candidates();
        let started = match &mut self.js {
            Some(js) => {
                for (url, profile, _) in rejected {
                    match profile {
                        Some(profile) => js.seed_render_image_resource(url, profile, None),
                        None => js.seed_render_resource(url, None),
                    }
                }
                let mut requests = js.mark_render_resources_in_flight(loadable);
                requests.extend(js.take_render_resource_requests());
                js.start_render_resource_loads(requests)
            }
            None => 0,
        };
        started
    }

    /// Whether background render-resource loads are still running.
    #[cfg(feature = "render")]
    pub fn has_pending_render_resources(&self) -> bool {
        self.js
            .as_ref()
            .is_some_and(|js| js.has_pending_render_resources())
    }

    /// Seed the renderer cache through the owning page transport and wait up
    /// to `max_ms` for the results. This removes serial image/font HTTP from
    /// the first screenshot while retaining cookies, proxy policy,
    /// interception, CORS, response limits, and connection pooling. Loads
    /// that miss the deadline keep running in the background and are applied
    /// by a later drain; they are neither cancelled nor negative-cached.
    #[cfg(feature = "render")]
    pub async fn prepare_screenshot_resources(&mut self, max_ms: u64) -> usize {
        let started = std::time::Instant::now();
        if max_ms == 0 || self.js.is_none() {
            return 0;
        }
        let mut loaded = 0;
        self.spawn_pending_render_resources();
        let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(max_ms);
        let Some(notify) = self.js.as_ref().map(|js| js.render_resource_notify()) else {
            return loaded;
        };
        loop {
            // Register the waiter first, then apply what already arrived,
            // then decide whether to wait: a load that finished after the
            // scan (its wake is already past) is picked up by the drain, and
            // one that finishes after the drain wakes the registered waiter.
            let notified = notify.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            loaded += self.drain_render_resource_results();
            if !self.has_pending_render_resources() {
                break;
            }
            if tokio::time::timeout_at(deadline, notified).await.is_err() {
                loaded += self.drain_render_resource_results();
                break;
            }
        }
        tracing::debug!(
            loaded,
            elapsed_ms = started.elapsed().as_millis(),
            "prepared screenshot resources through page transport"
        );
        loaded
    }

    /// Rasterize the current DOM to PNG bytes at `viewport` (CSS pixels), when
    /// the render feature is compiled in. None if the page has no DOM or the
    /// viewport is zero-sized. Never loads resources synchronously; without a
    /// runtime, external assets remain unavailable until the page is resumed
    /// and its resources are prepared.
    #[cfg(feature = "render")]
    pub fn screenshot(&self, viewport: (f32, f32)) -> Option<Vec<u8>> {
        self.screenshot_with_animation_sample(viewport, self.live_animation_sample())
    }

    /// Rasterize every CSS animation at one explicit local time. This mirrors
    /// Web Animations `currentTime` and is intended for deterministic parity
    /// capture; ordinary screenshots use each live instance's start epoch.
    #[cfg(feature = "render")]
    pub fn screenshot_at_animation_time(
        &self,
        viewport: (f32, f32),
        animation_sample_time: obscura_js::AnimationSampleTime,
    ) -> Option<Vec<u8>> {
        self.screenshot_with_animation_sample(
            viewport,
            obscura_js::AnimationSample {
                time: animation_sample_time,
                mode: obscura_js::AnimationSampleMode::LocalOverride,
            },
        )
    }

    #[cfg(feature = "render")]
    pub fn screenshot_with_animation_sample(
        &self,
        viewport: (f32, f32),
        animation_sample: obscura_js::AnimationSample,
    ) -> Option<Vec<u8>> {
        // Needed to resolve the relative image URLs ("logo.svg") that make up
        // the overwhelming majority of real markup.
        let base_url = self.resolve_base_url();
        let base_url = base_url.as_ref().map(|u| u.as_str());
        if let Some(js) = &self.js {
            if !js.set_animation_sample(animation_sample) {
                return None;
            }
            if let Some(png) = js.screenshot_prepared_with_surface_color(
                viewport,
                base_url,
                self.capture_surface_color(),
            ) {
                return Some(png);
            }
        }
        // Compatibility path for a page without a JS runtime or an ad-hoc
        // viewport/base that does not match the runtime's CSSOM render key.
        let scroll = self
            .js
            .as_ref()
            .map(|js| js.scroll_offset())
            .unwrap_or((0.0, 0.0));
        // When there IS a runtime, paint against the resource cache it already
        // holds for this document. Building a fresh one here refetched every
        // image on every capture, so a caller repeating a screenshot at a
        // viewport that does not match the prepared key paid the whole network
        // cost per frame.
        if let Some(js) = &self.js {
            if let Some(png) = js.screenshot_unprepared_with_retained_resources(
                viewport,
                base_url,
                scroll,
                animation_sample.time,
                self.capture_surface_color(),
            ) {
                return Some(png);
            }
        }
        // A DOM-only page still owns network policy. Its fallback must not
        // bypass the page transport through the standalone synchronous loader.
        self.with_dom(|dom| {
            let mut resources = obscura_js::RenderResourceCache::default();
            resources.set_sync_loading_enabled(false);
            obscura_js::screenshot_png_scrolled_at_animation_time_with_surface_color_and_resources(
                dom,
                viewport,
                base_url,
                scroll,
                animation_sample.time,
                self.capture_surface_color(),
                &mut resources,
            )
        })
            .flatten()
    }

    /// Rasterize an immutable document-space rectangle from the page's retained
    /// layout. Unlike [`Self::screenshot`], this may address content outside the
    /// live viewport and scale the output without relayout or scripted scroll.
    #[cfg(feature = "render")]
    pub fn screenshot_region(
        &self,
        region: obscura_js::CaptureRegion,
    ) -> Result<Vec<u8>, obscura_js::CaptureError> {
        self.screenshot_region_with_animation_sample(region, self.live_animation_sample())
    }

    #[cfg(feature = "render")]
    pub fn screenshot_region_at_animation_time(
        &self,
        region: obscura_js::CaptureRegion,
        animation_sample_time: obscura_js::AnimationSampleTime,
    ) -> Result<Vec<u8>, obscura_js::CaptureError> {
        self.screenshot_region_with_animation_sample(
            region,
            obscura_js::AnimationSample {
                time: animation_sample_time,
                mode: obscura_js::AnimationSampleMode::LocalOverride,
            },
        )
    }

    #[cfg(feature = "render")]
    pub fn screenshot_region_with_animation_sample(
        &self,
        region: obscura_js::CaptureRegion,
        animation_sample: obscura_js::AnimationSample,
    ) -> Result<Vec<u8>, obscura_js::CaptureError> {
        let js = self
            .js
            .as_ref()
            .ok_or(obscura_js::CaptureError::PaintFailed)?;
        if !js.set_animation_sample(animation_sample) {
            return Err(obscura_js::CaptureError::PaintFailed);
        }
        js.screenshot_prepared_region_with_surface_color(region, self.capture_surface_color())
    }

    #[cfg(feature = "render")]
    pub fn screenshot_region_raster_with_animation_sample(
        &self,
        region: obscura_js::CaptureRegion,
        animation_sample: obscura_js::AnimationSample,
    ) -> Result<image::RgbaImage, obscura_js::CaptureError> {
        let js = self
            .js
            .as_ref()
            .ok_or(obscura_js::CaptureError::PaintFailed)?;
        if !js.set_animation_sample(animation_sample) {
            return Err(obscura_js::CaptureError::PaintFailed);
        }
        let (width, height, pixels) = js
            .screenshot_prepared_region_raster_with_surface_color(
                region,
                self.capture_surface_color(),
            )?;
        image::RgbaImage::from_raw(width, height, pixels)
            .ok_or(obscura_js::CaptureError::PaintFailed)
    }

    /// Scrollable document dimensions from the retained render layout. Unlike
    /// DOM properties evaluated in page JavaScript, this cannot be shadowed or
    /// monkey-patched by the document being captured.
    #[cfg(feature = "render")]
    pub fn prepared_content_size(&self) -> Option<(f32, f32)> {
        self.prepared_content_size_with_animation_sample(self.live_animation_sample())
    }

    #[cfg(feature = "render")]
    pub fn prepared_content_size_at_animation_time(
        &self,
        animation_sample_time: obscura_js::AnimationSampleTime,
    ) -> Option<(f32, f32)> {
        self.prepared_content_size_with_animation_sample(obscura_js::AnimationSample {
            time: animation_sample_time,
            mode: obscura_js::AnimationSampleMode::LocalOverride,
        })
    }

    #[cfg(feature = "render")]
    pub fn prepared_content_size_with_animation_sample(
        &self,
        animation_sample: obscura_js::AnimationSample,
    ) -> Option<(f32, f32)> {
        let js = self.js.as_ref()?;
        js.set_animation_sample(animation_sample)
            .then(|| js.prepared_content_size())
            .flatten()
    }

    #[cfg(feature = "render")]
    pub fn live_animation_sample(&self) -> obscura_js::AnimationSample {
        if let Some(js) = &self.js {
            return js.live_animation_sample();
        }
        let milliseconds = self.document_timeline_origin.elapsed().as_secs_f64() * 1_000.0;
        obscura_js::AnimationSample {
            time: obscura_js::AnimationSampleTime {
                milliseconds: milliseconds.min(f64::from(f32::MAX)) as f32,
            },
            mode: obscura_js::AnimationSampleMode::DocumentTime,
        }
    }

    #[cfg(feature = "render")]
    pub fn prepared_has_active_css_animations(&self) -> bool {
        self.js
            .as_ref()
            .is_some_and(|js| js.prepared_has_active_css_animations())
    }

    /// Renderer-owned root scroll offset for document-space capture routing.
    #[cfg(feature = "render")]
    pub fn screenshot_scroll_offset(&self) -> (f32, f32) {
        self.js
            .as_ref()
            .map(|js| js.scroll_offset())
            .unwrap_or((0.0, 0.0))
    }

    /// Absolute URLs the page pulled in via fetch()/XHR (issue #301). Empty
    /// when the page has no live JS runtime.
    pub fn fetched_urls(&self) -> Vec<String> {
        self.js
            .as_ref()
            .map(|js| js.fetched_urls())
            .unwrap_or_default()
    }

    /// Move network events recorded for script-initiated requests
    /// (fetch/XHR/dynamic resource) from the JS runtime into this page's
    /// network_events, so the CDP layer emits Network.requestWillBeSent /
    /// responseReceived for them (issue #406). Idempotent: the runtime's queue
    /// is drained, so calling this repeatedly does not duplicate events. The
    /// fetch-{N} request id is preserved so Network.getResponseBody resolves.
    pub fn sync_js_network_events(&mut self) {
        let events = match self.js.as_ref() {
            Some(js) => js.take_js_network_events(),
            None => return,
        };
        for ev in events {
            self.network_events.push(NetworkEvent {
                request_id: ev.request_id,
                intercepted: ev.intercepted,
                url: ev.url,
                method: ev.method,
                resource_type: ev.resource_type,
                status: ev.status,
                headers: std::collections::HashMap::new(),
                response_headers: Arc::new(ev.response_headers),
                body_size: ev.body_size,
                timestamp: ev.timestamp,
                error_text: ev.error_text,
            });
        }
    }

    pub fn dom(&self) -> Option<&DomTree> {
        self.dom.as_ref()
    }

    /// V8 isolate handle for this page's runtime, if it has been initialized.
    /// Lets the CDP dispatcher arm a per-command watchdog (which bounds any one
    /// command so a hung page cannot hold this connection's V8 lock forever)
    /// without taking `&mut self`.
    pub fn isolate_handle(&self) -> Option<obscura_js::runtime::IsolateHandle> {
        self.js.as_ref().map(|js| js.isolate_handle())
    }

    /// Clear a V8 termination left by a per-command watchdog so the next command
    /// on this page can run. No-op if the runtime is absent or not terminating.
    pub fn cancel_v8_termination(&mut self) {
        if let Some(js) = self.js.as_mut() {
            js.cancel_termination();
        }
    }

    /// Like [`Self::evaluate`] but bounded by a V8 watchdog so a runaway
    /// expression cannot hang the process. A non-zero `timeout` of zero falls
    /// back to the unbounded path.
    pub fn evaluate_with_timeout(
        &mut self,
        expression: &str,
        timeout: std::time::Duration,
    ) -> serde_json::Value {
        if let Some(js) = &mut self.js {
            match js.evaluate_with_timeout(expression, timeout) {
                Ok(val) => val,
                Err(e) => {
                    tracing::debug!(
                        "JS eval error/timeout for '{}': {}",
                        truncate_on_char_boundary(expression, 80),
                        e
                    );
                    serde_json::Value::Null
                }
            }
        } else {
            self.evaluate(expression)
        }
    }

    /// Run a script and preserve JavaScript execution errors. The caller owns its deadline.
    pub fn evaluate_script(&mut self, script: &str) -> Result<serde_json::Value, String> {
        self.js.as_mut().ok_or("JavaScript runtime unavailable")?.evaluate_script(script)
    }

    pub fn evaluate(&mut self, expression: &str) -> serde_json::Value {
        if let Some(js) = &mut self.js {
            match js.evaluate(expression) {
                Ok(val) => val,
                Err(e) => {
                    tracing::debug!(
                        "JS eval error for '{}': {}",
                        truncate_on_char_boundary(expression, 80),
                        e
                    );
                    serde_json::Value::Null
                }
            }
        } else {
            match expression.trim() {
                "document.title" => serde_json::Value::String(self.title.clone()),
                "document.URL" | "document.location.href" | "window.location.href" => {
                    serde_json::Value::String(self.url_string())
                }
                _ => serde_json::Value::Null,
            }
        }
    }

    pub async fn evaluate_for_cdp(
        &mut self,
        expression: &str,
        return_by_value: bool,
        await_promise: bool,
    ) -> obscura_js::runtime::RemoteObjectInfo {
        if self.js.is_some() {
            match self
                .evaluate_for_cdp_with_timeout(expression, return_by_value, await_promise,
                    obscura_js::runtime::DEFAULT_CDP_AWAIT_TIMEOUT_MS)
                .await
            {
                Ok(info) => info,
                Err(e) => {
                    tracing::debug!("evaluate_for_cdp error: {}", e);
                    obscura_js::runtime::RemoteObjectInfo {
                        thrown: false,
                        unserializable_value: None,
                        js_type: "undefined".into(),
                        subtype: None,
                        class_name: String::new(),
                        description: String::new(),
                        object_id: None,
                        value: None,
                    }
                }
            }
        } else {
            let val = self.evaluate(expression);
            obscura_js::runtime::RemoteObjectInfo {
                thrown: false,
                unserializable_value: None,
                js_type: match &val {
                    serde_json::Value::String(_) => "string".into(),
                    serde_json::Value::Number(_) => "number".into(),
                    serde_json::Value::Bool(_) => "boolean".into(),
                    _ => "undefined".into(),
                },
                subtype: None,
                class_name: String::new(),
                description: String::new(),
                object_id: None,
                value: Some(val),
            }
        }
    }

    pub async fn evaluate_for_cdp_with_timeout(
        &mut self,
        expression: &str,
        return_by_value: bool,
        await_promise: bool,
        await_timeout_ms: u64,
    ) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
        self.evaluate_for_cdp_in_frame_with_timeout(
            None, expression, return_by_value, await_promise, await_timeout_ms,
        ).await
    }

    #[doc(hidden)]
    pub async fn evaluate_for_cdp_in_frame_with_timeout(
        &mut self,
        frame_id: Option<u32>,
        expression: &str,
        return_by_value: bool,
        await_promise: bool,
        await_timeout_ms: u64,
    ) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
        if let Some(js) = &mut self.js {
            let evaluation = js.start_cdp_evaluation_in_frame(
                frame_id, expression, return_by_value, await_promise,
            )?;
            self.await_cdp_evaluation(evaluation, return_by_value, await_timeout_ms, "Runtime.evaluate").await
        } else {
            if frame_id.is_some() { return Err("JavaScript runtime unavailable".into()); }
            let value = self.evaluate(expression);
            Ok(obscura_js::runtime::RemoteObjectInfo {
                thrown: false,
                unserializable_value: None,
                js_type: match &value {
                    serde_json::Value::String(_) => "string".into(),
                    serde_json::Value::Number(_) => "number".into(),
                    serde_json::Value::Bool(_) => "boolean".into(),
                    _ => "undefined".into(),
                },
                subtype: None,
                class_name: String::new(),
                description: String::new(),
                object_id: None,
                value: Some(value),
            })
        }
    }

    pub async fn call_function_on_for_cdp(
        &mut self,
        function_declaration: &str,
        object_id: Option<&str>,
        args: &[serde_json::Value],
        return_by_value: bool,
        await_promise: bool,
    ) -> obscura_js::runtime::RemoteObjectInfo {
        if self.js.is_some() {
            match self
                .call_function_on_for_cdp_with_timeout(
                    function_declaration,
                    object_id,
                    args,
                    return_by_value,
                    await_promise,
                    obscura_js::runtime::DEFAULT_CDP_AWAIT_TIMEOUT_MS,
                )
                .await
            {
                Ok(info) => info,
                Err(e) => {
                    tracing::debug!("callFunctionOn error: {}", e);
                    obscura_js::runtime::RemoteObjectInfo {
                        thrown: false,
                        unserializable_value: None,
                        js_type: "undefined".into(),
                        subtype: None,
                        class_name: String::new(),
                        description: String::new(),
                        object_id: None,
                        value: None,
                    }
                }
            }
        } else {
            obscura_js::runtime::RemoteObjectInfo {
                thrown: false,
                unserializable_value: None,
                js_type: "undefined".into(),
                subtype: None,
                class_name: String::new(),
                description: String::new(),
                object_id: None,
                value: None,
            }
        }
    }

    pub async fn call_function_on_for_cdp_with_timeout(
        &mut self,
        function_declaration: &str,
        object_id: Option<&str>,
        args: &[serde_json::Value],
        return_by_value: bool,
        await_promise: bool,
        await_timeout_ms: u64,
    ) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
        self.call_function_on_for_cdp_in_frame_with_timeout(
            None, function_declaration, object_id, args, return_by_value,
            await_promise, await_timeout_ms,
        ).await
    }

    #[doc(hidden)]
    pub async fn call_function_on_for_cdp_in_frame_with_timeout(
        &mut self,
        frame_id: Option<u32>,
        function_declaration: &str,
        object_id: Option<&str>,
        args: &[serde_json::Value],
        return_by_value: bool,
        await_promise: bool,
        await_timeout_ms: u64,
    ) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
        let js = self.js.as_mut().ok_or("JavaScript runtime unavailable")?;
        let evaluation = js.start_cdp_call_in_frame(
            frame_id,
            function_declaration,
            object_id,
            args,
            return_by_value,
            await_promise,
        )?;
        self.await_cdp_evaluation(evaluation, return_by_value, await_timeout_ms, "Runtime.callFunctionOn").await
    }

    async fn await_cdp_evaluation(
        &mut self,
        evaluation: obscura_js::runtime::CdpEvaluation,
        return_by_value: bool,
        timeout_ms: u64,
        method: &str,
    ) -> Result<obscura_js::runtime::RemoteObjectInfo, String> {
        let pending = match evaluation {
            obscura_js::runtime::CdpEvaluation::Complete(info) => return Ok(info),
            obscura_js::runtime::CdpEvaluation::Pending(pending) => pending,
        };
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
        let wait = async {
            loop {
                let queued = !self.pending_frame_work.is_empty();
                let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
                let js = self.js.as_mut().ok_or("JavaScript runtime unavailable")?;
                let mut ready = false;
                let progressed = js.resolve_promises_until(|js| {
                    ready = js.cdp_evaluation_ready(&pending);
                    ready || queued || js.has_pending_frame_tasks()
                }, duration_millis_u64(remaining)).await;
                if ready { return Ok(()); }
                if !progressed { return Err(format!("{method} promise did not settle within {timeout_ms}ms")); }
                self.advance_frames().await;
            }
        };
        let result = tokio::time::timeout_at(deadline, wait).await
            .unwrap_or_else(|_| Err(format!("{method} promise did not settle within {timeout_ms}ms")));
        let js = self.js.as_mut().ok_or("JavaScript runtime unavailable")?;
        match result {
            Ok(()) => js.finish_cdp_evaluation(pending, return_by_value),
            Err(error) => { js.cancel_cdp_evaluation(pending); Err(error) }
        }
    }

    pub fn set_blocked_urls(&mut self, patterns: Vec<String>) {
        self.blocked_url_patterns = patterns.clone();
        if let Some(js) = &self.js {
            js.set_blocked_urls(patterns);
        }
    }

    pub fn release_object(&mut self, object_id: &str) {
        if let Some(js) = &mut self.js {
            js.release_object(object_id);
        }
    }

    fn record_network_event_with_body(
        &mut self,
        url: &str,
        method: &str,
        resource_type: &str,
        status: u16,
        response_headers: &std::collections::HashMap<String, String>,
        body: &[u8],
        base64_encoded: bool,
    ) {
        let request_id = self.record_network_event_inner(
            url,
            method,
            resource_type,
            status,
            response_headers,
            body.len(),
        );
        self.store_response_body(request_id, body, base64_encoded);
    }

    fn record_network_event_inner(
        &mut self,
        url: &str,
        method: &str,
        resource_type: &str,
        status: u16,
        response_headers: &std::collections::HashMap<String, String>,
        body_size: usize,
    ) -> String {
        self.network_event_counter += 1;
        let request_id = format!("{}.{}", self.id, self.network_event_counter);
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs_f64();
        self.network_events.push(NetworkEvent {
            request_id: request_id.clone(),
            intercepted: false,
            url: url.to_string(),
            method: method.to_string(),
            resource_type: resource_type.to_string(),
            status,
            headers: std::collections::HashMap::new(),
            response_headers: Arc::new(response_headers.clone()),
            body_size,
            timestamp,
            error_text: None,
        });
        request_id
    }

    fn store_response_body(&mut self, request_id: String, body: &[u8], base64_encoded: bool) {
        let max_entries = response_body_entry_limit();
        let max_bytes = response_body_byte_limit();
        if max_entries == 0 || max_bytes == 0 || body.len() > max_bytes {
            return;
        }
        self.response_bodies.insert(
            request_id.clone(),
            StoredResponseBody {
                body: body.to_vec(),
                base64_encoded,
            },
        );
        self.response_body_order.push_back(request_id);
        while self.response_body_order.len() > max_entries {
            if let Some(oldest) = self.response_body_order.pop_front() {
                self.response_bodies.remove(&oldest);
            }
        }
    }

    pub fn get_response_body(&self, request_id: &str) -> Option<StoredResponseBody> {
        self.response_bodies.get(request_id).cloned().or_else(|| {
            let body = self
                .js
                .as_ref()?
                .get_network_response_body(request_id)?;
            // The JS-side store holds the lossy/base64 text form; convert to
            // raw bytes so the page-side store stays uniformly lazy.
            let raw = if body.base64_encoded {
                BASE64.decode(body.body.as_bytes()).ok()?
            } else {
                body.body.into_bytes()
            };
            Some(StoredResponseBody {
                body: raw,
                base64_encoded: body.base64_encoded,
            })
        })
    }

    /// Take a stored response body as raw bytes for CDP streaming
    /// (Fetch.takeResponseBodyAsStream). Removes it from the in-memory cache and
    /// transfers ownership to the caller, so a large body is held once and freed
    /// when the stream is closed rather than lingering in this long-running
    /// process (issue #360). Binary bodies are stored base64 (byte-exact); text
    /// bodies return their UTF-8 bytes. Returns None if the body was never
    /// cached (e.g. it exceeded OBSCURA_NETWORK_BODY_BUFFER_BYTES and was
    /// dropped) or the id is unknown.
    pub fn take_response_body_raw(&mut self, request_id: &str) -> Option<Vec<u8>> {
        if let Some(body) = self.response_bodies.remove(request_id) {
            self.response_body_order.retain(|id| id != request_id);
            // Raw bytes are what this returns; the base64 flag only says how
            // CDP would report the body, not how it is stored.
            return Some(body.body);
        }
        let b = self
            .js
            .as_ref()?
            .get_network_response_body(request_id)?;
        if b.base64_encoded {
            BASE64.decode(b.body.as_bytes()).ok()
        } else {
            Some(b.body.into_bytes())
        }
    }

    /// Make the body stored under `from_id` also retrievable under `to_id`.
    /// The main navigation resource is stored under its internal request id, but
    /// the CDP layer reports it to clients with the navigation's loaderId as the
    /// requestId (Chrome's `requestId === loaderId` convention). Without this
    /// alias, `Network.getResponseBody(loaderId)` misses and a client navigating
    /// straight to an image or other resource cannot read the main-response body
    /// (issue #340).
    pub fn alias_response_body(&mut self, from_id: &str, to_id: &str) {
        if from_id == to_id || self.response_bodies.contains_key(to_id) {
            return;
        }
        if let Some(body) = self.response_bodies.get(from_id).cloned() {
            self.response_bodies.insert(to_id.to_string(), body);
            self.response_body_order.push_back(to_id.to_string());
        }
    }

    pub fn clear_response_bodies(&mut self) {
        self.response_bodies.clear();
        self.response_body_order.clear();
        if let Some(js) = &self.js {
            js.clear_network_response_bodies();
        }
    }

    pub fn execute_preload_script(&mut self, source: &str) -> Result<(), String> {
        if let Some(js) = &mut self.js {
            js.execute_script("<preload>", source)
        } else {
            Err("No JS runtime".to_string())
        }
    }

    pub fn suspend_js(&mut self) {
        if self.js.is_none() {
            return;
        }
        // Completed module and JS requests must survive the realm's teardown.
        self.sync_js_network_events();
        let max_entries = response_body_entry_limit();
        for (id, body) in self.js.as_ref().unwrap().take_network_response_bodies() {
            // The JS-side store holds the lossy/base64 text form; convert to
            // raw bytes so the page-side store stays uniformly lazy.
            let raw = if body.base64_encoded {
                BASE64.decode(body.body.as_bytes()).unwrap_or_default()
            } else {
                body.body.into_bytes()
            };
            self.response_bodies.insert(id.clone(), StoredResponseBody {
                body: raw,
                base64_encoded: body.base64_encoded,
            });
            self.response_body_order.push_back(id);
        }
        while self.response_body_order.len() > max_entries {
            if let Some(oldest) = self.response_body_order.pop_front() {
                self.response_bodies.remove(&oldest);
            }
        }
        // Suspension rebuilds the renderer cache on resume (`take_dom`), so
        // results for the suspended realm would have nowhere to go.
        self.retire_render_resources();
        let Some(js) = &mut self.js else {
            return;
        };
        let started_script_ids = js.started_script_ids();
        self.navigation_timing = js.navigation_timing();
        // Preserve console messages logged before suspension: dropping the
        // runtime below would otherwise lose any not yet drained (#971).
        let pending_console = js.take_pending_console_messages();
        self.suspended_cdp_object_state = js.take_cdp_object_state();
        let dom = js.take_dom();
        if let Some(dom) = dom {
            self.dom = Some(dom);
            self.suspended_started_script_ids = started_script_ids;
        } else {
            self.suspended_started_script_ids.clear();
        }
        // Every frame realm holds a V8 handle into this isolate, so the frames
        // go before the runtime does — the same order init_js keeps on a new
        // document. Suspending is a teardown of the realm the frames live in,
        // and a realm cannot be suspended and resumed the way the page's DOM
        // can, so they are rebuilt when the page next loads a document.
        self.pending_frame_work.clear();
        self.frames.clear();
        self.suspended_console_messages.extend(pending_console);
        self.js = None;
    }

    pub fn resume_js(&mut self) {
        if self.js.is_some() {
            return;
        }
        let started_script_ids = std::mem::take(&mut self.suspended_started_script_ids);
        let cdp_object_state = std::mem::take(&mut self.suspended_cdp_object_state);
        self.init_js();
        if let Some(js) = &mut self.js {
            js.restore_started_script_ids(&started_script_ids);
            js.restore_cdp_object_state(cdp_object_state);
        }
    }

    pub fn has_js(&self) -> bool {
        self.js.is_some()
    }

    /// Origin-scoped sessionStorage for this tab, including inactive origins.
    pub fn session_storage(&self) -> &OriginStorage {
        &self.session_storage
    }

    pub fn has_pending_indexed_db_notifications(&self) -> bool {
        self.context.indexed_db.has_pending_notifications()
    }

    pub fn release_object_group(&mut self) {
        if let Some(js) = &mut self.js {
            js.release_object_group();
        }
    }

    pub fn take_pending_navigation(&self) -> Option<(String, String, String)> {
        let js = self.js.as_ref()?;
        let navigation = js.take_pending_navigation()?;
        if let Ok(mut traversal) = self.pending_history_traversal.lock() {
            *traversal = js.take_pending_history_traversal();
        }
        Some(navigation)
    }

    pub fn has_pending_navigation(&self) -> bool {
        self.js
            .as_ref()
            .is_some_and(|js| js.has_pending_navigation())
    }

    /// Discard a queued document navigation and cancel retained resource loads.
    /// The CDP processor separately cancels its borrowed navigation future.
    pub fn stop_loading(&mut self) {
        self.take_pending_navigation();
        #[cfg(feature = "render")]
        if let Some(js) = &mut self.js { js.stop_render_resource_loading(); }
    }

    pub fn take_pending_binding_calls(&self) -> Vec<(String, String)> {
        if let Some(js) = &self.js {
            js.take_pending_binding_calls()
        } else {
            Vec::new()
        }
    }

    pub fn take_pending_runtime_events(&mut self) -> Vec<obscura_js::ops::RuntimeEvent> {
        if let Some(js) = &mut self.js {
            js.take_pending_runtime_events()
        } else {
            Vec::new()
        }
    }

    pub fn take_pending_console_messages(&mut self) -> Vec<String> {
        // Buffered messages from any suspended runtime come first, then the
        // live runtime's messages (#971).
        let mut messages = std::mem::take(&mut self.suspended_console_messages);
        if let Some(js) = &self.js {
            messages.extend(js.take_pending_console_messages());
        }
        messages
    }

    pub fn set_runtime_events_enabled(&self, enabled: bool) {
        self.runtime_events_enabled.set(enabled);
        if let Some(js) = &self.js {
            js.set_runtime_events_enabled(enabled);
        }
    }

    pub fn set_console_messages_enabled(&self, enabled: bool) {
        self.console_messages_enabled.set(enabled);
        if let Some(js) = &self.js {
            js.set_console_messages_enabled(enabled);
        }
    }

    pub fn set_preload_scripts(&mut self, scripts: Vec<String>) {
        if let Some(js) = &self.js { js.set_frame_preload_scripts(&scripts); }
        self.preload_scripts = scripts;
    }

    /// Append a script that runs in the page before any of the page's own
    /// `<script>` tags, matching CDP `Page.addScriptToEvaluateOnNewDocument`.
    /// Takes effect on the next navigation (`goto` / `navigate*`).
    pub fn add_preload_script(&mut self, script: &str) {
        self.preload_scripts.push(script.to_string());
    }

    /// Enable CDP-Fetch-style interception of HTTP document navigation and JS `fetch()`/XHR.
    /// Returns a receiver yielding every such request; resolve each through its
    /// `resolver` with `InterceptResolution::{Continue, Fulfill, Fail}` to pass,
    /// mock, or block it. Works in stealth and non-stealth. Mirrors how the CDP
    /// server wires the channel (`obscura-cdp/src/server.rs`).
    pub fn enable_interception(
        &mut self,
    ) -> tokio::sync::mpsc::UnboundedReceiver<obscura_js::ops::InterceptedRequest> {
        let (tx, rx) =
            tokio::sync::mpsc::unbounded_channel::<obscura_js::ops::InterceptedRequest>();
        self.set_intercept_tx(tx);
        self.enable_intercept(true);
        rx
    }

    /// Register a passive callback fired for every JS `fetch()`/XHR (and
    /// navigation) request this page makes, once the method/headers/body are
    /// known and before it is sent. Non-blocking; use `enable_interception` to
    /// mutate or block. Returns a stable id; pass it to `off_request` to
    /// detach (issue #408). Scoped to this page: it never sees sibling pages'
    /// requests and dies with the page.
    pub fn on_request(&mut self, cb: RequestCallback) -> u64 {
        self.callbacks.add_request(cb)
    }

    /// Register a passive callback fired with every JS `fetch()`/XHR (and
    /// navigation) response this page receives, including its body.
    /// Non-blocking. The main path for crawlers that need to capture API
    /// response payloads. Returns a stable id for `off_response`. Page-scoped
    /// like `on_request`.
    pub fn on_response(&mut self, cb: ResponseCallback) -> u64 {
        self.callbacks.add_response(cb)
    }

    /// Detach a request observer registered with `on_request`. Returns true if
    /// one was removed.
    pub fn off_request(&mut self, id: u64) -> bool {
        self.callbacks.remove_request(id)
    }

    /// Detach a response observer registered with `on_response`. Returns true if
    /// one was removed.
    pub fn off_response(&mut self, id: u64) -> bool {
        self.callbacks.remove_response(id)
    }

    pub async fn process_pending_navigation(&mut self) -> Result<bool, PageError> {
        Ok(self.process_pending_navigation_outcome().await? != PendingNavigationOutcome::None)
    }

    /// Reject a document-driven cross-scheme jump to `file://` and restore
    /// the virtual URL that the location setter changed before queuing it.
    pub fn reject_page_initiated_file_navigation(&mut self, target: &str) -> bool {
        let current_url = self.url_string();
        if !cross_scheme_to_file(&current_url, target) {
            return false;
        }
        tracing::warn!(
            "blocking page-initiated cross-scheme navigation to file: {} -> {}",
            current_url,
            target,
        );
        if let Some(js) = self.js.as_mut() {
            let _ = js.execute_script(
                "<blocked-navigation>",
                &format!(
                    "globalThis.__virtualUrl = {};",
                    serde_json::to_string(&current_url).unwrap_or_else(|_| "null".into())
                ),
            );
        }
        true
    }

    pub async fn process_pending_navigation_outcome(
        &mut self,
    ) -> Result<PendingNavigationOutcome, PageError> {
        if let Some((url, method, body)) = self.take_pending_navigation() {
            // SOP gate for navigations the page queued itself (a timer or
            // handler assigning location, a link click, a form submit). They
            // arrive here as a fresh first URL, so the chain gate in
            // navigate_with_wait_post_inner never sees them. A web document
            // must not drive itself into file:// even in a context that lets
            // clients open local files (#1069).
            if self.reject_page_initiated_file_navigation(&url) {
                return Ok(PendingNavigationOutcome::None);
            }
            self.navigate_from_document(&url, &method, &body).await?;
            Ok(PendingNavigationOutcome::Document)
        } else {
            // Fork: a page that routed itself through history has still
            // navigated. See fork_virtual_url.rs.
            Ok(if self.sync_virtual_url() {
                PendingNavigationOutcome::SameDocument
            } else {
                PendingNavigationOutcome::None
            })
        }
    }

    /// Follow an in-document navigation, retaining its referrer and deadline
    /// even when an embedder services intercepted requests outside dispatch.
    pub async fn navigate_from_document(
        &mut self,
        url: &str,
        method: &str,
        body: &str,
    ) -> Result<(), PageError> {
        self.sync_history_updates();
        let initiator = self.url.clone();
        let source_url = initiator.as_ref().and_then(|source| {
            Url::parse(url).ok().map(|target| navigation_referrer(source, &target))
        }).unwrap_or_default();
        let nav_timeout = self.navigation_timeout();
        let nav_timeout_ms = duration_millis_u64(nav_timeout);
        tokio::time::timeout(
            nav_timeout,
            self.navigate_with_wait_post_inner(
                url, crate::lifecycle::WaitUntil::Load, method, body, &source_url, initiator.as_ref(),
            ),
        ).await.map_err(|_| {
            self.lifecycle = crate::lifecycle::LifecycleState::Failed;
            PageError::NetworkError(format!("navigation exceeded {nav_timeout_ms}ms deadline"))
        })??;
        self.push_history(self.url_string());
        Ok(())
    }

    pub fn set_intercept_tx(
        &mut self,
        tx: tokio::sync::mpsc::UnboundedSender<obscura_js::ops::InterceptedRequest>,
    ) {
        self.intercept_tx = Some(tx.clone());
        if let Some(js) = &self.js {
            js.set_intercept_tx(tx);
        }
    }

    pub fn enable_intercept(&mut self, enabled: bool) {
        self.intercept_enabled = enabled;
        if let Some(js) = &self.js {
            js.set_intercept_enabled(enabled);
            js.set_intercept_url_patterns(self.intercept_block_patterns.clone());
            // `Fetch.enable` assigns the patterns right before this call;
            // the renderer's loads follow the same interception policy.
            #[cfg(feature = "render")]
            js.set_intercept_block_patterns(self.intercept_block_patterns.clone());
        }
    }
}

fn script_response_is_executable(status: u16) -> bool {
    (200..=299).contains(&status)
}

pub use obscura_js::ops::url_matches_cdp_pattern;

impl Drop for Page {
    fn drop(&mut self) {
        // A closed target must not keep fetching for a document nobody can
        // observe any more.
        self.retire_render_resources();
    }
}

#[cfg(test)]
mod tests {
    use super::{
        css_resource_urls, linked_stylesheet_requests, materialize_stylesheet_graph,
        navigation_chain_limit_from_env_value, navigation_referrer,
        navigation_timeout_from_env_value, parse_import_url, rebase_css_urls,
        register_linked_stylesheet_script, script_response_is_executable, split_css_imports,
        stylesheet_graph_is_origin_clean, truncate_on_char_boundary, url_matches_cdp_pattern,
        LoadedStylesheet, PendingFrameWork, StylesheetImport, DEFAULT_NAVIGATION_CHAIN_LIMIT,
        Page, BrowserContext, LifecycleState, HistoryUpdate, BASE64,
    };
    #[cfg(feature = "render")]
    use super::remaining_settle_resource_warmup_ms;
    use base64::Engine as _;
    use std::sync::Arc;
    use obscura_dom::parse_html;

    #[cfg(feature = "stealth")]
    #[test]
    fn stealth_navigator_uses_the_explicit_context_user_agent() {
        let context=std::sync::Arc::new(crate::BrowserContext::with_storage_and_network("stealth-identity".into(),None,true,Some("TestingUA/1.0".into()),None,false));
        let mut page=super::Page::new("stealth-identity".into(),context);
        page.url=Some(url::Url::parse("https://example.test/").unwrap());
        page.dom=Some(parse_html("<html><body></body></html>"));page.init_js();
        assert_eq!(page.evaluate_script("navigator.userAgent").unwrap(),serde_json::json!("TestingUA/1.0"));
    }


    #[tokio::test(flavor = "current_thread")]
    async fn navigation_interception_fulfills_before_transport_and_preserves_bytes() {
        use obscura_js::ops::InterceptResolution;
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let context = Arc::new(BrowserContext::new("document-interception".into()));
        let mut page = Page::new("document-interception".into(), context);
        let mut requests = page.enable_interception();
        let bytes = b"<!doctype html><title>Fulfilled</title><p>replacement</p>".to_vec();
        let expected = bytes.clone();
        let (result, ()) = tokio::join!(page.navigate("http://127.0.0.1:9/original"), async {
            let request = tokio::time::timeout(std::time::Duration::from_secs(2), requests.recv()).await.unwrap().unwrap();
            assert_eq!(request.resource_type, "Document");
            assert_eq!(request.method, "GET");
            request.resolver.send(InterceptResolution::Fulfill {status: 201,
                headers: [("content-type".into(), "text/html".into()),
                    ("Set-Cookie".into(), "first=1; Path=/".into()),
                    ("set-cookie".into(), "second=2; Path=/".into())].into(),
                body: "not the decoded body".into(), body_base64: BASE64.encode(bytes)}).ok().unwrap();
        });
        result.unwrap();
        assert_eq!(page.title, "Fulfilled");
        let document = page.network_events.iter().find(|event| event.resource_type == "Document").unwrap();
        assert_eq!(document.status, 201);assert!(document.intercepted);
        assert_eq!(page.response_bodies.get(&document.request_id).unwrap().body, expected);
        let mut set_cookies = document.response_headers.get("set-cookie").unwrap().lines().collect::<Vec<_>>();
        set_cookies.sort_unstable();
        assert_eq!(set_cookies, ["first=1; Path=/", "second=2; Path=/"]);
        let cookies = page.context.cookie_jar.get_cookie_header(&url::Url::parse("http://127.0.0.1:9/original").unwrap());
        assert!(cookies.split("; ").any(|cookie| cookie == "first=1"), "{cookies}");
        assert!(cookies.split("; ").any(|cookie| cookie == "second=2"), "{cookies}");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_interception_continues_with_request_local_overrides() {
        assert_navigation_interception_continues_with_request_local_overrides(false).await;
    }

    #[cfg(feature = "stealth")]
    #[tokio::test(flavor = "current_thread")]
    async fn navigation_interception_continues_with_request_local_overrides_in_stealth() {
        assert_navigation_interception_continues_with_request_local_overrides(true).await;
    }

    async fn assert_navigation_interception_continues_with_request_local_overrides(stealth: bool) {
        use obscura_js::ops::InterceptResolution;
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let target = format!("http://{}/changed", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.unwrap();
            let mut request = Vec::new();let mut chunk = [0; 4096];
            loop {
                let n = socket.read(&mut chunk).await.unwrap();assert!(n>0);
                request.extend_from_slice(&chunk[..n]);
                if let Some(end) = request.windows(4).position(|bytes| bytes==b"\r\n\r\n") {
                    if request.len()>=end+4+3 {break;}
                }
            }
            let head=String::from_utf8_lossy(&request).to_ascii_lowercase();
            assert!(head.starts_with("post /changed http/1.1"));
            assert!(head.contains("content-type: application/octet-stream"));
            assert!(head.contains("x-navigation: isolated"));
            assert!(request.ends_with(&[0,255,128]));
            socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 24\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n<title>continued</title>").await.unwrap();
        });
        let context=Arc::new(BrowserContext::with_storage_and_network("continued-navigation".into(),None,stealth,None,None,true));
        let mut page=Page::new("continued-navigation".into(),context);
        let mut requests=page.enable_interception();
        let (result,())=tokio::join!(page.navigate("http://127.0.0.1:9/original"),async {
            let request=tokio::time::timeout(std::time::Duration::from_secs(2),requests.recv()).await.unwrap().unwrap();
            request.resolver.send(InterceptResolution::Continue {url:Some(target),method:Some("POST".into()),
                headers:Some([("content-type".into(),"application/octet-stream".into()),("x-navigation".into(),"isolated".into())].into()),
                body:Some(vec![0,255,128])}).ok().unwrap();
        });
        result.unwrap();server.await.unwrap();
        assert_eq!(page.title,"continued");
        assert_eq!(page.url_string(),"http://127.0.0.1:9/original","a network rewrite does not rewrite the document URL");
        assert!(page.http_client.extra_headers.read().await.is_empty(),"per-request headers cannot leak to another page");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_interception_can_fail_without_contacting_transport() {
        use obscura_js::ops::InterceptResolution;
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let context = Arc::new(BrowserContext::new("aborted-navigation".into()));
        let mut page = Page::new("aborted-navigation".into(), context);
        let mut requests = page.enable_interception();
        let (result, ()) = tokio::join!(page.navigate("http://127.0.0.1:9/aborted"), async {
            let request = tokio::time::timeout(std::time::Duration::from_secs(2), requests.recv()).await.unwrap().unwrap();
            request.resolver.send(InterceptResolution::Fail {reason: "Aborted".into()}).ok().unwrap();
        });
        assert!(result.unwrap_err().to_string().contains("ERR_ABORTED"));
        assert_eq!(page.lifecycle, LifecycleState::Failed);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn blank_navigation_has_no_doctype_and_starts_in_quirks_mode() {
        let context = std::sync::Arc::new(crate::BrowserContext::new("blank-mode".into()));
        let mut page = super::Page::new("blank-mode".into(), context);
        page.navigate("about:blank").await.unwrap();
        assert_eq!(page.evaluate(r#"(() => [
            document.compatMode, document.doctype,
            Array.from(document.childNodes, node => node.nodeType),
            document.documentElement.nodeName, document.head.nodeName, document.body.nodeName
        ])()"#), serde_json::json!(["BackCompat", null, [1], "HTML", "HEAD", "BODY"]));
        assert!(page.with_dom(|dom| dom.is_quirks()).unwrap());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_quiet_deadline_does_not_gain_an_extra_polling_slice() {
        use std::future::Future as _;

        // No JavaScript runtime is needed to test the lifecycle deadline.
        // This also keeps unrelated V8 maintenance wakes out of the clock test.
        let context = std::sync::Arc::new(crate::BrowserContext::new("idle-deadline".into()));
        let mut page = super::Page::new("idle-deadline".into(), context);
        assert!(page.js.is_none());
        tokio::time::pause();
        let started = tokio::time::Instant::now();
        let mut wait = Box::pin(page.wait_for_network_idle(0));
        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
        assert!(wait.as_mut().poll(&mut cx).is_pending());

        // Model a delayed executor poll just before the existing quiet window
        // ends. The next wake belongs to that window, not a fresh full slice.
        tokio::time::advance(std::time::Duration::from_millis(490)).await;
        assert!(wait.as_mut().poll(&mut cx).is_pending(),
            "network idle must not complete before the quiet window");
        tokio::time::advance(std::time::Duration::from_millis(11)).await;
        assert!(wait.as_mut().poll(&mut cx).is_ready(),
            "quiet-window expiry must not wait for another polling slice");
        drop(wait);
        assert_eq!(started.elapsed(), std::time::Duration::from_millis(501));
        assert_eq!(page.lifecycle, crate::lifecycle::LifecycleState::NetworkIdle);
    }

    fn network_idle_test_page() -> super::Page {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "network-idle-regression".into(), None, false, None, None, true,
        ));
        let mut page = super::Page::new("network-idle-regression".into(), context);
        page.url = Some(url::Url::parse("http://example.test/").unwrap());
        page.dom = Some(parse_html("<html><body></body></html>"));
        page.init_js();
        page
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_preserves_quiet_window_and_page_tasks() {
        let mut page = network_idle_test_page();
        page.js.as_mut().unwrap().execute_script("network-idle-interval", r#"
            globalThis.__idleTicks = 0;
            globalThis.__idleObserved = false;
            new MutationObserver(() => { __idleObserved = true; })
                .observe(document.body, { attributes: true });
            const id = setInterval(() => {
                if (++__idleTicks === 3) {
                    clearInterval(id);
                    Promise.resolve().then(() => document.body.setAttribute('data-ready', 'yes'));
                }
            }, 20);
        "#).unwrap();
        let started = tokio::time::Instant::now();
        tokio::time::timeout(std::time::Duration::from_secs(2), page.wait_for_network_idle(0))
            .await.expect("quiet page must finish within its normal window").expect("network idle reached");
        assert!(started.elapsed() >= std::time::Duration::from_millis(500));
        assert_eq!(page.lifecycle, crate::lifecycle::LifecycleState::NetworkIdle);
        assert_eq!(page.js.as_mut().unwrap().evaluate("[__idleTicks, __idleObserved]").unwrap(),
            serde_json::json!([3, true]));
    }

    async fn network_idle_held_request(
        client: std::sync::Arc<obscura_net::ObscuraHttpClient>,
    ) -> (tokio::sync::oneshot::Sender<()>, tokio::task::JoinHandle<()>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
        tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.unwrap();
            let mut request = Vec::new();
            let mut bytes = [0u8; 1024];
            while !request.windows(4).any(|part| part == b"\r\n\r\n") {
                let read = socket.read(&mut bytes).await.unwrap();
                assert!(read > 0 && request.len() < 16384);
                request.extend_from_slice(&bytes[..read]);
            }
            ready_tx.send(()).unwrap();
            let _ = release_rx.await;
            let _ = socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok").await;
        });
        let fetch = tokio::spawn(async move {
            assert_eq!(client.fetch(&url).await.unwrap().status, 200);
        });
        tokio::time::timeout(std::time::Duration::from_secs(2), ready_rx)
            .await.expect("request reached fixture").unwrap();
        (release_tx, fetch)
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_two_allows_two_active_requests() {
        let mut page = network_idle_test_page();
        let (release_a, fetch_a) = network_idle_held_request(page.http_client.clone()).await;
        let (release_b, fetch_b) = network_idle_held_request(page.http_client.clone()).await;
        assert_eq!(page.http_client.active_requests(), 2);
        let started = tokio::time::Instant::now();
        tokio::time::timeout(std::time::Duration::from_secs(2), page.wait_for_network_idle(2))
            .await.expect("two active requests must not force the five-second deadline").expect("network idle reached");
        assert!(started.elapsed() >= std::time::Duration::from_millis(500));
        assert_eq!(page.http_client.active_requests(), 2, "threshold two must allow both held requests");
        release_a.send(()).unwrap();
        release_b.send(()).unwrap();
        fetch_a.await.unwrap();
        fetch_b.await.unwrap();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_zero_starts_quiet_window_after_request_completion() {
        let mut page = network_idle_test_page();
        let (release, fetch) = network_idle_held_request(page.http_client.clone()).await;
        let completed = std::sync::Arc::new(std::sync::Mutex::new(None));
        let recorded = completed.clone();
        let release_task = tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(180)).await;
            release.send(()).unwrap();
            fetch.await.unwrap();
            *recorded.lock().unwrap() = Some(tokio::time::Instant::now());
        });
        tokio::time::timeout(std::time::Duration::from_secs(2), page.wait_for_network_idle(0))
            .await.expect("completed request must permit network idle").expect("network idle reached");
        release_task.await.unwrap();
        assert!(completed.lock().unwrap().unwrap().elapsed() >= std::time::Duration::from_millis(490),
            "an active request must prevent an earlier quiet-window start");
        assert_eq!(page.http_client.active_requests(), 0);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_restarts_quiet_window_when_request_begins() {
        let mut page = network_idle_test_page();
        let client = page.http_client.clone();
        let completed = std::sync::Arc::new(std::sync::Mutex::new(None));
        let recorded = completed.clone();
        let request_task = tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(150)).await;
            let (release, fetch) = network_idle_held_request(client).await;
            tokio::time::sleep(std::time::Duration::from_millis(150)).await;
            release.send(()).unwrap();
            fetch.await.unwrap();
            *recorded.lock().unwrap() = Some(tokio::time::Instant::now());
        });
        tokio::time::timeout(std::time::Duration::from_secs(2), page.wait_for_network_idle(0))
            .await.expect("a completed late request must permit network idle").expect("network idle reached");
        request_task.await.unwrap();
        assert!(completed.lock().unwrap().unwrap().elapsed() >= std::time::Duration::from_millis(490),
            "new traffic must reset the original quiet window");
    }

    #[cfg(feature = "stealth")]
    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_counts_active_stealth_requests() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "stealth-idle".into(), None, true, None, None, true,
        ));
        let mut page = super::Page::new("stealth-idle".into(), context);
        page.set_navigation_timeout(std::time::Duration::from_millis(700));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
        let server = tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.unwrap();
            let mut request = Vec::new();
            let mut bytes = [0u8; 1024];
            while !request.windows(4).any(|part| part == b"\r\n\r\n") {
                let read = socket.read(&mut bytes).await.unwrap();
                assert!(read > 0 && request.len() < 16384);
                request.extend_from_slice(&bytes[..read]);
            }
            ready_tx.send(()).unwrap();
            release_rx.await.unwrap();
            socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok").await.unwrap();
        });
        let client = page.stealth_client.as_ref().unwrap().clone();
        let request = tokio::spawn(async move { client.fetch(&url).await.unwrap() });
        tokio::time::timeout(std::time::Duration::from_secs(2), ready_rx).await.unwrap().unwrap();
        assert_eq!(page.http_client.active_requests(), 0);
        assert_eq!(page.stealth_client.as_ref().unwrap().active_requests(), 1);
        let result = page.wait_for_network_idle(0).await;
        release_tx.send(()).unwrap();
        assert_eq!(request.await.unwrap().status, 200);
        server.await.unwrap();
        assert!(result.unwrap_err().to_string().contains("deadline"));
        assert_eq!(page.lifecycle, crate::lifecycle::LifecycleState::Failed);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_uses_navigation_deadline_without_reporting_false_idle() {
        let mut page = network_idle_test_page();
        page.set_navigation_timeout(std::time::Duration::from_millis(80));
        let (release, fetch) = network_idle_held_request(page.http_client.clone()).await;
        let result = tokio::time::timeout(std::time::Duration::from_secs(1), page.wait_for_network_idle(0))
            .await.expect("configured deadline must finish");
        assert!(result.unwrap_err().to_string().contains("deadline"));
        assert_eq!(page.lifecycle, crate::lifecycle::LifecycleState::Failed);
        assert_eq!(page.http_client.active_requests(), 1);
        release.send(()).unwrap();fetch.await.unwrap();
        assert_eq!(page.js.as_mut().unwrap().evaluate("1 + 1").unwrap(), serde_json::json!(2.0));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn network_idle_does_not_stop_at_five_seconds_when_budget_remains() {
        use std::future::Future;
        let mut page = network_idle_test_page();
        page.set_navigation_timeout(std::time::Duration::from_secs(8));
        let (release, fetch) = network_idle_held_request(page.http_client.clone()).await;
        tokio::time::pause();
        let mut wait = Box::pin(page.wait_for_network_idle(0));
        let waker = futures::task::noop_waker();
        let mut context = std::task::Context::from_waker(&waker);
        assert!(wait.as_mut().poll(&mut context).is_pending());
        tokio::time::advance(std::time::Duration::from_secs(6)).await;
        assert!(wait.as_mut().poll(&mut context).is_pending(), "five seconds is not a successful idle result");
        tokio::time::resume();release.send(()).unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(2), wait).await.unwrap().unwrap();
        fetch.await.unwrap();
        assert_eq!(page.lifecycle, crate::lifecycle::LifecycleState::NetworkIdle);
    }

    fn install_linked_stylesheet(
        runtime: &mut obscura_js::runtime::ObscuraJsRuntime,
        index: usize,
        css: &str,
        origin_clean: bool,
        response_url: &str,
    ) {
        let link_nid = runtime
            .with_dom(|dom| {
                let links = dom
                    .query_selector_all(r#"link[rel~="stylesheet"]"#)
                    .expect("valid selector");
                let lid = links[index];
                let _ = dom.replace_external_stylesheet(lid, css.to_string(), origin_clean);
                lid.index() as usize
            })
            .expect("live DOM");
        runtime
            .execute_script(
                "<linked-sheet>",
                &register_linked_stylesheet_script(link_nid, response_url),
            )
            .expect("register linked sheet");
    }

    // #1044: registration must address the <link> by its node id, not a
    // query-order index that a load handler can shift.
    #[test]
    fn register_linked_stylesheet_addresses_the_node_by_nid() {
        let mut rt = obscura_js::runtime::ObscuraJsRuntime::new();
        rt.set_dom(parse_html(
            r#"<html><body><link id="a" rel="stylesheet" href="/a.css"><link id="b" rel="stylesheet" href="/b.css"></body></html>"#,
        ));
        rt.set_url("http://example.com/");
        rt.run_page_init();

        // Attach load handlers to both links, then register against b's node
        // id. The node id is not the query-order index (it counts every node
        // before the link), so an index-based lookup (`links[b_nid]`) would
        // miss the element entirely and fire nothing.
        let b_nid = rt
            .evaluate(
                r#"(() => {
            const a = document.getElementById('a');
            const b = document.getElementById('b');
            a.addEventListener('load', () => a.setAttribute('data-loaded', 'yes'));
            b.addEventListener('load', () => b.setAttribute('data-loaded', 'yes'));
            return b._nid;
        })()"#,
            )
            .unwrap()
            .as_f64()
            .expect("b nid is a number") as usize;
        assert!(
            b_nid >= 2,
            "node id must exceed the two-element query index for this test to be meaningful",
        );

        rt.execute_script(
            "<linked-sheet>",
            &register_linked_stylesheet_script(b_nid, "http://example.com/b.css"),
        )
        .expect("register linked sheet");

        let b_loaded = rt
            .evaluate(r#"document.getElementById('b').getAttribute('data-loaded')"#)
            .unwrap();
        let a_loaded = rt
            .evaluate(r#"document.getElementById('a').getAttribute('data-loaded')"#)
            .unwrap();
        assert_eq!(b_loaded.as_str(), Some("yes"), "load fired on the target link");
        assert_eq!(a_loaded.as_str(), None, "load did not fire on the other link");
    }

    fn local_html_fixture(tag: &str) -> (std::path::PathBuf, String) {
        let path = std::env::temp_dir().join(format!(
            "obscura-file-gate-{tag}-{}.html",
            std::process::id()
        ));
        std::fs::write(&path, "<p id=secret>local-secret</p>").expect("write fixture");
        let file_url = url::Url::from_file_path(&path).expect("file url").to_string();
        (path, file_url)
    }

    fn file_gate_context(name: &str, allow_file_access: bool) -> std::sync::Arc<crate::BrowserContext> {
        let mut context = crate::BrowserContext::with_storage_and_network(
            name.to_string(),
            None,
            false,
            None,
            None,
            true,
        );
        context.set_allow_file_access(allow_file_access);
        std::sync::Arc::new(context)
    }

    // file:// is a local file read, so a browser context must opt in before any
    // client-driven navigation reaches it. Every CLI, CDP and MCP route funnels
    // through the one navigation entry point, so the opt-in is enforced there
    // rather than copied into each handler.
    #[tokio::test(flavor = "current_thread")]
    async fn file_navigation_requires_the_context_to_allow_file_access() {
        let (path, file_url) = local_html_fixture("client");

        let mut locked = super::Page::new("file-gate".to_string(), file_gate_context("file-gate", false));
        let error = locked
            .navigate(&file_url)
            .await
            .expect_err("file:// must be refused unless the context allows it")
            .to_string();
        assert!(error.contains("file://"), "{error}");
        assert_ne!(locked.url_string(), file_url);

        let mut open = super::Page::new("file-gate-open".to_string(), file_gate_context("file-gate-open", true));
        open.navigate(&file_url).await.expect("an opted-in context reads local files");
        assert_eq!(open.url_string(), file_url);

        let _ = std::fs::remove_file(&path);
    }

    // Server connections navigate through an isolated copy of the startup
    // context, so the copy's own http client must carry the opt-in too.
    #[tokio::test(flavor = "current_thread")]
    async fn isolated_context_copy_keeps_the_file_access_setting() {
        let (path, file_url) = local_html_fixture("copy");

        let open_copy = std::sync::Arc::new(
            file_gate_context("file-gate-copy", true).isolated_copy("copy-open".to_string(), false),
        );
        let mut open = super::Page::new("file-gate-copy-open".to_string(), open_copy);
        open.navigate(&file_url).await.expect("the copy keeps the opt-in");

        let locked_copy = std::sync::Arc::new(
            file_gate_context("file-gate-copy-locked", false)
                .isolated_copy("copy-locked".to_string(), false),
        );
        assert!(locked_copy.http_client.fetch(&url::Url::parse(&file_url).unwrap()).await.is_err());

        let _ = std::fs::remove_file(&path);
    }

    // A page must never drive itself from a web origin into file://, even in a
    // context that lets clients open local files. Timers, link clicks and form
    // submits are consumed by process_pending_navigation as a fresh first URL,
    // so the in-navigation chain's cross-scheme gate never sees them.
    #[tokio::test(flavor = "current_thread")]
    async fn page_driven_navigation_cannot_cross_into_file_scheme() {
        let (path, file_url) = local_html_fixture("page");
        let mut page = super::Page::new("file-gate-page".to_string(), file_gate_context("file-gate-page", true));
        page.navigate("data:text/html,<p id=web>web</p>")
            .await
            .expect("web page");
        let web_url = page.url_string();

        page.evaluate(&format!(
            "location.href = {}",
            serde_json::to_string(&file_url).expect("json string")
        ));
        assert!(page.has_pending_navigation(), "the page queued a navigation");

        let navigated = page
            .process_pending_navigation()
            .await
            .expect("a blocked page navigation is not an error");
        assert!(!navigated);
        assert_eq!(page.url_string(), web_url);
        assert!(!page.has_pending_navigation(), "the blocked navigation is dropped");
        // The location setter published the target before the block; the
        // page must not keep reporting (or later adopt) a document it never
        // loaded.
        assert_eq!(page.evaluate("location.href"), serde_json::json!(web_url));
        assert!(!page.sync_virtual_url());
        assert_eq!(page.url_string(), web_url);

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn navigation_timeout_environment_default_remains_thirty_seconds() {
        assert_eq!(
            navigation_timeout_from_env_value(None),
            std::time::Duration::from_secs(30)
        );
        assert_eq!(
            navigation_timeout_from_env_value(Some("not-a-timeout")),
            std::time::Duration::from_secs(30)
        );
    }

    #[test]
    fn navigation_timeout_environment_override_remains_available() {
        assert_eq!(
            navigation_timeout_from_env_value(Some("42000")),
            std::time::Duration::from_secs(42)
        );
    }

    #[test]
    fn navigation_chain_limit_environment_default_remains_ten() {
        assert_eq!(navigation_chain_limit_from_env_value(None), 10);
        assert_eq!(
            navigation_chain_limit_from_env_value(Some("not-a-limit")),
            10
        );
    }

    #[test]
    fn navigation_chain_limit_environment_override_remains_available() {
        assert_eq!(navigation_chain_limit_from_env_value(Some("25")), 25);
    }

    #[test]
    fn navigation_chain_limit_raises_a_zero_that_would_load_nothing() {
        assert_eq!(navigation_chain_limit_from_env_value(Some("0")), 1);
    }

    #[test]
    fn css_resource_discovery_ignores_strings_comments_data_and_fragments() {
        let base = url::Url::parse("https://example.test/css/app/main.css").unwrap();
        let css = r#"
            /* url(ignored.png) */
            .copy::before { content: "url(also-ignored.png)"; }
            @import URL("theme.css") print;
            @import url("semi;colon.css") screen;
            .hero { background: url('../img/hero.png'); }
            .icon { mask: URL("https://cdn.test/icon.svg#shape"); }
            .inline { background: url(data:image/svg+xml,<svg/>); }
            .local { mask: url(#local); }
        "#;
        assert_eq!(
            css_resource_urls(css, &base),
            vec![
                "https://example.test/css/img/hero.png".to_string(),
                "https://cdn.test/icon.svg".to_string(),
            ]
        );
    }

    #[test]
    fn font_face_warmup_takes_the_last_src_descriptor_and_skips_undecodable_sources() {
        // The IE8 idiom: a bare `.eot` in its own descriptor, then the real
        // list. The renderer resolves the cascade to the second descriptor and
        // then drops `.eot` and `.svg`, so three of the six are all it will
        // ever consider. The warmup used to fetch all six.
        let base = url::Url::parse("https://example.test/css/app.css").unwrap();
        let css = r#"
            @font-face {
              font-family: 'Probe';
              src: url('/font/probe.eot');
              src: url('/font/probe.eot?#iefix') format('embedded-opentype'),
                   url('/font/probe.woff2') format('woff2'),
                   url('/font/probe.woff') format('woff'),
                   url('/font/probe.ttf') format('truetype'),
                   url('/font/probe.svg#probe') format('svg');
            }
        "#;
        assert_eq!(
            css_resource_urls(css, &base),
            vec![
                "https://example.test/font/probe.woff2".to_string(),
                "https://example.test/font/probe.woff".to_string(),
                "https://example.test/font/probe.ttf".to_string(),
            ]
        );
    }

    #[test]
    fn font_face_warmup_ignores_local_sources_and_keeps_scanning_after_the_block() {
        // `local()` names an installed face and is not a fetch, and the block
        // has to be reported as consumed at exactly its closing brace, or the
        // rule after it would be skipped with it.
        let base = url::Url::parse("https://example.test/css/app.css").unwrap();
        let css = r#"
            @font-face {
              font-family: 'Probe';
              src: local('Probe'), url('probe.woff2') format('woff2');
            }
            .hero { background: url('../img/hero.png'); }
        "#;
        assert_eq!(
            css_resource_urls(css, &base),
            vec![
                "https://example.test/css/probe.woff2".to_string(),
                "https://example.test/img/hero.png".to_string(),
            ]
        );
    }

    #[test]
    fn font_face_warmup_skips_data_sources_and_survives_a_brace_in_a_string() {
        let base = url::Url::parse("https://example.test/css/app.css").unwrap();
        let css = r#"
            @font-face {
              font-family: 'A }';
              src: url(data:font/woff2;base64,d09GMg==) format('woff2'),
                   url('fallback.woff') format('woff');
            }
            .after { background: url('after.png'); }
        "#;
        assert_eq!(
            css_resource_urls(css, &base),
            vec![
                "https://example.test/css/fallback.woff".to_string(),
                "https://example.test/css/after.png".to_string(),
            ]
        );
    }

    #[test]
    fn an_unterminated_font_face_block_falls_back_to_the_generic_scan() {
        // Better to warm too much than to drop the rest of the stylesheet on
        // the floor, which is the same policy `css_import_rule_len` follows.
        let base = url::Url::parse("https://example.test/css/app.css").unwrap();
        let css = "@font-face { src: url('probe.woff2') format('woff2');";
        assert_eq!(
            css_resource_urls(css, &base),
            vec!["https://example.test/css/probe.woff2".to_string()]
        );
    }

    fn spawn_stylesheet_graph_server(
        expected_requests: usize,
    ) -> (String, std::sync::mpsc::Receiver<String>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let origin = format!("http://{address}");
        let response_origin = origin.clone();
        let (request_tx, request_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};

            for _ in 0..expected_requests {
                let (mut stream, _) = listener.accept().unwrap();
                let mut request = [0u8; 4096];
                let length = stream.read(&mut request).unwrap();
                let request = String::from_utf8_lossy(&request[..length]);
                let path = request
                    .lines()
                    .next()
                    .and_then(|line| line.split_ascii_whitespace().nth(1))
                    .unwrap_or("/")
                    .to_string();
                request_tx.send(path.clone()).unwrap();
                let (content_type, body) = match path.as_str() {
                    "/" => (
                        "text/html",
                        r#"<!doctype html><html><head>
                            <link rel="stylesheet" href="/css/root.css#first">
                            <link rel="stylesheet" href="/css/root.css#second">
                            <link rel="preload stylesheet" href="/theme/second.css">
                        </head><body></body></html>"#
                            .to_string(),
                    ),
                    "/css/root.css" => (
                        "text/css",
                        "@import '/css/nested/shared.css';@import '/blocked.css';@import '/intercepted.css';.root{background:url('img/root.png')}".to_string(),
                    ),
                    "/theme/second.css" => (
                        "text/css",
                        "@import '../css/nested/shared.css';.second{background:url('img/second.png')}".to_string(),
                    ),
                    "/css/nested/shared.css" => (
                        "text/css",
                        "@import '../root.css';.shared{background:url('../img/shared.png')}".to_string(),
                    ),
                    _ => ("text/plain", "unexpected".to_string()),
                };
                let status = if path == "/blocked.css" || path == "/intercepted.css" {
                    "500 Unexpected Request"
                } else {
                    "200 OK"
                };
                let response = format!(
                    "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nX-Origin: {response_origin}\r\n\r\n{body}",
                    body.len(),
                );
                stream.write_all(response.as_bytes()).unwrap();
            }
        });
        (origin, request_rx)
    }

    fn spawn_inline_import_server() -> (String, std::sync::mpsc::Receiver<String>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let origin = format!("http://{address}");
        let (request_tx, request_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};

            // Five requests are expected after import/image deduplication. Keep
            // two extra accepts alive so a regression's bogus CSS-as-image
            // warmup still reaches the request callback and server cleanly.
            for _ in 0..7 {
                let (mut stream, _) = listener.accept().unwrap();
                let mut request = [0u8; 4096];
                let length = stream.read(&mut request).unwrap();
                let request = String::from_utf8_lossy(&request[..length]);
                let path = request
                    .lines()
                    .next()
                    .and_then(|line| line.split_ascii_whitespace().nth(1))
                    .unwrap_or("/")
                    .to_string();
                request_tx.send(path.clone()).unwrap();
                let (content_type, body) = match path.as_str() {
                    "/" => (
                        "text/html",
                        r#"<!doctype html><style media="screen, print">
                            @import url('/a.css') print;
                            @import '/b.css' print;
                            .local { color: white; background-image: url('/local.svg') }
                        </style><div class="local imported-a imported-b">marker</div>"#,
                    ),
                    "/a.css" => (
                        "text/css",
                        ".imported-a{background:#9020d0 url('/imported.svg')}",
                    ),
                    "/b.css" => ("text/css", ".imported-b{border-color:#f0d020}"),
                    "/local.svg" | "/imported.svg" => (
                        "image/svg+xml",
                        r#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><rect width="1" height="1" fill="white"/></svg>"#,
                    ),
                    _ => ("text/plain", "unexpected"),
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len(),
                );
                stream.write_all(response.as_bytes()).unwrap();
            }
        });
        (origin, request_rx)
    }

    #[test]
    fn default_navigation_referrer_matches_strict_origin_when_cross_origin() {
        let source = url::Url::parse("https://user:[email protected]/path?q=1#fragment").unwrap();
        let same_origin = url::Url::parse("https://source.example/next").unwrap();
        let cross_origin = url::Url::parse("https://target.example/next").unwrap();
        let downgrade = url::Url::parse("http://source.example/next").unwrap();

        assert_eq!(
            navigation_referrer(&source, &same_origin),
            "https://source.example/path?q=1"
        );
        assert_eq!(
            navigation_referrer(&source, &cross_origin),
            "https://source.example/"
        );
        assert_eq!(navigation_referrer(&source, &downgrade), "");

        let data_source = url::Url::parse("data:text/html,source").unwrap();
        assert_eq!(navigation_referrer(&data_source, &cross_origin), "");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn form_navigation_preserves_owning_document_metadata() {
        assert_form_navigation_preserves_owning_document_metadata(false, false, false).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn form_navigation_interception_preserves_owning_document_metadata() {
        assert_form_navigation_preserves_owning_document_metadata(false, true, false).await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn form_navigation_interception_preserves_empty_post() {
        assert_form_navigation_preserves_owning_document_metadata(false, true, true).await;
    }

    #[cfg(feature = "stealth")]
    #[tokio::test(flavor = "current_thread")]
    async fn form_navigation_preserves_owning_document_metadata_in_stealth() {
        assert_form_navigation_preserves_owning_document_metadata(true, false, false).await;
    }

    #[cfg(feature = "stealth")]
    #[tokio::test(flavor = "current_thread")]
    async fn form_navigation_interception_preserves_owning_document_metadata_in_stealth() {
        assert_form_navigation_preserves_owning_document_metadata(true, true, false).await;
    }

    #[cfg(feature = "stealth")]
    #[tokio::test(flavor = "current_thread")]
    async fn form_navigation_interception_preserves_empty_post_in_stealth() {
        assert_form_navigation_preserves_owning_document_metadata(true, true, true).await;
    }

    async fn assert_form_navigation_preserves_owning_document_metadata(stealth: bool, intercepted: bool, empty: bool) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let origin = format!("http://{}", listener.local_addr().unwrap());
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let server = tokio::spawn(async move {
            for index in 0..4 {
                let (mut socket, _) = tokio::time::timeout(std::time::Duration::from_secs(5), listener.accept()).await.unwrap().unwrap();
                let mut request = Vec::new();
                let mut chunk = [0; 2048];
                loop {
                    let read = tokio::time::timeout(std::time::Duration::from_secs(5), socket.read(&mut chunk)).await.unwrap().unwrap();
                    assert!(read > 0);
                    request.extend_from_slice(&chunk[..read]);
                    if let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") {
                        let head = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
                        let length = head.lines().find_map(|line| line.strip_prefix("content-length:")
                            .map(|value| value.trim().parse::<usize>().unwrap())).unwrap_or(0);
                        if request.len() >= end + 4 + length { break; }
                    }
                }
                tx.send(String::from_utf8(request).unwrap()).unwrap();
                let response = if index == 0 {
                    let fields = if empty { "" } else { "<input name=confirm value='token+value'><input name=same value=first><input name=same value=second>" };
                    let body = format!("<form id=f method=post action=/submit>{fields}</form><script>document.getElementById('f').submit()</script>");
                    format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nSet-Cookie: confirm=fixture; Path=/; SameSite=Strict\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len())
                } else if index == 1 {
                    "HTTP/1.1 307 Temporary Redirect\r\nLocation: /final\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
                } else {
                    "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
                };
                socket.write_all(response.as_bytes()).await.unwrap();
                socket.shutdown().await.unwrap();
            }
        });
        let context = Arc::new(BrowserContext::with_storage_and_network("form-origin".into(), None, stealth, None, None, true));
        let mut page = Page::new("form-origin".into(), context);
        page.http_client.extra_headers.write().await.extend([
            ("Origin".into(), "http://forged.example".into()), ("x-native-client".into(), "ordinary".into()),
        ]);
        #[cfg(feature = "stealth")]
        if stealth {
            page.stealth_client.as_ref().unwrap().extra_headers.write().await.extend([
                ("Origin".into(), "http://forged.example".into()), ("x-native-client".into(), "stealth".into()),
            ]);
        }
        let resolver = if intercepted {
            let mut requests = page.enable_interception();
            Some(tokio::spawn(async move {
                for _ in 0..3 {
                    let request = tokio::time::timeout(std::time::Duration::from_secs(5), requests.recv()).await.unwrap().unwrap();
                    let rewrite = (request.method == "POST").then(|| request.url.replace("/submit", "/continued"));
                    request.resolver.send(obscura_js::ops::InterceptResolution::Continue {
                        url: rewrite, method: None, headers: None, body: None,
                    }).ok().unwrap();
                }
            }))
        } else { None };
        page.navigate(&format!("{origin}/source?keep=1")).await.unwrap();
        assert_eq!(page.url_string(), format!("{origin}/final"));
        page.navigate(&format!("{origin}/direct")).await.unwrap();
        server.await.unwrap();
        if let Some(resolver) = resolver { resolver.await.unwrap(); }
        let mut requests = Vec::new();
        while let Ok(request) = rx.try_recv() { requests.push(request); }
        assert_eq!(requests.len(), 4);
        for request in &requests[1..3] {
            let (headers, body) = request.split_once("\r\n\r\n").unwrap();
            let headers = headers.to_ascii_lowercase();
            assert!(headers.starts_with("post "));
            assert!(headers.contains("sec-fetch-site: same-origin\r\n"));
            assert!(headers.contains(&format!("origin: {origin}\r\n")));
            assert!(headers.contains(&format!("referer: {origin}/source?keep=1\r\n")));
            assert!(headers.contains("cookie: confirm=fixture\r\n"));
            assert!(headers.contains("content-type: application/x-www-form-urlencoded\r\n"));
            assert!(headers.contains(if stealth { "x-native-client: stealth\r\n" } else { "x-native-client: ordinary\r\n" }));
            assert_eq!(body, if empty { "" } else { "confirm=token%2Bvalue&same=first&same=second" });
        }
        if intercepted { assert!(requests[1].starts_with("POST /continued ")); }
        let direct = requests[3].to_ascii_lowercase();
        assert!(direct.starts_with("get /direct "));
        assert!(direct.contains("sec-fetch-site: none\r\n"));
        assert!(!direct.contains("\r\norigin:"));
        assert!(!direct.contains("\r\nreferer:"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn document_navigation_referrer_survives_http_redirects() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let server = std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};

            let mut requests = Vec::new();
            for _ in 0..3 {
                let (mut stream, _) = listener.accept().unwrap();
                stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
                stream.set_write_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
                let mut request = Vec::new();
                loop {
                    let mut chunk = [0; 2048];
                    let read = stream.read(&mut chunk).unwrap();
                    assert!(read > 0);
                    request.extend_from_slice(&chunk[..read]);
                    assert!(request.len() < 1024 * 1024);
                    if request.windows(4).any(|part| part == b"\r\n\r\n") { break; }
                }
                let request_text = String::from_utf8(request).unwrap();
                let path = request_text
                    .lines()
                    .next()
                    .and_then(|line| line.split_ascii_whitespace().nth(1))
                    .unwrap_or("/");
                let response = match path {
                    "/source" => {
                        let body = "<script>location.href='/redirect'</script>";
                        format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                            body.len(),
                        )
                    }
                    "/redirect" => "HTTP/1.1 302 Found\r\nLocation: /final\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_string(),
                    "/final" => {
                        let body = "<!doctype html><title>final</title>";
                        format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                            body.len(),
                        )
                    }
                    _ => "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_string(),
                };
                stream.write_all(response.as_bytes()).unwrap();
                requests.push(request_text);
            }
            requests
        });

        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "referrer-redirect".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("referrer-redirect".to_string(), context);
        let source = format!("http://{address}/source");
        page.navigate(&source).await.unwrap();

        let observed = page
            .js
            .as_mut()
            .unwrap()
            .evaluate("[document.URL, document.referrer]")
            .unwrap();
        assert_eq!(
            observed,
            serde_json::json!([format!("http://{address}/final"), source])
        );
        for request in server.join().unwrap().iter().skip(1) {
            let request = request.to_ascii_lowercase();
            assert!(request.starts_with("get "));
            assert!(request.contains("sec-fetch-site: same-origin\r\n"));
            assert!(request.contains(&format!("referer: {source}\r\n")));
            assert!(!request.contains("\r\norigin:"));
        }
    }

    // A bare HTTP error (rate limiter, WAF) with no body must fail the
    // navigation like Chrome's net::ERR_HTTP_RESPONSE_CODE_FAILURE instead of
    // committing an empty document; an error status with a body still renders.
    #[tokio::test(flavor = "current_thread")]
    async fn empty_body_http_error_fails_navigation_but_error_page_renders() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};
            for _ in 0..2 {
                let (mut stream, _) = listener.accept().unwrap();
                let mut request = [0u8; 2048];
                let length = stream.read(&mut request).unwrap();
                let request = String::from_utf8_lossy(&request[..length]);
                let response = if request.starts_with("GET /blocked ") {
                    "HTTP/1.1 429 Too Many Requests\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_string()
                } else {
                    let body = "<html><body><h1>Not here</h1></body></html>";
                    format!(
                        "HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len()
                    )
                };
                stream.write_all(response.as_bytes()).unwrap();
            }
        });

        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "empty-http-error".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("empty-http-error".to_string(), context);
        let error = page
            .navigate(&format!("http://{address}/blocked"))
            .await
            .expect_err("an empty 429 must not become an empty document");
        assert!(error.to_string().contains("ERR_HTTP_RESPONSE_CODE_FAILURE"), "{error}");
        assert!(error.to_string().contains("429"), "{error}");
        assert_eq!(page.lifecycle, crate::LifecycleState::Failed);

        page.navigate(&format!("http://{address}/missing")).await.unwrap();
        let heading = page.evaluate("document.querySelector('h1').textContent");
        assert_eq!(heading.as_str(), Some("Not here"));
    }

    // #1231: a text/plain or text/markdown response is a plain-text document.
    // Parsing it as HTML turned every <word> in the body into an element and
    // dropped its text, and document.contentType reported text/html.
    #[tokio::test(flavor = "current_thread")]
    async fn plain_text_response_builds_a_pre_document() {
        let body = "RFC 9110 <URI-reference>: see <https://example.com/>\n2nd line";
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};
            let (mut stream, _) = listener.accept().unwrap();
            let mut request = [0u8; 2048];
            let _ = stream.read(&mut request).unwrap();
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len(),
            );
            stream.write_all(response.as_bytes()).unwrap();
        });

        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "plain-text".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("plain-text".to_string(), context);
        page.navigate(&format!("http://{address}/rfc9110.txt")).await.unwrap();

        let observed = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(
                "(function(){return [document.contentType, \
                 document.body.firstElementChild.tagName, \
                 document.body.childNodes.length, \
                 document.body.textContent];})()",
            )
            .unwrap();
        assert_eq!(
            observed,
            serde_json::json!(["text/plain", "PRE", 1, body])
        );
    }

    #[test]
    fn plain_text_document_preserves_leading_newlines_and_literal_markup() {
        for (text, expected) in [
            ("\nfirst\nlast", "\nfirst\nlast"),
            ("\r\nfirst\rsecond", "\nfirst\nsecond"),
            ("\n\n", "\n\n"),
            ("<&amp;> </pre><script>bad()</script>", "<&amp;> </pre><script>bad()</script>"),
        ] {
            let dom = super::parse_plain_text_document(text);
            let pre = dom.query_selector("pre").unwrap().unwrap();
            assert_eq!(dom.text_content(pre), expected, "input {text:?}");
            assert!(dom.query_selector("script").unwrap().is_none());
        }
        let empty = super::parse_plain_text_document("");
        assert_eq!(empty.text_content(empty.document()), "");
        assert!(empty.query_selector("pre").unwrap().is_none());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn plain_text_navigation_resets_content_type_on_about_blank() {
        let mut page = super::Page::new(
            "plain-text-blank".to_string(),
            std::sync::Arc::new(crate::BrowserContext::new("plain-text-blank".to_string())),
        );
        page.navigate("data:text/plain,first%0Alast").await.unwrap();
        assert_eq!(page.js.as_mut().unwrap().evaluate(
            "[document.contentType, document.body.textContent]"
        ).unwrap(), serde_json::json!(["text/plain", "first\nlast"]));
        page.navigate("about:blank").await.unwrap();
        assert_eq!(page.js.as_mut().unwrap().evaluate(
            "[document.contentType, document.body.textContent]"
        ).unwrap(), serde_json::json!(["text/html", ""]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn text_markdown_response_keeps_markup_as_text() {
        let body = "# Title\n\nSee <Component prop={1} /> and 3 < 4.";
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};
            let (mut stream, _) = listener.accept().unwrap();
            let mut request = [0u8; 2048];
            let _ = stream.read(&mut request).unwrap();
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: text/markdown\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len(),
            );
            stream.write_all(response.as_bytes()).unwrap();
        });

        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "markdown-text".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("markdown-text".to_string(), context);
        page.navigate(&format!("http://{address}/settings-reference")).await.unwrap();

        let observed = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(
                "(function(){return [document.contentType, \
                 document.body.textContent, \
                 document.body.querySelectorAll('component').length];})()",
            )
            .unwrap();
        assert_eq!(
            observed,
            serde_json::json!(["text/markdown", body, 0])
        );
    }

    // The HTML parse path is unchanged, including the URL-derived contentType
    // sniffing for documents served without a usable Content-Type.
    #[tokio::test(flavor = "current_thread")]
    async fn html_response_still_builds_an_html_document() {
        let body = "<!doctype html><title>page</title><p>hello <b>world</b></p>";
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};
            let (mut stream, _) = listener.accept().unwrap();
            let mut request = [0u8; 2048];
            let _ = stream.read(&mut request).unwrap();
            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()).unwrap();
        });

        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "html-doc".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("html-doc".to_string(), context);
        page.navigate(&format!("http://{address}/index")).await.unwrap();

        let observed = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(
                "(function(){return [document.contentType, \
                 document.body.firstElementChild.tagName, \
                 document.body.querySelectorAll('b').length, \
                 document.body.textContent];})()",
            )
            .unwrap();
        assert_eq!(
            observed,
            serde_json::json!(["text/html", "P", 1, "hello world"])
        );
    }

    // #971: a tab switch suspends other tabs (drops their runtime). Console
    // messages logged before suspension must be preserved, not lost.
    #[tokio::test(flavor = "current_thread")]
    async fn suspend_js_preserves_pending_console_messages() {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "console-suspend".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("console-suspend".to_string(), context);
        page.navigate("data:text/html,<html><body></body></html>")
            .await
            .unwrap();

        page.set_console_messages_enabled(true);
        page.js
            .as_mut()
            .unwrap()
            .evaluate("console.log('important-message')")
            .unwrap();

        // Switching away suspends this tab and drops its runtime.
        page.suspend_js();

        let messages = page.take_pending_console_messages();
        assert!(
            messages.iter().any(|m| m.contains("important-message")),
            "console messages logged before suspend_js must survive it, got: {messages:?}"
        );
    }

    /// `/hop/N` sets `location.href = "/hop/N-1"`, `/hop/0` is the target.
    /// An unreadable path gets a 404, so a broken fixture fails the test.
    fn client_navigation_chain_address(name: &str, connections: usize) -> std::net::SocketAddr {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let name = name.to_string();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};

            for _ in 0..connections {
                let Ok((mut stream, _)) = listener.accept() else {
                    return;
                };
                let mut buffer = [0u8; 2048];
                let length = stream.read(&mut buffer).unwrap_or(0);
                let hop = String::from_utf8_lossy(&buffer[..length])
                    .lines()
                    .next()
                    .and_then(|line| line.split_ascii_whitespace().nth(1))
                    .and_then(|path| path.strip_prefix("/hop/"))
                    .and_then(|hop| hop.parse::<usize>().ok());
                let response = match hop {
                    Some(0) => {
                        let body = format!("<!doctype html><title>{name}</title>");
                        format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                            body.len(),
                        )
                    }
                    Some(hop) => {
                        let body = format!("<script>location.href='/hop/{}'</script>", hop - 1);
                        format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                            body.len(),
                        )
                    }
                    None => {
                        "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                            .to_string()
                    }
                };
                let _ = stream.write_all(response.as_bytes());
            }
        });
        address
    }

    /// Without a limit set the getter reaches its fallback to the environment.
    fn page_without_chain_limit(name: &str) -> super::Page {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            name.to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        super::Page::new(name.to_string(), context)
    }

    /// The only place where the name of the environment variable is checked
    /// as a string, and the variable is the only way to raise the limit at
    /// runtime. Without this test a typo in the name would stay green.
    #[test]
    fn navigation_chain_limit_reads_the_environment_variable_by_name() {
        std::env::set_var("OBSCURA_NAV_CHAIN_LIMIT", "17");

        let page = page_without_chain_limit("chain-from-environment");

        assert_eq!(page.navigation_chain_limit(), 17);
    }

    /// Issue #1068: page script sees the tab's session history. history.length
    /// counts earlier documents, and history.back()/forward() load them while
    /// moving the history cursor instead of appending entries.
    #[tokio::test(flavor = "current_thread")]
    async fn page_history_traverses_across_documents() {
        let one = "data:text/html,<title>one</title>";
        let two = "data:text/html,<title>two</title>";
        let mut page = page_without_chain_limit("history-across-documents");
        page.navigate(one).await.unwrap();
        page.navigate(two).await.unwrap();
        assert_eq!(page.evaluate("history.length"), serde_json::json!(2.0));

        page.evaluate("history.back()");
        assert!(page.process_pending_navigation().await.unwrap());
        assert_eq!(page.url_string(), one);
        assert_eq!((page.history.len(), page.history_index), (2, 0));
        assert_eq!(page.evaluate("history.length"), serde_json::json!(2.0));

        page.evaluate("history.go(1)");
        assert!(page.process_pending_navigation().await.unwrap());
        assert_eq!(page.url_string(), two);
        assert_eq!((page.history.len(), page.history_index), (2, 1));

        // Out-of-range traversal stays put.
        page.evaluate("history.go(5)");
        assert!(!page.process_pending_navigation().await.unwrap());
        assert_eq!(page.url_string(), two);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn same_document_history_keeps_entries_when_the_cursor_moves() {
        let url = "data:text/html,<title>history</title>";
        let mut page = page_without_chain_limit("history-cursor");
        page.navigate(url).await.unwrap();
        page.evaluate("(() => { globalThis.marker=42; history.pushState({n:1}, '', '#one'); history.pushState({n:2}, '', '#two'); })()");
        page.sync_virtual_url();
        let entries = vec![url.to_string(), format!("{url}#one"), format!("{url}#two")];
        assert_eq!(page.history, entries);
        assert_eq!(page.history_index, 2);
        page.evaluate("history.back()");
        page.sync_virtual_url();
        assert_eq!(page.history, entries);
        assert_eq!(page.history_index, 1);
        assert_eq!(page.evaluate("[marker, history.state.n, history.length]"), serde_json::json!([42, 1, 3]));
        page.evaluate("history.replaceState({n:3}, '', '#replaced')");
        page.sync_virtual_url();
        assert_eq!(page.history.len(), 3);
        assert_eq!(page.history[1], format!("{url}#replaced"));
        page.evaluate("history.forward()");
        page.sync_virtual_url();
        assert_eq!(page.history_index, 2);
        assert_eq!(page.evaluate("history.state.n"), serde_json::json!(2.0));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn same_document_history_keeps_distinct_entries_with_the_same_url() {
        let url = "data:text/html,<title>history</title>";
        let mut page = page_without_chain_limit("history-same-url");
        page.navigate(url).await.unwrap();
        page.evaluate("(() => { history.pushState({n:1}, ''); history.pushState({n:2}, ''); })()");
        page.sync_virtual_url();
        assert_eq!(page.history, vec![url.to_string(); 3]);
        assert_eq!(page.history_index, 2);
        page.evaluate("history.back()");
        page.sync_virtual_url();
        assert_eq!(page.history_index, 1);
        assert_eq!(page.evaluate("history.state.n"), serde_json::json!(1.0));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn same_document_history_sync_ignores_authored_json_serialization() {
        let url = "data:text/html,<title>history</title>";
        let mut page = page_without_chain_limit("history-json-override");
        page.navigate(url).await.unwrap();
        page.evaluate("(() => { history.pushState({n:1}, '', '#one'); JSON.stringify=()=> '\"forged\"'; Array.prototype.toJSON=()=> 'forged'; })()");
        page.sync_virtual_url();
        assert_eq!(page.history, vec![url.to_string(), format!("{url}#one")]);
        assert_eq!(page.history_index, 1);
        assert_eq!(page.url_string(), format!("{url}#one"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn history_sync_keeps_native_document_position_when_authors_patch_array_map() {
        let one = "data:text/html,<title>one</title>";
        let two = "data:text/html,<title>two</title>";
        let mut page = page_without_chain_limit("history-native-position");
        page.navigate(one).await.unwrap();
        page.navigate(two).await.unwrap();
        page.evaluate("(() => { const map=Array.prototype.map; Array.prototype.map=function(...args){if(this.length===3 && this.every(v=>typeof v==='string' && /^\\d+$/.test(v)))throw new Error('authored map');return Reflect.apply(map,this,args);}; history.pushState(1,'','#one'); })()");
        page.sync_virtual_url();
        assert_eq!(page.history, vec![one.to_string(), two.to_string(), format!("{two}#one")]);
        assert_eq!(page.history_index, 2);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn history_sync_metadata_is_bounded_by_entries() {
        let url = "data:text/html,<title>history</title>";
        let mut page = page_without_chain_limit("history-metadata");
        page.navigate(url).await.unwrap();
        page.evaluate("(() => { for(let i=0;i<10000;i++) history.replaceState(i, '', '#'+i); })()");
        let update = page.js.as_mut().unwrap().take_history_update().unwrap();
        assert!(matches!(update, HistoryUpdate::Entries { urls, .. }
            if urls.len() == 1 && urls[0].len() < 512), "one entry must not retain a mutation log");
        page.evaluate("history.replaceState(null, '', '#last')");
        page.sync_virtual_url();
        assert_eq!(page.history, vec![format!("{url}#last")]);
        assert_eq!(page.history_index, 0);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn history_sync_does_not_transfer_unchanged_entries() {
        let url = "data:text/html,<title>history</title>";
        let mut page = page_without_chain_limit("history-incremental-sync");
        page.navigate(url).await.unwrap();
        for index in 0..1000 {
            page.evaluate(&format!("history.pushState({index}, '', '#{index}')"));
            page.sync_virtual_url();
        }
        page.evaluate("history.replaceState(null, '', '#last')");
        let update = page.js.as_mut().unwrap().take_history_update().unwrap();
        assert!(matches!(update, HistoryUpdate::Entries { urls, .. }
            if urls.len() == 1 && urls[0].len() < 512), "one changed entry must not transfer the unchanged history");
        page.evaluate("history.replaceState(null, '', '#verified')");
        page.sync_virtual_url();
        assert_eq!(page.history.len(), 1001);
        assert_eq!(page.history[0], url);
        assert_eq!(page.history[1000], format!("{url}#verified"));
        page.evaluate("history.go(-500)");
        page.sync_virtual_url();
        assert_eq!(page.history_index, 500);
        assert_eq!(page.url_string(), format!("{url}#499"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn history_sync_keeps_only_surviving_batched_changes() {
        let url = "data:text/html,<title>history</title>";
        let mut page = page_without_chain_limit("history-batched-changes");
        page.navigate(url).await.unwrap();
        page.evaluate("(() => { history.pushState(1, '', '#one'); history.pushState(2, '', '#two'); history.pushState(3, '', '#three'); })()");
        page.sync_virtual_url();
        page.evaluate("(() => { history.replaceState(4, '', '#discarded'); history.go(-2); history.pushState(5, '', '#last'); })()");
        page.sync_virtual_url();
        assert_eq!(page.history, vec![url.to_string(), format!("{url}#one"), format!("{url}#last")]);
        assert_eq!(page.history_index, 2);
        page.evaluate("(() => { history.back(); history.replaceState(6, '', '#changed'); history.forward(); })()");
        page.sync_virtual_url();
        assert_eq!(page.history, vec![url.to_string(), format!("{url}#changed"), format!("{url}#last")]);
        assert_eq!(page.history_index, 2);
        assert_eq!(page.url_string(), format!("{url}#last"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn history_sync_does_not_commit_a_pending_location_navigation() {
        let url = "data:text/html,<title>history</title>";
        let mut page = page_without_chain_limit("history-location-preview");
        page.navigate(url).await.unwrap();
        page.evaluate("(() => { history.pushState(1, '', '#one'); location.href='https://example.org/next'; })()");
        page.sync_history_updates();
        assert_eq!(page.url_string(), format!("{url}#one"));
        assert_eq!(page.history, vec![url.to_string(), format!("{url}#one")]);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn history_urls_keep_the_committed_origin_during_pending_navigation() {
        let mut page = import_map_test_page("history-committed-origin", "http://example.com/current", "<title>history</title>");
        let result = page.evaluate("(() => { location.href='https://other.example/next'; let error=null; try { history.pushState({}, '', 'https://other.example/spoof'); } catch(e) { error=e.name; } history.pushState({n:1}, '', '/kept'); location.href='https://other.example/again'; history.replaceState({n:2}, ''); return {error,href:location.href,state:history.state}; })()");
        assert_eq!(result, serde_json::json!({"error":"SecurityError","href":"http://example.com/kept","state":{"n":2}}));
        page.sync_history_updates();
        assert_eq!(page.url_string(), "http://example.com/kept");
        assert!(page.history.iter().all(|url| url.starts_with("http://example.com/")));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn history_sync_rejects_non_url_page_values() {
        let mut page = page_without_chain_limit("history-url-type");
        page.navigate("data:text/html,<title>history</title>").await.unwrap();
        page.evaluate("globalThis.__virtualUrl = new Array(100000)");
        assert!(matches!(page.js.as_mut().unwrap().take_history_update().unwrap(),
            HistoryUpdate::Url(url) if url.is_empty()));
    }

    /// Same-document entries sit between the documents: a push drops the
    /// forward documents, and back() past the document's own entries loads
    /// the previous document.
    #[tokio::test(flavor = "current_thread")]
    async fn page_history_counts_same_document_entries_once() {
        let one = "data:text/html,<title>one</title>";
        let two = "data:text/html,<title>two</title>";
        let mut page = page_without_chain_limit("history-same-document");
        page.navigate(one).await.unwrap();
        page.navigate(two).await.unwrap();
        page.evaluate("history.back()");
        page.process_pending_navigation().await.unwrap();
        assert_eq!(page.url_string(), one);

        page.evaluate("history.pushState(null, '', '#a')");
        assert_eq!(page.evaluate("history.length"), serde_json::json!(2.0));
        // Recording the pushState URL on the page must not double count it.
        page.sync_virtual_url();
        assert_eq!(page.evaluate("history.length"), serde_json::json!(2.0));

        page.evaluate("history.go(-2)");
        assert!(!page.process_pending_navigation().await.unwrap());
        page.evaluate("history.back()");
        assert!(page.process_pending_navigation().await.unwrap());
        assert_eq!(page.url_string(), one);
        assert_eq!(page.evaluate("location.hash"), serde_json::json!(""));
    }

    #[test]
    fn a_per_page_navigation_chain_limit_wins_over_the_environment() {
        std::env::set_var("OBSCURA_NAV_CHAIN_LIMIT", "17");

        let mut page = page_without_chain_limit("chain-per-page-wins");
        page.set_navigation_chain_limit(4);

        assert_eq!(page.navigation_chain_limit(), 4);
    }

    /// The limit is always set explicitly, never inherited. Otherwise anyone
    /// running the suite with `OBSCURA_NAV_CHAIN_LIMIT` set would see these
    /// tests fail through no fault of the code.
    fn chain_page(name: &str, limit: usize) -> super::Page {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            name.to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new(name.to_string(), context);
        page.set_navigation_chain_limit(limit);
        page
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_chain_default_allows_nine_client_navigations() {
        let address = client_navigation_chain_address("arrived", 10);
        let mut page = chain_page("chain-within-default", DEFAULT_NAVIGATION_CHAIN_LIMIT);

        page.navigate(&format!("http://{address}/hop/9"))
            .await
            .unwrap();

        assert_eq!(page.url_string(), format!("http://{address}/hop/0"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_chain_beyond_the_default_reports_client_navigations() {
        let address = client_navigation_chain_address("arrived", 10);
        let mut page = chain_page("chain-beyond-default", DEFAULT_NAVIGATION_CHAIN_LIMIT);

        let error = page
            .navigate(&format!("http://{address}/hop/10"))
            .await
            .expect_err("a chain past the limit must not report success");

        assert!(
            matches!(error, super::PageError::TooManyClientNavigations(10)),
            "unexpected error: {error:?}"
        );
        assert_eq!(
            error.to_string(),
            "Too many client-initiated navigations, the chain reached its limit of 10 documents"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn raised_navigation_chain_limit_reaches_a_longer_chain() {
        let address = client_navigation_chain_address("arrived", 12);
        let mut page = chain_page("chain-raised", 12);

        page.navigate(&format!("http://{address}/hop/11"))
            .await
            .unwrap();

        assert_eq!(page.url_string(), format!("http://{address}/hop/0"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn a_zero_navigation_chain_limit_still_loads_the_initial_document() {
        let address = client_navigation_chain_address("arrived", 1);
        let mut page = chain_page("chain-zero", 0);

        page.navigate(&format!("http://{address}/hop/0"))
            .await
            .unwrap();

        assert_eq!(page.url_string(), format!("http://{address}/hop/0"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn linked_stylesheet_graph_fetches_once_and_preserves_order_and_bases() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let (origin, requests) = spawn_stylesheet_graph_server(4);
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "stylesheet-graph".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("stylesheet-graph".to_string(), context);
        page.set_blocked_urls(vec![
            "*blocked.css".to_string(),
            "*intercepted.css".to_string(),
        ]);

        let request_count = std::sync::Arc::new(AtomicUsize::new(0));
        let response_count = std::sync::Arc::new(AtomicUsize::new(0));
        let observed_requests = request_count.clone();
        page.on_request(std::sync::Arc::new(move |request| {
            if request.resource_type == obscura_net::ResourceType::Stylesheet {
                observed_requests.fetch_add(1, Ordering::SeqCst);
            }
        }));
        let observed_responses = response_count.clone();
        page.on_response(std::sync::Arc::new(move |request, _| {
            if request.resource_type == obscura_net::ResourceType::Stylesheet {
                observed_responses.fetch_add(1, Ordering::SeqCst);
            }
        }));

        page.navigate(&format!("{origin}/")).await.unwrap();

        let mut paths = (0..4)
            .map(|_| {
                requests
                    .recv_timeout(std::time::Duration::from_secs(1))
                    .unwrap()
            })
            .collect::<Vec<_>>();
        paths.sort();
        assert_eq!(
            paths,
            vec![
                "/".to_string(),
                "/css/nested/shared.css".to_string(),
                "/css/root.css".to_string(),
                "/theme/second.css".to_string(),
            ]
        );
        assert_eq!(request_count.load(Ordering::SeqCst), 3);
        assert_eq!(response_count.load(Ordering::SeqCst), 3);
        assert_eq!(
            page.network_events
                .iter()
                .filter(|event| event.resource_type == "Stylesheet")
                .count(),
            3
        );

        let sheets = page
            .js
            .as_ref()
            .unwrap()
            .with_dom(|dom| {
                dom.query_selector_all(r#"link[rel~="stylesheet"]"#)
                    .unwrap()
                    .into_iter()
                    .map(|nid| {
                        dom.external_stylesheet(nid)
                            .expect("loaded linked sheet")
                            .sources
                            .iter()
                            .map(|source| source.as_ref())
                            .collect::<Vec<_>>()
                            .join("\n")
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap();
        assert_eq!(sheets.len(), 3);
        assert_eq!(sheets[0], sheets[1], "duplicate links reuse one download");
        let shared = sheets[0].find(".shared").unwrap();
        let root = sheets[0].find(".root").unwrap();
        assert!(shared < root, "imports precede the importing sheet");
        assert!(sheets[0].contains(&format!("url(\"{origin}/css/img/shared.png\")")));
        assert!(sheets[0].contains(&format!("url(\"{origin}/css/img/root.png\")")));
        let root = sheets[2].find(".root").unwrap();
        let shared = sheets[2].find(".shared").unwrap();
        let second = sheets[2].find(".second").unwrap();
        assert!(
            root < shared && shared < second,
            "cycle is cut without reordering rules"
        );
        assert!(sheets[2].contains(&format!("url(\"{origin}/theme/img/second.png\")")));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn inline_imports_fetch_in_order_and_materialize_before_source_style() {
        let (origin, requests) = spawn_inline_import_server();
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "inline-imports".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("inline-imports".to_string(), context);
        page.set_viewport((100.0, 80.0));
        let observed_requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let callback_requests = observed_requests.clone();
        page.on_request(std::sync::Arc::new(move |request| {
            callback_requests
                .lock()
                .unwrap()
                .push((request.url.path().to_string(), request.resource_type));
        }));
        page.navigate(&format!("{origin}/")).await.unwrap();

        let mut paths = (0..3)
            .map(|_| {
                requests
                    .recv_timeout(std::time::Duration::from_secs(1))
                    .unwrap()
            })
            .collect::<Vec<_>>();
        paths.sort();
        assert_eq!(paths, vec!["/", "/a.css", "/b.css"]);
        let observed_requests = observed_requests.lock().unwrap();
        for path in ["/a.css", "/b.css"] {
            assert_eq!(
                observed_requests
                    .iter()
                    .filter(|(request_path, _)| request_path == path)
                    .map(|(_, resource_type)| *resource_type)
                    .collect::<Vec<_>>(),
                vec![obscura_net::ResourceType::Stylesheet],
                "an inline import must fetch exactly once as a stylesheet"
            );
        }
        #[cfg(feature = "render")]
        {
            for path in ["/local.svg", "/imported.svg"] {
                assert_eq!(
                    observed_requests
                        .iter()
                        .filter(|(request_path, _)| request_path == path)
                        .map(|(_, resource_type)| *resource_type)
                        .collect::<Vec<_>>(),
                    vec![obscura_net::ResourceType::Image],
                    "ordinary rule assets must remain in render warmup"
                );
            }
        }
        drop(observed_requests);

        let styles = page
            .js
            .as_ref()
            .unwrap()
            .with_dom(|dom| {
                dom.query_selector_all("style")
                    .unwrap()
                    .into_iter()
                    .map(|nid| {
                        (
                            dom.external_stylesheet(nid)
                                .map(|sheet| {
                                    sheet
                                        .sources
                                        .iter()
                                        .map(|source| source.as_ref())
                                        .collect::<Vec<_>>()
                                        .join("\n")
                                })
                                .unwrap_or_default(),
                            dom.text_content(nid),
                        )
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap();
        assert_eq!(
            styles.len(),
            1,
            "imports must not create observable style nodes"
        );
        assert!(styles[0].0.contains(".imported-a"));
        assert!(styles[0].0.contains(".imported-b"));
        assert!(styles[0].0.starts_with("@media print {\n"));
        assert!(styles[0].1.contains(".local"));

        #[cfg(feature = "render")]
        {
            let pdf = page
                .raster_pdf(crate::RasterPdfOptions {
                    print_background: true,
                    paper_width_in: 100.0 / 72.0,
                    paper_height_in: 80.0 / 72.0,
                    margin_top_in: 0.0,
                    margin_bottom_in: 0.0,
                    margin_left_in: 0.0,
                    margin_right_in: 0.0,
                    ..crate::RasterPdfOptions::default()
                })
                .expect("inline-import print PDF");
            assert!(pdf.starts_with(b"%PDF-1.4"));
        }
    }

    fn client_replacement_page(name: &str, deferred: bool) -> super::Page {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            name.to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new(name.to_string(), context);
        let server_content = (0..45)
            .map(|index| format!("<p>server content item {index} with enough text</p>"))
            .collect::<String>();
        let start = if deferred {
            "window.addEventListener('mount-client', () => setTimeout(mountClient, 0));"
        } else {
            "mountClient();"
        };
        let html = format!(
            r#"<!doctype html><html><body><main id="ssr">{server_content}</main><script>
                function mountClient() {{
                    document.body.innerHTML = '<button id="client" data-clicks="0">Client view</button>';
                    const button = document.getElementById('client');
                    button.addEventListener('click', () => {{
                        button.setAttribute('data-clicks', String(Number(button.getAttribute('data-clicks')) + 1));
                    }});
                }}
                {start}
            </script></body></html>"#,
        );
        let encoded = base64::engine::general_purpose::STANDARD.encode(html);
        page.url =
            Some(url::Url::parse(&format!("data:text/html;base64,{encoded}")).expect("data URL"));
        page
    }

    fn assert_client_replacement_survived(page: &mut super::Page) {
        let state = page
            .js
            .as_mut()
            .expect("page runtime")
            .evaluate(
                r#"
                var clientReplacementCheck = true;
                const button = document.getElementById('client');
                if (button) button.dispatchEvent(new Event('click'));
                return {
                    staleServerContent: !!document.getElementById('ssr'),
                    clientPresent: !!button,
                    clientText: button ? button.textContent : null,
                    clicks: button ? button.getAttribute('data-clicks') : null,
                    bodyElements: document.querySelectorAll('body *').length
                };
                "#,
            )
            .expect("inspect client replacement");
        assert_eq!(
            state,
            serde_json::json!({
                "staleServerContent": false,
                "clientPresent": true,
                "clientText": "Client view",
                "clicks": "1",
                "bodyElements": 1,
            }),
        );
    }

    fn spawn_parser_import_map_server(
        expected_requests: usize,
    ) -> (String, std::sync::mpsc::Receiver<String>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (request_tx, request_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};

            for _ in 0..expected_requests {
                let (mut stream, _) = listener.accept().unwrap();
                let mut request = [0u8; 2048];
                let length = stream.read(&mut request).unwrap();
                let request = String::from_utf8_lossy(&request[..length]);
                let path = request
                    .lines()
                    .next()
                    .and_then(|line| line.split_ascii_whitespace().nth(1))
                    .unwrap_or("/")
                    .to_string();
                request_tx.send(path.clone()).unwrap();
                let (status, body) = match path.as_str() {
                    "/app/before.js" => ("200 OK", "export const value = 'before-first-module';"),
                    "/app/later.js" => ("200 OK", "export const value = 'later-map';"),
                    "/app/async.js" => (
                        "200 OK",
                        "import('too-late')\
                           .then(module => globalThis.__async_before_map = module.value)\
                           .catch(() => globalThis.__async_before_map = 'rejected');",
                    ),
                    _ => ("404 Not Found", "not found"),
                };
                let response = format!(
                    "HTTP/1.1 {status}\r\nContent-Type: application/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len(),
                );
                stream.write_all(response.as_bytes()).unwrap();
            }
        });
        (format!("http://{}", address), request_rx)
    }

    fn spawn_delayed_classic_script_server(
        delay: std::time::Duration,
        body: &'static str,
    ) -> (String, std::sync::mpsc::Receiver<String>) {
        use std::io::{Read as _, Write as _};

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (request_tx, request_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut request = [0u8; 2048];
            let length = stream.read(&mut request).unwrap();
            let path = String::from_utf8_lossy(&request[..length])
                .lines()
                .next()
                .and_then(|line| line.split_ascii_whitespace().nth(1))
                .unwrap_or("/")
                .to_string();
            request_tx.send(path).unwrap();
            std::thread::sleep(delay);
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len(),
            );
            stream.write_all(response.as_bytes()).unwrap();
        });
        (format!("http://{address}"), request_rx)
    }

    fn spawn_written_script_order_server() -> String {
        use std::io::{Read as _, Write as _};
        use std::sync::atomic::{AtomicBool, Ordering};

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let vendor_finished = std::sync::Arc::new(AtomicBool::new(false));
        std::thread::spawn(move || {
            for stream in listener.incoming().take(2) {
                let Ok(mut stream) = stream else {
                    continue;
                };
                let vendor_finished = vendor_finished.clone();
                std::thread::spawn(move || {
                    let mut request = [0u8; 2048];
                    let length = stream.read(&mut request).unwrap_or(0);
                    let request = String::from_utf8_lossy(&request[..length]);
                    let path = request
                        .lines()
                        .next()
                        .and_then(|line| line.split_ascii_whitespace().nth(1))
                        .unwrap_or("/");
                    let body = if path == "/vendor.js" {
                        std::thread::sleep(std::time::Duration::from_millis(125));
                        vendor_finished.store(true, Ordering::SeqCst);
                        "globalThis.__vendorValue = 1;".to_string()
                    } else {
                        format!(
                            "globalThis.__appRequestFollowedVendor = {}; globalThis.__appSawVendor = globalThis.__vendorValue;",
                            vendor_finished.load(Ordering::SeqCst),
                        )
                    };
                    let response = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len(),
                    );
                    stream.write_all(response.as_bytes()).unwrap();
                });
            }
        });
        format!("http://{address}")
    }

    fn spawn_script_resource_cache_server(
        distinct: bool,
    ) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
        use std::io::{Read as _, Write as _};
        use std::sync::atomic::Ordering;

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let script_requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let observed_requests = script_requests.clone();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else {
                    continue;
                };
                let observed_requests = observed_requests.clone();
                std::thread::spawn(move || {
                    let mut request = [0u8; 2048];
                    let length = stream.read(&mut request).unwrap_or(0);
                    let request_text = String::from_utf8_lossy(&request[..length]);
                    let path = request_text
                        .lines()
                        .next()
                        .and_then(|line| line.split_ascii_whitespace().nth(1))
                        .unwrap_or("/");
                    let (content_type, cache_control, body) = if path == "/duplicate.html" {
                        let tags = (0..32)
                            .map(|_| "<script src='/shared.js'></script>")
                            .collect::<String>();
                        (
                            "text/html",
                            "no-store",
                            format!(
                                "<!doctype html><html><body><script>globalThis.__runs=0</script>{tags}</body></html>"
                            ),
                        )
                    } else if path == "/distinct.html" {
                        let tags = (0..24)
                            .map(|index| format!("<script src='/distinct/{index}.js'></script>"))
                            .collect::<String>();
                        (
                            "text/html",
                            "no-store",
                            format!(
                                "<!doctype html><html><body><script>globalThis.__runs=0</script>{tags}</body></html>"
                            ),
                        )
                    } else if path == "/shared.js" || path.starts_with("/distinct/") {
                        observed_requests.fetch_add(1, Ordering::SeqCst);
                        std::thread::sleep(std::time::Duration::from_millis(80));
                        (
                            "application/javascript",
                            "public, max-age=3600",
                            "globalThis.__runs=(globalThis.__runs||0)+1;".to_string(),
                        )
                    } else {
                        ("text/plain", "no-store", "not found".to_string())
                    };
                    let response = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nCache-Control: {cache_control}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len(),
                    );
                    let _ = stream.write_all(response.as_bytes());
                });
            }
        });
        let page = if distinct {
            "distinct.html"
        } else {
            "duplicate.html"
        };
        (format!("http://{address}/{page}"), script_requests)
    }

    #[tokio::test(flavor = "current_thread")]
    async fn duplicate_cacheable_scripts_fetch_once_but_execute_for_each_element() {
        use std::sync::atomic::Ordering;

        let (url, script_requests) = spawn_script_resource_cache_server(false);
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "duplicate-script-cache".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("duplicate-script-cache".to_string(), context);

        page.navigate(&url).await.unwrap();

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__runs")
                .unwrap(),
            serde_json::json!(32.0),
            "a cached response must still execute for every script element",
        );
        assert_eq!(script_requests.load(Ordering::SeqCst), 1);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn distinct_cacheable_scripts_keep_distinct_network_requests() {
        use std::sync::atomic::Ordering;

        let (url, script_requests) = spawn_script_resource_cache_server(true);
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "distinct-script-cache".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("distinct-script-cache".to_string(), context);

        page.navigate(&url).await.unwrap();

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__runs")
                .unwrap(),
            serde_json::json!(24.0),
        );
        assert_eq!(script_requests.load(Ordering::SeqCst), 24);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn fetch_interception_patterns_do_not_block_parser_scripts() {
        let (url, _) = spawn_script_resource_cache_server(false);
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "fetch-pattern-is-not-blocklist".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("fetch-pattern-is-not-blocklist".to_string(), context);
        page.intercept_block_patterns = vec!["*".to_string()];
        page.enable_intercept(true);

        page.navigate(&url).await.unwrap();

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__runs")
                .unwrap(),
            serde_json::json!(32.0),
            "Fetch.enable patterns pause matching requests; they are not blocked URLs",
        );
    }

    #[test]
    fn external_scripts_require_a_successful_http_status() {
        assert!(script_response_is_executable(200));
        assert!(script_response_is_executable(204));
        assert!(script_response_is_executable(299));
        assert!(!script_response_is_executable(0));
        assert!(!script_response_is_executable(304));
        assert!(!script_response_is_executable(401));
        assert!(!script_response_is_executable(404));
        assert!(!script_response_is_executable(500));
    }

    /// Issue #678: `localStorage` belongs to the BrowserContext and
    /// `sessionStorage` to the Page, so both survive the realm rebuild that
    /// `init_js` performs on every navigation. The fixture serves one origin on
    /// two paths plus a second origin, so a cross-origin hop is testable too.
    async fn spawn_storage_server() -> (String, String) {
        let first = "<html><body><script>window.__ran='YES';</script></body></html>";
        async fn serve(listener: tokio::net::TcpListener, body: &'static str) {
            while let Ok((mut socket, _)) = listener.accept().await {
                let body = body.to_string();
                tokio::spawn(async move {
                    use tokio::io::{AsyncReadExt, AsyncWriteExt};
                    let mut buf = [0u8; 2048];
                    let _ = socket.read(&mut buf).await;
                    let resp = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len()
                    );
                    let _ = socket.write_all(resp.as_bytes()).await;
                });
            }
        }
        let listener_a = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr_a = listener_a.local_addr().unwrap();
        let listener_b = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr_b = listener_b.local_addr().unwrap();
        tokio::spawn(serve(listener_a, first));
        tokio::spawn(serve(listener_b, first));
        (format!("http://{addr_a}"), format!("http://{addr_b}"))
    }

    fn storage_page(name: &str, context: std::sync::Arc<crate::BrowserContext>) -> super::Page {
        super::Page::new(name.to_string(), context)
    }

    #[tokio::test]
    async fn web_storage_survives_navigation_and_is_scoped_per_origin() {
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let (origin_a, origin_b) = spawn_storage_server().await;
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "storage-regression".into(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = storage_page("storage-regression", context.clone());

        page.navigate(&origin_a).await.unwrap();
        page.evaluate(
            r#"(() => {
                localStorage.setItem('l1', 'local-value');
                sessionStorage.setItem('s1', 'session-value');
                return 'seeded';
            })()"#,
        );

        // Same origin, different path: a new document, and therefore a new realm.
        page.navigate(&format!("{origin_a}/second")).await.unwrap();
        let after = page
            .evaluate(
                r#"({
                    local: localStorage.getItem('l1'),
                    session: sessionStorage.getItem('s1'),
                    length: localStorage.length,
                    viaProperty: localStorage.l1,
                    has: 'l1' in localStorage,
                    keys: Object.keys(localStorage),
                })"#,
            );
        assert_eq!(
            after.get("local").and_then(|v| v.as_str()),
            Some("local-value"),
            "localStorage must survive a same-origin navigation: {after:?}"
        );
        assert_eq!(
            after.get("session").and_then(|v| v.as_str()),
            Some("session-value"),
            "sessionStorage must survive a same-origin navigation in the same tab: {after:?}"
        );
        // The Proxy surface has to agree with the methods now that the data
        // lives in Rust: property access, `in`, key enumeration and length.
        assert_eq!(after.get("viaProperty").and_then(|v| v.as_str()), Some("local-value"));
        assert_eq!(after.get("has").and_then(|v| v.as_bool()), Some(true));
        assert_eq!(after.get("length").and_then(|v| v.as_u64()), Some(1));
        assert_eq!(
            after.get("keys").and_then(|v| v.as_array()).map(|k| k.len()),
            Some(1)
        );

        // Another origin gets an empty store of its own: no cross-origin leak.
        page.navigate(&origin_b).await.unwrap();
        let other = page
            .evaluate(
                r#"({
                    local: localStorage.getItem('l1'),
                    session: sessionStorage.getItem('s1'),
                })"#,
            );
        assert!(
            other["local"].is_null() && other["session"].is_null(),
            "a different origin must not see this origin's storage: {other:?}"
        );

        // Coming back, the original origin's data is still there.
        page.navigate(&origin_a).await.unwrap();
        let back = page.evaluate("localStorage.getItem('l1')");
        assert_eq!(back.as_str(), Some("local-value"));
        assert_eq!(page.evaluate("sessionStorage.getItem('s1')").as_str(), Some("session-value"));
    }

    #[tokio::test]
    async fn indexeddb_records_survive_navigation_and_share_only_their_context_and_origin() {
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let (origin_a, _) = spawn_storage_server().await;
        let (origin_b, _) = spawn_storage_server().await;
        let context = std::sync::Arc::new(crate::BrowserContext::new("idb-shared".into()));
        let mut first = storage_page("idb-first", context.clone());
        first.navigate(&origin_a).await.unwrap();
        first.evaluate(r#"(() => {
            globalThis.idbSaved = false;
            const r = indexedDB.open('shared',1);
            r.onupgradeneeded = () => r.result.createObjectStore('items');
            r.onsuccess = () => {
                const tx = r.result.transaction('items','readwrite');
                tx.objectStore('items').put({value:'kept'},1);
                tx.oncomplete = () => idbSaved = true;
            };
        })()"#);
        first.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();
        assert_eq!(first.evaluate("idbSaved"), serde_json::json!(true));
        let read = r#"(() => {
            globalThis.idbRead = 'pending';
            const r = indexedDB.open('shared',1);
            r.onupgradeneeded = () => r.result.createObjectStore('items');
            r.onsuccess = () => {
                const q = r.result.transaction('items').objectStore('items').get(1);
                q.onsuccess = () => idbRead = q.result?.value ?? null;
            };
        })()"#;
        first.navigate(&origin_b).await.unwrap();
        first.evaluate(read);
        first.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();
        assert_eq!(first.evaluate("idbRead"), serde_json::Value::Null);
        first.navigate(&origin_a).await.unwrap();
        first.evaluate(read);
        first.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();
        assert_eq!(first.evaluate("idbRead"), serde_json::json!("kept"));
        let mut second = storage_page("idb-second", context);
        second.navigate(&origin_a).await.unwrap();
        second.evaluate(read);
        second.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();
        assert_eq!(second.evaluate("idbRead"), serde_json::json!("kept"));
        let mut isolated = storage_page("idb-isolated", std::sync::Arc::new(crate::BrowserContext::new("idb-private".into())));
        isolated.navigate(&origin_a).await.unwrap();
        isolated.evaluate(read);
        isolated.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();
        assert_eq!(isolated.evaluate("idbRead"), serde_json::Value::Null);
    }

    #[tokio::test]
    async fn session_storage_stays_inside_the_tab_and_local_storage_is_shared() {
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let (origin, _) = spawn_storage_server().await;
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "storage-scope".into(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut first = storage_page("storage-scope-1", context.clone());
        first.navigate(&origin).await.unwrap();
        first.evaluate(
            r#"(() => {
                localStorage.setItem('shared', 'from-tab-one');
                sessionStorage.setItem('tab', 'from-tab-one');
                return 'ok';
            })()"#,
        );

        // A second page of the same context shares localStorage but not
        // sessionStorage, which is the split the storage bug got wrong.
        let mut second = storage_page("storage-scope-2", context.clone());
        second.navigate(&origin).await.unwrap();
        let view = second
            .evaluate(
                r#"({
                    local: localStorage.getItem('shared'),
                    session: sessionStorage.getItem('tab'),
                })"#,
            );
        assert_eq!(
            view.get("local").and_then(|v| v.as_str()),
            Some("from-tab-one"),
            "localStorage is scoped to the BrowserContext: {view:?}"
        );
        assert!(
            view.get("session") == Some(&serde_json::Value::Null),
            "sessionStorage must not cross tabs: {view:?}"
        );
        assert_eq!(second.evaluate("(() => { localStorage.setItem('shared', 'from-tab-two'); sessionStorage.setItem('tab', 'from-tab-two'); return localStorage.getItem('shared'); })()"),
            serde_json::json!("from-tab-two"));
        second.suspend_js();
        first.suspend_js();
        first.resume_js();
        assert_eq!(first.evaluate("[localStorage.getItem('shared'), sessionStorage.getItem('tab')]"),
            serde_json::json!(["from-tab-two", "from-tab-one"]));
        first.suspend_js();
        second.resume_js();
        assert_eq!(second.evaluate("sessionStorage.getItem('tab')").as_str(), Some("from-tab-two"));
    }

    /// `/` puts its iframe inside a closed shadow root, `/plain.html` puts the
    /// same iframe straight in the document, and `/child.html` is the frame.
    async fn spawn_shadow_frame_server() -> String {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            while let Ok((mut socket, _)) = listener.accept().await {
                tokio::spawn(async move {
                    use tokio::io::{AsyncReadExt, AsyncWriteExt};
                    let mut buf = [0u8; 2048];
                    let read = socket.read(&mut buf).await.unwrap_or(0);
                    let request = String::from_utf8_lossy(&buf[..read]).to_string();
                    let body = if request.starts_with("GET /child.html ") {
                        "<html><body><script>window.__ran = 'YES';</script></body></html>"
                    } else if request.starts_with("GET /plain.html ") {
                        "<html><body><iframe src=\"/child.html\"></iframe></body></html>"
                    } else {
                        "<html><body><div id=\"host\"></div><script>\
                         var r = document.getElementById('host').attachShadow({mode:'closed'});\
                         var f = document.createElement('iframe');\
                         f.src = '/child.html';\
                         r.appendChild(f);\
                         </script></body></html>"
                    };
                    let resp = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len()
                    );
                    let _ = socket.write_all(resp.as_bytes()).await;
                });
            }
        });
        format!("http://{addr}/")
    }

    async fn spawn_slow_frame_script_server() -> (
        String,
        std::sync::Arc<std::sync::Mutex<Vec<String>>>,
        std::sync::Arc<tokio::sync::Notify>,
    ) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let server_requests = requests.clone();
        let slow_seen = std::sync::Arc::new(tokio::sync::Notify::new());
        let server_slow_seen = slow_seen.clone();
        tokio::spawn(async move {
            while let Ok((mut socket, _)) = listener.accept().await {
                let requests = server_requests.clone();
                let slow_seen = server_slow_seen.clone();
                tokio::spawn(async move {
                    use tokio::io::{AsyncReadExt, AsyncWriteExt};
                    let mut buf = [0u8; 2048];
                    let read = socket.read(&mut buf).await.unwrap_or(0);
                    let request = String::from_utf8_lossy(&buf[..read]);
                    let path = request
                        .lines()
                        .next()
                        .and_then(|line| line.split_ascii_whitespace().nth(1))
                        .unwrap_or("/")
                        .to_string();
                    requests.lock().unwrap().push(path.clone());
                    let (content_type, body) = if path == "/slow.js" {
                        slow_seen.notify_waiters();
                        tokio::time::sleep(std::time::Duration::from_millis(250)).await;
                        (
                            "application/javascript",
                            "globalThis.__order.push('second'); globalThis.__childReady = true;",
                        )
                    } else if path == "/first.js" {
                        (
                            "application/javascript",
                            "globalThis.__order.push('first');",
                        )
                    } else {
                        (
                            "text/html",
                            "<html><body><script src=/first.js></script><script src=/slow.js></script></body></html>",
                        )
                    };
                    let response = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len(),
                    );
                    let _ = socket.write_all(response.as_bytes()).await;
                });
            }
        });
        (format!("http://{addr}"), requests, slow_seen)
    }

    async fn page_with_fetched_slow_frames(
        name: &str,
        frame_count: usize,
    ) -> (
        super::Page,
        std::sync::Arc<std::sync::Mutex<Vec<String>>>,
        std::sync::Arc<tokio::sync::Notify>,
    ) {
        let (base, requests, slow_seen) = spawn_slow_frame_script_server().await;
        let iframes = (0..frame_count)
            .map(|_| "<iframe src=/child.html></iframe>")
            .collect::<String>();
        let html = format!("<html><body>{iframes}</body></html>");
        let mut page = import_map_test_page(name, &base, &html);
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            page.js.as_mut().unwrap().run_event_loop(),
        )
        .await
        .expect("frame documents did not finish fetching")
        .unwrap();
        (page, requests, slow_seen)
    }

    async fn spawn_nested_pending_frame_server() -> (
        String,
        std::sync::Arc<std::sync::Mutex<Vec<String>>>,
    ) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let server_requests = requests.clone();
        tokio::spawn(async move {
            while let Ok((mut socket, _)) = listener.accept().await {
                let requests = server_requests.clone();
                tokio::spawn(async move {
                    use tokio::io::{AsyncReadExt, AsyncWriteExt};
                    let mut buf = [0u8; 2048];
                    let read = socket.read(&mut buf).await.unwrap_or(0);
                    let request = String::from_utf8_lossy(&buf[..read]);
                    let path = request
                        .lines()
                        .next()
                        .and_then(|line| line.split_ascii_whitespace().nth(1))
                        .unwrap_or("/")
                        .to_string();
                    requests.lock().unwrap().push(path.clone());
                    let (content_type, body) = match path.as_str() {
                        "/parent.html" => (
                            "text/html",
                            "<html><body><script>const child = document.createElement('iframe'); child.src = '/grandchild.html'; document.body.appendChild(child);</script></body></html>",
                        ),
                        "/grandchild.html" => (
                            "text/html",
                            "<html><body><script src=/grandchild-slow.js></script></body></html>",
                        ),
                        _ => ("application/javascript", "globalThis.__mustNotRun = true;"),
                    };
                    let response = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len(),
                    );
                    let _ = socket.write_all(response.as_bytes()).await;
                });
            }
        });
        (format!("http://{addr}"), requests)
    }

    async fn pump_srcdoc_frames(page: &mut super::Page) {
        for _ in 0..4 {
            tokio::time::timeout(std::time::Duration::from_secs(2),
                page.js.as_mut().unwrap().run_event_loop()).await.unwrap().unwrap();
            if !page.advance_frames().await { break; }
        }
    }

    async fn spawn_form_target_server() -> (
        String, tokio::sync::mpsc::UnboundedReceiver<(String, String)>,
    ) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let (sent, requests) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(async move {
            while let Ok((mut socket, _)) = listener.accept().await {
                let sent = sent.clone();
                tokio::spawn(async move {
                    let mut request = Vec::new();
                    loop {
                        let mut buffer = [0; 2048];
                        let count = socket.read(&mut buffer).await.unwrap();
                        if count == 0 { return; }
                        request.extend_from_slice(&buffer[..count]);
                        let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") else { continue };
                        let headers = String::from_utf8_lossy(&request[..end]);
                        let length = headers.lines().find_map(|line| {
                            let (name, value) = line.split_once(':')?;
                            name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse::<usize>().unwrap())
                        }).unwrap_or(0);
                        if request.len() < end + 4 + length { continue; }
                        sent.send((headers.lines().next().unwrap().to_string(),
                            String::from_utf8_lossy(&request[end + 4..]).to_string())).unwrap();
                        break;
                    }
                    let body = "<title>Child response</title><p>submitted</p><script>globalThis.formRan=true</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());
                    socket.write_all(response.as_bytes()).await.unwrap();
                });
            }
        });
        (base, requests)
    }

    #[tokio::test(flavor = "current_thread")]
    async fn form_submission_to_named_iframe_keeps_the_top_document() {
        let (base, mut requests) = spawn_form_target_server().await;
        for method in ["GET", "POST"] {
            for dynamic in [false, true] {
                let frame = if dynamic { "" } else { "<iframe name='sink'></iframe>" };
                let html = format!("<title>Top document</title>{frame}<form action='/submit' method='{method}' target='sink'><input name='value' value='hello world'></form>");
                let mut page = import_map_test_page("named-form", &base, &html);
                page.evaluate_script(&format!(r#"(() => {{
                    if ({dynamic}) {{ const frame = document.createElement('iframe'); frame.name = 'sink'; document.body.appendChild(frame); }}
                    document.forms[0].submit(); return true;
                }})()"#)).unwrap();
                assert!(!page.has_pending_navigation(), "{method}, dynamic={dynamic}: submission targeted the top document");
                pump_srcdoc_frames(&mut page).await;
                let expected = if method == "POST" {
                    ("POST /submit HTTP/1.1", "value=hello+world")
                } else {
                    ("GET /submit?value=hello+world HTTP/1.1", "")
                };
                let request = requests.try_recv().expect("form request reached the server");
                assert_eq!(request, (expected.0.to_string(), expected.1.to_string()));
                assert_eq!(page.evaluate_script("[document.title, document.querySelector('iframe').contentDocument.title, document.querySelector('iframe').contentWindow.formRan]").unwrap(),
                    serde_json::json!(["Top document", "Child response", true]));
            }
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn named_iframe_form_navigation_preserves_targets_and_origin_checks() {
        let (base, mut requests) = spawn_form_target_server().await;
        let (other, mut cross_requests) = spawn_form_target_server().await;
        let mut page = import_map_test_page("named-form-overrides", &base,
            "<base target='sink'><title>Top document</title><iframe name='sink' srcdoc='initial'></iframe><form action='/submit' method='POST' target='_self'><input name='x' value='1'><button id='send' formtarget='sink'>Send</button></form>");
        for _ in 0..2 {
            page.evaluate_script("document.forms[0].requestSubmit(document.getElementById('send'))").unwrap();
            assert!(!page.has_pending_navigation());
            pump_srcdoc_frames(&mut page).await;
            assert_eq!(requests.try_recv().unwrap(), ("POST /submit HTTP/1.1".into(), "x=1".into()));
            assert_eq!(page.evaluate_script("document.querySelector('iframe').contentDocument.title").unwrap(),
                serde_json::json!("Child response"));
        }
        page.evaluate_script(&format!("document.forms[0].removeAttribute('target'); document.forms[0].action = '{other}/cross'; document.forms[0].submit()" )).unwrap();
        assert!(!page.has_pending_navigation());
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(cross_requests.try_recv().unwrap(), ("POST /cross HTTP/1.1".into(), "x=1".into()));
        assert_eq!(page.evaluate_script(r#"(() => {
            const frame = document.querySelector('iframe');
            let readable = false;
            try { readable = !!frame.contentWindow.document?.body; } catch (_) {}
            return [document.title, frame.contentDocument === null, readable];
        })()"#).unwrap(), serde_json::json!(["Top document", true, false]));
    }

    #[test]
    fn foreign_iframe_elements_do_not_create_browsing_contexts() {
        let mut page = import_map_test_page("foreign-frame", "https://parent.test",
            "<body><svg><iframe id='foreign'></iframe></svg></body>");
        assert!(!page.js.as_ref().unwrap().has_pending_frame_tasks(), "parser-created SVG iframe");
        page.evaluate_script(r#"(() => {
            const root = document.createElement('div');
            root.appendChild(document.createElementNS('http://www.w3.org/2000/svg', 'iframe'));
            document.body.appendChild(root);
            root.innerHTML = '<svg><iframe></iframe></svg>';
            return true;
        })()"#).unwrap();
        assert!(!page.js.as_ref().unwrap().has_pending_frame_tasks(), "inserted SVG iframe");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn blank_iframe_load_runs_while_an_unrelated_timer_is_pending() {
        for inserted in [false, true] {
            let html = if inserted { "<body></body>" } else {
                "<body><iframe id='f' onload='globalThis.loads = (globalThis.loads || 0) + 1'></iframe></body>"
            };
            let mut page = import_map_test_page("blank-frame-load", "https://parent.test", html);
            page.set_preload_scripts(vec!["globalThis.eval = () => undefined;".into(),
            "globalThis.preloadCount = (globalThis.preloadCount || 0) + 1;".into()]);
            page.evaluate_script(&format!(r#"(() => {{
                globalThis.loads = globalThis.loads || 0;
                if ({inserted}) {{
                    const frame = document.createElement('iframe');
                    frame.id = 'f'; frame.onload = () => loads++;
                    document.body.appendChild(frame);
                }}
                setTimeout(() => {{}}, 60000);
                return true;
            }})()"#)).unwrap();
            assert_eq!(page.evaluate_script("loads").unwrap().as_f64(), Some(1.0),
                "initial blank load must fire during insertion, without getters");
            tokio::time::timeout(std::time::Duration::from_secs(2),
                page.run_autonomous_event_loop_turn()).await
                .expect("frame adoption must not wait for an unrelated timer").unwrap();
            assert_eq!(page.frame_urls(), ["about:blank"]);
            assert_eq!(page.evaluate_script("[document.getElementById('f').contentDocument.URL, loads]").unwrap(),
                serde_json::json!(["about:blank", 1]));
            if inserted {
                assert_eq!(page.evaluate_script("document.getElementById('f').contentWindow.preloadCount").unwrap().as_f64(),
                    Some(1.0), "initial-frame preloads run once");
            }
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn parser_blank_iframe_load_runs_after_parent_initialization_scripts() {
        let mut page = import_map_test_page("parser-frame-order", "https://parent.test", "<body></body>");
        page.set_preload_scripts(vec!["globalThis.preloadMarker = 'ready';".into()]);
        page.navigate("data:text/html,<body><iframe onload='globalThis.observed = [window.preloadMarker, this.contentWindow.preloadMarker]'></iframe></body>").await.unwrap();
        assert_eq!(page.evaluate_script("observed").unwrap(), serde_json::json!(["ready", "ready"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn blank_iframe_load_observes_preloads_and_precedes_append_return() {
        let mut page = import_map_test_page("blank-frame-order", "https://parent.test", "<body></body>");
        page.set_preload_scripts(vec!["globalThis.preloadCount = (globalThis.preloadCount || 0) + 1;".into()]);
        assert_eq!(page.evaluate_script(r#"(() => {
            const events = []; const frame = document.createElement('iframe');
            frame.onload = () => events.push(['load', frame.contentDocument.readyState, frame.contentWindow.preloadCount]);
            document.body.appendChild(frame); events.push(['after']);
            return events;
        })()"#).unwrap(), serde_json::json!([["load", "complete", 1], ["after"]]));
        page.set_preload_scripts(vec!["globalThis.preloadCount = 7;".into()]);
        assert_eq!(page.evaluate_script(r#"(() => {
            const parent = document.querySelector('iframe').contentDocument;
            const nested = parent.createElement('iframe'); parent.body.appendChild(nested);
            return nested.contentWindow.preloadCount;
        })()"#).unwrap().as_f64(), Some(7.0), "existing parent frames see updated initialization scripts");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_loads_parser_and_inserted_documents_in_their_own_realms() {
        let mut page = import_map_test_page("srcdoc", "https://parent.test",
            r#"<html><head><base href="https://assets.test/dir/"></head><body>
            <iframe id="parsed" src="data:text/html,FALLBACK" srcdoc="&lt;p&gt;parsed&lt;/p&gt;"></iframe>
            </body></html>"#);
        page.evaluate_script(r#"(() => {
            globalThis.loads = [];
            localStorage.setItem('shared', 'parent');
            const frame = document.createElement('iframe'); frame.id = 'inserted';
            frame.srcdoc = '<p>inserted</p><script>globalThis.childOnly=42;document.body.dataset.ready="yes";</script>';
            frame.onload = () => loads.push([frame.contentDocument.URL,
                frame.contentDocument.body.dataset.ready, frame.contentWindow.childOnly]);
            document.body.appendChild(frame);
            return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        let value = page.evaluate_script(r#"(() => {
            const parsed = document.getElementById('parsed').contentDocument;
            const f = document.getElementById('inserted'), d = f.contentDocument;
            const a = d.createElement('a'); a.href = 'next';
            return [parsed.URL, parsed.body.textContent, d.URL, d.baseURI, a.href,
                f.contentWindow.localStorage.getItem('shared'), typeof globalThis.childOnly,
                loads, d.defaultView === f.contentWindow, parsed.compatMode];
        })()"#).unwrap();
        assert_eq!(value, serde_json::json!(["about:srcdoc", "parsed", "about:srcdoc",
            "https://assets.test/dir/", "https://assets.test/dir/next", "parent", "undefined",
            [["about:srcdoc", "yes", 42]], true, "CSS1Compat"]));
        assert_eq!(page.frame_urls(), vec!["about:srcdoc", "about:srcdoc"]);
    }

    /// A child realm's node ids index its own document. Native ops that
    /// resolved the page's document instead left a frame's `<img>` without a
    /// load or error event, returned a null 2D context for a frame's canvas,
    /// and silently dropped every script that frame code inserted.
    #[tokio::test(flavor = "current_thread")]
    async fn iframe_realm_node_ops_resolve_the_frame_document() {
        let mut page = import_map_test_page("frame-node-ops", "https://parent.test",
            "<body><p>parent</p></body>");
        page.evaluate_script(r#"(() => {
            const frame = document.createElement('iframe'); frame.id = 'child';
            frame.srcdoc = `<body><script>
                globalThis.results = {};
                const ctx = document.createElement('canvas').getContext('2d');
                results.canvas = ctx ? 'context' : 'null';
                const inserted = document.createElement('script');
                inserted.textContent = 'results.script = "ran"';
                document.head.appendChild(inserted);
                const image = new Image();
                image.onload = () => { results.image = 'load'; };
                image.onerror = () => { results.image = 'error'; };
                image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
            <\/script></body>`;
            document.body.appendChild(frame);
            return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        let mut value = serde_json::Value::Null;
        for _ in 0..20 {
            value = page.evaluate_script(
                "JSON.stringify(document.getElementById('child').contentWindow.results)").unwrap();
            if value.as_str().is_some_and(|json| json.contains("image")) { break; }
            page.js.as_mut().unwrap().run_event_loop_bounded(20).await.unwrap();
        }
        let results: serde_json::Value = serde_json::from_str(value.as_str().unwrap()).unwrap();
        assert_eq!(results, serde_json::json!({"canvas": "context", "script": "ran", "image": "load"}));
    }

    /// A page script can call a frame's own Location methods (lazy-load
    /// scripts do `iframe.contentWindow.location.replace(src)`). The running
    /// context is then the page's, so the navigation was queued on the top
    /// document, which loaded the iframe's URL in place of its own.
    #[tokio::test(flavor = "current_thread")]
    async fn frame_location_navigation_loads_the_child_and_ignores_detached_windows() {
        use std::io::{Read as _, Write as _};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        std::thread::spawn(move || {
            let (mut socket, _) = listener.accept().unwrap();
            let mut request = [0; 4096];socket.read(&mut request).unwrap();
            let body = "<!doctype html><title>Child after</title><p>after</p>";
            write!(socket, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
        });
        let mut page = import_map_test_page("frame-location-commit", &base,
            "<title>Parent</title><iframe srcdoc='<p>before</p>'></iframe>");
        pump_srcdoc_frames(&mut page).await;
        page.evaluate_script(&format!("document.querySelector('iframe').contentWindow.location.replace({});1",serde_json::to_string(&format!("{base}/after")).unwrap())).unwrap();
        assert!(!page.has_pending_navigation());
        for _ in 0..20 {
            page.advance_frames().await;
            if let Some(js)=page.js.as_mut() {js.run_event_loop_bounded(20).await.unwrap();}
            if page.frame_urls().iter().any(|url|url.ends_with("/after")) { break; }
        }
        assert_eq!(page.frame_urls(),vec![format!("{base}/after")]);
        assert_eq!(page.evaluate_in_frame(0,"document.body.textContent").unwrap(),serde_json::json!("after"));
        assert_eq!(page.evaluate_script("document.title").unwrap(),serde_json::json!("Parent"));
        page.evaluate_script("globalThis.stale=document.querySelector('iframe').contentWindow;document.querySelector('iframe').remove();1").unwrap();
        page.advance_frames().await;
        page.evaluate_script("stale.location.assign('https://other.test/');1").unwrap();
        assert!(!page.has_pending_navigation(),"a discarded child cannot navigate the top document");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigating_a_frame_from_the_page_keeps_the_top_document() {
        let mut page = import_map_test_page("frame-location-from-page", "https://parent.test",
            "<title>Top document</title><body><iframe srcdoc='<form id=f action=/x></form>'></iframe></body>");
        pump_srcdoc_frames(&mut page).await;
        for call in [
            "location.replace('https://embed.test/video')",
            "location.assign('https://embed.test/video')",
            "location.href = 'https://embed.test/video'",
            "location.reload()",
            "document.getElementById('f').submit()",
        ] {
            page.evaluate_script(&format!("document.querySelector('iframe').contentWindow.{call}; 1")).unwrap();
            assert!(!page.has_pending_navigation(), "{call} queued a navigation on the top document");
        }
        assert_eq!(page.evaluate_script("[location.href, document.title]").unwrap(),
            serde_json::json!(["https://parent.test/app/index.html", "Top document"]));
        // The top document still navigates itself.
        page.evaluate_script("location.href = 'https://other.test/'; 1").unwrap();
        assert!(page.has_pending_navigation());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_replacement_cancels_stale_documents() {
        let mut page = import_map_test_page("srcdoc-replace", "https://parent.test", "<body></body>");
        page.evaluate_script(r#"(() => {
            globalThis.executed = []; globalThis.loaded = [];
            const host = document.createElement('div');
            host.innerHTML = '<iframe id="f" srcdoc="first"></iframe>';
            document.body.appendChild(host);
            const f = document.getElementById('f');
            f.onload = () => loaded.push(f.contentDocument.body.textContent);
            f.setAttributeNS(null, 'srcdoc', '<script>parent.executed.push("stale")</script>stale');
            f.srcdoc = '<script>parent.executed.push("latest")</script><p>latest</p>';
            return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(page.evaluate_script("[executed, loaded.map(text => text.endsWith('latest')), document.getElementById('f').srcdoc.includes('<p>latest</p>')]").unwrap(),
            serde_json::json!([["latest"], [true], true]));
        page.evaluate_script("document.getElementById('f').removeAttribute('srcdoc'); 1").unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(page.evaluate_script("document.getElementById('f').contentDocument.URL").unwrap(),
            serde_json::json!("about:blank"));
        assert!(page.frames.len() <= 1, "replaced srcdoc realms must be released");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_sandbox_blocks_scripts_and_opaque_document_access() {
        let mut page = import_map_test_page("srcdoc-sandbox", "https://parent.test", "<body></body>");
        page.evaluate_script(r#"(() => {
            globalThis.escaped = false;
            for (const [id, policy] of [['opaque', 'ALLOW-SCRIPTS'], ['inert', 'ALLOW-SAME-ORIGIN']]) {
                const f = document.createElement('iframe'); f.id = id;
                f.setAttribute('sandbox', policy);
                f.srcdoc = '<button onclick="parent.escaped=true">hello</button><script>globalThis.ran=true;try{parent.escaped=true}catch(e){}</script><noscript><i>fallback</i></noscript>';
                document.body.appendChild(f);
            }
            return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(page.evaluate_script(r#"(() => {
            const opaque = document.getElementById('opaque');
            const inert = document.getElementById('inert');
            inert.contentDocument.querySelector('button').click();
            return [opaque.contentDocument === null, inert.contentDocument.URL,
                inert.contentDocument.querySelector('button').textContent,
                typeof inert.contentWindow.ran, escaped,
                inert.contentDocument.querySelector('noscript i')?.textContent];
        })()"#).unwrap(), serde_json::json!([true, "about:srcdoc", "hello", "undefined", false, "fallback"]));
        assert_eq!(page.evaluate_in_frame(0, "[document.URL, globalThis.ran, location.origin]").unwrap(),
            serde_json::json!(["about:srcdoc", true, "null"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_nested_and_empty_documents_keep_the_creator_base() {
        let mut page = import_map_test_page("srcdoc-nested", "https://parent.test", "<body></body>");
        page.evaluate_script(r#"(() => {
            const f = document.createElement('iframe'); f.id = 'outer';
            f.srcdoc = '<base href="https://nested.test/path/"><iframe srcdoc=""></iframe>';
            document.body.appendChild(f); return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(page.evaluate_script(r#"(() => {
            const child = document.getElementById('outer').contentDocument.querySelector('iframe');
            return [child.contentDocument.URL, child.contentDocument.baseURI,
                child.contentDocument.body.textContent,
                child.contentWindow.parent === document.getElementById('outer').contentWindow];
        })()"#).unwrap(), serde_json::json!(["about:srcdoc", "https://nested.test/path/", "", true]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_from_connected_inner_html_survives_initial_document_reads() {
        let mut page = import_map_test_page("srcdoc-connected", "https://parent.test", "<body></body>");
        page.evaluate_script(r#"(() => {
            document.body.innerHTML = '<iframe id="f" srcdoc="hello"></iframe>';
            globalThis.initial = document.getElementById('f').contentDocument.URL;
            return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(page.evaluate_script("[initial, document.getElementById('f').contentDocument.URL, document.getElementById('f').contentDocument.body.textContent]").unwrap(),
            serde_json::json!(["about:blank", "about:srcdoc", "hello"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_external_scripts_resolve_against_the_creator() {
        let (base, requests) = spawn_nested_pending_frame_server().await;
        let mut page = import_map_test_page("srcdoc-script-base", &base,
            r#"<body><iframe srcdoc="&lt;script src=child.js&gt;&lt;/script&gt;"></iframe></body>"#);
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(*requests.lock().unwrap(), vec!["/app/child.js"]);
        assert_eq!(page.evaluate_script("document.querySelector('iframe').contentWindow.__mustNotRun").unwrap(),
            serde_json::json!(true));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_inherits_sandbox_restrictions_in_nested_documents() {
        let mut page = import_map_test_page("srcdoc-inherited-sandbox", "https://parent.test", "<body></body>");
        page.evaluate_script(r#"(() => {
            for (const policy of ['allow-scripts', 'allow-same-origin']) {
                const f = document.createElement('iframe'); f.id = policy; f.setAttribute('sandbox', policy);
                f.srcdoc = '<iframe srcdoc="&lt;script&gt;globalThis.ran=true&lt;/script&gt;"></iframe>';
                document.body.appendChild(f);
            }
            return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(page.evaluate_in_frame(0, "document.querySelector('iframe').contentDocument === null").unwrap(),
            serde_json::json!(true));
        assert_eq!(page.evaluate_script("typeof document.getElementById('allow-same-origin').contentDocument.querySelector('iframe').contentWindow.ran").unwrap(),
            serde_json::json!("undefined"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_ignores_absent_attributes_and_non_html_elements() {
        let mut page = import_map_test_page("srcdoc-noop", "https://parent.test", "<body></body>");
        let values = page.evaluate_script(r#"(() => {
            globalThis.escaped = false;
            const f = document.createElement('iframe'); document.body.appendChild(f);
            f.contentWindow.kept = 73;
            f.removeAttribute('srcdoc');
            const first = f.contentWindow.kept;
            f.removeAttributeNS(null, 'srcdoc');
            const second = f.contentWindow.kept;
            const plain = document.createElement('div'); plain.srcdoc = 'expando';
            const svg = document.createElementNS('http://www.w3.org/2000/svg', 'iframe');
            svg.setAttribute('srcdoc', '<script>parent.escaped=true</script>');
            const host = document.createElement('div'); host.appendChild(svg);
            document.body.appendChild(host);
            return [first, second, plain.hasAttribute('srcdoc')];
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(values, serde_json::json!([73, 73, false]));
        assert_eq!(page.evaluate_script("escaped").unwrap(), serde_json::json!(false));
        assert_eq!(page.frames.len(), 1, "SVG iframe is not a browsing context");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_navigation_waits_until_after_the_microtask_checkpoint() {
        let mut page = import_map_test_page("srcdoc-task", "https://parent.test", "<body></body>");
        page.evaluate_script(r#"(() => {
            const f = document.createElement('iframe'); f.srcdoc = 'hello';
            document.body.appendChild(f);
            Promise.resolve().then(() => { globalThis.beforeNavigation = f.contentDocument.URL; });
            return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(page.evaluate_script("[beforeNavigation, document.querySelector('iframe').contentDocument.URL]").unwrap(),
            serde_json::json!(["about:blank", "about:srcdoc"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_is_ready_after_data_document_navigation() {
        let mut page = import_map_test_page("srcdoc-data-navigation", "https://parent.test", "<body></body>");
        page.navigate("data:text/html,%3Ciframe%20srcdoc%3D%22HELLO%22%3E%3C%2Fiframe%3E").await.unwrap();
        assert_eq!(page.evaluate_script("[document.querySelector('iframe').contentDocument.URL, document.querySelector('iframe').contentDocument.body.textContent]").unwrap(),
            serde_json::json!(["about:srcdoc", "HELLO"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_srcdoc_opaque_document_is_not_published_to_creator_objects() {
        let mut page = import_map_test_page("srcdoc-private-realm", "https://parent.test", "<body></body>");
        page.evaluate_script(r#"(() => {
            globalThis.seenOpaqueSource = false;
            const f = document.createElement('iframe'); f.id = 'opaque';
            f.setAttribute('sandbox', 'allow-scripts');
            f.srcdoc = '<p>private</p><script>parent.postMessage("loaded", "*")</script>';
            window.addEventListener('message', event => {
                seenOpaqueSource = event.data === 'loaded' && event.source === f.contentWindow;
            });
            document.body.appendChild(f); return 1;
        })()"#).unwrap();
        pump_srcdoc_frames(&mut page).await;
        assert_eq!(page.evaluate_script(r#"(() => {
            const f = document.getElementById('opaque');
            const references = [
                () => f._iframeDoc,
                () => f._iframeWin?.document,
                () => globalThis.__obscura_frameObjects[f._frameId]?.document,
                () => globalThis.__obscura_frameObjects[f._frameId]?.window?.document,
            ];
            const readable = references.map(getDocument => {
                try { return getDocument()?.body?.textContent ?? null; }
                catch (_) { return null; }
            });
            return [f.contentDocument === null, readable, seenOpaqueSource];
        })()"#).unwrap(), serde_json::json!([true, [null, null, null, null], true]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn iframe_load_waits_for_the_real_document_and_author_scripts() {
        let (base, _, _) = spawn_slow_frame_script_server().await;
        let mut page = import_map_test_page("frame-load-ready", &base, "<html><body></body></html>");
        page.add_preload_script("globalThis.__order = ['preload'];");
        page.js.as_mut().unwrap().evaluate(
            "(function(){ globalThis.loads = []; const frame = document.createElement('iframe'); \
             frame.onload = function(){ loads.push([typeof frame.contentDocument.appendChild, \
               frame.contentWindow.__childReady === true, frame.contentDocument.readyState]); }; \
             frame.src = '/child.html'; document.body.appendChild(frame); return 1; })()"
        ).unwrap();
        tokio::time::timeout(
            std::time::Duration::from_secs(2), page.js.as_mut().unwrap().run_event_loop(),
        ).await.unwrap().unwrap();
        assert_eq!(page.js.as_mut().unwrap().evaluate("loads").unwrap(), serde_json::json!([]),
            "the iframe fired load before its scripts could run");
        tokio::time::timeout(std::time::Duration::from_secs(2), page.advance_frames())
            .await.unwrap();
        assert_eq!(page.js.as_mut().unwrap().evaluate("loads").unwrap(),
            serde_json::json!([["function", true, "complete"]]));
        page.advance_frames().await;
        assert_eq!(page.js.as_mut().unwrap().evaluate("loads.length === 1").unwrap(), serde_json::json!(true));

        let script = "new Promise(resolve => { const frame = document.createElement('iframe'); \
            frame.onload = () => resolve([typeof frame.contentDocument.appendChild, \
                frame.contentWindow.__childReady === true]); \
            frame.src = '/child.html'; document.body.appendChild(frame); })";
        let evaluated = page.evaluate_for_cdp_with_timeout(script, true, true, 2_000).await.unwrap();
        assert_eq!(evaluated.value.unwrap(), serde_json::json!(["function", true]));
        let called = page.call_function_on_for_cdp_with_timeout(
            &format!("() => {script}"), None, &[], true, true, 2_000,
        ).await.unwrap();
        assert_eq!(called.value.unwrap(), serde_json::json!(["function", true]));
    }

    // Anti-bot scripts walk `parent` from a frame's window until they reach
    // their own; a chain that never gets there hangs the page for good.
    #[tokio::test(flavor = "current_thread")]
    async fn loaded_frame_parent_chain_reaches_the_page() {
        let (base, _, _) = spawn_slow_frame_script_server().await;
        let mut page = import_map_test_page("frame-parent", &base, "<html><body></body></html>");
        let script = "new Promise(resolve => { const frame = document.createElement('iframe'); \
            frame.onload = () => { const w = frame.contentWindow; \
                resolve([w.parent === window, w.top === window, \
                    w.parent.parent === window]); }; \
            frame.src = '/child.html'; document.body.appendChild(frame); })";
        let evaluated = page.evaluate_for_cdp_with_timeout(script, true, true, 2_000).await.unwrap();
        assert_eq!(evaluated.value.unwrap(), serde_json::json!([true, true, true]));
    }

    // Issue #1490: cross-origin child frame sees parent.frames.length,
    // parent.length, indexed access to self/siblings, and named access to siblings.
    #[tokio::test(flavor = "current_thread")]
    async fn cross_origin_child_frame_sees_parent_frames_and_named_siblings() {
        let (base, _, _) = spawn_slow_frame_script_server().await;
        let mut page = import_map_test_page(
            "cross-origin-frames",
            &base,
            "<html><body>\
                <iframe name=\"a\" src=\"/child.html?a\"></iframe>\
                <iframe name=\"b\" src=\"/child.html?b\"></iframe>\
            </body></html>",
        );
        let script = "new Promise(resolve => {\
            const iframes = document.querySelectorAll('iframe');\
            let loaded = 0;\
            const onLoaded = () => {\
                if (++loaded === 2) {\
                    const a = iframes[0].contentWindow;\
                    const b = iframes[1].contentWindow;\
                    resolve([\
                        a.parent.frames.length,\
                        a.parent.length,\
                        a.parent.frames[0] === a,\
                        a.parent.frames[1] === a,\
                        typeof a.parent.frames.b,\
                        b.parent.frames.length,\
                        b.parent.frames[1] === b,\
                        b.parent.frames.b === b,\
                    ]);\
                }\
            };\
            iframes[0].onload = onLoaded;\
            iframes[1].onload = onLoaded;\
        })";
        let evaluated = page.evaluate_for_cdp_with_timeout(script, true, true, 2_000).await.unwrap();
        assert_eq!(evaluated.value.unwrap(), serde_json::json!([
            2, 2, true, false, "object", 2, true, true
        ]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn cancelling_frame_script_fetch_keeps_all_siblings_resumable() {
        let (mut page, requests, slow_seen) =
            page_with_fetched_slow_frames("cancel-frame-scripts", 2).await;
        page.add_preload_script("globalThis.__order = ['preload'];");
        assert!(page.queue_pending_frames());
        let (attached_frame_id, expected_viewport) = match &page.pending_frame_work[0] {
            PendingFrameWork::Unattached(frame) => (
                frame.frame_id,
                (frame.viewport_width, frame.viewport_height),
            ),
            PendingFrameWork::Attached { .. } => panic!("frame work started before advancement"),
        };
        let slow_request = slow_seen.notified();
        let mut advance = Box::pin(page.advance_frames());
        tokio::select! {
            _ = advance.as_mut() => panic!("frame advance completed before the slow request"),
            _ = slow_request => {}
            _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {
                panic!("frame advance never reached the slow request")
            }
        }
        drop(advance);
        assert_eq!(page.frames.len(), 1);
        let observable = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(&format!(
                "(function(){{ \
                       const frame = Array.from(document.querySelectorAll('iframe')) \
                         .find(frame => frame._frameId === {attached_frame_id}); \
                       const w = frame.contentWindow; \
                       return {{ order: w.__order, width: w.innerWidth, height: w.innerHeight }}; \
                     }})()"
            ))
            .unwrap();
        assert_eq!(
            observable,
            serde_json::json!({
                "order": ["preload"],
                "width": expected_viewport.0,
                "height": expected_viewport.1,
            }),
            "the attached loading frame was observable before new-document initialization",
        );
        assert_eq!(page.pending_frame_work.len(), 2);
        assert!(matches!(
            page.pending_frame_work[0],
            PendingFrameWork::Attached { next_url: 1, .. }
        ));
        assert!(matches!(page.pending_frame_work[1], PendingFrameWork::Unattached(_)));

        tokio::time::timeout(std::time::Duration::from_secs(2), page.advance_frames())
            .await
            .expect("resumed frame script fetch timed out");
        assert!(page.pending_frame_work.is_empty());
        for index in 0..2 {
            assert_eq!(
                page.evaluate_in_frame(index, "globalThis.__childReady").unwrap(),
                serde_json::json!(true),
            );
            assert_eq!(
                page.evaluate_in_frame(index, "globalThis.__order").unwrap(),
                serde_json::json!(["preload", "first", "second"]),
            );
        }
        assert_eq!(
            requests
                .lock()
                .unwrap()
                .iter()
                .filter(|path| path.as_str() == "/first.js")
                .count(),
            2,
            "a completed source was fetched again after cancellation",
        );
        let script_order: Vec<String> = requests
            .lock()
            .unwrap()
            .iter()
            .filter(|path| path.ends_with(".js"))
            .cloned()
            .collect();
        assert_eq!(
            script_order,
            ["/first.js", "/slow.js", "/slow.js", "/first.js", "/slow.js"],
            "sibling script fetches were interleaved or reordered",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn detached_frame_discards_queued_script_work_before_fetching() {
        let (mut page, _, slow_seen) = page_with_fetched_slow_frames("detach-frame-scripts", 2).await;
        let slow_request = slow_seen.notified();
        let mut advance = Box::pin(page.advance_frames());
        tokio::select! {
            _ = advance.as_mut() => panic!("frame advance completed before the slow request"),
            _ = slow_request => {}
            _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {
                panic!("frame advance never reached the slow request")
            }
        }
        drop(advance);
        page.js
            .as_mut()
            .unwrap()
            .evaluate("(document.querySelector('iframe').remove(), 1)")
            .unwrap();

        page.release_detached_frames();
        assert!(page.frames.is_empty());
        assert_eq!(page.pending_frame_work.len(), 1);
        assert!(matches!(page.pending_frame_work[0], PendingFrameWork::Unattached(_)));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn detached_unattached_frame_is_discarded_before_realm_or_script_work() {
        let (mut page, requests, _) =
            page_with_fetched_slow_frames("detach-unattached-frame", 1).await;
        assert!(page.queue_pending_frames());
        assert!(page.frames.is_empty());
        assert!(matches!(page.pending_frame_work[0], PendingFrameWork::Unattached(_)));

        page.js
            .as_mut()
            .unwrap()
            .evaluate("(document.querySelector('iframe').remove(), 1)")
            .unwrap();
        page.release_detached_frames();

        assert!(page.frames.is_empty());
        assert!(page.pending_frame_work.is_empty());
        assert!(!requests
            .lock()
            .unwrap()
            .iter()
            .any(|path| path.ends_with(".js")));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn pruning_an_old_batch_does_not_strand_a_new_runtime_batch() {
        let (mut page, _, slow_seen) =
            page_with_fetched_slow_frames("replace-frame-work-batch", 1).await;
        page.add_preload_script("globalThis.__order = ['preload'];");
        let slow_request = slow_seen.notified();
        let mut advance = Box::pin(page.advance_frames());
        tokio::select! {
            _ = advance.as_mut() => panic!("frame advance completed before the slow request"),
            _ = slow_request => {}
            _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {
                panic!("frame advance never reached the slow request")
            }
        }
        drop(advance);
        assert_eq!(page.pending_frame_work.len(), 1);

        page.js
            .as_mut()
            .unwrap()
            .evaluate(
                "(function(){ const next = document.createElement('iframe'); next.src = '/child.html'; document.body.appendChild(next); return 1; })()",
            )
            .unwrap();
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            page.js.as_mut().unwrap().run_event_loop(),
        )
        .await
        .unwrap()
        .unwrap();
        page.js
            .as_mut()
            .unwrap()
            .evaluate("(document.querySelector('iframe').remove(), 1)")
            .unwrap();

        tokio::time::timeout(std::time::Duration::from_secs(1), page.advance_frames())
            .await
            .expect("new runtime batch was stranded after old batch cleanup");
        assert_eq!(page.frames.len(), 1);
        assert!(page.pending_frame_work.is_empty());
        assert_eq!(
            page.evaluate_in_frame(0, "globalThis.__childReady").unwrap(),
            serde_json::json!(true),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn runtime_teardown_discards_queued_frame_script_work() {
        let (mut suspended, _, _) = page_with_fetched_slow_frames("suspend-frame-scripts", 1).await;
        assert!(suspended.queue_pending_frames());
        suspended.suspend_js();
        assert!(suspended.frames.is_empty());
        assert!(suspended.pending_frame_work.is_empty());

        let (mut replaced, _, _) = page_with_fetched_slow_frames("replace-frame-scripts", 1).await;
        assert!(replaced.queue_pending_frames());
        replaced.navigate_blank();
        assert!(replaced.frames.is_empty());
        assert!(replaced.pending_frame_work.is_empty());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn detaching_a_parent_discards_its_queued_descendant_work() {
        let (base, requests) = spawn_nested_pending_frame_server().await;
        let mut page = import_map_test_page(
            "detach-nested-frame-work",
            &base,
            "<html><body><iframe src=/parent.html></iframe></body></html>",
        );
        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            page.js.as_mut().unwrap().run_event_loop(),
        )
        .await
        .unwrap()
        .unwrap();
        assert!(page.queue_pending_frames());
        assert!(page.run_next_pending_frame().await);
        assert_eq!(page.frames.len(), 1);

        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            page.js.as_mut().unwrap().run_event_loop(),
        )
        .await
        .unwrap()
        .unwrap();
        assert!(page.queue_pending_frames());
        assert_eq!(page.pending_frame_work.len(), 1);
        assert_eq!(
            page.pending_frame_work[0].parent_frame_id(),
            page.frames[0].frame_id(),
        );

        page.js
            .as_mut()
            .unwrap()
            .evaluate("(document.querySelector('iframe').remove(), 1)")
            .unwrap();
        page.release_detached_frames();
        assert!(page.frames.is_empty());
        assert!(page.pending_frame_work.is_empty());
        assert!(!requests
            .lock()
            .unwrap()
            .iter()
            .any(|path| path == "/grandchild-slow.js"));
    }

    /// A `FrameRealm` owns a `v8::Global` into the runtime's isolate, which is
    /// why `init_js` clears the frames before it drops the runtime. `suspend_js`
    /// drops the same runtime and has to honour the same order, otherwise the
    /// realms of a suspended page outlive the isolate they point into and the
    /// next navigation drops those handles against a different one.
    #[tokio::test]
    async fn suspending_the_runtime_releases_the_frame_realms_it_owns() {
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let base = spawn_shadow_frame_server().await;
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "suspend-frames".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("suspend-frames".to_string(), context);
        page.navigate(&format!("{base}plain.html")).await.unwrap();
        assert_eq!(
            page.frame_urls().len(),
            1,
            "the page never built its child frame, so this proves nothing"
        );

        page.suspend_js();
        assert!(
            page.frame_urls().is_empty(),
            "the frame realms outlived the isolate they hold a handle into: {:?}",
            page.frame_urls()
        );

        // The page still works afterwards: resuming rebuilds the runtime, and
        // navigating again builds the frames of the new document.
        page.resume_js();
        page.navigate(&format!("{base}plain.html")).await.unwrap();
        assert_eq!(page.frame_urls().len(), 1);
    }

    fn frame_page(name: &str) -> super::Page {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            name.to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        super::Page::new(name.to_string(), context)
    }

    /// An iframe inside a shadow root is absent from
    /// `document.querySelectorAll('iframe')` — real Chrome reports 0 for it too
    /// — so a liveness check built on that query reads a live frame as detached
    /// and tears it down. That is the shape a challenge widget uses, so the
    /// frame it depends on would be discarded moments after it loaded.
    #[tokio::test(flavor = "current_thread")]
    async fn a_frame_inside_a_shadow_root_survives_the_detach_sweep() {
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let base = spawn_shadow_frame_server().await;
        let mut page = frame_page("shadow-frame-survives");
        page.navigate(&base).await.unwrap();
        page.settle(1_000).await;

        assert_eq!(
            page.frames.len(),
            1,
            "the shadow-root frame was discarded as detached: {:?}",
            page.frame_urls()
        );
        // The realm is not merely alive; the page can still reach into it.
        let published = page
            .js
            .as_mut()
            .unwrap()
            .evaluate("Object.keys(globalThis.__obscura_frameObjects).length")
            .unwrap();
        assert_eq!(published.as_f64(), Some(1.0), "the page cannot reach the frame");
    }

    /// The sweep still does its job: an iframe removed from the document has
    /// its realm and every reference the page realm holds to it released.
    #[tokio::test(flavor = "current_thread")]
    async fn removing_an_iframe_releases_its_realm() {
        std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
        let base = spawn_shadow_frame_server().await;
        let mut page = frame_page("detached-frame-released");
        page.navigate(&format!("{base}plain.html")).await.unwrap();
        page.settle(1_000).await;
        assert_eq!(page.frames.len(), 1, "no frame to remove");

        page.js
            .as_mut()
            .unwrap()
            .evaluate("(document.querySelector('iframe').remove(), 1)")
            .unwrap();
        page.release_detached_frames();

        assert!(page.frames.is_empty(), "the detached realm was kept");
        let left = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(
                "Object.keys(globalThis.__obscura_frameObjects).length\
                 + Object.keys(globalThis.__obscura_frameWindows).length\
                 + Object.keys(globalThis.__obscura_frameElements).length",
            )
            .unwrap();
        assert_eq!(
            left.as_f64(),
            Some(0.0),
            "a reference to the discarded frame survived, so its context cannot be collected"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn suspend_resume_preserves_document_script_start_state() {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "script-state-suspend".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("script-state-suspend".to_string(), context);
        page.url = Some(url::Url::parse("http://example.com/suspend.html").unwrap());
        page.dom = Some(parse_html(
            r#"<html><head></head><body data-parser-runs="0" data-dynamic-runs="0" data-inert-runs="0">
            <script id="parser">
              document.body.setAttribute("data-parser-runs", String(Number(document.body.getAttribute("data-parser-runs")) + 1));
            </script>
            </body></html>"#,
        ));
        page.init_js();
        page.execute_scripts().await;

        let before = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(
                r#"
                var scriptStateSetup = true;
                const dynamic = document.createElement("script");
                dynamic.id = "dynamic";
                dynamic.textContent =
                  'document.body.setAttribute("data-dynamic-runs", String(Number(document.body.getAttribute("data-dynamic-runs")) + 1))';
                document.body.appendChild(dynamic);

                const holder = document.createElement("div");
                holder.innerHTML =
                  '<script id="inert">document.body.setAttribute("data-inert-runs", String(Number(document.body.getAttribute("data-inert-runs")) + 1))<\/script>';
                document.body.appendChild(holder.firstChild);
                return [
                  document.body.getAttribute("data-parser-runs"),
                  document.body.getAttribute("data-dynamic-runs"),
                  document.body.getAttribute("data-inert-runs")
                ];
                "#,
            )
            .unwrap();
        assert_eq!(before, serde_json::json!(["1", "1", "0"]));

        page.suspend_js();
        page.suspend_js();
        page.resume_js();

        let after = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(
                r#"
                var scriptStateCheck = true;
                for (const id of ["parser", "dynamic", "inert"]) {
                  const script = document.getElementById(id);
                  document.head.appendChild(script);
                  document.body.appendChild(script.cloneNode(true));
                }
                return [
                  document.body.getAttribute("data-parser-runs"),
                  document.body.getAttribute("data-dynamic-runs"),
                  document.body.getAttribute("data-inert-runs")
                ];
                "#,
            )
            .unwrap();
        assert_eq!(after, serde_json::json!(["1", "1", "0"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn suspend_resume_preserves_cdp_evaluation_handles() {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "cdp-handle-suspend".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("cdp-handle-suspend".to_string(), context);
        page.url = Some(url::Url::parse("http://example.com/").unwrap());
        page.dom = Some(parse_html("<html><body></body></html>"));
        page.init_js();

        let object = page
            .evaluate_for_cdp_with_timeout("({ increment(value) { return value + 1; } })", false, false, 1_000)
            .await
            .unwrap();
        let object_id = object.object_id.expect("remote evaluation returned no handle");

        page.suspend_js();
        page.resume_js();

        let result = page
            .call_function_on_for_cdp_with_timeout(
                "function(value) { return this.increment(value); }",
                Some(&object_id),
                &[serde_json::json!({ "value": 41 })],
                true,
                false,
                1_000,
            )
            .await
            .unwrap();
        assert_eq!(result.value, Some(serde_json::json!(42.0)));
    }

    #[test]
    fn new_document_does_not_inherit_suspended_script_ids() {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "script-state-navigation".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("script-state-navigation".to_string(), context);
        page.url = Some(url::Url::parse("http://example.com/old.html").unwrap());
        page.dom = Some(parse_html(
            "<html><head></head><body><script id=old></script></body></html>",
        ));
        page.init_js();
        page.js
            .as_mut()
            .unwrap()
            .evaluate(
                "var setup = true; const old = document.getElementById('old'); globalThis.__markParserScripts([old._nid]); return old._nid;",
            )
            .unwrap();
        page.suspend_js();

        page.url = Some(url::Url::parse("http://example.com/new.html").unwrap());
        page.dom = Some(parse_html(
            "<html><head></head><body data-fresh-runs=0><script id=fresh>document.body.setAttribute('data-fresh-runs', '1')</script></body></html>",
        ));
        page.init_js();
        let result = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(
                "var check = true; document.head.appendChild(document.getElementById('fresh')); return document.body.getAttribute('data-fresh-runs');",
            )
            .unwrap();
        assert_eq!(result, serde_json::json!("1"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn stale_release_cannot_delete_a_new_document_handle() {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "cdp-handle-navigation".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("cdp-handle-navigation".to_string(), context);
        page.url = Some(url::Url::parse("http://example.com/old.html").unwrap());
        page.dom = Some(parse_html("<html><body></body></html>"));
        page.init_js();
        let old_id = page
            .evaluate_for_cdp_with_timeout("({ marker: 1 })", false, false, 1_000)
            .await
            .unwrap()
            .object_id
            .unwrap();

        page.navigate_blank();
        page.init_js();
        let new_id = page
            .evaluate_for_cdp_with_timeout("({ marker: 2 })", false, false, 1_000)
            .await
            .unwrap()
            .object_id
            .unwrap();

        assert_ne!(old_id, new_id, "remote object IDs must not repeat across documents");
        page.release_object(&old_id);
        let result = page
            .call_function_on_for_cdp_with_timeout(
                "function() { return this.marker; }",
                Some(&new_id),
                &[],
                true,
                false,
                1_000,
            )
            .await
            .unwrap();
        assert_eq!(result.value, Some(serde_json::json!(2.0)));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn nomodule_classic_scripts_do_not_run() {
        let mut page = import_map_test_page(
            "nomodule",
            "http://127.0.0.1:9",
            r#"<html><head>
                <script>globalThis.__ran = ['classic'];</script>
                <script nomodule>globalThis.__ran.push('nomodule-inline');</script>
                <script type="module">globalThis.__ran.push('module');</script>
                <script nomodule type="text/javascript">globalThis.__ran.push('nomodule-typed');</script>
                <script>
                  const dynamic = document.createElement('script');
                  dynamic.setAttribute('nomodule', '');
                  dynamic.textContent = "globalThis.__ran.push('nomodule-dynamic')";
                  document.head.appendChild(dynamic);
                  const plain = document.createElement('script');
                  plain.textContent = "globalThis.__ran.push('dynamic')";
                  document.head.appendChild(plain);
                </script>
            </head><body></body></html>"#,
        );
        page.execute_scripts_with_module_budget(None).await;
        let ran = page.js.as_mut().unwrap().evaluate("globalThis.__ran").unwrap();
        assert_eq!(ran, serde_json::json!(["classic", "dynamic", "module"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn foreign_xmlns_attribute_has_no_prefix() {
        let mut page = import_map_test_page(
            "xmlns",
            "http://127.0.0.1:9",
            r#"<html><body><div id=w><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg></div></body></html>"#,
        );
        page.execute_scripts_with_module_budget(None).await;
        let result = page.js.as_mut().unwrap().evaluate(r#"(() => {
            const attr = document.querySelector('svg').attributes[0];
            return [attr.name, attr.localName, attr.prefix, attr.namespaceURI,
                document.getElementById('w').innerHTML,
                document.querySelector('svg').getAttribute('xmlns')];
        })()"#).unwrap();
        assert_eq!(result, serde_json::json!([
            "xmlns", "xmlns", null, "http://www.w3.org/2000/xmlns/",
            r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>"#,
            "http://www.w3.org/2000/svg"
        ]));
    }

    fn import_map_test_page(name: &str, base: &str, html: &str) -> super::Page {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            name.to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new(name.to_string(), context);
        page.url = Some(url::Url::parse(&format!("{}/app/index.html", base)).unwrap());
        page.dom = Some(parse_html(html));
        page.init_js();
        page
    }

    #[tokio::test(flavor = "current_thread")]
    async fn module_graph_and_evaluation_share_one_active_budget() {
        use std::io::{Read as _, Write as _};

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (request_tx, request_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut request = [0u8; 2048];
            let length = stream.read(&mut request).unwrap();
            let path = String::from_utf8_lossy(&request[..length])
                .lines()
                .next()
                .and_then(|line| line.split_ascii_whitespace().nth(1))
                .unwrap_or("/")
                .to_string();
            request_tx.send(path).unwrap();

            // Spend part of the module's allowance loading its graph. The
            // synchronous top-level work then fits in a freshly reset budget,
            // but cannot fit in the shared active load+evaluation budget.
            std::thread::sleep(std::time::Duration::from_millis(100));
            let body = "export const delayed = true;";
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len(),
            );
            stream.write_all(response.as_bytes()).unwrap();
        });

        let base = format!("http://{address}");
        let mut page = import_map_test_page(
            "shared-module-budget",
            &base,
            r#"<html><head><script type="module">
                import "./delayed.js";
                globalThis.__shared_deadline_started = true;
                const until = Date.now() + 300;
                while (Date.now() < until) {}
                globalThis.__shared_deadline_completed = true;
            </script></head><body></body></html>"#,
        );
        page.execute_scripts_with_module_budget(Some(350)).await;

        assert_eq!(
            request_rx
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/app/delayed.js",
        );
        let state = page
            .js
            .as_mut()
            .unwrap()
            .evaluate(
                "[globalThis.__shared_deadline_started === true, \
                  globalThis.__shared_deadline_completed === true]",
            )
            .unwrap();
        assert_eq!(
            state,
            serde_json::json!([true, false]),
            "evaluation must be terminated at the remaining shared deadline",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn queued_module_does_not_spend_its_budget_waiting_for_deferred_script() {
        use std::io::{Read as _, Write as _};

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            for _ in 0..2 {
                let (mut stream, _) = listener.accept().unwrap();
                let mut request = [0u8; 2048];
                let length = stream.read(&mut request).unwrap();
                let path = String::from_utf8_lossy(&request[..length])
                    .lines()
                    .next()
                    .and_then(|line| line.split_ascii_whitespace().nth(1))
                    .unwrap_or("/")
                    .to_string();
                let body = if path.ends_with("deferred.js") {
                    "const until=Date.now()+500;while(Date.now()<until){}"
                } else {
                    "export const ready=true;"
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len(),
                );
                stream.write_all(response.as_bytes()).unwrap();
            }
        });

        let base = format!("http://{address}");
        let mut page = import_map_test_page(
            "module-queue-budget",
            &base,
            r#"<html><head>
                <script defer src="./deferred.js"></script>
                <script type="module">
                    import { ready } from "./quick.js";
                    globalThis.__queued_module_completed = ready;
                </script>
            </head><body></body></html>"#,
        );
        page.execute_scripts_with_module_budget(Some(300)).await;

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__queued_module_completed === true")
                .unwrap(),
            serde_json::json!(true),
            "queue latency must not consume a module's active-work budget",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn parser_import_map_before_first_module_controls_resolution() {
        let (base, requests) = spawn_parser_import_map_server(1);
        let mut page = import_map_test_page(
            "import-map-order",
            &base,
            r#"<html><head>
            <script type="importmap">{"imports":{"ordered":"./before.js"}}</script>
            <script type="module">
                import { value } from "ordered";
                globalThis.__parser_import_map_value = value;
            </script>
            <script type="importmap">{"imports":{"ordered":"./after.js"}}</script>
        </head><body></body></html>"#,
        );
        page.execute_scripts().await;

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__parser_import_map_value")
                .unwrap(),
            serde_json::json!("before-first-module"),
        );
        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/app/before.js"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn later_import_map_adds_unrelated_rule_without_rebinding_resolved_rule() {
        let (base, requests) = spawn_parser_import_map_server(2);
        let mut page = import_map_test_page(
            "multiple-import-map-order",
            &base,
            r#"<html><head>
            <script type="importmap">{"imports":{"fixed":"./before.js"}}</script>
            <script type="module">
                import { value } from "fixed";
                globalThis.__first_map_value = value;
            </script>
            <script type="importmap">{"imports":{"fixed":"./after.js","later":"./later.js"}}</script>
            <script type="module">
                import { value as fixed } from "fixed";
                import { value as later } from "later";
                globalThis.__later_map_values = [fixed, later];
            </script>
        </head><body></body></html>"#,
        );
        page.execute_scripts().await;

        let js = page.js.as_mut().unwrap();
        assert_eq!(
            js.evaluate("globalThis.__first_map_value").unwrap(),
            serde_json::json!("before-first-module")
        );
        assert_eq!(
            js.evaluate("globalThis.__later_map_values").unwrap(),
            serde_json::json!(["before-first-module", "later-map"])
        );
        let paths = (0..2)
            .map(|_| {
                requests
                    .recv_timeout(std::time::Duration::from_secs(1))
                    .unwrap()
            })
            .collect::<Vec<_>>();
        assert!(paths.contains(&"/app/before.js".to_string()), "{paths:?}");
        assert!(paths.contains(&"/app/later.js".to_string()), "{paths:?}");
        assert!(!paths.contains(&"/app/after.js".to_string()), "{paths:?}");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn classic_dynamic_import_does_not_see_a_later_parser_import_map() {
        let (base, _requests) = spawn_parser_import_map_server(1);
        let mut page = import_map_test_page(
            "classic-before-import-map",
            &base,
            r#"<html><head>
            <script>
                import("too-late")
                    .then(() => globalThis.__classic_before_map = "resolved")
                    .catch(() => globalThis.__classic_before_map = "rejected");
            </script>
            <script type="importmap">{"imports":{"too-late":"./later.js"}}</script>
        </head><body></body></html>"#,
        );
        page.execute_scripts().await;
        page.settle_for_duration(500).await;
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__classic_before_map")
                .unwrap(),
            serde_json::json!("rejected"),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn ready_async_classic_script_runs_before_a_later_parser_import_map() {
        let (base, requests) = spawn_parser_import_map_server(2);
        let mut page = import_map_test_page(
            "async-classic-before-map",
            &base,
            r#"<html><head>
            <script async src="./async.js"></script>
            <script type="importmap">{"imports":{"too-late":"./later.js"}}</script>
        </head><body></body></html>"#,
        );
        page.execute_scripts().await;
        page.settle_for_duration(500).await;
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__async_before_map")
                .unwrap(),
            serde_json::json!("rejected"),
        );
        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/app/async.js"
        );
        assert!(requests.try_recv().is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn dynamically_inserted_import_map_controls_later_dynamic_import() {
        let (base, requests) = spawn_parser_import_map_server(1);
        let mut page = import_map_test_page(
            "dynamic-import-map",
            &base,
            r#"<html><head></head><body>
            <script>
                const map = document.createElement("script");
                map.type = "importmap";
                map.textContent = JSON.stringify({imports:{dynamicName:"./later.js"}});
                document.head.appendChild(map);
                import("dynamicName")
                    .then(module => globalThis.__dynamic_map_value = module.value)
                    .catch(error => globalThis.__dynamic_map_value = error.message);
            </script>
        </body></html>"#,
        );
        page.execute_scripts().await;
        page.settle_for_duration(500).await;
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__dynamic_map_value")
                .unwrap(),
            serde_json::json!("later-map"),
        );
        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/app/later.js"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn body_onload_content_attribute_reflects_to_window() {
        let mut page = import_map_test_page(
            "body-onload-content-attribute",
            "http://127.0.0.1:9",
            r#"<html><head></head><body onload="
                globalThis.__bodyOnloadCalls++;
                globalThis.__bodyOnloadThisIsWindow = this === window;
                globalThis.__bodyOnloadEventType = event && event.type;
                throw new Error('body onload failure');
            "><script>
                globalThis.__bodyOnloadCalls = 0;
                globalThis.__bodyOnloadThisIsWindow = false;
                globalThis.__bodyOnloadEventType = null;
                globalThis.__bodyOnloadReflectedBeforeLoad =
                    typeof document.body.onload === 'function' &&
                    document.body.onload === window.onload;
                globalThis.__windowLoadListenerCalls = 0;
                window.addEventListener('load', () => __windowLoadListenerCalls++);
            </script></body></html>"#,
        );

        page.execute_scripts().await;

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate(
                    r#"[
                        __bodyOnloadCalls,
                        __bodyOnloadThisIsWindow,
                        __bodyOnloadEventType,
                        __bodyOnloadReflectedBeforeLoad,
                        __windowLoadListenerCalls
                    ]"#,
                )
                .unwrap(),
            serde_json::json!([1, true, "load", true, 1]),
        );

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate(
                    r#"(function() {
                        const fromBody = function fromBody() {};
                        document.body.onload = fromBody;
                        const bodySetsWindow = window.onload === fromBody;
                        const fromWindow = function fromWindow() {};
                        window.onload = fromWindow;
                        const windowSetsBody = document.body.onload === fromWindow;
                        document.body.setAttribute('onload', 'globalThis.__bodyOnloadFromAttribute = true');
                        const attributeReplacesWindow = document.body.onload !== fromWindow
                            && document.body.onload === window.onload;
                        const reflected = window.onload;
                        const detachedBody = document.createElement('body');
                        detachedBody.onload = function detachedBodyOnload() {};
                        const detachedBodyStaysLocal = window.onload === reflected
                            && detachedBody.onload !== window.onload;
                        return bodySetsWindow && windowSetsBody && attributeReplacesWindow
                            && detachedBodyStaysLocal;
                    })()"#,
                )
                .unwrap(),
            serde_json::json!(true),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_timing_records_lifecycle_boundaries_not_future_events() {
        let mut page = import_map_test_page(
            "navigation-timing", "http://127.0.0.1:9", "<html><body></body></html>",
        );
        let html = r#"<!doctype html><script>
            globalThis.__navigationSamples = [];
            function sample() {
                const timing = performance.timing;
                __navigationSamples.push([
                    timing.navigationStart, timing.responseEnd,
                    timing.domContentLoadedEventStart, timing.domContentLoadedEventEnd,
                    timing.loadEventStart, timing.loadEventEnd
                ]);
            }
            sample();
            document.addEventListener('DOMContentLoaded', sample);
            window.addEventListener('load', sample);
        </script><p>Real navigation timing</p>"#;
        let encoded = base64::engine::general_purpose::STANDARD.encode(html);
        page.navigate(&format!("data:text/html;base64,{encoded}")).await.unwrap();
        let actual = page.js.as_mut().unwrap().evaluate(r#"(() => {
            const [parser, dom, load] = __navigationSamples;
            const final = performance.timing;
            return [
                parser[3] === 0 && parser[5] === 0,
                Number.isFinite(parser[1]) && parser[1] >= parser[0],
                dom[2] > 0 && dom[3] === 0,
                load[4] > 0 && load[5] === 0,
                final.domContentLoadedEventEnd >= dom[2],
                final.loadEventStart >= final.domContentLoadedEventEnd,
                final.loadEventEnd >= load[4],
                performance.timeOrigin >= final.navigationStart
                    && performance.timeOrigin < final.navigationStart + 1
            ];
        })()"#).unwrap();
        assert_eq!(actual, serde_json::json!([true, true, true, true, true, true, true, true]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_timing_survives_suspension_but_resets_on_navigation() {
        let mut page = import_map_test_page(
            "navigation-timing-retention", "http://127.0.0.1:9", "<html><body></body></html>",
        );
        page.navigate("data:text/html,<p>First</p>").await.unwrap();
        let expression = "[performance.timeOrigin, performance.timing.navigationStart, performance.timing.loadEventEnd]";
        let before = page.js.as_mut().unwrap().evaluate(expression).unwrap();
        assert!(before[2].as_f64().unwrap() > before[1].as_f64().unwrap());
        page.suspend_js();
        page.resume_js();
        assert_eq!(page.js.as_mut().unwrap().evaluate(expression).unwrap(), before);
        page.navigate("data:text/html,<p>Second</p>").await.unwrap();
        let after = page.js.as_mut().unwrap().evaluate(expression).unwrap();
        assert!(after[0].as_f64().unwrap() > before[0].as_f64().unwrap());
        assert!(after[1].as_f64().unwrap() >= before[2].as_f64().unwrap());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn navigation_timing_terminated_handlers_do_not_record_completion() {
        std::env::set_var("OBSCURA_SCRIPT_DEADLINE_MS", "250");
        let mut page = import_map_test_page(
            "terminated-navigation-timing", "http://127.0.0.1:9", "<html><body></body></html>",
        );
        for (event, field) in [
            ("DOMContentLoaded", "domContentLoadedEventEnd"), ("load", "loadEventEnd"),
        ] {
            let html = format!("<script>window.addEventListener('{event}',()=>{{globalThis.entered=true;while(true){{}}}});</script>");
            let encoded = base64::engine::general_purpose::STANDARD.encode(html);
            page.navigate(&format!("data:text/html;base64,{encoded}")).await.unwrap();
            assert_eq!(page.js.as_mut().unwrap().evaluate("globalThis.entered === true").unwrap(),
                serde_json::json!(true), "the {event} handler must actually have started");
            assert_eq!(page.js.as_mut().unwrap().evaluate(&format!("performance.timing.{field}")).unwrap().as_f64(),
                Some(0.0), "the terminated {event} handler never completed");
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn preload_dynamic_script_delays_load_but_not_dom_content_loaded() {
        let (base, requests) = spawn_delayed_classic_script_server(
            std::time::Duration::from_millis(150),
            "globalThis.__lifecycleOrder.push('dynamic-exec');",
        );
        let html = format!(
            r#"<html><head></head><body><script>
                globalThis.__lifecycleOrder = [];
                document.addEventListener('DOMContentLoaded', () =>
                    globalThis.__lifecycleOrder.push('dom-content-loaded'));
                window.onload = () =>
                    globalThis.__lifecycleOrder.push('window-onload');
                window.addEventListener('load', () =>
                    globalThis.__lifecycleOrder.push('window-load'));
                const script = document.createElement('script');
                script.src = '{base}/preload-dynamic.js';
                script.onload = () => globalThis.__lifecycleOrder.push('script-load');
                document.head.appendChild(script);
            </script></body></html>"#,
        );
        let mut page = import_map_test_page(
            "preload-dynamic-lifecycle",
            "http://127.0.0.1:9",
            &html,
        );

        page.execute_scripts().await;

        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/preload-dynamic.js",
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__lifecycleOrder")
                .unwrap(),
            serde_json::json!([
                "dom-content-loaded",
                "dynamic-exec",
                "script-load",
                "window-onload",
                "window-load"
            ]),
            "dynamic async scripts gate load, not DOMContentLoaded",
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate(
                    "globalThis.__lifecycleOrder.filter(value => value === 'window-onload').length",
                )
                .unwrap(),
            serde_json::json!(1.0),
            "window.onload must fire exactly once",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn document_close_waits_for_written_parser_blocking_scripts() {
        let (base, requests) = spawn_delayed_classic_script_server(
            std::time::Duration::from_millis(75),
            "globalThis.__closeOrder.push('external');",
        );
        let mut page = import_map_test_page(
            "document-close-parser-blocking", "http://127.0.0.1:9",
            "<html><body></body></html>",
        );
        page.js.as_mut().unwrap().execute_script("replacement", &format!(r#"
            document.open();
            globalThis.__closeOrder = [];
            document.addEventListener('DOMContentLoaded', () => __closeOrder.push('dom'), {{once:true}});
            window.addEventListener('load', () => __closeOrder.push('load'), {{once:true}});
            document.write('<script src="{base}/written.js"><\/script>');
            document.write('<script>globalThis.__closeOrder.push("inline");<\/script>');
            document.close();
        "#)).unwrap();
        page.settle(250).await;
        assert_eq!(requests.recv_timeout(std::time::Duration::from_secs(1)).unwrap(), "/written.js");
        assert_eq!(page.js.as_mut().unwrap().evaluate("__closeOrder").unwrap(),
            serde_json::json!(["external", "inline", "dom", "load"]));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn document_write_external_script_blocks_later_parser_scripts() {
        let (base, requests) = spawn_delayed_classic_script_server(
            std::time::Duration::from_millis(75),
            "globalThis.__writtenOrder.push('external'); globalThis.__writtenValue = 1;",
        );
        let html = format!(
            r#"<html><body>
                <script>globalThis.__writtenOrder = [];</script>
                <script>
                    document.write('<script src="{base}/written.js"><\/script>');
                    document.write('<script>globalThis.__writtenOrder.push("written:" + String(globalThis.__writtenValue));<\/script>');
                </script>
                <script>globalThis.__writtenOrder.push('after:' + String(globalThis.__writtenValue));</script>
            </body></html>"#,
        );
        let mut page = import_map_test_page(
            "document-write-parser-blocking",
            "http://127.0.0.1:9",
            &html,
        );

        page.execute_scripts().await;

        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/written.js",
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__writtenOrder")
                .unwrap(),
            serde_json::json!(["external", "written:1", "after:1"]),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn document_write_does_not_start_later_async_script_before_blocker() {
        let base = spawn_written_script_order_server();
        let html = format!(
            r#"<html><body><script>
                document.write('<script src="{base}/vendor.js"><\/script>');
                document.write('<script async src="{base}/app.js"><\/script>');
            </script><script>
                globalThis.__afterWriteSawVendor = globalThis.__vendorValue;
            </script></body></html>"#,
        );
        let mut page = import_map_test_page(
            "document-write-async-after-blocker",
            "http://127.0.0.1:9",
            &html,
        );

        page.execute_scripts().await;

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate(
                    "[globalThis.__afterWriteSawVendor, globalThis.__appSawVendor, globalThis.__appRequestFollowedVendor]"
                )
                .unwrap(),
            serde_json::json!([1, 1, true]),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn frame_discovery_bounds_a_microtask_storm() {
        let mut page = import_map_test_page(
            "frame-discovery-microtasks",
            "https://example.test/",
            "<html><body><iframe></iframe></body></html>",
        );
        page.js.as_mut().unwrap().execute_script(
            "frame-discovery-busy-task",
            "setTimeout(() => {\
               const end = Date.now() + 7000;\
               const spin = () => { if (Date.now() < end) Promise.resolve().then(spin); };\
               spin();\
             }, 0);",
        ).unwrap();

        let started = std::time::Instant::now();
        page.build_document_frames().await;
        assert!(started.elapsed() < std::time::Duration::from_millis(6500),
            "frame discovery must bound synchronous microtasks, not rely on a Tokio timeout: {:?}",
            started.elapsed());
        assert_eq!(page.js.as_mut().unwrap().evaluate("1 + 1").unwrap(), serde_json::json!(2.0),
            "the page must remain usable after an overrun");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn load_delaying_script_progresses_through_continuously_ready_timer_work() {
        let (base, requests) = spawn_delayed_classic_script_server(
            std::time::Duration::from_millis(75),
            "globalThis.__fairDynamicRan = true;",
        );
        let html = format!(
            r#"<html><head></head><body><script>
                globalThis.__schedulerTicks = 0;
                setInterval(() => globalThis.__schedulerTicks++, 0);
                const script = document.createElement('script');
                script.src = '{base}/fair-dynamic.js';
                script.onload = () => globalThis.__fairDynamicLoaded = true;
                document.head.appendChild(script);
            </script></body></html>"#,
        );
        let mut page = import_map_test_page(
            "load-delayer-scheduler-fairness",
            "http://127.0.0.1:9",
            &html,
        );
        let started = std::time::Instant::now();

        page.execute_scripts().await;

        let elapsed = started.elapsed();
        assert!(
            elapsed < std::time::Duration::from_millis(1500),
            "continuous ready work must not starve a load-delaying fetch; elapsed={elapsed:?}",
        );
        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/fair-dynamic.js",
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate(
                    "[globalThis.__fairDynamicRan === true, \
                     globalThis.__fairDynamicLoaded === true, \
                     globalThis.__schedulerTicks > 0]",
                )
                .unwrap(),
            serde_json::json!([true, true, true]),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn load_delaying_script_driver_respects_absolute_deadline() {
        let (base, requests) = spawn_delayed_classic_script_server(
            std::time::Duration::from_secs(1),
            "globalThis.__lateDynamicRan = true;",
        );
        let mut page = import_map_test_page(
            "load-delayer-deadline",
            "http://127.0.0.1:9",
            "<html><head></head><body></body></html>",
        );
        page.js
            .as_mut()
            .unwrap()
            .execute_script(
                "install-load-delayer",
                &format!(
                    "globalThis.__documentReadyState__ = 'loading'; \
                     const script = document.createElement('script'); \
                     script.src = '{base}/slow-dynamic.js'; \
                     document.head.appendChild(script);",
                ),
            )
            .unwrap();
        assert!(page
            .js
            .as_mut()
            .unwrap()
            .has_pending_load_delaying_scripts());
        let started = std::time::Instant::now();
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(125);

        let completed = super::Page::drive_load_delaying_scripts(
            page.js.as_mut().unwrap(),
            deadline,
        )
        .await;

        let elapsed = started.elapsed();
        assert!(!completed, "the delayed resource must exceed the deadline");
        assert!(
            elapsed >= std::time::Duration::from_millis(100)
                && elapsed < std::time::Duration::from_millis(500),
            "the driver must honor its absolute wall-clock bound; elapsed={elapsed:?}",
        );
        assert!(page
            .js
            .as_mut()
            .unwrap()
            .has_pending_load_delaying_scripts());
        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/slow-dynamic.js",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn load_delaying_script_driver_survives_a_page_script_exception() {
        // An exception from an async page callback reaches the pump as an
        // event-loop error, and the pump used to answer it by abandoning every
        // still-pending load-delaying script. The error is transient: measured
        // against this runtime, the tick carrying it fails and the following
        // ticks poll clean, so the pending script below was dropped over a
        // condition that had already cleared, and dropped silently, since the
        // script simply never arrives.
        //
        // The throw is deferred through a timer so it lands on a pump tick.
        // Thrown during the installing script's own microtask drain it would
        // clear the pending-script bookkeeping before the fetch even starts,
        // which is a different bug from the one under test here.
        let (base, requests) = spawn_delayed_classic_script_server(
            std::time::Duration::from_millis(150),
            "globalThis.__lateDynamicRan = true;",
        );
        let mut page = import_map_test_page(
            "load-delayer-throws",
            "http://127.0.0.1:9",
            "<html><head></head><body></body></html>",
        );
        page.js
            .as_mut()
            .unwrap()
            .execute_script(
                "install-load-delayer",
                &format!(
                    "globalThis.__documentReadyState__ = 'loading'; \
                     const script = document.createElement('script'); \
                     script.src = '{base}/slow-dynamic.js'; \
                     document.head.appendChild(script); \
                     setTimeout(() => {{ \
                         queueMicrotask(() => {{ throw new Error('page script boom'); }}); \
                     }}, 0);",
                ),
            )
            .unwrap();
        assert!(page
            .js
            .as_mut()
            .unwrap()
            .has_pending_load_delaying_scripts());

        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        let completed =
            super::Page::drive_load_delaying_scripts(page.js.as_mut().unwrap(), deadline).await;

        assert!(
            completed,
            "the throw must not end the pump while a script is still pending"
        );
        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/slow-dynamic.js",
            "the pending script must still be fetched"
        );
        assert!(!page
            .js
            .as_mut()
            .unwrap()
            .has_pending_load_delaying_scripts());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn post_load_dynamic_script_waits_only_when_caller_requests_settle() {
        let (base, requests) = spawn_delayed_classic_script_server(
            std::time::Duration::from_millis(400),
            "globalThis.__postLoadDynamicRan = true;",
        );
        let html = format!(
            r#"<html><body><script>
                window.addEventListener('load', () => {{
                    const script = document.createElement('script');
                    script.src = '{base}/post-load.js';
                    document.head.appendChild(script);
                }});
            </script></body></html>"#,
        );
        let mut page = import_map_test_page("post-load-dynamic-lifecycle", &base, &html);
        let started = std::time::Instant::now();

        page.execute_scripts().await;

        let navigation_elapsed = started.elapsed();
        assert!(
            navigation_elapsed < std::time::Duration::from_millis(300),
            "post-load enhancement must not extend navigation; elapsed={navigation_elapsed:?}",
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate(
                    "[document.readyState, globalThis.__postLoadDynamicRan === true, \
                     globalThis.__obscura_hasPendingDynamicScripts(), \
                     globalThis.__obscura_hasPendingLoadDelayingScripts()]",
                )
                .unwrap(),
            serde_json::json!(["complete", false, true, false]),
            "a script prepared by load is pending enhancement work, not a load blocker",
        );

        page.settle_for_duration(700).await;

        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/post-load.js",
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__postLoadDynamicRan === true")
                .unwrap(),
            serde_json::json!(true),
            "an explicit caller settle must drive post-load script completion",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn timer_hydration_runs_during_explicit_adaptive_settle_not_navigation_load() {
        let mut page = import_map_test_page(
            "timer-hydration-lifecycle",
            "http://example.com",
            r#"<html><body><main id="app">Server shell</main><script>
                window.addEventListener('load', () => {
                    setTimeout(() => {
                        document.getElementById('app').textContent = 'Hydrated app';
                        document.body.setAttribute('data-hydrated', 'true');
                    }, 80);
                });
            </script></body></html>"#,
        );

        page.execute_scripts().await;
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate(
                    "[document.readyState, document.body.getAttribute('data-hydrated'), \
                     document.getElementById('app').textContent]",
                )
                .unwrap(),
            serde_json::json!(["complete", null, "Server shell"]),
            "navigation load observes load semantics without inventing a timer settle",
        );

        page.settle(500).await;
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate(
                    "[document.body.getAttribute('data-hydrated'), \
                     document.getElementById('app').textContent]",
                )
                .unwrap(),
            serde_json::json!(["true", "Hydrated app"]),
            "the automation caller's adaptive settle must retain timer hydration",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn lazy_module_graph_is_post_load_work_until_caller_settles() {
        use std::io::{Read as _, Write as _};

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            for _ in 0..2 {
                let (mut stream, _) = listener.accept().unwrap();
                let mut request = [0u8; 2048];
                let length = stream.read(&mut request).unwrap();
                let request_text = String::from_utf8_lossy(&request[..length]);
                let path = request_text
                    .lines()
                    .next()
                    .and_then(|line| line.split_ascii_whitespace().nth(1))
                    .unwrap_or("/");
                let body = match path {
                    "/app/lazy.js" => {
                        "import { ready } from './lazy-child.js'; export { ready };"
                    }
                    "/app/lazy-child.js" => {
                        // Cross the lifecycle's 500ms fast-settle floor on a
                        // descendant edge. deno_core must propagate the lazy
                        // graph marker beyond its root for this to stay alive.
                        std::thread::sleep(std::time::Duration::from_millis(700));
                        "export const ready = 'lazy-ready';"
                    }
                    unexpected => panic!("unexpected module request: {unexpected}"),
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len(),
                );
                stream.write_all(response.as_bytes()).unwrap();
            }
        });

        let base = format!("http://{address}");
        let mut page = import_map_test_page(
            "lazy-module-readiness",
            &base,
            r#"<html><body><script>
                import("./lazy.js").then(module => {
                    document.body.setAttribute("data-lazy-state", module.ready);
                });
            </script></body></html>"#,
        );
        let started = std::time::Instant::now();
        page.execute_scripts().await;

        assert!(
            started.elapsed() < std::time::Duration::from_millis(500),
            "dynamic import() must not become an implicit navigation settle",
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("document.body.getAttribute('data-lazy-state')")
                .unwrap(),
            serde_json::Value::Null,
        );

        page.settle_for_duration(1_000).await;

        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("document.body.getAttribute('data-lazy-state')")
                .unwrap(),
            serde_json::json!("lazy-ready"),
            "an explicit caller settle must drive the lazy module graph",
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn ordinary_fetch_does_not_extend_dynamic_module_settle() {
        use std::io::{Read as _, Write as _};

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (accepted_tx, accepted_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let _ = accepted_tx.send(());
            let mut request = [0u8; 2048];
            let length = stream.read(&mut request).unwrap();
            assert!(String::from_utf8_lossy(&request[..length])
                .starts_with("GET /app/analytics "));
            std::thread::sleep(std::time::Duration::from_secs(2));
            let body = "{}";
            let response = format!(
                "HTTP/1.1 200 OK\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 base = format!("http://{address}");
        let html = format!(
            r#"<html><body><script>
                globalThis.__analyticsStarted = true;
                fetch("{base}/app/analytics").catch(error => {{
                    globalThis.__analyticsError = error.message;
                }});
            </script></body></html>"#,
        );
        let mut page = import_map_test_page(
            "ordinary-fetch-readiness",
            &base,
            &html,
        );
        let started = std::time::Instant::now();
        page.execute_scripts().await;
        let elapsed = started.elapsed();

        assert!(
            accepted_rx
                .recv_timeout(std::time::Duration::from_millis(100))
                .is_ok(),
            "ordinary fetch fixture must actually start its network request",
        );
        assert!(
            elapsed < std::time::Duration::from_millis(1_500),
            "ordinary fetch/XHR must retain the fast settle path; elapsed={elapsed:?}",
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__analyticsStarted")
                .unwrap(),
            serde_json::json!(true),
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn dynamic_import_map_uses_live_document_base_at_insertion() {
        let (base, requests) = spawn_parser_import_map_server(1);
        let mut page = import_map_test_page(
            "dynamic-import-map-base",
            &base,
            r#"<html><head><base href="/old/"></head><body>
            <script>
                document.querySelector("base").setAttribute("href", "/app/");
                const map = document.createElement("script");
                map.type = "importmap";
                map.textContent = JSON.stringify({imports:{liveBase:"./later.js"}});
                document.head.appendChild(map);
                import("liveBase")
                    .then(module => globalThis.__dynamic_map_base = module.value)
                    .catch(error => globalThis.__dynamic_map_base = error.message);
            </script>
        </body></html>"#,
        );
        page.execute_scripts().await;
        page.settle_for_duration(500).await;
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__dynamic_map_base")
                .unwrap(),
            serde_json::json!("later-map"),
        );
        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/app/later.js"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn later_base_element_does_not_rebase_an_earlier_import_map() {
        let (base, requests) = spawn_parser_import_map_server(1);
        let mut page = import_map_test_page(
            "temporal-import-map-base",
            &base,
            r#"<html><head>
            <script type="importmap">{"imports":{"fixed":"./before.js"}}</script>
            <base href="/assets/">
            <script type="module">
                import { value } from "fixed";
                globalThis.__temporal_base_value = value;
            </script>
        </head><body></body></html>"#,
        );
        page.execute_scripts().await;
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("globalThis.__temporal_base_value")
                .unwrap(),
            serde_json::json!("before-first-module"),
        );
        assert_eq!(
            requests
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "/app/before.js"
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn page_transport_prefetches_once_and_capture_reuses_the_bytes() {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let address = listener.local_addr().unwrap();
        let (seen_tx, seen_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
            while std::time::Instant::now() < deadline {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        // Accepted sockets can inherit the listener's nonblocking
                        // mode. Consume the complete request before responding,
                        // including fragmented headers.
                        stream.set_nonblocking(false).unwrap();
                        stream.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap();
                        let mut request = Vec::new();
                        let mut chunk = [0u8; 2048];
                        while !request.windows(4).any(|part| part == b"\r\n\r\n") {
                            let size = stream.read(&mut chunk).unwrap();
                            assert_ne!(size, 0, "request closed before its headers completed");
                            request.extend_from_slice(&chunk[..size]);
                            assert!(request.len() <= 16_384, "fixture request headers too large");
                        }
                        let first = String::from_utf8_lossy(&request)
                            .lines()
                            .next()
                            .unwrap_or_default()
                            .to_string();
                        seen_tx.send(first).unwrap();
                        let body = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="#f00"/></svg>"##;
                        let response = format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                            body.len()
                        );
                        stream.write_all(response.as_bytes()).unwrap();
                        stream.write_all(body).unwrap();
                    }
                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(std::time::Duration::from_millis(5));
                    }
                    Err(_) => break,
                }
            }
        });

        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "render-prefetch".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("render-prefetch".to_string(), context);
        page.set_viewport((100.0, 80.0));
        let page_url = format!("http://{address}/page");
        let asset_network_url = format!("http://{address}/asset.svg");
        let asset_url = format!("{asset_network_url}#icon");
        let dom = parse_html(&format!(
            r#"<html><body><img src="{asset_url}" style="width:20px;height:10px"></body></html>"#
        ));
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(dom);
        runtime.set_url(&page_url);
        runtime.set_viewport(100.0, 80.0);
        runtime.run_page_init();
        page.js = Some(runtime);
        page.url = Some(url::Url::parse(&page_url).unwrap());

        assert_eq!(page.prepare_screenshot_resources(1_000).await, 1);
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("document.querySelector('img').currentSrc")
                .unwrap(),
            serde_json::json!(asset_url),
            "cache/network fragment normalization must not alter currentSrc"
        );
        page.screenshot(page.viewport).expect("prefetched capture");
        assert!(seen_rx
            .recv_timeout(std::time::Duration::from_secs(1))
            .unwrap()
            .starts_with("GET /asset.svg "));
        assert!(
            seen_rx
                .recv_timeout(std::time::Duration::from_millis(200))
                .is_err(),
            "capture must not open a second synchronous renderer request"
        );
    }

    /// Serve one SVG for every request after `delay_ms`, for `seconds`.
    /// Reports each request line so tests can count transport requests.
    #[cfg(feature = "render")]
    fn spawn_delayed_svg_server(
        delay_ms: u64,
        seconds: u64,
    ) -> (std::net::SocketAddr, std::sync::mpsc::Receiver<String>) {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let address = listener.local_addr().unwrap();
        let (seen_tx, seen_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(seconds);
            while std::time::Instant::now() < deadline {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        let seen_tx = seen_tx.clone();
                        std::thread::spawn(move || {
                            // Accepted sockets inherit nonblocking mode on macOS.
                            // Wait for request bytes, but bound a stalled fixture client.
                            stream.set_nonblocking(false).unwrap();
                            stream
                                .set_read_timeout(Some(std::time::Duration::from_secs(1)))
                                .unwrap();
                            let mut request = [0u8; 2048];
                            let read = stream.read(&mut request).unwrap_or(0);
                            let first = String::from_utf8_lossy(&request[..read])
                                .lines()
                                .next()
                                .unwrap_or_default()
                                .to_string();
                            let _ = seen_tx.send(first);
                            std::thread::sleep(std::time::Duration::from_millis(delay_ms));
                            let body = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="#f00"/></svg>"##;
                            let response = format!(
                                "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                                body.len()
                            );
                            let _ = stream.write_all(response.as_bytes());
                            let _ = stream.write_all(body);
                        });
                    }
                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(std::time::Duration::from_millis(5));
                    }
                    Err(_) => break,
                }
            }
        });
        (address, seen_rx)
    }

    /// A page with a transport and one `<img>`, wired the way `init_js` does
    /// it (transport installed on the runtime before page script runs).
    #[cfg(feature = "render")]
    fn page_with_transport_and_image(id: &str, page_url: &str, image_url: &str) -> super::Page {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            id.to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new(id.to_string(), context);
        page.set_viewport((100.0, 80.0));
        let dom = parse_html(&format!(
            r#"<html><body><img id="i" src="{image_url}"></body></html>"#
        ));
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(dom);
        runtime.set_url(page_url);
        runtime.set_viewport(100.0, 80.0);
        runtime.set_http_client(page.http_client.clone());
        runtime.set_callbacks(page.callbacks.clone());
        runtime.run_page_init();
        page.js = Some(runtime);
        page.url = Some(url::Url::parse(page_url).unwrap());
        page
    }

    #[cfg(feature = "render")]
    #[test]
    fn render_resource_warmup_keeps_the_existing_candidate_bound() {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "warmup-bound".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("warmup-bound".to_string(), context);
        let mut html = String::from("<html><body>");
        for index in 0..(super::MAX_STYLESHEET_RESOURCES + 4) {
            html.push_str(&format!("<img src=\"https://assets.test/{index}.png\">"));
        }
        html.push_str("</body></html>");
        let runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(parse_html(&html));
        runtime.set_url("https://example.test/page");
        page.js = Some(runtime);
        page.url = Some(url::Url::parse("https://example.test/page").unwrap());

        let (loadable, rejected) = page.render_resource_candidates();
        assert_eq!(
            loadable.len() + rejected.len(),
            super::MAX_STYLESHEET_RESOURCES
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn cache_only_layout_never_blocks_on_a_slow_asset_and_late_bytes_update_geometry() {
        let (address, seen_rx) = spawn_delayed_svg_server(1_200, 8);
        let page_url = format!("http://{address}/page");
        let asset_url = format!("http://{address}/slow.svg");
        let mut page = page_with_transport_and_image("cache-only", &page_url, &asset_url);
        assert!(
            !page
                .js
                .as_ref()
                .unwrap()
                .render_resource_sync_loading_enabled(),
            "a page-owned runtime must not own a synchronous loader"
        );

        // Layout must answer from placeholder geometry immediately instead of
        // fetching the asset on the V8 thread.
        let started = std::time::Instant::now();
        let width = page
            .js
            .as_mut()
            .unwrap()
            .evaluate("document.getElementById('i').getBoundingClientRect().width")
            .unwrap();
        assert!(
            started.elapsed() < std::time::Duration::from_millis(600),
            "layout query took {:?} while the asset needs 1.2 s",
            started.elapsed()
        );
        // Chromium lays out a not-yet-loaded <img> without size attributes as
        // an empty box; the intrinsic width must not be known yet either way.
        assert!(width.is_number(), "layout answered: {width}");
        assert_ne!(width.as_f64(), Some(20.0), "intrinsic size is not known yet");
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("document.getElementById('i').naturalWidth")
                .unwrap()
                .as_f64(),
            Some(0.0)
        );

        // The miss is queued through the page transport exactly once (the
        // geometry read above already handed it to the transport).
        page.queue_pending_render_resources();
        assert!(page.has_pending_render_resources());
        page.queue_pending_render_resources();
        // The load runs on the runtime, so yield to it instead of blocking the
        // single test thread on the channel.
        let mut first_request = None;
        for _ in 0..40 {
            if let Ok(line) = seen_rx.try_recv() {
                first_request = Some(line);
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
        assert!(
            first_request
                .as_deref()
                .is_some_and(|line| line.starts_with("GET /slow.svg ")),
            "transport request expected, got {first_request:?}"
        );

        // Waiting for the transport (here via the capture warmup) applies the
        // late bytes: cache known, intrinsic size visible to script and layout.
        assert_eq!(page.prepare_screenshot_resources(5_000).await, 1);
        assert!(!page.has_pending_render_resources());
        assert!(page.js.as_ref().unwrap().render_image_resource_is_known(
            &asset_url,
            obscura_js::ImageRequestProfile::NoCorsInclude
        ));
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("document.getElementById('i').naturalWidth")
                .unwrap()
                .as_f64(),
            Some(20.0)
        );
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("document.getElementById('i').getBoundingClientRect().width")
                .unwrap()
                .as_f64(),
            Some(20.0)
        );
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        assert!(
            seen_rx.try_recv().is_err(),
            "neither layout nor capture may open a second request"
        );
    }

    #[cfg(feature = "render")]
    async fn assert_render_resource_blocklist(warmup: bool) {
        let (address, seen_rx) = spawn_delayed_svg_server(0, 5);
        let page_url = format!("http://{address}/page");
        let mut page = page_with_transport_and_body(
            "blocked",
            &page_url,
            &format!(r#"
                <img id="allowed" src="http://{address}/allowed.svg">
                <img src="http://{address}/blocked.svg">
                <div style="width:20px;height:20px;background-image:url(http://{address}/blocked-css.svg)"></div>
            "#),
        );
        page.set_blocked_urls(vec!["*blocked*".to_string()]);

        // Each caller gets a fresh page: a prior miss cached by the other
        // path would hide a missing blocklist check here.
        if warmup {
            assert_eq!(page.prepare_screenshot_resources(2_000).await, 1);
        } else {
            page.screenshot(page.viewport).expect("cache-only capture");
            page.queue_pending_render_resources();
            tokio::time::timeout(std::time::Duration::from_secs(2), async {
                while page.has_pending_render_resources() {
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                    page.drain_render_resource_results();
                }
            })
            .await
            .expect("renderer loads must finish");
        }
        assert_eq!(
            page.js
                .as_mut()
                .unwrap()
                .evaluate("document.getElementById('allowed').naturalWidth")
                .unwrap()
                .as_f64(),
            Some(20.0),
            "the allowed image must actually load"
        );
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        let requests: Vec<_> = seen_rx.try_iter().collect();
        assert_eq!(
            requests.len(), 1,
            "only the allowed image may reach the server: {requests:?}"
        );
        assert!(requests[0].starts_with("GET /allowed.svg "), "{requests:?}");
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn screenshot_warmup_honours_blocked_urls_on_a_fresh_page() {
        assert_render_resource_blocklist(true).await;
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn renderer_misses_honour_blocked_urls_on_a_fresh_page() {
        assert_render_resource_blocklist(false).await;
    }

    #[cfg(feature = "render")]
    #[test]
    fn suspended_page_screenshot_never_opens_resource_requests() {
        let (address, seen_rx) = spawn_delayed_svg_server(0, 5);
        let mut page = page_with_transport_and_image(
            "suspended-capture",
            &format!("http://{address}/page"),
            &format!("http://{address}/blocked.svg"),
        );
        page.set_blocked_urls(vec!["*blocked.svg".to_string()]);
        page.suspend_js();
        assert!(page.js.is_none());
        let png = page.screenshot(page.viewport).expect("DOM-only capture");
        assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
        assert!(
            seen_rx
                .recv_timeout(std::time::Duration::from_millis(100))
                .is_err(),
            "a suspended page must not use the synchronous renderer HTTP loader"
        );
    }

    /// Serve every request after `delay_ms` for `seconds`, tracking how many
    /// connections are open at once. Bodies are a 20x10 SVG.
    #[cfg(feature = "render")]
    fn spawn_counting_svg_server(
        delay_ms: u64,
        seconds: u64,
    ) -> (
        std::net::SocketAddr,
        std::sync::Arc<std::sync::atomic::AtomicUsize>,
        std::sync::Arc<std::sync::atomic::AtomicUsize>,
        std::sync::mpsc::Receiver<String>,
    ) {
        use std::io::{Read, Write};
        use std::sync::atomic::{AtomicUsize, Ordering};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let address = listener.local_addr().unwrap();
        let open = std::sync::Arc::new(AtomicUsize::new(0));
        let peak = std::sync::Arc::new(AtomicUsize::new(0));
        let (seen_tx, seen_rx) = std::sync::mpsc::channel();
        let (open_thread, peak_thread) = (open.clone(), peak.clone());
        std::thread::spawn(move || {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(seconds);
            while std::time::Instant::now() < deadline {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        let (open, peak, seen_tx) =
                            (open_thread.clone(), peak_thread.clone(), seen_tx.clone());
                        std::thread::spawn(move || {
                            // Accepted sockets inherit nonblocking mode on macOS.
                            // Wait for request bytes before sending the delayed body.
                            stream.set_nonblocking(false).unwrap();
                            stream
                                .set_read_timeout(Some(std::time::Duration::from_secs(1)))
                                .unwrap();
                            let now = open.fetch_add(1, Ordering::SeqCst) + 1;
                            peak.fetch_max(now, Ordering::SeqCst);
                            let mut request = [0u8; 4096];
                            let read = stream.read(&mut request).unwrap_or(0);
                            let first = String::from_utf8_lossy(&request[..read])
                                .lines()
                                .next()
                                .unwrap_or_default()
                                .to_string();
                            let _ = seen_tx.send(first);
                            std::thread::sleep(std::time::Duration::from_millis(delay_ms));
                            let body = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="#f00"/></svg>"##;
                            let response = format!(
                                "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                                body.len()
                            );
                            let _ = stream.write_all(response.as_bytes());
                            let _ = stream.write_all(body);
                            open.fetch_sub(1, Ordering::SeqCst);
                        });
                    }
                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(std::time::Duration::from_millis(2));
                    }
                    Err(_) => break,
                }
            }
        });
        (address, peak, open, seen_rx)
    }

    /// A page with a transport and arbitrary body markup, wired like `init_js`.
    #[cfg(feature = "render")]
    fn page_with_transport_and_body(id: &str, page_url: &str, body: &str) -> super::Page {
        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            id.to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new(id.to_string(), context);
        page.set_viewport((400.0, 300.0));
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(parse_html(&format!("<html><body>{body}</body></html>")));
        runtime.set_url(page_url);
        runtime.set_viewport(400.0, 300.0);
        runtime.set_http_client(page.http_client.clone());
        runtime.set_callbacks(page.callbacks.clone());
        runtime.run_page_init();
        page.js = Some(runtime);
        page.url = Some(url::Url::parse(page_url).unwrap());
        page
    }

    #[cfg(feature = "render")]
    #[test]
    fn inner_text_matches_rendered_text_semantics() {
        let mut page = page_with_transport_and_body(
            "inner-text",
            "http://example.test/",
            r#"<div id="visible">A<span style="display:none">B</span><span hidden>C</span><span style="visibility:hidden">H<span style="visibility:visible">D</span></span><script>window.__not_visible = true</script><style>.unused{}</style><p>E</p><br>F</div><div id="blocks">A<div>B</div>C</div><div id="paragraph">A<p>B</p></div><div id="br">A<br>B</div>"#,
        );
        let actual = page.evaluate(
            r#"(() => {
                const detached = document.createElement('div');
                detached.textContent = 'Q';
                const script = document.createElement('script');
                script.textContent = 'R';
                detached.append(script);
                const hidden = document.createElement('span');
                hidden.hidden = true;
                hidden.textContent = 'S';
                detached.append(hidden);

                const hiddenRoot = document.createElement('div');
                hiddenRoot.style.display = 'none';
                hiddenRoot.textContent = 'T';
                const hiddenScript = document.createElement('script');
                hiddenScript.textContent = 'U';
                hiddenRoot.append(hiddenScript);
                document.body.append(hiddenRoot);

                return [
                    visible.innerText,
                    blocks.innerText,
                    paragraph.innerText,
                    br.innerText,
                    detached.innerText,
                    hiddenRoot.innerText,
                ];
            })()"#,
        );
        assert_eq!(
            actual,
            serde_json::json!(["AD\n\nE\n\n\nF", "A\nB\nC", "A\n\nB", "A\nB", "QRS", "TU"]),
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn renderer_misses_cover_script_fonts_and_shadow_root_styles() {
        let (address, _peak, _open, seen_rx) = spawn_counting_svg_server(0, 6);
        let page_url = format!("http://{address}/page");
        let shadow_font = format!("http://{address}/shadow.ttf");
        let dynamic_font = format!("http://{address}/dynamic.ttf");
        let mut page = page_with_transport_and_body(
            "misses",
            &page_url,
            r#"<div id="host"></div><p id="dyn" style="font-family:Dyn">dynamic</p>"#,
        );
        {
            let js = page.js.as_mut().unwrap();
            // Neither source is visible to a light-DOM scan: one lives in a
            // shadow root, the other only in the script FontFaceSet.
            js.evaluate(&format!(
                r#"(function() {{
                    const root = document.getElementById('host').attachShadow({{mode: 'open'}});
                    root.innerHTML = '<style>@font-face {{ font-family: Shadow; src: url({shadow_font}); }}</style><p style="font-family:Shadow">shadow</p>';
                    document.fonts.add(new FontFace('Dyn', 'url({dynamic_font})'));
                    return true;
                }})()"#
            ))
            .unwrap();
            js.evaluate("document.getElementById('dyn').getBoundingClientRect().width")
                .unwrap();
        }
        page.queue_pending_render_resources();
        assert!(page.has_pending_render_resources(), "layout misses must name both fonts");
        page.prepare_screenshot_resources(3_000).await;
        assert!(!page.has_pending_render_resources());
        let mut lines = Vec::new();
        while let Ok(line) = seen_rx.try_recv() {
            lines.push(line);
        }
        assert!(
            lines.iter().any(|line| line.starts_with("GET /shadow.ttf ")),
            "shadow-root font must be requested through the transport: {lines:?}"
        );
        assert!(
            lines.iter().any(|line| line.starts_with("GET /dynamic.ttf ")),
            "script-registered font must be requested through the transport: {lines:?}"
        );
        let js = page.js.as_ref().unwrap();
        assert!(js.render_resource_is_known(&shadow_font));
        assert!(js.render_resource_is_known(&dynamic_font));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn late_bytes_apply_while_the_runtime_waits_for_a_promise() {
        let (address, _peak, _open, _seen_rx) = spawn_counting_svg_server(1_200, 6);
        let page_url = format!("http://{address}/page");
        let asset_url = format!("http://{address}/late.svg");
        let mut page = page_with_transport_and_image("promise-wait", &page_url, &asset_url);
        page.js
            .as_mut()
            .unwrap()
            .evaluate("document.getElementById('i').getBoundingClientRect().width")
            .unwrap();
        page.queue_pending_render_resources();
        assert!(page.has_pending_render_resources());

        // No protocol command and no page pump runs here: only the runtime's
        // own promise wait, as `Runtime.evaluate` with `awaitPromise` does.
        let started = std::time::Instant::now();
        let resolved = page
            .js
            .as_mut()
            .unwrap()
            .resolve_promises_until(
                |js| {
                    js.evaluate("document.getElementById('i').naturalWidth")
                        .ok()
                        .and_then(|value| value.as_f64())
                        == Some(20.0)
                },
                4_000,
            )
            .await;
        assert!(resolved, "the wait must observe the late bytes");
        assert!(
            started.elapsed() < std::time::Duration::from_millis(3_000),
            "observed after {:?}, expected shortly after the 1.2 s response",
            started.elapsed()
        );
    }

    /// Serves one fixed body with one content type after `delay_ms`, for
    /// `seconds`. Reports every request line.
    #[cfg(feature = "render")]
    fn spawn_delayed_bytes_server(
        delay_ms: u64,
        seconds: u64,
        content_type: &'static str,
        body: &'static [u8],
    ) -> (std::net::SocketAddr, std::sync::mpsc::Receiver<String>) {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let address = listener.local_addr().unwrap();
        let (seen_tx, seen_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(seconds);
            while std::time::Instant::now() < deadline {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        let seen_tx = seen_tx.clone();
                        std::thread::spawn(move || {
                            // Accepted sockets inherit nonblocking mode on macOS.
                            // Wait for request bytes, but bound a stalled fixture client.
                            stream.set_nonblocking(false).unwrap();
                            stream
                                .set_read_timeout(Some(std::time::Duration::from_secs(1)))
                                .unwrap();
                            let mut request = [0u8; 4096];
                            let read = stream.read(&mut request).unwrap_or(0);
                            let first = String::from_utf8_lossy(&request[..read])
                                .lines()
                                .next()
                                .unwrap_or_default()
                                .to_string();
                            let _ = seen_tx.send(first);
                            std::thread::sleep(std::time::Duration::from_millis(delay_ms));
                            let response = format!(
                                "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                                body.len()
                            );
                            let _ = stream.write_all(response.as_bytes());
                            let _ = stream.write_all(body);
                        });
                    }
                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(std::time::Duration::from_millis(5));
                    }
                    Err(_) => break,
                }
            }
        });
        (address, seen_rx)
    }

    /// DejaVu Sans is much wider than the renderer's default Liberation
    /// Sans, so a paragraph changes width once the served font applies.
    #[cfg(feature = "render")]
    static LATE_FONT: &[u8] = include_bytes!("../../obscura-render/assets/dejavu-sans.ttf");

    /// A single awaited CDP expression creates the miss (a script-added
    /// `@font-face`), and nothing but the runtime's own promise wait runs
    /// until it resolves: the load must be started and its bytes applied
    /// from inside that wait.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn a_miss_created_inside_an_awaited_expression_loads_during_the_wait() {
        let (address, seen_rx) = spawn_delayed_bytes_server(1_200, 8, "font/ttf", LATE_FONT);
        let page_url = format!("http://{address}/page");
        let font_url = format!("http://{address}/late.ttf");
        let mut page = page_with_transport_and_body(
            "await-miss",
            &page_url,
            r#"<p><span id="t" style="font-size:20px">MMMMMMMMMMMMMMMMMMMM</span></p>"#,
        );
        let expression = format!(
            r#"(async () => {{
                const style = document.createElement('style');
                style.textContent = '@font-face {{ font-family: Late; src: url({font_url}); }}';
                document.head.appendChild(style);
                const t = document.getElementById('t');
                t.style.fontFamily = 'Late';
                const before = t.getBoundingClientRect().width;
                const started = Date.now();
                while (Date.now() - started < 4000) {{
                    await new Promise(resolve => setTimeout(resolve, 20));
                    const now = t.getBoundingClientRect().width;
                    if (now !== before) return [before, now, Date.now() - started];
                }}
                return [before, t.getBoundingClientRect().width, -1];
            }})()"#
        );
        let started = std::time::Instant::now();
        let result = page
            .js
            .as_mut()
            .unwrap()
            .evaluate_for_cdp_with_timeout(&expression, true, true, 5_000)
            .await
            .unwrap();
        let elapsed = started.elapsed();
        let value = result.value.clone().unwrap_or_default();
        let samples = value.as_array().cloned().unwrap_or_default();
        assert_eq!(samples.len(), 3, "unexpected result {value}");
        let (before, after, at_ms) = (
            samples[0].as_f64().unwrap(),
            samples[1].as_f64().unwrap(),
            samples[2].as_f64().unwrap(),
        );
        let requests: Vec<String> = seen_rx.try_iter().collect();
        assert!(
            at_ms >= 0.0,
            "the font must apply inside the awaited expression (before {before}, after {after}, requests {requests:?}, pending {})",
            page.has_pending_render_resources()
        );
        assert!(after != before && after > 0.0, "before {before}, after {after}");
        assert!(
            elapsed < std::time::Duration::from_millis(3_500),
            "resolved after {elapsed:?}, expected shortly after the 1.2 s response"
        );
        assert!(
            requests.iter().any(|line| line.starts_with("GET /late.ttf ")),
            "the font is requested through the transport: {requests:?}"
        );
    }

    /// Timer-driven page script inside one fixed-length wait
    /// (`run_event_loop_for_duration`, the CLI `--wait` path) observes the
    /// bytes that land during the wait; no external evaluate samples for it.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn timers_inside_a_fixed_wait_observe_bytes_that_land_during_it() {
        let (address, _seen_rx) = spawn_delayed_bytes_server(1_200, 8, "font/ttf", LATE_FONT);
        let page_url = format!("http://{address}/page");
        let font_url = format!("http://{address}/late.ttf");
        let mut page = page_with_transport_and_body(
            "fixed-wait",
            &page_url,
            &format!(
                r#"<style>@font-face {{ font-family: Late; src: url({font_url}); }}</style>
                <p><span id="t" style="font-family:Late;font-size:20px">MMMMMMMMMMMMMMMMMMMM</span></p>"#
            ),
        );
        {
            let js = page.js.as_mut().unwrap();
            js.evaluate(
                r#"(function() {
                    const t = document.getElementById('t');
                    // The first geometry read records the miss; the timers
                    // only sample.
                    window.__samples = [[0, t.getBoundingClientRect().width]];
                    const started = Date.now();
                    setInterval(() => {
                        window.__samples.push([Date.now() - started, t.getBoundingClientRect().width]);
                    }, 20);
                    return true;
                })()"#,
            )
            .unwrap();
        }
        page.queue_pending_render_resources();
        assert!(page.has_pending_render_resources(), "the font is a layout miss");
        page.js
            .as_mut()
            .unwrap()
            .run_event_loop_for_duration(2_200)
            .await
            .unwrap();
        let samples = page
            .js
            .as_mut()
            .unwrap()
            .evaluate("JSON.stringify(window.__samples)")
            .unwrap();
        let samples: Vec<(f64, f64)> =
            serde_json::from_str(samples.as_str().unwrap_or("[]")).unwrap();
        assert!(samples.len() > 20, "timers must have run: {samples:?}");
        let first = samples[0].1;
        let changed = samples.iter().find(|(_, width)| *width != first);
        assert!(
            changed.is_some(),
            "a sample inside the wait must show the applied font, all {first}: {samples:?}"
        );
        let (at_ms, _) = changed.unwrap();
        assert!(*at_ms < 2_100.0, "observed only at {at_ms} ms: {samples:?}");
    }

    /// A load that finishes while the warmup scan runs (its wake is already
    /// past when the wait is registered) must be applied without waiting for
    /// the whole deadline. Two worker threads let the transport finish while
    /// the page is busy scanning a large document.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_load_that_finished_during_the_scan_does_not_cost_the_deadline() {
        let (address, _seen_rx) = spawn_delayed_bytes_server(1, 8, "font/ttf", LATE_FONT);
        let page_url = format!("http://{address}/page");
        let font_url = format!("http://{address}/quick.ttf");
        // A large document makes the warmup's light-DOM scan take tens of
        // milliseconds without any layout (nothing here reads geometry).
        let filler: String = (0..200_000).map(|_| "<i></i>").collect();
        let mut page = page_with_transport_and_body(
            "scan-race",
            &page_url,
            &format!(
                r#"<style>@font-face {{ font-family: Q; src: url({font_url}); }}</style>
                <span id="t" style="font-family:Q">t</span>{filler}"#
            ),
        );
        {
            // The font is already in flight (as after a layout miss); it
            // answers in about a millisecond, while the scan runs far longer.
            let js = page.js.as_mut().unwrap();
            let requests =
                js.mark_render_resources_in_flight(vec![(font_url.clone(), None, true)]);
            assert_eq!(js.start_render_resource_loads(requests), 1);
        }
        assert!(page.has_pending_render_resources());
        let started = std::time::Instant::now();
        let loaded = page.prepare_screenshot_resources(1_000).await;
        let elapsed = started.elapsed();
        assert_eq!(loaded, 1);
        assert!(!page.has_pending_render_resources());
        assert!(
            elapsed < std::time::Duration::from_millis(900),
            "prepare must return once the load is applied, took {elapsed:?}"
        );
    }

    /// Fetch.enable patterns are not renderer block rules. Playwright enables
    /// Fetch with `*` and filters routes client-side, so treating those patterns
    /// as blocked URLs would remove every image and font from the page.
    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn renderer_misses_ignore_fetch_interception_patterns() {
        let (address, _peak, _open, seen_rx) = spawn_counting_svg_server(0, 6);
        let page_url = format!("http://{address}/page");
        let intercepted = format!("http://{address}/intercepted.ttf");
        let plain = format!("http://{address}/plain.ttf");
        let mut page = page_with_transport_and_body(
            "interception",
            &page_url,
            &format!(
                r#"<style>@font-face {{ font-family: A; src: url({intercepted}); }}
                @font-face {{ font-family: B; src: url({plain}); }}</style>
                <p id="a" style="font-family:A">a</p><p id="b" style="font-family:B">b</p>"#
            ),
        );
        // What `Fetch.enable` does: patterns first, then enable.
        page.intercept_block_patterns = vec!["*intercepted.ttf".to_string()];
        page.enable_intercept(true);
        page.js
            .as_mut()
            .unwrap()
            .evaluate("document.getElementById('a').getBoundingClientRect().width + document.getElementById('b').getBoundingClientRect().width")
            .unwrap();
        page.queue_pending_render_resources();
        assert_eq!(page.prepare_screenshot_resources(3_000).await, 2);
        assert!(!page.has_pending_render_resources());
        let mut lines = Vec::new();
        while let Ok(line) = seen_rx.try_recv() {
            lines.push(line);
        }
        assert!(
            lines.iter().any(|line| line.starts_with("GET /intercepted.ttf ")),
            "Fetch patterns must not block static resources: {lines:?}"
        );
        assert!(
            lines.iter().any(|line| line.starts_with("GET /plain.ttf ")),
            "other URLs still load: {lines:?}"
        );
        let js = page.js.as_ref().unwrap();
        assert!(js.render_resource_is_known(&intercepted), "intercepted URL is settled as missing");
        assert!(js.render_resource_is_known(&plain));
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn render_resource_loads_share_one_page_wide_concurrency_limit() {
        let (address, peak, _open, _seen_rx) = spawn_counting_svg_server(300, 8);
        let page_url = format!("http://{address}/page");
        let mut page = page_with_transport_and_body("limit", &page_url, "");
        // Three groups added one after the other, each queued by its own
        // paint miss while the previous group's loads are still running: all
        // of them share one limiter. Every group must actually start loads.
        for group in 0..3 {
            let markup: String = (0..14)
                .map(|index| {
                    format!(
                        r#"<div style="width:10px;height:10px;background-image:url(http://{address}/bg{group}-{index}.svg)"></div>"#
                    )
                })
                .collect::<Vec<_>>()
                .join("");
            page.js
                .as_mut()
                .unwrap()
                .evaluate(&format!(
                    "document.body.insertAdjacentHTML('beforeend', {});",
                    serde_json::to_string(&markup).unwrap()
                ))
                .unwrap();
            page.screenshot(page.viewport);
            page.queue_pending_render_resources();
            assert!(
                page.has_pending_render_resources(),
                "group {group} must have started loads of its own"
            );
        }
        page.prepare_screenshot_resources(8_000).await;
        assert!(!page.has_pending_render_resources());
        // Earlier evaluate/queue steps may already have applied responses.
        // The final wait returns only its own drain count, not the page total.
        // Check every successful response across all three groups instead.
        assert_eq!(page.network_events.len(), 42);
        for group in 0..3 {
            for index in 0..14 {
                let url = format!("http://{address}/bg{group}-{index}.svg");
                let response = page.network_events.iter()
                    .find(|event| event.url == url)
                    .unwrap_or_else(|| panic!("missing applied response: {url}"));
                assert_eq!(response.status, 200, "{url}");
                assert!(response.body_size > 0, "empty response: {url}");
            }
        }
        let peak = peak.load(std::sync::atomic::Ordering::SeqCst);
        assert!(
            peak <= obscura_js::ops::RENDER_RESOURCE_CONCURRENCY,
            "at most {} concurrent transport requests, observed {peak}",
            obscura_js::ops::RENDER_RESOURCE_CONCURRENCY
        );
        assert!(peak >= 2, "loads still run concurrently, observed {peak}");
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn retired_document_loads_never_seed_the_next_document() {
        use std::io::{Read, Write};
        // First request: slow, 20x10. Every later request: immediate, 30x10.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let address = listener.local_addr().unwrap();
        let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let served = hits.clone();
        std::thread::spawn(move || {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8);
            while std::time::Instant::now() < deadline {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        let served = served.clone();
                        std::thread::spawn(move || {
                            // Accepted sockets can inherit the listener's nonblocking
                            // mode. Consume the complete request before responding or
                            // signalling A's readiness, including fragmented headers.
                            stream.set_nonblocking(false).unwrap();
                            stream.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap();
                            let mut request = Vec::new();
                            let mut chunk = [0u8; 2048];
                            while !request.windows(4).any(|part| part == b"\r\n\r\n") {
                                let size = stream.read(&mut chunk).unwrap();
                                assert_ne!(size, 0, "request closed before its headers completed");
                                request.extend_from_slice(&chunk[..size]);
                                assert!(request.len() <= 16_384, "fixture request headers too large");
                            }
                            let index = served.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                            let width = if index == 0 {
                                std::thread::sleep(std::time::Duration::from_millis(1_500));
                                20
                            } else {
                                30
                            };
                            let body = format!(
                                r##"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="10"><rect width="{width}" height="10" fill="#f00"/></svg>"##
                            );
                            let response = format!(
                                "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                                body.len()
                            );
                            let _ = stream.write_all(response.as_bytes());
                            let _ = stream.write_all(body.as_bytes());
                        });
                    }
                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(std::time::Duration::from_millis(5));
                    }
                    Err(_) => break,
                }
            }
        });

        let page_url = format!("http://{address}/page");
        let asset_url = format!("http://{address}/shared.svg");
        let mut page = page_with_transport_and_image("retire", &page_url, &asset_url);
        page.js
            .as_mut()
            .unwrap()
            .evaluate("document.getElementById('i').getBoundingClientRect().width")
            .unwrap();
        page.queue_pending_render_resources();
        assert!(page.has_pending_render_resources(), "document A requests the asset");
        // Let A's request reach the server before the document changes; the
        // slow response is still 1.5 s away.
        for _ in 0..40 {
            if hits.load(std::sync::atomic::Ordering::SeqCst) >= 1 {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 1, "A's request is in flight");

        // Document B replaces A before A's slow response arrives (what
        // navigate_single does before loading the next document).
        page.retire_render_resources();
        assert!(!page.has_pending_render_resources());
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(parse_html(&format!(
            r#"<html><body><img id="i" src="{asset_url}"></body></html>"#
        )));
        runtime.set_url(&page_url);
        runtime.set_viewport(100.0, 80.0);
        runtime.set_http_client(page.http_client.clone());
        runtime.set_callbacks(page.callbacks.clone());
        runtime.run_page_init();
        page.js = Some(runtime);
        page.js
            .as_mut()
            .unwrap()
            .evaluate("document.getElementById('i').getBoundingClientRect().width")
            .unwrap();
        page.queue_pending_render_resources();
        assert!(
            page.has_pending_render_resources(),
            "document B must request the same URL itself despite A's abandoned load"
        );
        assert_eq!(page.prepare_screenshot_resources(3_000).await, 1);
        let natural_width = |page: &mut super::Page| {
            page.js
                .as_mut()
                .unwrap()
                .evaluate("document.getElementById('i').naturalWidth")
                .unwrap()
                .as_f64()
        };
        assert_eq!(natural_width(&mut page), Some(30.0), "B sees its own response");

        // A's response would land now if its task were still alive; either
        // way it must not replace B's bytes.
        tokio::time::sleep(std::time::Duration::from_millis(1_800)).await;
        page.drain_render_resource_results();
        assert_eq!(natural_width(&mut page), Some(30.0), "A's stale response is discarded");
        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 2, "one request per document");
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn render_resource_deadline_does_not_negative_cache_cancelled_requests() {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            let Ok((mut stream, _)) = listener.accept() else {
                return;
            };
            let mut request = [0u8; 2048];
            let _ = stream.read(&mut request);
            std::thread::sleep(std::time::Duration::from_millis(100));
            let body = br##"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"/>"##;
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: image/svg+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                body.len()
            );
            let _ = stream.write_all(response.as_bytes());
            let _ = stream.write_all(body);
        });

        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "render-deadline".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("render-deadline".to_string(), context);
        page.set_viewport((100.0, 80.0));
        let page_url = format!("http://{address}/page");
        let asset_url = format!("http://{address}/slow.svg");
        let dom = parse_html(&format!(
            r#"<html><body><img src="{asset_url}"></body></html>"#
        ));
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(dom);
        runtime.set_url(&page_url);
        runtime.set_viewport(100.0, 80.0);
        runtime.run_page_init();
        page.js = Some(runtime);
        page.url = Some(url::Url::parse(&page_url).unwrap());

        assert_eq!(page.prepare_screenshot_resources(5).await, 0);
        assert!(
            !page
                .js
                .as_ref()
                .unwrap()
                .render_resource_is_known(&asset_url),
            "a deadline-cancelled request must remain retryable"
        );
    }

    #[cfg(feature = "render")]
    #[tokio::test(flavor = "current_thread")]
    async fn navigation_post_script_warmup_seeds_dynamic_images_and_fonts() {
        use std::io::{Read, Write};

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let address = listener.local_addr().unwrap();
        let (seen_tx, seen_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            for _ in 0..3 {
                let (mut stream, _) = listener.accept().unwrap();
                let mut request = [0u8; 4096];
                let read = stream.read(&mut request).unwrap_or(0);
                let path = String::from_utf8_lossy(&request[..read])
                    .lines()
                    .next()
                    .and_then(|line| line.split_ascii_whitespace().nth(1))
                    .unwrap_or("/")
                    .to_string();
                seen_tx.send(path.clone()).unwrap();
                let (content_type, body): (&str, &[u8]) = match path.as_str() {
                    "/page" => (
                        "text/html",
                        br#"<!doctype html><html><head></head><body><script>
                            const image = document.createElement('img');
                            image.src = '/dynamic.svg';
                            document.body.appendChild(image);
                            const style = document.createElement('style');
                            style.textContent = "@font-face{font-family:Dynamic;src:url('/dynamic.woff2')}body{font-family:Dynamic}";
                            document.head.appendChild(style);
                        </script></body></html>"#,
                    ),
                    "/dynamic.svg" => (
                        "image/svg+xml",
                        br#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"><rect width="20" height="10" fill="red"/></svg>"#,
                    ),
                    "/dynamic.woff2" => ("font/woff2", b"not-a-real-font"),
                    _ => ("text/plain", b"not found"),
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                stream.write_all(response.as_bytes()).unwrap();
                stream.write_all(body).unwrap();
            }
        });

        let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
            "dynamic-render-warmup".to_string(),
            None,
            false,
            None,
            None,
            true,
        ));
        let mut page = super::Page::new("dynamic-render-warmup".to_string(), context);
        let page_url = format!("http://{address}/page");
        page.navigate(&page_url).await.unwrap();

        let mut paths = (0..3)
            .map(|_| seen_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap())
            .collect::<Vec<_>>();
        paths.sort();
        assert_eq!(
            paths,
            vec![
                "/dynamic.svg".to_string(),
                "/dynamic.woff2".to_string(),
                "/page".to_string(),
            ]
        );
        let js = page.js.as_ref().expect("navigation runtime");
        assert!(js.render_resource_is_known(&format!(
            "http://{address}/dynamic.svg"
        )));
        assert!(js.render_resource_is_known(&format!(
            "http://{address}/dynamic.woff2"
        )));
    }

    #[cfg(feature = "render")]
    #[test]
    fn page_screenshot_uses_the_live_window_scroll_offset() {
        let context = std::sync::Arc::new(crate::BrowserContext::new("scroll-test".to_string()));
        let mut page = super::Page::new("scroll-page".to_string(), context);
        page.set_viewport((100.0, 80.0));

        let dom = parse_html(
            r#"<html style="margin:0"><body style="margin:0">
                <div style="height:80px;background:#ff0000"></div>
                <div id="second" style="height:80px;background:#0000ff"></div>
                <div style="position:fixed;left:0;top:0;width:20px;height:20px;background:#00ff00"></div>
            </body></html>"#,
        );
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(dom);
        runtime.set_url("https://example.test/scroll");
        runtime.set_viewport(100.0, 80.0);
        runtime.run_page_init();
        page.js = Some(runtime);
        page.url = Some(url::Url::parse("https://example.test/scroll").unwrap());

        let before = page.screenshot(page.viewport).expect("top screenshot");
        assert_eq!(
            page.evaluate(
                "return (document.getElementById('second').scrollIntoView(), window.scrollY)"
            )
            .as_f64(),
            Some(80.0)
        );
        let after = page.screenshot(page.viewport).expect("scrolled screenshot");

        assert_ne!(
            before, after,
            "Page screenshot must paint the scrolled viewport"
        );
        assert_eq!(
            page.js.as_ref().expect("runtime").scroll_offset(),
            (0.0, 80.0)
        );
    }

    #[test]
    fn truncate_never_splits_a_multibyte_char() {
        // A caller-supplied expression whose byte 80 lands inside a multi-byte
        // char would make `&expression[..80]` panic; the helper truncates safely.
        let s = format!("{}€tail", "a".repeat(79));
        assert!(!s.is_char_boundary(80), "setup: byte 80 splits the € char");
        let t = truncate_on_char_boundary(&s, 80);
        assert!(s.starts_with(t));
        assert_eq!(t.len(), 79, "should stop right before the € char");
        assert_eq!(truncate_on_char_boundary("short", 80), "short");
    }

    #[test]
    fn parse_import_url_extracts_url_forms() {
        for (source, expected_url) in [
            (" url(\"basic.css\")", "basic.css"),
            (" url(basic.css)", "basic.css"),
            (" \"basic.css\"", "basic.css"),
            (" 'theme.css'", "theme.css"),
            (" URL('x.css')", "x.css"),
        ] {
            assert_eq!(
                parse_import_url(source),
                Some(StylesheetImport {
                    url: expected_url.to_string(),
                    media: None,
                })
            );
        }
    }

    #[test]
    fn parse_import_url_accepts_non_ascii_without_url_function() {
        // A statement whose fourth byte falls inside a multi-byte character
        // must not be sliced there.
        assert_eq!(
            parse_import_url(" \"Guía.css\""),
            Some(StylesheetImport { url: "Guía.css".to_string(), media: None })
        );
        assert_eq!(parse_import_url("aí;"), None);
        assert_eq!(parse_import_url("é"), None);
    }

    #[test]
    fn parse_import_url_preserves_print_and_color_scheme_media() {
        assert_eq!(
            parse_import_url("url(\"p.css\") print"),
            Some(StylesheetImport {
                url: "p.css".to_string(),
                media: Some("print".to_string()),
            })
        );
        assert_eq!(
            parse_import_url("url(\"d.css\") (prefers-color-scheme: dark)"),
            Some(StylesheetImport {
                url: "d.css".to_string(),
                media: Some("(prefers-color-scheme: dark)".to_string()),
            })
        );
        assert_eq!(
            parse_import_url("url(\"a.css\") print, screen"),
            Some(StylesheetImport {
                url: "a.css".to_string(),
                media: Some("print, screen".to_string()),
            })
        );
    }

    #[test]
    fn split_css_imports_pulls_imports_and_strips_them() {
        let css = "@import url(\"basic.css\");\nbody { color: red; }";
        let (imports, stripped) = split_css_imports(css);
        assert_eq!(
            imports,
            vec![StylesheetImport {
                url: "basic.css".to_string(),
                media: None,
            }]
        );
        assert!(!stripped.contains("@import"));
        assert!(stripped.contains("body { color: red; }"));
    }

    #[test]
    fn split_css_imports_leaves_import_free_css_untouched() {
        let css = "body { color: red; }";
        let (imports, stripped) = split_css_imports(css);
        assert!(imports.is_empty());
        assert_eq!(stripped, css);
    }

    #[test]
    fn materialized_import_graph_retains_print_condition_and_import_base() {
        let root_url = url::Url::parse("https://example.test/css/root.css").unwrap();
        let print_url = root_url.join("print/print.css").unwrap();
        let mut sheets = std::collections::HashMap::new();
        sheets.insert(
            root_url.to_string(),
            LoadedStylesheet {
                response_url: root_url.clone(),
                imports: vec![StylesheetImport {
                    url: "print/print.css".to_string(),
                    media: Some("print".to_string()),
                }],
                rules: ".root{color:red}".to_string(),
            },
        );
        sheets.insert(
            print_url.to_string(),
            LoadedStylesheet {
                response_url: print_url.clone(),
                imports: Vec::new(),
                rules: ".print{background:url(../mark.svg)}".to_string(),
            },
        );
        let aliases = std::collections::HashMap::from([
            (root_url.to_string(), root_url.to_string()),
            (print_url.to_string(), print_url.to_string()),
        ]);
        let materialized = materialize_stylesheet_graph(
            root_url.as_str(),
            &sheets,
            &aliases,
            &mut std::collections::HashSet::new(),
        )
        .expect("materialized graph");

        assert!(materialized.starts_with("@media print {\n"));
        assert!(materialized.contains(
            r#".print{background:url("https://example.test/css/mark.svg")}"#
        ));
        assert!(materialized.ends_with(".root{color:red}"));
    }

    #[test]
    fn cross_origin_import_taints_the_materialized_stylesheet_cssom() {
        let document_url = url::Url::parse("https://example.test/page").unwrap();
        let root_url = url::Url::parse("https://example.test/root.css").unwrap();
        let imported_url = url::Url::parse("https://cdn.test/imported.css").unwrap();
        let sheets = std::collections::HashMap::from([
            (
                root_url.to_string(),
                LoadedStylesheet {
                    response_url: root_url.clone(),
                    imports: vec![StylesheetImport {
                        url: imported_url.to_string(),
                        media: None,
                    }],
                    rules: String::new(),
                },
            ),
            (
                imported_url.to_string(),
                LoadedStylesheet {
                    response_url: imported_url.clone(),
                    imports: Vec::new(),
                    rules: ".secret{}".to_string(),
                },
            ),
        ]);
        let aliases = std::collections::HashMap::from([
            (root_url.to_string(), root_url.to_string()),
            (imported_url.to_string(), imported_url.to_string()),
        ]);

        assert!(!stylesheet_graph_is_origin_clean(
            root_url.as_str(),
            &sheets,
            &aliases,
            &mut std::collections::HashSet::new(),
            &document_url,
        ));
    }

    #[test]
    fn stylesheet_asset_urls_keep_the_importing_sheets_base() {
        let base = url::Url::parse("https://example.com/css/theme/app.css").unwrap();
        let css = r#"
            .hero { background:url("../img/hero.png") }
            .icon { mask-image:URL('./icons/mark.svg') }
            .data { background:url("data:image/svg+xml,<svg></svg>") }
            .fragment { mask:url(#shape) }
            .copy::before { content:"url(../not-an-asset.png)" }
            /* url(../not-an-asset-either.png) */
        "#;
        let rebased = rebase_css_urls(css, &base);

        assert!(rebased.contains(r#"url("https://example.com/css/img/hero.png")"#));
        assert!(rebased.contains(r#"url("https://example.com/css/theme/icons/mark.svg")"#));
        assert!(rebased.contains(r#"url("data:image/svg+xml,<svg></svg>")"#));
        assert!(rebased.contains("url(#shape)"));
        assert!(rebased.contains(r#"content:"url(../not-an-asset.png)""#));
        assert!(rebased.contains("/* url(../not-an-asset-either.png) */"));
    }

    #[test]
    fn stylesheet_rel_token_selector_includes_preloaded_stylesheets() {
        let dom = parse_html(
            r#"<link rel="preload stylesheet" href="app.css">
               <link rel="preload" href="font.woff2">"#,
        );
        let links = dom
            .query_selector_all(r#"link[rel~="stylesheet"]"#)
            .expect("valid selector");
        assert_eq!(links.len(), 1);
        assert_eq!(
            dom.get_node(links[0])
                .and_then(|node| node.get_attribute("href").map(str::to_owned)),
            Some("app.css".to_string())
        );
    }

    #[test]
    fn media_gated_stylesheets_are_fetched_but_disabled_sheets_are_not() {
        let dom = parse_html(
            r#"<link rel="stylesheet" href="screen.css">
               <link rel="stylesheet" href="async.css" media="print"
                     onload="this.media='all'">
               <link rel="stylesheet" href="dark.css"
                     media="(prefers-color-scheme: dark)">
               <link rel="stylesheet" href="disabled.css" disabled>"#,
        );

        let requests = linked_stylesheet_requests(&dom);

        // Media-gated sheets still load; the disabled sheet is skipped. Order
        // follows document order.
        let hrefs: Vec<&str> = requests.iter().map(|(_, href)| href.as_str()).collect();
        assert_eq!(hrefs, vec!["screen.css", "async.css", "dark.css"]);

        // Each request carries the link's node id (#1044), so it must resolve
        // back to that exact node, not a query-order position.
        for (nid, href) in &requests {
            let node = dom
                .get_node(obscura_dom::NodeId::new(*nid as u32))
                .expect("node id resolves to a live node");
            assert_eq!(node.get_attribute("href"), Some(href.as_str()));
        }
    }

    #[test]
    fn print_media_onload_can_activate_a_fetched_stylesheet() {
        let dom = parse_html(
            r#"<html><head>
                <link id="async" rel="stylesheet" href="async.css" media="print"
                      onload="this.media='all';this.setAttribute('data-loaded','yes')">
            </head><body></body></html>"#,
        );
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(dom);
        runtime.run_page_init();
        install_linked_stylesheet(
            &mut runtime,
            0,
            ".target{color:red}",
            true,
            "https://example.com/style.css",
        );

        let state = runtime
            .with_dom(|dom| {
                let link = dom
                    .query_selector("#async")
                    .expect("valid selector")
                    .expect("async link");
                (
                    dom.get_node(link)
                        .and_then(|node| node.get_attribute("data-loaded").map(str::to_owned)),
                    dom.external_stylesheet(link)
                        .and_then(|sheet| sheet.sources.first().map(ToString::to_string)),
                )
            })
            .expect("live DOM");

        assert_eq!(
            state.0.as_deref(),
            Some("yes"),
            "link load handler must run"
        );
        assert_eq!(
            state.1.as_deref(),
            Some(".target{color:red}"),
            "the handler's `this.media = 'all'` must activate the sheet"
        );
    }

    #[test]
    fn true_print_stylesheet_loads_and_remains_media_gated() {
        let dom = parse_html(
            r#"<html><head>
                <link id="print" rel="stylesheet" href="print.css" media="print"
                      onload="this.setAttribute('data-loaded','yes')">
            </head><body></body></html>"#,
        );
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(dom);
        runtime.run_page_init();
        install_linked_stylesheet(
            &mut runtime,
            0,
            "body{display:none}",
            true,
            "https://example.com/style.css",
        );

        let state = runtime
            .with_dom(|dom| {
                let link = dom
                    .query_selector("#print")
                    .expect("valid selector")
                    .expect("print link");
                (
                    dom.get_node(link)
                        .and_then(|node| node.get_attribute("data-loaded").map(str::to_owned)),
                    dom.get_node(link)
                        .and_then(|node| node.get_attribute("media").map(str::to_owned)),
                )
            })
            .expect("live DOM");

        assert_eq!(
            state.0.as_deref(),
            Some("yes"),
            "print link still fires load"
        );
        assert_eq!(
            state.1.as_deref(),
            Some("print"),
            "the fetched sheet must remain available for PDF print selection"
        );
    }

    #[test]
    fn materialized_linked_stylesheets_expose_link_owned_cssom_with_origin_security() {
        let dom = parse_html(
            r#"<html><head>
                <link id="same" rel="stylesheet" href="/assets/app.css" title="app">
                <style id="inline">.inline { color: green }</style>
                <link id="cross" rel="stylesheet" href="https://cdn.example.test/theme.css">
            </head><body></body></html>"#,
        );
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(dom);
        runtime.set_url("https://example.test/products/widget");
        runtime.run_page_init();
        install_linked_stylesheet(
            &mut runtime,
            0,
            ".app { color: red } .wide { width: 20px }",
            true,
            "https://example.test/assets/app.css",
        );
        install_linked_stylesheet(
            &mut runtime,
            1,
            ".secret { color: purple }",
            false,
            "https://cdn.example.test/theme.css",
        );

        let result = runtime
            .evaluate(
                r#"
                (() => {
                    const list = document.styleSheets;
                    const same = document.getElementById('same');
                    const inline = document.getElementById('inline');
                    const cross = document.getElementById('cross');
                    const sameSheet = same.sheet;
                    const sameRules = sameSheet.cssRules;
                    const crossSheet = cross.sheet;
                    // Public-looking implementation fields must not be able to
                    // bypass the closure-private origin decision.
                    crossSheet._originClean = true;
                    crossSheet._sourceText = '.forged { color: red }';
                    const security = [];
                    for (const operation of [
                        () => crossSheet.cssRules,
                        () => crossSheet.rules,
                        () => crossSheet.insertRule('.leak {}', 0),
                        () => crossSheet.deleteRule(0),
                        () => crossSheet.replaceSync('.leak {}'),
                    ]) {
                        try { operation(); security.push('missing'); }
                        catch (error) { security.push(error && error.name); }
                    }
                    sameSheet.insertRule('.added { height: 9px }', sameRules.length);
                    return {
                        stableList: list === document.styleSheets,
                        length: list.length,
                        order: [list[0] === sameSheet, list[1] === inline.sheet,
                                list[2] === crossSheet],
                        sameIdentity: same.sheet === sameSheet,
                        owner: sameSheet.ownerNode === same,
                        href: sameSheet.href,
                        title: sameSheet.title,
                        rulesIdentity: sameSheet.cssRules === sameRules,
                        rules: Array.from(sameRules, rule => rule.selectorText),
                        bridgeTextHidden: !document.documentElement.textContent.includes('.secret')
                            && !document.querySelector('style[data-obscura-external-stylesheets]'),
                        crossOwner: crossSheet.ownerNode === cross,
                        crossHref: crossSheet.href,
                        privateRulesHidden: crossSheet._rules.length === 0,
                        security,
                    };
                })()
                "#,
            )
            .expect("inspect linked stylesheet CSSOM");

        assert_eq!(
            result,
            serde_json::json!({
                "stableList": true,
                "length": 3,
                "order": [true, true, true],
                "sameIdentity": true,
                "owner": true,
                "href": "https://example.test/assets/app.css",
                "title": "app",
                "rulesIdentity": true,
                "rules": [".app", ".wide", ".added"],
                "bridgeTextHidden": true,
                "crossOwner": true,
                "crossHref": "https://cdn.example.test/theme.css",
                "privateRulesHidden": true,
                "security": ["SecurityError", "SecurityError", "SecurityError",
                             "SecurityError", "SecurityError"],
            })
        );
    }

    #[test]
    fn external_stylesheets_keep_their_positions_between_inline_sheets() {
        let dom = parse_html(
            r#"<html><head>
                <link rel="stylesheet" href="first.css">
                <style data-name="inline">.target{height:20px}</style>
                <link rel="preload stylesheet" href="second.css">
            </head><body></body></html>"#,
        );
        let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
        runtime.set_dom(dom);
        runtime.run_page_init();
        install_linked_stylesheet(
            &mut runtime,
            0,
            ".target{height:10px}",
            true,
            "https://example.com/first.css",
        );
        install_linked_stylesheet(
            &mut runtime,
            1,
            ".target{height:30px}",
            true,
            "https://example.com/second.css",
        );

        let sheet_text = runtime
            .with_dom(|dom| {
                dom.descendants(dom.document())
                    .into_iter()
                    .flat_map(|nid| {
                        let mut sources: Vec<String> = dom
                            .external_stylesheet(nid)
                            .map(|sheet| sheet.sources.iter().map(ToString::to_string).collect())
                            .unwrap_or_default();
                        if dom.get_node(nid).is_some_and(|node| {
                            node.as_element()
                                .is_some_and(|element| element.local.as_ref() == "style")
                        }) {
                            sources.push(dom.text_content(nid));
                        }
                        sources
                    })
                    .collect::<Vec<_>>()
            })
            .expect("live DOM");
        assert_eq!(
            sheet_text,
            vec![
                ".target{height:10px}",
                ".target{height:20px}",
                ".target{height:30px}",
            ]
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn parser_script_body_replacement_survives_navigation() {
        let mut page = client_replacement_page("parser-client-replacement", false);
        let target = page.url_string();

        page.navigate(&target)
            .await
            .expect("navigate replacement page");

        assert_client_replacement_survived(&mut page);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn timer_body_replacement_survives_settle() {
        let mut page = client_replacement_page("timer-client-replacement", true);
        let target = page.url_string();
        page.navigate(&target)
            .await
            .expect("navigate deferred replacement page");

        let before_timer = page
            .js
            .as_mut()
            .expect("page runtime")
            .evaluate(
                "var scheduleClientReplacement = true; window.dispatchEvent(new Event('mount-client')); return !!document.getElementById('ssr');",
            )
            .expect("schedule client replacement");
        assert_eq!(before_timer, serde_json::json!(true));

        page.settle(100).await;

        assert_client_replacement_survived(&mut page);
    }

    #[cfg(feature = "render")]
    #[test]
    fn settle_resource_warmup_uses_only_remaining_absolute_budget() {
        assert_eq!(
            remaining_settle_resource_warmup_ms(
                1_000,
                std::time::Duration::from_millis(250),
                1_000,
            ),
            750
        );
        assert_eq!(
            remaining_settle_resource_warmup_ms(
                1_000,
                std::time::Duration::from_millis(250),
                100,
            ),
            100
        );
        assert_eq!(
            remaining_settle_resource_warmup_ms(
                1_000,
                std::time::Duration::from_micros(999_500),
                1_000,
            ),
            0,
            "a sub-millisecond remainder cannot safely fund a millisecond timeout"
        );
        assert_eq!(
            remaining_settle_resource_warmup_ms(
                1_000,
                std::time::Duration::from_millis(1_001),
                1_000,
            ),
            0
        );
    }

    #[test]
    fn url_matches_cdp_pattern_handles_wildcards_across_url_parts() {
        assert!(url_matches_cdp_pattern(
            "*://*.gstatic.com/*.woff2",
            "https://fonts.gstatic.com/s/inter/v18/UcCO3FwrK3iLTcviYwYZ8UA3.woff2",
        ));
        assert!(url_matches_cdp_pattern(
            "*://*.google.com/maps/vt/*",
            "https://www.google.com/maps/vt/pb=!1m4!1m3",
        ));
        assert!(url_matches_cdp_pattern(
            "https://example.com/assets/*",
            "https://example.com/assets/app.js",
        ));
        assert!(!url_matches_cdp_pattern(
            "https://example.com/assets/*",
            "https://cdn.example.com/assets/app.js",
        ));
        assert!(!url_matches_cdp_pattern(
            "*://*.gstatic.com/*.woff2",
            "https://fonts.gstatic.com/s/inter/v18/font.woff",
        ));
    }
}

#[derive(Debug, thiserror::Error)]
pub enum PageError {
    #[error("Invalid URL: {0}")]
    InvalidUrl(String),

    #[error("Network error: {0}")]
    NetworkError(String),

    #[error("Parse error: {0}")]
    ParseError(String),

    /// A page kept triggering its own navigations until the chain's limit
    /// was exhausted. HTTP 3xx redirects are followed one layer down, in
    /// obscura-net, and report `ObscuraNetError::TooManyRedirects`.
    #[error("Too many client-initiated navigations, the chain reached its limit of {0} documents")]
    TooManyClientNavigations(usize),
}

impl From<ObscuraNetError> for PageError {
    fn from(e: ObscuraNetError) -> Self {
        PageError::NetworkError(e.to_string())
    }
}

/// Whether a Content-Type is text-like and can be stored/returned as a UTF-8
/// string. Everything else (images, PDF, fonts, octet-stream) is binary and must
/// be base64-encoded so Network.getResponseBody returns intact bytes.
fn is_text_like_content_type(content_type: Option<&str>) -> bool {
    let ct = match content_type {
        Some(c) => c.split(';').next().unwrap_or(c).trim().to_ascii_lowercase(),
        // No Content-Type: assume text (matches the HTML-parse default).
        None => return true,
    };
    if ct.is_empty() {
        return true;
    }
    ct.starts_with("text/")
        || ct == "application/json"
        || ct == "application/xml"
        || ct == "application/xhtml+xml"
        || ct == "application/javascript"
        || ct == "application/ecmascript"
        || ct == "image/svg+xml"
        || ct.ends_with("+json")
        || ct.ends_with("+xml")
}

/// Lowercased MIME type of a Content-Type header, without parameters.
fn base_content_type(content_type: Option<&str>) -> Option<String> {
    let ct = content_type?.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
    if ct.is_empty() { None } else { Some(ct) }
}

/// A response whose body is text but not markup gets a plain-text document
/// rather than an HTML parse of its content (`text/plain`, `text/markdown`).
/// Returns the MIME type to report as `document.contentType`.
fn plain_text_document_type(content_type: Option<&str>) -> Option<String> {
    let ct = base_content_type(content_type)?;
    // XML and HTML families keep their existing parse path, including the
    // `.xhtml`/`.xml` URL sniffing that `contentType` still applies.
    if ct == "text/html"
        || ct == "application/xhtml+xml"
        || ct == "text/xml"
        || ct == "application/xml"
        || ct.ends_with("+xml")
    {
        return None;
    }
    matches!(ct.as_str(), "text/plain" | "text/markdown" | "text/x-markdown")
        .then_some(ct)
}

/// Escape text for insertion as HTML character data, then build the document
/// Chrome builds for a plain-text response: `<body>` holding one `<pre>` with
/// the whole text. Serializing through the HTML parser keeps one code path for
/// document construction instead of a second native tree builder.
fn parse_plain_text_document(text: &str) -> DomTree {
    if text.is_empty() {
        return parse_html("<!DOCTYPE html>");
    }
    let mut html = String::with_capacity(text.len() + 64);
    // The parser discards the synthetic newline, not the document's first one.
    html.push_str("<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body><pre>\n");
    html.push_str(&escape_html_text(text));
    html.push_str("</pre></body></html>");
    parse_html(&html)
}

fn escape_html_text(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(ch),
        }
    }
    out
}

fn response_body_entry_limit() -> usize {
    std::env::var("OBSCURA_NETWORK_BODY_BUFFER_ENTRIES")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(128)
}

fn response_body_byte_limit() -> usize {
    std::env::var("OBSCURA_NETWORK_BODY_BUFFER_BYTES")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(2 * 1024 * 1024)
}