The headless browser for AI agents and web scraping
Advance modern page lifecycle and geometry
SGavrld7883e7885a1
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex cc0f1414..1af45b6c 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -730,6 +730,12 @@ fn materialize_linked_stylesheet_script(link_index: usize, css: &str) -> Stringreturn link.getAttribute('media') || '';}}function syncSheet() {{+ if (!style) {{+ style = document.createElement('style');+ style.setAttribute('data-obscura-external-stylesheets', '');+ style.textContent = `{escaped_css}`;+ globalThis.__obscura_registerLinkedStylesheet(link, style);+ }}var enabled = link.parentNode&& !link.disabled&& !link.hasAttribute('disabled');@@ -737,11 +743,6 @@ fn materialize_linked_stylesheet_script(link_index: usize, css: &str) -> Stringif (style && style.parentNode) style.parentNode.removeChild(style);return;}}- if (!style) {{- style = document.createElement('style');- style.setAttribute('data-obscura-external-stylesheets', '');- style.textContent = `{escaped_css}`;- }}var media = effectiveMedia().trim();if (media) style.setAttribute('media', media);else style.removeAttribute('media');@@ -2244,6 +2245,18 @@ impl Page {}}+ /// 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> {+ match self.js.as_mut() {+ Some(js) => js.run_autonomous_event_loop_turn().await,+ None => Ok(true),+ }+ }+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;@@ -2516,6 +2529,7 @@ impl Page {}}self.document_timeline_origin = std::time::Instant::now();+ #[cfg(feature = "render")]if let Some(js) = &self.js {js.reset_animation_timeline();}@@ -3170,6 +3184,39 @@ impl Page {}}+ 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> {+ if let Some(js) = &mut self.js {+ js.evaluate_for_cdp_with_timeout(+ expression,+ return_by_value,+ await_promise,+ await_timeout_ms,+ )+ .await+ } else {+ let value = self.evaluate(expression);+ Ok(obscura_js::runtime::RemoteObjectInfo {+ 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,@@ -3214,6 +3261,27 @@ impl Page {}}+ 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> {+ let js = self.js.as_mut().ok_or("JavaScript runtime unavailable")?;+ js.call_function_on_for_cdp_with_timeout(+ function_declaration,+ object_id,+ args,+ return_by_value,+ await_promise,+ await_timeout_ms,+ )+ .await+ }+pub fn set_blocked_urls(&mut self, patterns: Vec<String>) {self.blocked_url_patterns = patterns.clone();if let Some(js) = &self.js {@@ -5761,6 +5829,106 @@ mod tests {);}+ #[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();+ runtime+ .execute_script(+ "<same-origin-sheet>",+ &materialize_linked_stylesheet_script(+ 0,+ ".app { color: red } .wide { width: 20px }",+ ),+ )+ .expect("materialize same-origin linked sheet");+ runtime+ .execute_script(+ "<cross-origin-sheet>",+ &materialize_linked_stylesheet_script(1, ".secret { color: purple }"),+ )+ .expect("materialize cross-origin linked sheet");++ 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;+ 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);+ const source = document.querySelector(+ 'style[data-obscura-external-stylesheets]'+ );+ 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),+ sourceUpdated: source.textContent.includes('.added'),+ crossOwner: crossSheet.ownerNode === cross,+ crossHref: crossSheet.href,+ bridgeSheetsHidden: same.nextSibling.sheet === null+ && cross.nextSibling.sheet === null,+ 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"],+ "sourceUpdated": true,+ "crossOwner": true,+ "crossHref": "https://cdn.example.test/theme.css",+ "bridgeSheetsHidden": true,+ "security": ["SecurityError", "SecurityError", "SecurityError",+ "SecurityError", "SecurityError"],+ })+ );+ }+#[test]fn external_stylesheets_keep_their_positions_between_inline_sheets() {let dom = parse_html(diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex 6dcb713f..5f13b015 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -40,6 +40,10 @@ pub(crate) struct ScreencastState {pub struct CdpContext {pub pages: Vec<Page>,pub sessions: HashMap<String, String>, // session_id -> page_id+ /// Current document loader per page. Navigation events and later+ /// script-initiated Network events must share this id; inventing a loader+ /// for each fetch breaks DevTools request grouping.+ pub current_loader_ids: HashMap<String, String>,pub pending_events: Vec<CdpEvent>,#[cfg(feature = "render")]pub(crate) screencasts: HashMap<String, ScreencastState>,@@ -149,6 +153,7 @@ impl CdpContext {CdpContext {pages: Vec::new(),sessions: HashMap::new(),+ current_loader_ids: HashMap::new(),pending_events: Vec::new(),#[cfg(feature = "render")]screencasts: HashMap::new(),@@ -217,6 +222,8 @@ impl CdpContext {let mut page = Page::new(page_id.clone(), context);page.navigate_blank();self.pages.push(page);+ self.current_loader_ids+ .insert(page_id.clone(), format!("loader-blank-{page_id}"));Ok(page_id)}@@ -266,6 +273,7 @@ impl CdpContext {pub fn remove_page(&mut self, id: &str) {self.pages.retain(|p| p.id != id);+ self.current_loader_ids.remove(id);#[cfg(feature = "render")]{let removed: Vec<String> = self@@ -531,7 +539,7 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {// connected client. Called after every dispatch — binding calls only land// in the queue while V8 is running inside a CDP handler, so there is no// window in which they could pile up without a draining opportunity.-fn drain_binding_calls(ctx: &mut CdpContext) {+pub(crate) fn drain_binding_calls(ctx: &mut CdpContext) {// page_id -> session_id (any one session that holds this page).let page_to_session: HashMap<String, String> = ctx.sessionsdiff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rsindex 806df9b3..01fb7d49 100644--- a/crates/obscura-cdp/src/domains/page.rs+++ b/crates/obscura-cdp/src/domains/page.rs@@ -646,8 +646,6 @@ pub(crate) fn queue_screencast_frame(/// acknowledgement window, ensuring neither mechanism loses the latest frame.#[cfg(feature = "render")]pub(crate) async fn pump_screencast_frames(ctx: &mut CdpContext) {- const EVENT_LOOP_SLICE_MS: u64 = 4;-let sessions: Vec<String> = ctx.screencasts.keys().cloned().collect();for cdp_session_id in sessions {if !ctx.screencasts.contains_key(&cdp_session_id) {@@ -658,12 +656,9 @@ pub(crate) async fn pump_screencast_frames(ctx: &mut CdpContext) {let Some(page) = ctx.get_session_page_mut(&attached_session) else {continue;};- let Some(js) = page.js.as_mut() else {+ let Some(js) = page.js.as_ref() else {continue;};- // A V8 watchdog bounds synchronous callbacks as well as the async- // timeout, so a hostile timer cannot freeze the CDP connection.- let _ = js.run_event_loop_bounded(EVENT_LOOP_SLICE_MS).await;let generation = js.activity_generation();let css_animation_active = page.prepared_has_active_css_animations();(generation, css_animation_active)@@ -725,6 +720,8 @@ pub fn emit_navigation_events(wait_until: WaitUntil,reached_network_idle: bool,) {+ ctx.current_loader_ids+ .insert(page_id.to_string(), loader_id.to_string());let es = session_id.clone();let ts = timestamp();@@ -930,6 +927,79 @@ pub fn emit_navigation_events());}+/// Emit completed script-initiated requests after the document lifecycle has+/// already finished. These requests belong to the current document loader and+/// must not replay frame navigation or load lifecycle events.+pub(crate) fn emit_runtime_network_events(+ ctx: &mut CdpContext,+ session_id: &Option<String>,+ frame_id: &str,+ page_url: &str,+ page_id: &str,+ network_events: &[obscura_browser::NetworkEvent],+) {+ if network_events.is_empty() {+ return;+ }+ let loader_id = ctx+ .current_loader_ids+ .get(page_id)+ .cloned()+ .unwrap_or_else(|| format!("loader-blank-{page_id}"));+ for network_event in network_events {+ let request_id = &network_event.request_id;+ ctx.pending_events.push(CdpEvent {+ method: "Network.requestWillBeSent".into(),+ params: json!({+ "requestId": request_id,+ "loaderId": loader_id,+ "documentURL": page_url,+ "request": {+ "url": network_event.url,+ "method": network_event.method,+ "headers": network_event.headers,+ },+ "timestamp": network_event.timestamp,+ "wallTime": network_event.timestamp,+ "initiator": {"type": "script"},+ "type": network_event.resource_type,+ "frameId": frame_id,+ }),+ session_id: session_id.clone(),+ });+ ctx.pending_events.push(CdpEvent {+ method: "Network.responseReceived".into(),+ params: json!({+ "requestId": request_id,+ "loaderId": loader_id,+ "timestamp": network_event.timestamp,+ "type": network_event.resource_type,+ "response": {+ "url": network_event.url,+ "status": network_event.status,+ "statusText": "",+ "headers": &*network_event.response_headers,+ "mimeType": network_event.response_headers+ .get("content-type")+ .cloned()+ .unwrap_or_default(),+ },+ "frameId": frame_id,+ }),+ session_id: session_id.clone(),+ });+ ctx.pending_events.push(CdpEvent {+ method: "Network.loadingFinished".into(),+ params: json!({+ "requestId": request_id,+ "timestamp": network_event.timestamp,+ "encodedDataLength": network_event.body_size,+ }),+ session_id: session_id.clone(),+ });+ }+}+/// Parse the `waitUntil` argument that Puppeteer/Playwright pass on/// `Page.navigate`.pub fn parse_wait_until(params: &Value) -> WaitUntil {@@ -1540,6 +1610,53 @@ mod tests {use super::*;use crate::dispatch::CdpContext;+ #[test]+ fn runtime_network_events_reuse_the_document_loader_without_lifecycle_replay() {+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let session_id = Some(format!("{page_id}-session"));+ ctx.sessions+ .insert(session_id.clone().unwrap(), page_id.clone());+ ctx.current_loader_ids+ .insert(page_id.clone(), "loader-current".into());+ let event = obscura_browser::NetworkEvent {+ request_id: "fetch-7".into(),+ url: "https://example.test/data.json".into(),+ method: "GET".into(),+ resource_type: "Fetch".into(),+ status: 200,+ headers: std::collections::HashMap::new(),+ response_headers: std::sync::Arc::new(std::collections::HashMap::from([(+ "content-type".into(),+ "application/json".into(),+ )])),+ body_size: 12,+ timestamp: 42.0,+ };++ emit_runtime_network_events(+ &mut ctx,+ &session_id,+ "frame-1",+ "https://example.test/",+ &page_id,+ &[event],+ );++ assert_eq!(ctx.pending_events.len(), 3);+ assert_eq!(ctx.pending_events[0].method, "Network.requestWillBeSent");+ assert_eq!(ctx.pending_events[0].params["loaderId"], "loader-current");+ assert_eq!(ctx.pending_events[1].method, "Network.responseReceived");+ assert_eq!(ctx.pending_events[1].params["loaderId"], "loader-current");+ assert_eq!(ctx.pending_events[2].method, "Network.loadingFinished");+ assert!(ctx.pending_events.iter().all(|event| {+ !matches!(+ event.method.as_str(),+ "Page.frameNavigated" | "Page.lifecycleEvent"+ )+ }));+ }+#[tokio::test]async fn get_layout_metrics_returns_chrome_default_viewport() {let mut ctx = CdpContext::new();diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rsindex fd102c33..652c68fe 100644--- a/crates/obscura-cdp/src/domains/runtime.rs+++ b/crates/obscura-cdp/src/domains/runtime.rs@@ -117,11 +117,17 @@ pub async fn handle(.ok_or("No page")?;let info = match tokio::time::timeout(std::time::Duration::from_millis(timeout_ms),- page.evaluate_for_cdp(expression, return_by_value, await_promise),+ page.evaluate_for_cdp_with_timeout(+ expression,+ return_by_value,+ await_promise,+ timeout_ms,+ ),).await{- Ok(info) => info,+ Ok(Ok(info)) => info,+ Ok(Err(error)) => return Err(error),Err(_) => {return Err(format!("Runtime.evaluate exceeded {timeout_ms}ms timeout"@@ -159,11 +165,39 @@ pub async fn handle(// no-op and the default context is used.validate_context_id(params, "executionContextId", ctx, "callFunctionOn")?;+ // Keep awaitPromise alive for the same command budget as evaluate.+ // Playwright implements waits with callFunctionOn on some utility+ // paths, so a shorter hidden cap makes the client return before the+ // requested browser timer fires.+ let timeout_ms = params+ .get("timeout")+ .and_then(|v| v.as_u64())+ .unwrap_or(30_000);+let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;- let info =- page.call_function_on_for_cdp(function_declaration, object_id, &arguments, return_by_value, await_promise).await;+ let info = match tokio::time::timeout(+ std::time::Duration::from_millis(timeout_ms),+ page.call_function_on_for_cdp_with_timeout(+ function_declaration,+ object_id,+ &arguments,+ return_by_value,+ await_promise,+ timeout_ms,+ ),+ )+ .await+ {+ Ok(Ok(info)) => info,+ Ok(Err(error)) => return Err(error),+ Err(_) => {+ return Err(format!(+ "Runtime.callFunctionOn exceeded {timeout_ms}ms timeout"+ ));+ }+ };emit_post_eval_nav(ctx, session_id).await?;Ok(json!({ "result": remote_object_from_info(&info) }))@@ -488,6 +522,32 @@ mod tests {}}+ #[tokio::test(flavor = "current_thread")]+ async fn evaluate_await_promise_reports_the_requested_timeout() {+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let session_id = "await-timeout-session".to_string();+ ctx.sessions.insert(session_id.clone(), page_id);++ let error = handle(+ "evaluate",+ &json!({+ "expression": "new Promise(() => {})",+ "returnByValue": true,+ "awaitPromise": true,+ "timeout": 25,+ }),+ &mut ctx,+ &Some(session_id),+ )+ .await+ .expect_err("an unsettled promise must not return stale result metadata");+ assert!(+ error.contains("25ms timeout") || error.contains("within 25ms"),+ "unexpected timeout error: {error}"+ );+ }+#[tokio::test]async fn create_isolated_world_registers_id_for_evaluate() {// Round-trip: Page.createIsolatedWorld returns contextId N, and adiff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex 26179008..9ee15949 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -717,6 +717,14 @@ async fn cdp_processor(let mut screencast_tick = tokio::time::interval(tokio::time::Duration::from_millis(33));screencast_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);let mut connection_reply_tx: Option<mpsc::UnboundedSender<String>> = None;+ // A real browser renderer continues servicing timers, networking, posted+ // tasks, and animation callbacks while its DevTools client is silent. Keep+ // one wake-driven deno_core turn armed after work may have been scheduled;+ // the future parks on the runtime's own waker and is cancelled whenever a+ // higher-priority protocol command arrives. Full idle disarms it until the+ // next command/navigation, so static pages consume no polling budget.+ let mut runtime_pump_armed = false;+ let mut runtime_pump_error_streak = 0_u8;loop {// Drain any deferred messages from the previous interception window@@ -724,27 +732,113 @@ async fn cdp_processor(// nav-task spawn_local in flight, so this connection's only entered// Isolate is the one dispatch is about to touch.let msg = if let Some(d) = deferred.pop_front() {- d+ Some(d)} else {+ let screencast_active = has_active_screencast(&ctx);+ let live_page_route = ctx+ .pages+ .iter()+ .find(|page| page.has_js())+ .and_then(|page| {+ ctx.sessions+ .iter()+ .find(|(_, page_id)| *page_id == &page.id)+ .map(|(session_id, _)| (session_id.clone(), page.frame_id.clone()))+ });+ let has_intercept_rx = intercept_rx.is_some();tokio::select! {+ biased;msg = rx.recv() => match msg {- Some(m) => m,+ Some(m) => Some(m),None => break,},- _ = screencast_tick.tick(), if has_active_screencast(&ctx) => {+ _ = &mut shutdown => {+ tracing::info!("Shutdown signal received (connection processor)");+ break;+ },+ pump_result = pump_live_page_event_loop(&mut ctx), if runtime_pump_armed => {+ match pump_result {+ Ok(reached_idle) => {+ runtime_pump_error_streak = 0;+ runtime_pump_armed = !reached_idle;+ }+ Err(error) => {+ runtime_pump_error_streak = runtime_pump_error_streak.saturating_add(1);+ runtime_pump_armed = runtime_pump_error_streak <= 3+ && ctx.pages.iter().any(|page| page.has_js());+ tracing::warn!("autonomous page task failed: {error}");+ tokio::task::yield_now().await;+ }+ }+ sync_live_page_network_events(&mut ctx);+ dispatch::drain_binding_calls(&mut ctx);+ forward_pending_events(&mut ctx, connection_reply_tx.as_ref());+ if let (Some(reply_tx), Some((session_id, url, method, body))) = (+ connection_reply_tx.as_ref(),+ take_live_pending_navigation(&ctx),+ ) {+ let navigation = json!({+ "id": 0,+ "method": "Page.navigate",+ "params": {"url": url, "__method": method, "__body": body},+ "sessionId": session_id,+ })+ .to_string();+ process_with_interception(+ &navigation,+ &mut ctx,+ reply_tx,+ &mut rx,+ &mut intercept_rx,+ &mut intercepted_paused,+ &mut deferred,+ false,+ )+ .await;+ runtime_pump_armed = ctx.pages.iter().any(|page| page.has_js());+ }+ None+ },+ Some(intercepted) = async {+ if let Some(ref mut receiver) = intercept_rx {+ receiver.recv().await+ } else {+ std::future::pending().await+ }+ }, if has_intercept_rx => {+ if let (Some((session_id, frame_id)), Some(reply_tx)) =+ (live_page_route.as_ref(), connection_reply_tx.as_ref())+ {+ emit_intercepted_request(+ intercepted,+ frame_id,+ Some(session_id.clone()),+ reply_tx,+ &mut intercepted_paused,+ );+ } else {+ let _ = intercepted.resolver.send(+ obscura_js::ops::InterceptResolution::Fail {+ reason: "Aborted".into(),+ },+ );+ }+ None+ },+ _ = screencast_tick.tick(), if screencast_active => {pump_and_forward_screencast_frames(&mut ctx,connection_reply_tx.as_ref(),).await;- continue;- },- _ = &mut shutdown => {- tracing::info!("Shutdown signal received (connection processor)");- break;+ None}}};+ let Some(msg) = msg else {+ continue;+ };+match msg {ServerMessage::NewConnection { reply_tx } => {connection_reply_tx = Some(reply_tx.clone());@@ -768,17 +862,29 @@ async fn cdp_processor(process_with_interception(&cdp_msg.text, &mut ctx, &cdp_msg.reply_tx, &mut rx,&mut intercept_rx, &mut intercepted_paused,- &mut deferred,+ &mut deferred, true,).await;} else {- if cdp_msg.text.contains("Fetch.") {- handle_fetch_resolution(&cdp_msg.text, &mut ctx, &cdp_msg.reply_tx, &mut intercepted_paused);+ let fetch_was_resolved = cdp_msg.text.contains("Fetch.")+ && handle_fetch_resolution(+ &cdp_msg.text,+ &mut ctx,+ &cdp_msg.reply_tx,+ &mut intercepted_paused,+ );+ if !fetch_was_resolved {+ process_cdp_message(&cdp_msg.text, &mut ctx, &cdp_msg.reply_tx).await;}- process_cdp_message(&cdp_msg.text, &mut ctx, &cdp_msg.reply_tx).await;}}}+ // Dispatch may have created a page or scheduled new asynchronous work.+ // A single live isolate is the connection's current active target; the+ // pump will park cheaply if its next task is a distant timer.+ runtime_pump_armed = ctx.pages.iter().any(|page| page.has_js());+ runtime_pump_error_streak = 0;+}// The connection thread merges this context's cookie delta into the@@ -786,6 +892,135 @@ async fn cdp_processor(let _ = &ctx;}+fn emit_intercepted_request(+ intercepted: obscura_js::ops::InterceptedRequest,+ frame_id: &str,+ session_id: Option<String>,+ reply_tx: &mpsc::UnboundedSender<String>,+ intercepted_paused: &mut HashMap<+ String,+ tokio::sync::oneshot::Sender<obscura_js::ops::InterceptResolution>,+ >,+) {+ tracing::info!(+ "INTERCEPTION: requestPaused for {} {} (sending to client)",+ intercepted.method,+ intercepted.url+ );+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs_f64();+ let request = json!({+ "url": intercepted.url,+ "method": intercepted.method,+ "headers": intercepted.headers,+ "initialPriority": "High",+ "referrerPolicy": "strict-origin-when-cross-origin",+ });+ let request_will_be_sent = json!({+ "method": "Network.requestWillBeSent",+ "params": {+ "requestId": intercepted.request_id,+ "loaderId": "",+ "documentURL": "",+ "request": request,+ "timestamp": now,+ "wallTime": now,+ "initiator": {"type": "script"},+ "type": intercepted.resource_type,+ "frameId": frame_id,+ },+ "sessionId": session_id,+ });+ let _ = reply_tx.send(request_will_be_sent.to_string());++ let request_paused = json!({+ "method": "Fetch.requestPaused",+ "params": {+ "requestId": intercepted.request_id,+ "request": request,+ "frameId": frame_id,+ "resourceType": intercepted.resource_type,+ "networkId": intercepted.request_id,+ "responseErrorReason": null,+ "responseStatusCode": null,+ "responseHeaders": null,+ },+ "sessionId": session_id,+ });+ let _ = reply_tx.send(request_paused.to_string());+ intercepted_paused.insert(intercepted.request_id, intercepted.resolver);+}++async fn pump_live_page_event_loop(ctx: &mut CdpContext) -> Result<bool, String> {+ let Some(page) = ctx.pages.iter_mut().find(|page| page.has_js()) else {+ return Ok(true);+ };+ page.run_autonomous_event_loop_turn().await+}++fn sync_live_page_network_events(ctx: &mut CdpContext) {+ let page_route = ctx.pages.iter().find(|page| page.has_js()).and_then(|page| {+ ctx.sessions+ .iter()+ .find(|(_, page_id)| *page_id == &page.id)+ .map(|(session_id, _)| {+ (+ Some(session_id.clone()),+ page.id.clone(),+ page.frame_id.clone(),+ page.url_string(),+ )+ })+ });+ let Some((session_id, page_id, frame_id, page_url)) = page_route else {+ return;+ };+ let network_events = {+ let Some(page) = ctx.get_page_mut(&page_id) else {+ return;+ };+ page.sync_js_network_events();+ page.network_events.drain(..).collect::<Vec<_>>()+ };+ crate::domains::page::emit_runtime_network_events(+ ctx,+ &session_id,+ &frame_id,+ &page_url,+ &page_id,+ &network_events,+ );+}++fn take_live_pending_navigation(+ ctx: &CdpContext,+) -> Option<(String, String, String, String)> {+ let page = ctx.pages.iter().find(|page| page.has_js())?;+ let session_id = ctx+ .sessions+ .iter()+ .find(|(_, page_id)| *page_id == &page.id)+ .map(|(session_id, _)| session_id.clone())?;+ let (url, method, body) = page.take_pending_navigation()?;+ Some((session_id, url, method, body))+}++fn forward_pending_events(+ ctx: &mut CdpContext,+ reply_tx: Option<&mpsc::UnboundedSender<String>>,+) {+ let Some(reply_tx) = reply_tx else {+ return;+ };+ for event in ctx.pending_events.drain(..) {+ if let Ok(json) = serde_json::to_string(&event) {+ let _ = reply_tx.send(json);+ }+ }+}+fn has_active_screencast(ctx: &CdpContext) -> bool {#[cfg(feature = "render")]{@@ -807,14 +1042,7 @@ async fn pump_and_forward_screencast_frames(#[cfg(not(feature = "render"))]let _ = ctx;- let Some(reply_tx) = reply_tx else {- return;- };- for event in ctx.pending_events.drain(..) {- if let Ok(json) = serde_json::to_string(&event) {- let _ = reply_tx.send(json);- }- }+ forward_pending_events(ctx, reply_tx);}// Whether a raw CDP frame is exactly a `Page.navigate` call, and so should take@@ -852,7 +1080,7 @@ fn handle_fetch_resolution(_ctx: &mut CdpContext,reply_tx: &mpsc::UnboundedSender<String>,intercepted_paused: &mut HashMap<String, tokio::sync::oneshot::Sender<obscura_js::ops::InterceptResolution>>,-) {+) -> bool {if let Ok(req) = serde_json::from_str::<CdpRequest>(text) {let method = req.method.as_str();let request_id = req.params.get("requestId").and_then(|v| v.as_str()).unwrap_or("");@@ -887,15 +1115,17 @@ fn handle_fetch_resolution(let reason = req.params.get("errorReason").and_then(|v| v.as_str()).unwrap_or("Failed").to_string();obscura_js::ops::InterceptResolution::Fail { reason }}- _ => return,+ _ => return false,};let _ = resolver.send(resolution);let resp = crate::types::CdpResponse::success(req.id, json!({}), req.session_id);if let Ok(json) = serde_json::to_string(&resp) {let _ = reply_tx.send(json);}+ return true;}}+ false}async fn process_with_interception(@@ -906,6 +1136,7 @@ async fn process_with_interception(intercept_rx: &mut Option<mpsc::UnboundedReceiver<obscura_js::ops::InterceptedRequest>>,intercepted_paused: &mut HashMap<String, tokio::sync::oneshot::Sender<obscura_js::ops::InterceptResolution>>,deferred: &mut std::collections::VecDeque<ServerMessage>,+ send_command_response: bool,) {let req: CdpRequest = match serde_json::from_str(text) {Ok(r) => r,@@ -1034,54 +1265,13 @@ async fn process_with_interception(std::future::pending().await}}, if has_irx => {- tracing::info!("INTERCEPTION: requestPaused for {} {} (sending to client)", intercepted.method, intercepted.url);- let rws_event = json!({- "method": "Network.requestWillBeSent",- "params": {- "requestId": intercepted.request_id,- "loaderId": "",- "documentURL": "",- "request": {- "url": intercepted.url,- "method": intercepted.method,- "headers": intercepted.headers,- "initialPriority": "High",- "referrerPolicy": "strict-origin-when-cross-origin",- },- "timestamp": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs_f64(),- "wallTime": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs_f64(),- "initiator": {"type": "script"},- "type": intercepted.resource_type,- "frameId": frame_id,- },- "sessionId": session_for_events,- });- let _ = reply_tx.send(rws_event.to_string());-- let event_json = json!({- "method": "Fetch.requestPaused",- "params": {- "requestId": intercepted.request_id,- "request": {- "url": intercepted.url,- "method": intercepted.method,- "headers": intercepted.headers,- "initialPriority": "High",- "referrerPolicy": "strict-origin-when-cross-origin",- },- "frameId": frame_id,- "resourceType": intercepted.resource_type,- "networkId": intercepted.request_id,- "responseErrorReason": null,- "responseStatusCode": null,- "responseHeaders": null,- },- "sessionId": session_for_events,- });- let event_str = event_json.to_string();- tracing::info!("INTERCEPTION event JSON: {}", crate::util::truncate_on_char_boundary(&event_str, 300));- let _ = reply_tx.send(event_str);- intercepted_paused.insert(intercepted.request_id.clone(), intercepted.resolver);+ emit_intercepted_request(+ intercepted,+ &frame_id,+ session_for_events.clone(),+ reply_tx,+ intercepted_paused,+ );tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;}Some(msg) = rx.recv() => {@@ -1162,8 +1352,10 @@ async fn process_with_interception(Err(e) => crate::types::CdpResponse::error(req.id, -32000, e, req.session_id.clone()),};- if let Ok(json) = serde_json::to_string(&response) {- let _ = reply_tx.send(json);+ if send_command_response {+ if let Ok(json) = serde_json::to_string(&response) {+ let _ = reply_tx.send(json);+ }}// Shared event emission: includes the post-#190 Network.requestWillBeSent@@ -1401,11 +1593,14 @@ async fn handle_connection_ws(#[cfg(test)]mod tests {- use super::{is_navigate_method, merge_cookie_delta, parse_cdp_headers};+ use super::{+ handle_fetch_resolution, is_navigate_method, merge_cookie_delta, parse_cdp_headers,+ };#[cfg(feature = "render")]- use super::pump_and_forward_screencast_frames;+ use super::{pump_and_forward_screencast_frames, pump_live_page_event_loop};use obscura_net::{CookieInfo, CookieJar};use serde_json::json;+ use std::collections::HashMap;fn cookie(name: &str, value: &str) -> CookieInfo {CookieInfo {@@ -1420,6 +1615,130 @@ mod tests {}}+ #[tokio::test(flavor = "current_thread")]+ async fn page_runtime_advances_while_cdp_client_is_silent() {+ tokio::task::LocalSet::new()+ .run_until(async {+ let (server_tx, server_rx) = tokio::sync::mpsc::unbounded_channel();+ let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel();+ let shutdown = std::sync::Arc::new(tokio::sync::Notify::new());+ let default_context = crate::dispatch::CdpContext::new().default_context;+ let processor = tokio::task::spawn_local(super::cdp_processor(+ server_rx,+ default_context,+ shutdown,+ ));++ server_tx+ .send(super::ServerMessage::NewConnection {+ reply_tx: reply_tx.clone(),+ })+ .unwrap();+ let init = reply_rx.recv().await.expect("processor init");+ assert!(init.contains("__init"));++ let send = |value: serde_json::Value| {+ server_tx+ .send(super::ServerMessage::Cdp(super::CdpMessage {+ text: value.to_string(),+ reply_tx: reply_tx.clone(),+ }))+ .unwrap();+ };+ send(json!({+ "id": 1,+ "method": "Target.createTarget",+ "params": {"url": "about:blank"},+ }));++ let mut session_id = None;+ loop {+ let value: serde_json::Value = serde_json::from_str(+ &tokio::time::timeout(+ std::time::Duration::from_secs(2),+ reply_rx.recv(),+ )+ .await+ .expect("create target response timeout")+ .expect("create target response channel"),+ )+ .unwrap();+ if session_id.is_none() {+ session_id = value["params"]["sessionId"]+ .as_str()+ .map(str::to_string);+ }+ if value["id"] == 1 {+ break;+ }+ }+ let session_id = session_id.expect("attached page session");++ send(json!({+ "id": 2,+ "method": "Runtime.evaluate",+ "sessionId": session_id,+ "params": {+ "expression": "(() => { setTimeout(() => globalThis.__autonomousDone = 'yes', 40); return 'armed'; })()",+ "returnByValue": true,+ },+ }));+ loop {+ let value: serde_json::Value = serde_json::from_str(+ &tokio::time::timeout(+ std::time::Duration::from_secs(2),+ reply_rx.recv(),+ )+ .await+ .expect("timer arm response timeout")+ .expect("timer arm response channel"),+ )+ .unwrap();+ if value["id"] == 2 {+ break;+ }+ }++ // This is deliberately host/client time. No CDP message is sent+ // while the timeout becomes due; Chrome's renderer still runs,+ // and Obscura's connection-owned page pump must do the same.+ tokio::time::sleep(std::time::Duration::from_millis(120)).await;++ send(json!({+ "id": 3,+ "method": "Runtime.evaluate",+ "sessionId": session_id,+ "params": {+ "expression": "globalThis.__autonomousDone || 'missing'",+ "returnByValue": true,+ },+ }));+ loop {+ let value: serde_json::Value = serde_json::from_str(+ &tokio::time::timeout(+ std::time::Duration::from_secs(2),+ reply_rx.recv(),+ )+ .await+ .expect("timer observation response timeout")+ .expect("timer observation response channel"),+ )+ .unwrap();+ if value["id"] == 3 {+ assert_eq!(value["result"]["result"]["value"], "yes");+ break;+ }+ }++ drop(server_tx);+ tokio::time::timeout(std::time::Duration::from_secs(2), processor)+ .await+ .expect("processor shutdown timeout")+ .expect("processor task");+ })+ .await;+ }+#[test]fn cookie_delta_merges_changes_without_reverting_other_connections() {let destination = CookieJar::new();@@ -1484,6 +1803,29 @@ mod tests {assert!(parse_cdp_headers(&json!({"url": "https://example.com"})).is_none());}+ #[test]+ fn fetch_resolution_is_handled_once_by_the_outer_processor() {+ let (resolution_tx, mut resolution_rx) = tokio::sync::oneshot::channel();+ let mut paused = HashMap::from([("request-1".to_string(), resolution_tx)]);+ let (reply_tx, mut reply_rx) = tokio::sync::mpsc::unbounded_channel::<String>();+ let mut ctx = crate::dispatch::CdpContext::new();++ assert!(handle_fetch_resolution(+ r#"{"id":17,"method":"Fetch.continueRequest","params":{"requestId":"request-1"}}"#,+ &mut ctx,+ &reply_tx,+ &mut paused,+ ));+ assert!(matches!(+ resolution_rx.try_recv(),+ Ok(obscura_js::ops::InterceptResolution::Continue { .. })+ ));+ let response: serde_json::Value =+ serde_json::from_str(&reply_rx.try_recv().expect("one command response")).unwrap();+ assert_eq!(response["id"], 17);+ assert!(reply_rx.try_recv().is_err(), "must not emit a duplicate response");+ }+#[cfg(feature = "render")]#[tokio::test(flavor = "current_thread")]async fn autonomous_screencast_pumps_timers_and_retains_backpressured_damage() {@@ -1529,6 +1871,7 @@ mod tests {.evaluate("setTimeout(() => document.body.setAttribute('style', 'margin:0;width:96px;height:64px;background:green'), 0)",);+ pump_live_page_event_loop(&mut ctx).await.unwrap();pump_and_forward_screencast_frames(&mut ctx, Some(&reply_tx)).await;let first_update: serde_json::Value = serde_json::from_str(&reply_rx.try_recv().expect("timer mutation should emit a frame"),@@ -1547,6 +1890,7 @@ mod tests {.evaluate("setTimeout(() => document.body.setAttribute('style', 'margin:0;width:96px;height:64px;background:blue'), 0)",);+ pump_live_page_event_loop(&mut ctx).await.unwrap();pump_and_forward_screencast_frames(&mut ctx, Some(&reply_tx)).await;assert!(reply_rx.try_recv().is_err());assert!(ctx.screencasts[&session_id].autonomous_frame_pending);@@ -1628,6 +1972,7 @@ mod tests {"requestAnimationFrame(() => document.body.setAttribute('style','margin:0;width:96px;height:64px;background:lime'))",);tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ pump_live_page_event_loop(&mut ctx).await.unwrap();pump_and_forward_screencast_frames(&mut ctx, None).await;let raf_frame = ctx.pending_eventsdiff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rsindex 2c38acd2..ff2d73aa 100644--- a/crates/obscura-dom/src/tree.rs+++ b/crates/obscura-dom/src/tree.rs@@ -121,6 +121,9 @@ pub enum NodeData {#[derive(Clone, Debug)]pub struct Node {pub id: NodeId,+ /// Shadow-including document connectivity, maintained incrementally on+ /// insertion/removal so hot DOM mutation paths do not walk every ancestor.+ pub connected: bool,pub parent: Option<NodeId>,pub first_child: Option<NodeId>,pub last_child: Option<NodeId>,@@ -267,6 +270,7 @@ impl DomTree {pub fn new() -> Self {let doc_node = Node {id: NodeId(0),+ connected: true,parent: None,first_child: None,last_child: None,@@ -393,6 +397,12 @@ impl DomTree {};inner.shadow_roots.insert(root, info);inner.shadow_roots_by_host.insert(host, root);+ let connected = inner+ .nodes+ .get(host.index())+ .and_then(|node| node.as_ref())+ .is_some_and(|node| node.connected);+ Self::set_subtree_connected(&mut inner, root, connected);Ok(())}@@ -449,6 +459,67 @@ impl DomTree {None}+ /// Constant-time shadow-including connectivity. The bit is propagated over+ /// ordinary children and hosted shadow roots whenever a subtree moves.+ pub fn is_connected(&self, node: NodeId) -> bool {+ self.inner+ .borrow()+ .nodes+ .get(node.index())+ .and_then(|entry| entry.as_ref())+ .is_some_and(|node| node.connected)+ }++ fn set_subtree_connected(inner: &mut DomTreeInner, root: NodeId, connected: bool) {+ // Fresh parser/framework insertions are overwhelmingly leaves. Avoid+ // allocating traversal state for the one-node case.+ let is_leaf = inner+ .nodes+ .get(root.index())+ .and_then(|entry| entry.as_ref())+ .is_some_and(|node| node.first_child.is_none())+ && !inner.shadow_roots_by_host.contains_key(&root);+ if is_leaf {+ if let Some(Some(node)) = inner.nodes.get_mut(root.index()) {+ node.connected = connected;+ }+ return;+ }++ let mut stack = vec![root];+ let mut seen = HashSet::new();+ while let Some(node_id) = stack.pop() {+ if !seen.insert(node_id) {+ continue;+ }+ let (mut child, shadow_root) = match inner+ .nodes+ .get_mut(node_id.index())+ .and_then(|entry| entry.as_mut())+ {+ Some(node) => {+ node.connected = connected;+ (node.first_child, inner.shadow_roots_by_host.get(&node_id).copied())+ }+ None => continue,+ };+ if let Some(root) = shadow_root {+ stack.push(root);+ }+ // Valid trees terminate naturally. The bound is defense in depth+ // against a corrupt sibling cycle, which must not spin here.+ for _ in 0..=inner.nodes.len() {+ let Some(child_id) = child else { break };+ stack.push(child_id);+ child = inner+ .nodes+ .get(child_id.index())+ .and_then(|entry| entry.as_ref())+ .and_then(|node| node.next_sibling);+ }+ }+ }+fn host_including_parent(inner: &DomTreeInner, node: NodeId) -> Option<NodeId> {inner.nodes@@ -514,6 +585,7 @@ impl DomTree {inner.nodes[id.index()] = Some(Node {id,+ connected: false,parent: None,first_child: None,last_child: None,@@ -556,7 +628,7 @@ impl DomTree {// A ShadowRoot is never itself an ordinary child, and moving a host// below its own root would create a cycle even though the root's parent// pointer is null. Follow both ordinary parents and root-to-host edges.- {+ let (parent_connected, child_connected) = {let inner = self.inner.borrow();let parent_exists = inner.nodes@@ -566,15 +638,39 @@ impl DomTree {.nodes.get(child_id.index()).is_some_and(Option::is_some);+ // A leaf which is not a shadow host cannot be an inclusive+ // ancestor of the destination parent. Detached framework tree+ // construction appends thousands of freshly-created leaves; doing+ // a complete parent walk for each one makes a deep chain O(n²).+ // Non-leaves and shadow hosts retain the full host-including cycle+ // check, where reparenting really can create a cycle.+ let child_can_be_ancestor = inner+ .nodes+ .get(child_id.index())+ .and_then(|entry| entry.as_ref())+ .is_some_and(|child| child.first_child.is_some())+ || inner.shadow_roots_by_host.contains_key(&child_id);if !parent_exists|| !child_exists|| inner.shadow_roots.contains_key(&child_id)- || Self::would_create_host_including_cycle(&inner, parent_id, child_id)+ || (child_can_be_ancestor+ && Self::would_create_host_including_cycle(&inner, parent_id, child_id)){return;}- }- self.detach(child_id);+ let parent_connected = inner+ .nodes+ .get(parent_id.index())+ .and_then(|entry| entry.as_ref())+ .is_some_and(|parent| parent.connected);+ let child_connected = inner+ .nodes+ .get(child_id.index())+ .and_then(|entry| entry.as_ref())+ .is_some_and(|child| child.connected);+ (parent_connected, child_connected)+ };+ self.detach_for_reparent(child_id, child_connected && !parent_connected);let mut inner = self.inner.borrow_mut();@@ -600,6 +696,9 @@ impl DomTree {}parent.last_child = Some(child_id);}+ if parent_connected && !child_connected {+ Self::set_subtree_connected(&mut inner, child_id, true);+ }}pub fn insert_before(&self, existing_id: NodeId, new_sibling_id: NodeId) {@@ -612,10 +711,17 @@ impl DomTree {if existing_id == new_sibling_id {return;}- let parent_id = {+ let (parent_id, parent_connected) = {let inner = self.inner.borrow();match inner.nodes.get(existing_id.index()).and_then(|n| n.as_ref()).and_then(|n| n.parent) {- Some(p) => p,+ Some(parent) => {+ let connected = inner+ .nodes+ .get(parent.index())+ .and_then(|entry| entry.as_ref())+ .is_some_and(|node| node.connected);+ (parent, connected)+ }None => return,}};@@ -637,7 +743,11 @@ impl DomTree {}}- self.detach(new_sibling_id);+ let child_connected = self.is_connected(new_sibling_id);+ self.detach_for_reparent(+ new_sibling_id,+ child_connected && !parent_connected,+ );// Read existing's prev AFTER detaching new. If new was existing's// immediate previous sibling, detach moved that pointer; using the@@ -669,15 +779,36 @@ impl DomTree {} else if let Some(Some(parent)) = inner.nodes.get_mut(parent_id.index()) {parent.first_child = Some(new_sibling_id);}+ if parent_connected && !child_connected {+ Self::set_subtree_connected(&mut inner, new_sibling_id, true);+ }}pub fn detach(&self, node_id: NodeId) {+ self.detach_for_reparent(node_id, true);+ }++ fn detach_for_reparent(&self, node_id: NodeId, disconnect: bool) {let mut inner = self.inner.borrow_mut();+ // The document and registered ShadowRoots have no ordinary parent and+ // cannot be detached through light-tree mutation APIs.+ if node_id == inner.document || inner.shadow_roots.contains_key(&node_id) {+ return;+ }+let (parent_id, prev_id, next_id) = match inner.nodes.get(node_id.index()).and_then(|n| n.as_ref()) {Some(node) => (node.parent, node.prev_sibling, node.next_sibling),None => return,};+ if disconnect && inner+ .nodes+ .get(node_id.index())+ .and_then(|entry| entry.as_ref())+ .is_some_and(|node| node.connected)+ {+ Self::set_subtree_connected(&mut inner, node_id, false);+ }if let Some(prev) = prev_id {if let Some(Some(node)) = inner.nodes.get_mut(prev.index()) {@@ -1675,6 +1806,66 @@ mod tests {assert_eq!(tree.children(root), vec![shadow_child]);}+ #[test]+ fn connectivity_propagates_across_light_and_shadow_subtrees() {+ let tree = DomTree::new();+ let host = element(&tree, "x-card");+ let light = element(&tree, "span");+ tree.append_child(host, light);+ let root = tree+ .attach_shadow_root(host, ShadowRootMode::Open)+ .unwrap();+ let shadow = element(&tree, "button");+ tree.append_child(root, shadow);+ for node in [host, light, root, shadow] {+ assert!(!tree.is_connected(node));+ }++ tree.append_child(tree.document(), host);+ for node in [host, light, root, shadow] {+ assert!(tree.is_connected(node));+ }++ tree.detach(host);+ for node in [host, light, root, shadow] {+ assert!(!tree.is_connected(node));+ }+ }++ #[test]+ fn connectivity_survives_connected_moves_and_root_detach_attempts() {+ let tree = DomTree::new();+ let document = tree.document();+ let left = element(&tree, "section");+ let right = element(&tree, "section");+ let host = element(&tree, "x-card");+ let light = element(&tree, "span");+ tree.append_child(document, left);+ tree.append_child(document, right);+ tree.append_child(host, light);+ let root = tree+ .attach_shadow_root(host, ShadowRootMode::Open)+ .unwrap();+ let shadow = element(&tree, "button");+ tree.append_child(root, shadow);+ tree.append_child(left, host);++ tree.append_child(right, host);+ assert!(tree.children(left).is_empty());+ assert_eq!(tree.children(right), vec![host]);+ for node in [document, left, right, host, light, root, shadow] {+ assert!(tree.is_connected(node));+ }++ // Neither root participates in the ordinary child list, so a generic+ // detach must not corrupt the cached connectivity invariant.+ tree.detach(document);+ tree.detach(root);+ for node in [document, left, right, host, light, root, shadow] {+ assert!(tree.is_connected(node));+ }+ }+#[test]fn freeing_a_host_reclaims_shadow_nodes_and_registry_entries() {let tree = DomTree::new();@@ -1729,6 +1920,7 @@ mod tests {contents: "hello".into(),});let doc = tree.document();+ assert!(!tree.is_connected(child));tree.append_child(doc, child);assert_eq!(tree.len(), 2);@@ -1738,6 +1930,7 @@ mod tests {let child_node = tree.get_node(child).unwrap();assert_eq!(child_node.parent, Some(doc));+ assert!(tree.is_connected(child));}#[test]@@ -1765,6 +1958,8 @@ mod tests {tree.detach(c1);assert_eq!(tree.children(doc), vec![c2]);+ assert!(!tree.is_connected(c1));+ assert!(tree.is_connected(c2));}#[test]diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 61156f20..2ca54d53 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -16,6 +16,7 @@'__obscura_objects', '__obscura_oid', '__obscura_ua','__obscura_platform', '__obscura_ua_platform', '__obscura_ua_platform_version','__obscura_stealth', '__obscura_markTrusted',+ '__obscura_registerLinkedStylesheet','__markParserScripts', '__obscura_hasPendingDynamicScripts','__obscura_hasPendingLoadDelayingScripts','__obscura_nextPendingTimeoutDelay',@@ -390,6 +391,38 @@ function _resolveResourceUrl(src) {}const _linkedStylesheetNodes = new WeakMap();+const _linkElementSheets = new WeakMap();++function _linkedStylesheetHref(link, explicitHref) {+ const raw = explicitHref || link?.getAttribute?.("href") || link?.href || "";+ return raw ? _resolveResourceUrl(String(raw)) : "";+}++function _linkedStylesheetIsOriginClean(href) {+ try {+ const documentUrl = new URL(globalThis.document?.URL || globalThis.location?.href || "about:blank");+ const stylesheetUrl = new URL(href, documentUrl.href);+ return stylesheetUrl.origin === documentUrl.origin;+ } catch(e) {+ // An unresolved relative URL in an about:blank-style synthetic document+ // has no distinct remote origin and is safe to expose.+ return !/^[a-z][a-z0-9+.-]*:/i.test(String(href || ""));+ }+}++function _registerLinkedStylesheet(link, sourceNode, explicitHref) {+ if (!link || !sourceNode) return null;+ const href = _linkedStylesheetHref(link, explicitHref);+ _linkedStylesheetNodes.set(link, sourceNode);+ let sheet = _linkElementSheets.get(link);+ if (!sheet) {+ sheet = new CSSStyleSheet();+ _linkElementSheets.set(link, sheet);+ }+ sheet._bindLinkedOwner(link, sourceNode, href, _linkedStylesheetIsOriginClean(href));+ return sheet;+}+globalThis.__obscura_registerLinkedStylesheet = _registerLinkedStylesheet;// A fetched sheet becomes an inline <style>, so relative url() references// must keep resolving against the stylesheet URL rather than document.URL.@@ -527,12 +560,12 @@ async function _loadLinkedStylesheet(c) {const previous = _linkedStylesheetNodes.get(c);if (previous?.parentNode) previous.parentNode.removeChild(previous);const media = c.getAttribute("media") || "";+ const style = document.createElement("style");+ style.setAttribute("data-obscura-linked", fullUrl);+ style.textContent = css;+ _registerLinkedStylesheet(c, style, fullUrl);if (c.parentNode && !c.disabled && _cssImportApplies(media)) {- const style = document.createElement("style");- style.setAttribute("data-obscura-linked", fullUrl);- style.textContent = css;c.parentNode.insertBefore(style, c.nextSibling);- _linkedStylesheetNodes.set(c, style);}try { c.dispatchEvent(new Event('load', { bubbles: true })); } catch(e) {}} catch(e) {@@ -868,6 +901,57 @@ globalThis.cancelAnimationFrame = (id) => {};globalThis.queueMicrotask = globalThis.queueMicrotask || ((fn) => Promise.resolve().then(fn));+// Browser posted tasks need an event-loop boundary but no clock delay. Tokio's+// timer wheel imposes roughly a one-millisecond floor even for delay zero,+// which turns MessageChannel and scheduler chains into artificial latency.+// Keep one shared priority/FIFO queue in JavaScript and use a yield-only async+// op solely to wake one delivery. Scheduling the next wake after the callback+// gives V8 a microtask checkpoint between every pair of posted tasks.+const _browserPostedTaskQueues = Array.from({ length: 6 }, () => []);+let _browserPostedTaskWakePending = false;++function _browserPostedTaskScheduleWake() {+ if (_browserPostedTaskWakePending) return;+ if (!Deno.core.ops.op_async_runtime_available()) return;+ _browserPostedTaskWakePending = true;+ Deno.core.ops.op_posted_task().then(+ _browserPostedTaskRunOne,+ () => {+ _browserPostedTaskWakePending = false;+ if (_browserPostedTaskQueues.some(queue => queue.length)) {+ _scheduleAfter(0, _browserPostedTaskRunOne);+ }+ },+ );+}++function _browserPostedTaskEnqueue(callback, priority) {+ _browserPostedTaskQueues[priority].push(callback);+ _browserPostedTaskScheduleWake();+}++function _browserPostedTaskRunOne() {+ _browserPostedTaskWakePending = false;+ let callback = null;+ for (let priority = _browserPostedTaskQueues.length - 1; priority >= 0; priority--) {+ const queue = _browserPostedTaskQueues[priority];+ if (queue.length) {+ callback = queue.shift();+ break;+ }+ }+ if (!callback) return;++ Deno.core.ops.op_begin_render_task?.();+ try { callback(); }+ catch (error) { console.error("Posted task error:", error); }+ finally {+ if (_browserPostedTaskQueues.some(queue => queue.length)) {+ _browserPostedTaskScheduleWake();+ }+ }+}+// Prioritized Task Scheduling. A scheduler task is a real event-loop task,// ordered strictly by effective priority and FIFO within one priority. Yield// continuations rank immediately above ordinary tasks of the same priority.@@ -880,8 +964,6 @@ const _schedulerPriorityRank = {"user-visible": 1,"user-blocking": 2,};-const _schedulerTaskQueues = Array.from({ length: 6 }, () => []);-let _schedulerPumpScheduled = false;let _schedulerCurrentState = null;function _schedulerRemoveAbort(task) {@@ -891,35 +973,15 @@ function _schedulerRemoveAbort(task) {}}-function _schedulerSchedulePump() {- if (_schedulerPumpScheduled) return;- _schedulerPumpScheduled = true;- _scheduleAfter(0, _schedulerRunOneTask);-}-function _schedulerEnqueue(task, continuation) {if (task.canceled) return;const effectivePriority = _schedulerPriorityRank[task.priority] * 2+ (continuation ? 1 : 0);- _schedulerTaskQueues[effectivePriority].push(task);- _schedulerSchedulePump();-}--function _schedulerRunOneTask() {- _schedulerPumpScheduled = false;- let task = null;- for (let priority = _schedulerTaskQueues.length - 1; priority >= 0; priority--) {- const queue = _schedulerTaskQueues[priority];- while (queue.length) {- const candidate = queue.shift();- if (!candidate.canceled) {- task = candidate;- break;- }- }- if (task) break;- }- if (!task) return;+ _browserPostedTaskEnqueue(() => _schedulerRunTask(task), effectivePriority);+}++function _schedulerRunTask(task) {+ if (task.canceled) return;task.started = true;const previousState = _schedulerCurrentState;@@ -938,11 +1000,6 @@ function _schedulerRunOneTask() {task.completed = true;_schedulerRemoveAbort(task);}-- // Queue only one native task at a time. This preserves a microtask- // checkpoint between scheduler callbacks and lets newly posted high-priority- // work overtake lower-priority work which is still waiting.- if (_schedulerTaskQueues.some(queue => queue.length)) _schedulerSchedulePump();}function _schedulerNormalizeOptions(options) {@@ -1109,7 +1166,9 @@ function _messagePortScheduleDelivery(port) {const state = _messagePortStateFor(port);if (state.closed || !state.messageQueueEnabled || state.messageDeliveryPending || !state.messageQueue.length) return;state.messageDeliveryPending = true;- _scheduleAfter(0, () => {+ // User-visible ordinary rank. Scheduler continuations at the same priority+ // remain immediately above this task; FIFO holds across all ordinary tasks.+ _browserPostedTaskEnqueue(() => {const current = _messagePortState.get(port);if (!current) return;current.messageDeliveryPending = false;@@ -1124,7 +1183,7 @@ function _messagePortScheduleDelivery(port) {});_eventTargetDispatch(port, event);_messagePortScheduleDelivery(port);- });+ }, _schedulerPriorityRank["user-visible"] * 2);}class MessagePort {constructor(key) {@@ -1810,7 +1869,12 @@ class Node {return c;}removeChild(c) {- if (!c) return c;+ if (!c || c.parentNode !== this) {+ throw new DOMException(+ "Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.",+ 'NotFoundError'+ );+ }const removedWindowNames = _windowNamedNamesInTree(c);const linkedStyle = c instanceof Element? _linkedStylesheetNodes.get(c)@@ -1914,13 +1978,15 @@ class Node {return (+_dom("compare_order", this._nid, other._nid) < 0) ? 4 : 2;}getRootNode(options) {- let root = this;- while (root.parentNode) root = root.parentNode;+ const root = _wrap(+_dom("node_root", this._nid));if (options?.composed && root instanceof ShadowRoot) {return root.host.getRootNode(options);}return root;}+ get isConnected() {+ return _dom("is_connected", this._nid) === "true";+ }normalize() {// Merge adjacent exclusive Text nodes, drop empty ones, recurse. Detached// removed nodes keep their own data (read from the backing node by nid).@@ -4158,10 +4224,6 @@ class Element extends Node {return animation;}getAnimations() { return _animationsForTarget(this); }- get isConnected() {- const root = this.getRootNode({ composed: true });- return !!root && root.nodeType === 9;- }remove() { if (this.parentNode) this.parentNode.removeChild(this); }append(...nodes) { for (const n of _convertNodes(nodes)) this.appendChild(n); }prepend(...nodes) {@@ -7652,6 +7714,8 @@ class CSSStyleSheet {this._ownerNode = null;this._sourceNode = null;this._sourceText = "";+ this._href = null;+ this._originClean = true;this._rules = [];this._cssRules = new CSSRuleList(this);this._adopters = new Set();@@ -7659,9 +7723,13 @@ class CSSStyleSheet {get type() { return "text/css"; }get ownerNode() { return this._ownerNode; }get parentStyleSheet() { return null; }- get href() { return null; }+ get href() { return this._href; }get title() { return this._ownerNode?.getAttribute?.("title") || ""; }- get cssRules() { this._refreshFromOwner(); return this._cssRules; }+ get cssRules() {+ this._assertOriginClean();+ this._refreshFromOwner();+ return this._cssRules;+ }get rules() { return this.cssRules; }_bindOwner(ownerNode, sourceNode = ownerNode) {this._ownerNode = ownerNode;@@ -7669,8 +7737,25 @@ class CSSStyleSheet {this._sourceText = null;this._refreshFromOwner();}+ _bindLinkedOwner(ownerNode, sourceNode, href, originClean) {+ this._ownerNode = ownerNode;+ this._sourceNode = sourceNode;+ this._sourceText = null;+ this._href = href || null;+ this._originClean = originClean !== false;+ if (this._originClean) this._refreshFromOwner();+ else {+ this._setRules([]);+ this._sourceText = sourceNode?.textContent || "";+ }+ }+ _assertOriginClean() {+ if (!this._originClean) {+ throw new DOMException("Cannot access rules in a cross-origin stylesheet", "SecurityError");+ }+ }_refreshFromOwner() {- if (!this._sourceNode) return;+ if (!this._sourceNode || !this._originClean) return;const text = this._sourceNode.textContent || "";if (text === this._sourceText) return;const parsed = _splitTopLevelCssRules(text);@@ -7696,6 +7781,7 @@ class CSSStyleSheet {}insertRule(rule, index = 0) {if (arguments.length < 1) throw new TypeError("CSSStyleSheet.insertRule requires a rule");+ this._assertOriginClean();this._refreshFromOwner();const idx = Number(index) >>> 0;if (idx > this._rules.length) throw new DOMException("Rule index is out of range", "IndexSizeError");@@ -7712,6 +7798,7 @@ class CSSStyleSheet {}deleteRule(index) {if (arguments.length < 1) throw new TypeError("CSSStyleSheet.deleteRule requires an index");+ this._assertOriginClean();this._refreshFromOwner();const idx = Number(index) >>> 0;if (idx >= this._rules.length) throw new DOMException("Rule index is out of range", "IndexSizeError");@@ -7726,6 +7813,7 @@ class CSSStyleSheet {removeRule(index = 0) { this.deleteRule(index); }replace(text) { this.replaceSync(text); return Promise.resolve(this); }replaceSync(text) {+ this._assertOriginClean();const parsed = _splitTopLevelCssRules(String(text));this._setRules(parsed.rules.map(_cssRuleFromText).filter(Boolean));this._ruleChanged();@@ -7733,8 +7821,18 @@ class CSSStyleSheet {}const _styleElementSheets = new WeakMap();+function _styleElementIsCssomBridge(style) {+ return style.hasAttribute("data-obscura-adopted")+ || style.hasAttribute("data-obscura-linked")+ || style.hasAttribute("data-obscura-external-stylesheets")+ || style.hasAttribute("data-obscura-inline-import");+}function _styleElementHasCssSheet(style) {if (!style || style.localName !== "style" || !style.isConnected) return false;+ // These nodes carry renderer input for another stylesheet owner. Exposing a+ // second style-owned sheet would duplicate entries and, for remote links,+ // bypass the link sheet's origin-clean cssRules check.+ if (_styleElementIsCssomBridge(style)) return false;const type = (style.getAttribute("type") || "").trim().toLowerCase();return !type || type === "text/css";}@@ -7758,11 +7856,40 @@ function _detachStyleSheet(style) {sheet._sourceNode = null;_styleElementSheets.delete(style);}+function _linkElementHasCssSheet(link) {+ if (!link || link.localName !== "link" || !link.isConnected) return false;+ const rel = (link.getAttribute("rel") || link.rel || "").toLowerCase().split(/\s+/);+ const type = (link.getAttribute("type") || "").trim().toLowerCase();+ return rel.includes("stylesheet") && (!type || type === "text/css")+ && _linkedStylesheetNodes.has(link);+}+function _sheetForLinkElement(link) {+ if (!_linkElementHasCssSheet(link)) {+ _detachLinkedStyleSheet(link);+ return null;+ }+ let sheet = _linkElementSheets.get(link);+ if (!sheet) {+ sheet = _registerLinkedStylesheet(link, _linkedStylesheetNodes.get(link));+ }+ return sheet;+}+function _detachLinkedStyleSheet(link) {+ const sheet = _linkElementSheets.get(link);+ if (!sheet) return;+ sheet._ownerNode = null;+ sheet._sourceNode = null;+ _linkElementSheets.delete(link);+}function _detachStyleSheetsInSubtree(root) {if (!root) return;if (root.nodeType === 1 && root.localName === "style") _detachStyleSheet(root);+ if (root.nodeType === 1 && root.localName === "link") _detachLinkedStyleSheet(root);if (!root.querySelectorAll) return;for (const style of root.querySelectorAll("style")) _detachStyleSheet(style);+ for (const link of root.querySelectorAll('link[rel~="stylesheet"]')) {+ _detachLinkedStyleSheet(link);+ }}class StyleSheetList {@@ -7784,13 +7911,17 @@ class StyleSheetList {});}_sheets() {- const styles = this._root.querySelectorAll ? this._root.querySelectorAll("style") : [];+ const nodes = this._root.querySelectorAll+ ? this._root.querySelectorAll('style, link[rel~="stylesheet"]')+ : [];const out = [];- for (const style of styles) {- if (style.hasAttribute("data-obscura-adopted")- || style.hasAttribute("data-obscura-linked")- || style.hasAttribute("data-obscura-external-stylesheets")- || style.hasAttribute("data-obscura-inline-import")) continue;+ for (const style of nodes) {+ if (style.localName === "link") {+ const sheet = _sheetForLinkElement(style);+ if (sheet) out.push(sheet);+ continue;+ }+ if (_styleElementIsCssomBridge(style)) continue;const sheet = _sheetForStyleElement(style);if (sheet) out.push(sheet);}@@ -7806,7 +7937,11 @@ class StyleSheetList {}Object.defineProperty(Element.prototype, "sheet", {- get() { return this.localName === "style" ? _sheetForStyleElement(this) : null; },+ get() {+ if (this.localName === "style") return _sheetForStyleElement(this);+ if (this.localName === "link") return _sheetForLinkElement(this);+ return null;+ },configurable: true,});globalThis.CSSRule = CSSRule;@@ -10585,8 +10720,10 @@ function _windowNamedNamesInTree(root) {function _registerWindowNamedTree(root) {// Window named access only considers the document tree. Detached nodes and- // attached shadow trees must not manufacture own Window properties.- if (!root || root.getRootNode() !== globalThis.document) return;+ // attached shadow trees must not manufacture own Window properties. Check+ // connectivity first: getRootNode() walks every ancestor, which made the+ // common framework pattern of building a deep detached subtree quadratic.+ if (!root || !root.isConnected || root.getRootNode() !== globalThis.document) return;const names = _windowNamedNamesInTree(root);for (const name of names) _ensureWindowNamedProperty(name);}diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex c82c0263..098039c8 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -407,7 +407,7 @@ struct RenderMutationImpact {}fn node_is_connected(dom: &DomTree, node: NodeId) -> bool {- dom.shadow_including_root(node) == Some(dom.document())+ dom.is_connected(node)}#[cfg(feature = "render")]@@ -673,6 +673,45 @@ fn retained_style_mutation(}}+#[cfg(feature = "render")]+const MAX_PENDING_STYLE_MUTATIONS: usize = 256;++/// Queue one retained-style invalidation without letting animation frameworks+/// evict the whole prepared render merely because they rewrite the same inline+/// style more than once before the next rendering opportunity.+///+/// A `style` mutation does not carry selector values: the retained planner+/// dirties that element/subtree and reads the final inline declaration from the+/// live DOM. Repeating the same dirty marker for one node is therefore+/// idempotent. Other attributes retain their complete transition sequence;+/// selector invalidation needs their old and new values.+#[cfg(feature = "render")]+fn queue_retained_style_mutation(+ pending: &mut Vec<obscura_render::RetainedStyleMutation>,+ mutation: obscura_render::RetainedStyleMutation,+) -> bool {+ if let obscura_render::RetainedStyleMutation::Attribute(next) = &mutation {+ if next.name.eq_ignore_ascii_case("style")+ && pending.iter().any(|queued| {+ matches!(+ queued,+ obscura_render::RetainedStyleMutation::Attribute(current)+ if current.node == next.node+ && current.name.eq_ignore_ascii_case("style")+ )+ })+ {+ return true;+ }+ }++ if pending.len() >= MAX_PENDING_STYLE_MUTATIONS {+ return false;+ }+ pending.push(mutation);+ true+}+#[cfg(feature = "render")]fn render_timing_enabled() -> bool {static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();@@ -936,11 +975,12 @@ fn op_dom_inner(state: &OpState, cmd: String, arg1: String, arg2: String) -> Str.note_subtree_start_candidate(root, mutation_time_ms);}if let Some(mutation) = retained_style_mutation {- if state.prepared_render.is_some()- && state.pending_style_mutations.len() < 256- {- state.pending_style_mutations.push(mutation);- } else {+ let retained = state.prepared_render.is_some()+ && queue_retained_style_mutation(+ &mut state.pending_style_mutations,+ mutation,+ );+ if !retained {state.prepared_render = None;state.pending_style_mutations.clear();}@@ -1533,6 +1573,13 @@ fn op_dom_inner(state: &OpState, cmd: String, arg1: String, arg2: String) -> Str.contains(&NodeId::new(other)).to_string()}+ // Connectivity is maintained incrementally by DomTree. Exposing the+ // cached bit avoids an ancestor op crossing for every level when JS+ // builds a deep detached subtree.+ "is_connected" => {+ let nid = arg1.parse::<u32>().unwrap_or(0);+ dom.is_connected(NodeId::new(nid)).to_string()+ }// Index of a node among its parent's children. Walks prev siblings in// Rust, avoiding the per-step JS->op round trips a Range comparison// would otherwise make.@@ -2519,14 +2566,17 @@ fn glob_match(pattern: &str, url: &str) -> bool {#[cfg(test)]mod tests {use super::{cors_response_allows, glob_match, validate_fetch_url, FetchCredentials};+ use crate::runtime::ObscuraJsRuntime;+ use obscura_dom::parse_html;#[cfg(feature = "render")]use super::{ensure_prepared_geometry, ensure_prepared_render, node_is_connected,- retained_style_mutation, shadow_including_connected_nodes, ObscuraState,+ queue_retained_style_mutation, retained_style_mutation,+ shadow_including_connected_nodes, ObscuraState,};#[cfg(feature = "render")]- use obscura_dom::{parse_html, ShadowRootMode};+ use obscura_dom::ShadowRootMode;#[test]fn glob_match_handles_cdp_blocked_url_patterns() {@@ -2606,6 +2656,134 @@ mod tests {assert!(validate_fetch_url(&loopback, true).is_ok());}+ #[tokio::test(flavor = "current_thread")]+ async fn posted_task_chains_complete_without_zero_delay_timer_floor() {+ let mut runtime = ObscuraJsRuntime::new();+ runtime.set_dom(parse_html("<html><body></body></html>"));+ runtime.set_url("http://example.com/posted-task-test");+ runtime.run_page_init();+ runtime+ .execute_script(+ "posted-task-throughput",+ r#"+ globalThis.__postedTaskBench = {+ message: 0,+ postTask: 0,+ yields: 0,+ started: performance.now(),+ finished: 0,+ };+ const markFinished = () => {+ if (__postedTaskBench.message === 100 &&+ __postedTaskBench.postTask === 100 &&+ __postedTaskBench.yields === 100) {+ __postedTaskBench.finished = performance.now();+ }+ };++ const channel = new MessageChannel();+ channel.port2.onmessage = () => {+ __postedTaskBench.message++;+ if (__postedTaskBench.message < 100) channel.port1.postMessage(null);+ else markFinished();+ };+ channel.port1.postMessage(null);++ const postNext = () => scheduler.postTask(() => {+ __postedTaskBench.postTask++;+ if (__postedTaskBench.postTask < 100) postNext();+ else markFinished();+ });+ postNext();++ scheduler.postTask(async () => {+ while (__postedTaskBench.yields < 100) {+ await scheduler.yield();+ __postedTaskBench.yields++;+ }+ markFinished();+ });+ "#,+ )+ .unwrap();++ runtime.run_event_loop_bounded(100).await.unwrap();+ let result = runtime+ .evaluate(+ r#"[+ __postedTaskBench.message,+ __postedTaskBench.postTask,+ __postedTaskBench.yields,+ __postedTaskBench.finished - __postedTaskBench.started,+ ]"#,+ )+ .unwrap();+ let values = result.as_array().unwrap();+ assert!(+ values[..3].iter().all(|value| value.as_f64() == Some(100.0)),+ "posted-task chains did not finish inside the 100ms pump: {result}",+ );+ assert!(+ values[3].as_f64().is_some_and(|elapsed| elapsed >= 0.0 && elapsed < 75.0),+ "300 chained posted-task deliveries retained timer-wheel latency: {result}",+ );+ }++ #[tokio::test(flavor = "current_thread")]+ async fn shared_posted_task_queue_preserves_priority_fifo_and_microtasks() {+ let mut runtime = ObscuraJsRuntime::new();+ runtime.set_dom(parse_html("<html><body></body></html>"));+ runtime.set_url("http://example.com/posted-task-order");+ runtime.run_page_init();+ runtime+ .execute_script(+ "shared-posted-task-order",+ r#"+ globalThis.__sharedPostedOrder = ["sync"];+ const channel = new MessageChannel();+ channel.port2.onmessage = event => {+ __sharedPostedOrder.push("message-" + event.data);+ Promise.resolve().then(() => {+ __sharedPostedOrder.push("message-" + event.data + "-microtask");+ });+ };+ channel.port1.postMessage(1);+ scheduler.postTask(() => {+ __sharedPostedOrder.push("visible");+ Promise.resolve().then(() => __sharedPostedOrder.push("visible-microtask"));+ });+ channel.port1.postMessage(2);+ scheduler.postTask(() => {+ __sharedPostedOrder.push("background");+ }, { priority: "background" });+ scheduler.postTask(() => {+ __sharedPostedOrder.push("blocking");+ Promise.resolve().then(() => __sharedPostedOrder.push("blocking-microtask"));+ }, { priority: "user-blocking" });+ Promise.resolve().then(() => __sharedPostedOrder.push("initial-microtask"));+ "#,+ )+ .unwrap();++ runtime.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ runtime.evaluate("__sharedPostedOrder").unwrap(),+ serde_json::json!([+ "sync",+ "initial-microtask",+ "blocking",+ "blocking-microtask",+ "message-1",+ "message-1-microtask",+ "visible",+ "visible-microtask",+ "message-2",+ "message-2-microtask",+ "background",+ ]),+ );+ }+#[cfg(feature = "render")]#[test]fn connected_shadow_nodes_invalidate_without_entering_light_tree_retention() {@@ -2635,6 +2813,56 @@ mod tests {assert!(!shadow_including_connected_nodes(&dom).contains(&child));}+ #[cfg(feature = "render")]+ #[test]+ fn repeated_inline_style_writes_share_one_retained_dirty_marker_per_node() {+ let mut pending = Vec::new();+ let style_mutation = |raw| {+ obscura_render::RetainedStyleMutation::Attribute(+ obscura_render::AttributeStyleMutation {+ node: obscura_dom::tree::NodeId::new(raw),+ name: "style".to_string(),+ old_value: None,+ new_value: None,+ },+ )+ };++ // Motion/React commonly writes a connected element's serialized style+ // twice in one commit. The old queue reached its 256-record ceiling at+ // only 128 elements and discarded the complete PreparedRender.+ for raw in 1..=200 {+ assert!(queue_retained_style_mutation(+ &mut pending,+ style_mutation(raw),+ ));+ assert!(queue_retained_style_mutation(+ &mut pending,+ style_mutation(raw),+ ));+ }+ assert_eq!(pending.len(), 200);++ // The memory bound remains real: unique dirty nodes still consume one+ // slot, while an already-recorded node remains safe at the ceiling.+ for raw in 201..=256 {+ assert!(queue_retained_style_mutation(+ &mut pending,+ style_mutation(raw),+ ));+ }+ assert_eq!(pending.len(), 256);+ assert!(queue_retained_style_mutation(+ &mut pending,+ style_mutation(1),+ ));+ assert!(!queue_retained_style_mutation(+ &mut pending,+ style_mutation(257),+ ));+ assert_eq!(pending.len(), 256);+ }+#[cfg(feature = "render")]#[test]fn geometry_consumer_defers_paint_only_sample_until_exact_consumer() {@@ -2794,6 +3022,16 @@ fn op_async_runtime_available() -> bool {tokio::runtime::Handle::try_current().is_ok()}+/// Wake one browser posted task without routing through Tokio's timer wheel.+/// `yield_now` guarantees the op cannot settle in the initiating JavaScript+/// turn, while avoiding the roughly one-millisecond floor of a zero-duration+/// timer. The bootstrap owns task priority, FIFO order, and one-at-a-time+/// delivery; this op supplies only the event-loop wake boundary.+#[op2(async)]+async fn op_posted_task() {+ tokio::task::yield_now().await;+}+// Records a binding call from page JS. The CDP layer drains this queue// after every dispatch and emits one `Runtime.bindingCalled` event per// entry, that's how puppeteer's `page.exposeFunction` callbacks fire.@@ -3498,6 +3736,7 @@ pub fn build_extension() -> Extension {op_set_cookie(),op_navigate(),op_async_runtime_available(),+ op_posted_task(),op_binding_called(),op_subtle_digest(),op_subtle_hmac(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 1617ba05..4629df63 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -50,6 +50,8 @@ static SNAPSHOT: &[u8] = include_bytes!(env!("OBSCURA_SNAPSHOT_PATH"));/// parallel, each isolate on its own thread with no shared lock.static ISOLATE_CREATE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+const DEFAULT_CDP_AWAIT_TIMEOUT_MS: u64 = 30_000;+#[cfg(feature = "render")]fn with_sync_render_loading_disabled<R>(state: &mut ObscuraState,@@ -918,6 +920,22 @@ impl ObscuraJsRuntime {expression: &str,return_by_value: bool,await_promise: bool,+ ) -> Result<RemoteObjectInfo, String> {+ self.evaluate_for_cdp_with_timeout(+ expression,+ return_by_value,+ await_promise,+ DEFAULT_CDP_AWAIT_TIMEOUT_MS,+ )+ .await+ }++ pub async fn evaluate_for_cdp_with_timeout(+ &mut self,+ expression: &str,+ return_by_value: bool,+ await_promise: bool,+ await_timeout_ms: u64,) -> Result<RemoteObjectInfo, String> {if !await_promise && return_by_value {let val = self.evaluate(expression)?;@@ -984,18 +1002,24 @@ impl ObscuraJsRuntime {let meta_str = if await_promise {let __t0 = std::time::Instant::now();let sentinel = format!("globalThis.__obscura_done_{done_counter} === true");- self.resolve_promises_until(- |rt| {- rt.runtime- .execute_script("<done?>", sentinel.clone())- .ok()- .and_then(|v| rt.v8_to_json(v).ok())- .and_then(|j| j.as_bool())- .unwrap_or(false)- },- 5000,- )- .await;+ let settled = self+ .resolve_promises_until(+ |rt| {+ rt.runtime+ .execute_script("<done?>", sentinel.clone())+ .ok()+ .and_then(|v| rt.v8_to_json(v).ok())+ .and_then(|j| j.as_bool())+ .unwrap_or(false)+ },+ await_timeout_ms,+ )+ .await;+ if !settled {+ return Err(format!(+ "Runtime.evaluate promise did not settle within {await_timeout_ms}ms"+ ));+ }let __dt = __t0.elapsed();if __dt > std::time::Duration::from_secs(1) {let preview: String = expression@@ -1063,6 +1087,26 @@ impl ObscuraJsRuntime {arguments: &[serde_json::Value],return_by_value: bool,await_promise: bool,+ ) -> Result<RemoteObjectInfo, String> {+ self.call_function_on_for_cdp_with_timeout(+ function_declaration,+ object_id,+ arguments,+ return_by_value,+ await_promise,+ DEFAULT_CDP_AWAIT_TIMEOUT_MS,+ )+ .await+ }++ pub async fn call_function_on_for_cdp_with_timeout(+ &mut self,+ function_declaration: &str,+ object_id: Option<&str>,+ arguments: &[serde_json::Value],+ return_by_value: bool,+ await_promise: bool,+ await_timeout_ms: u64,) -> Result<RemoteObjectInfo, String> {self.begin_javascript_task();let this_expr = self.resolve_this(object_id);@@ -1108,18 +1152,24 @@ impl ObscuraJsRuntime {let __t0 = std::time::Instant::now();let sentinel = format!("globalThis.__obscura_done_{done_counter} === true");- self.resolve_promises_until(- |rt| {- rt.runtime- .execute_script("<done?>", sentinel.clone())- .ok()- .and_then(|v| rt.v8_to_json(v).ok())- .and_then(|j| j.as_bool())- .unwrap_or(false)- },- 5000,- )- .await;+ let settled = self+ .resolve_promises_until(+ |rt| {+ rt.runtime+ .execute_script("<done?>", sentinel.clone())+ .ok()+ .and_then(|v| rt.v8_to_json(v).ok())+ .and_then(|j| j.as_bool())+ .unwrap_or(false)+ },+ await_timeout_ms,+ )+ .await;+ if !settled {+ return Err(format!(+ "Runtime.callFunctionOn promise did not settle within {await_timeout_ms}ms"+ ));+ }let __dt = __t0.elapsed();if __dt > std::time::Duration::from_secs(1) {let preview: String = function_declaration@@ -1836,6 +1886,68 @@ impl ObscuraJsRuntime {.await}+ /// Drive one browser task while allowing the future to remain parked on+ /// deno_core's real timer/network waker. This is the long-lived browser+ /// server counterpart to bounded screenshot settling: the owner selects+ /// this future alongside incoming protocol commands, so a page continues+ /// to make progress while the automation client is idle without polling at+ /// a fixed frequency.+ ///+ /// The shared CDP watchdog is armed only around synchronous V8 entry. It is+ /// deliberately disarmed while `Poll::Pending`; a legitimate distant timer+ /// must not look like a hung JavaScript task merely because the runtime is+ /// asleep waiting for it.+ #[doc(hidden)]+ pub async fn run_autonomous_event_loop_turn(&mut self) -> Result<bool, String> {+ const AUTONOMOUS_TASK_WATCHDOG_MS: u64 =+ SYNCHRONOUS_TASK_FLOOR_MS + WATCHDOG_SCHEDULING_MARGIN_MS;++ self.begin_javascript_task();++ let checkpoint_watchdog = crate::cdp_watchdog::arm(+ self.isolate_handle(),+ std::time::Duration::from_millis(AUTONOMOUS_TASK_WATCHDOG_MS),+ );+ self.runtime.v8_isolate().perform_microtask_checkpoint();+ if crate::cdp_watchdog::disarm(checkpoint_watchdog) {+ self.cancel_termination();+ return Err("autonomous microtask checkpoint exceeded its task budget".into());+ }++ let isolate_handle = self.isolate_handle();+ let mut waiting_for_wake = false;+ std::future::poll_fn(|cx| {+ let watchdog = crate::cdp_watchdog::arm(+ isolate_handle.clone(),+ std::time::Duration::from_millis(AUTONOMOUS_TASK_WATCHDOG_MS),+ );+ let tick = self+ .runtime+ .poll_event_loop(cx, deno_core::PollEventLoopOptions::default());+ let watchdog_fired = crate::cdp_watchdog::disarm(watchdog);+ if watchdog_fired {+ self.runtime.v8_isolate().cancel_terminate_execution();+ return std::task::Poll::Ready(Err(+ "autonomous browser task exceeded its task budget".into(),+ ));+ }+ match tick {+ std::task::Poll::Ready(Ok(())) => std::task::Poll::Ready(Ok(true)),+ std::task::Poll::Ready(Err(error)) => std::task::Poll::Ready(Err(format!(+ "Event loop error: {error}"+ ))),+ std::task::Poll::Pending if waiting_for_wake => {+ std::task::Poll::Ready(Ok(false))+ }+ std::task::Poll::Pending => {+ waiting_for_wake = true;+ std::task::Poll::Pending+ }+ }+ })+ .await+ }+/// Drive one cooperative event-loop turn for browser lifecycle code that/// must re-check an external readiness predicate after every wake. The/// boolean is true only when deno_core reached full idle.@@ -2011,7 +2123,8 @@ impl ObscuraJsRuntime {}/// Pump the event loop until `done_check` returns true (e.g. an IIFE- /// has written its result sentinel), or `max_total_ms` elapses.+ /// has written its result sentinel), or `max_total_ms` elapses. Returns+ /// whether the predicate completed before the deadline.////// Why this exists: `run_event_loop(default)` only returns when there is/// no pending work. Page JS routinely schedules long setTimeouts@@ -2021,7 +2134,11 @@ impl ObscuraJsRuntime {/// added ~7s per click because Puppeteer's `isIntersectingViewport`/// disconnects its observer in the callback, but our scheduled/// re-fires keep the event loop "busy" until they all fire.- pub async fn resolve_promises_until<F>(&mut self, mut done_check: F, max_total_ms: u64)+ pub async fn resolve_promises_until<F>(+ &mut self,+ mut done_check: F,+ max_total_ms: u64,+ ) -> boolwhereF: FnMut(&mut Self) -> bool,{@@ -2031,10 +2148,10 @@ impl ObscuraJsRuntime {loop {self.begin_javascript_task();if done_check(self) {- return;+ return true;}if tokio::time::Instant::now() >= deadline {- return;+ return false;}// Pump for a short slice. If the loop returns idle in <tick_ms,// run_event_loop returns Ok and we check the predicate again.@@ -12047,6 +12164,46 @@ mod tests {assert_eq!(result.value.unwrap().as_str().unwrap(), "done");}+ #[tokio::test(flavor = "current_thread")]+ async fn test_evaluate_for_cdp_can_await_beyond_legacy_five_second_cap() {+ let mut rt = setup_runtime("<html><body></body></html>");+ let started = std::time::Instant::now();+ let result = rt+ .evaluate_for_cdp_with_timeout(+ "new Promise(resolve => setTimeout(() => resolve('after-five'), 5100))",+ true,+ true,+ 6000,+ )+ .await+ .unwrap();+ assert_eq!(result.value.unwrap().as_str(), Some("after-five"));+ assert!(+ started.elapsed() >= std::time::Duration::from_secs(5),+ "long promise resolved before its timer deadline"+ );+ }++ #[tokio::test(flavor = "current_thread")]+ async fn test_call_function_on_for_cdp_reports_unsettled_promise_timeout() {+ let mut rt = setup_runtime("<html><body></body></html>");+ let error = rt+ .call_function_on_for_cdp_with_timeout(+ "() => new Promise(() => {})",+ None,+ &[],+ true,+ true,+ 25,+ )+ .await+ .unwrap_err();+ assert!(+ error.contains("did not settle within 25ms"),+ "unexpected timeout error: {error}"+ );+ }+#[tokio::test(flavor = "current_thread")]async fn test_evaluate_for_cdp_awaits_async_function() {let mut rt = setup_runtime("<html><body></body></html>");@@ -12786,6 +12943,16 @@ mod tests {const style = document.querySelector("style[data-obscura-linked]");const css = style.textContent;const afterLink = link.nextSibling === style;+ const list = document.styleSheets;+ const sheet = link.sheet;+ const rules = sheet.cssRules;+ const cssom = {+ listed: list.length === 1 && list[0] === sheet,+ stable: link.sheet === sheet && sheet.cssRules === rules,+ owner: sheet.ownerNode === link,+ href: sheet.href,+ selectors: Array.from(rules, rule => rule.selectorText),+ };link.remove();return {afterLink,@@ -12797,6 +12964,10 @@ mod tests {css.includes("http://example.com/img/card.png"),removedWithLink:!document.querySelector("style[data-obscura-linked]"),+ cssom,+ detachedCssom: sheet.ownerNode === null+ && link.sheet === null+ && list.length === 0,};} finally {Deno.core.ops.op_fetch_url = originalFetchOp;@@ -12818,6 +12989,14 @@ mod tests {"importedUrl": true,"routeUrl": true,"removedWithLink": true,+ "cssom": {+ "listed": true,+ "stable": true,+ "owner": true,+ "href": "http://example.com/assets/route.css",+ "selectors": [".card", ".card"],+ },+ "detachedCssom": true,}));}diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 013c8a3f..6e7f819b 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -11970,7 +11970,15 @@ fn build({taffy_style.display = taffy::style::Display::Flex;taffy_style.flex_direction = taffy::FlexDirection::Row;- taffy_style.flex_wrap = taffy::FlexWrap::Wrap;+ // The row-flex stand-in is our inline formatting context. A nowrap+ // table cell (Bootstrap input groups, segmented controls, toolbars)+ // must keep adjacent atomic inline children on one line; wrapping+ // them here doubles the table row and stretches every sibling cell.+ taffy_style.flex_wrap = if style.white_space == Some(crate::WhiteSpace::NoWrap) {+ taffy::FlexWrap::NoWrap+ } else {+ taffy::FlexWrap::Wrap+ };// The promoted container's main axis is horizontal, so text alignment// belongs on `justify_content`. Real `justify-content` from actual CSS@@ -18248,6 +18256,39 @@ mod tests {}}+ #[cfg(feature = "paint")]+ #[test]+ fn nowrap_table_cell_keeps_bootstrap_controls_on_one_row() {+ let tree = parse_html(+ r#"<style>+ * { box-sizing:border-box }+ html,body { margin:0 }+ #group { display:table; width:750px; border-collapse:separate }+ #field,#actions { display:table-cell; height:55px }+ #field { float:left; width:100% }+ #actions { width:1%; white-space:nowrap }+ #bulk,#submit { display:inline-block; height:55px }+ #bulk { width:60px }+ #submit { width:42px }+ </style>+ <div id="group"><input id="field"><span id="actions"><a id="bulk"></a><button id="submit"></button></span></div>"#,+ );+ let laid = layout_dom(&tree, (900.0, 250.0));+ let rect = |id: &str| laid.rects[&tree.get_element_by_id(id).unwrap()];+ let group = rect("group");+ let field = rect("field");+ let actions = rect("actions");+ let bulk = rect("bulk");+ let submit = rect("submit");++ assert!((group.height - 55.0).abs() < 0.1, "{group:?}");+ assert!((field.height - 55.0).abs() < 0.1, "{field:?}");+ assert!((actions.height - 55.0).abs() < 0.1, "{actions:?}");+ assert!((submit.x - (bulk.x + bulk.width)).abs() < 0.1);+ assert!((bulk.y - submit.y).abs() < 0.1);+ assert!(((submit.x + submit.width) - (group.x + group.width)).abs() < 0.1);+ }+#[test]fn auto_width_authored_table_honors_percentage_cell_intrinsic_constraints() {let tree = parse_html(