The headless browser for AI agents and web scraping
Retain rendering through resource and hydration updates
SGavrl4686e8f4074c
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex a262fa99..03749031 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -674,22 +674,32 @@ fn retained_style_mutation(}#[cfg(feature = "render")]-const MAX_PENDING_STYLE_MUTATIONS: usize = 256;+// Modern hydration can touch thousands of distinct connected nodes before the+// first rendering opportunity. Keep a bounded safety valve for adversarial+// churn, but do not force a whole-document cascade at the scale of an ordinary+// React/Framer commit.+const MAX_PENDING_STYLE_MUTATIONS: usize = 4_096;/// 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.+/// Rendering observes the attribute state at flush boundaries. Repeated writes+/// to the same node/name therefore retain the first old value and final new+/// value; intermediate values were never rendered and cannot affect selector+/// matching. Inline style uses the same rule without storing serialized values.#[cfg(feature = "render")]-fn queue_retained_style_mutation(+pub(crate) fn queue_retained_style_mutation(pending: &mut Vec<obscura_render::RetainedStyleMutation>,mutation: obscura_render::RetainedStyleMutation,) -> bool {+ let is_resource = matches!(mutation, obscura_render::RetainedStyleMutation::Resource);+ let has_resource = pending+ .iter()+ .any(|queued| matches!(queued, obscura_render::RetainedStyleMutation::Resource));+ if is_resource && has_resource {+ return true;+ }if let obscura_render::RetainedStyleMutation::Animation { node } = &mutation {if pending.iter().any(|queued| {matches!(@@ -702,27 +712,51 @@ fn queue_retained_style_mutation(}}if let obscura_render::RetainedStyleMutation::Attribute(next) = &mutation {- if next.name.eq_ignore_ascii_case("style")- && pending.iter().any(|queued| {+ if let Some(obscura_render::RetainedStyleMutation::Attribute(current)) =+ pending.iter_mut().find(|queued| {matches!(queued,obscura_render::RetainedStyleMutation::Attribute(current)if current.node == next.node- && current.name.eq_ignore_ascii_case("style")+ && current.name.eq_ignore_ascii_case(&next.name))}){+ current.new_value.clone_from(&next.new_value);return true;}}- if pending.len() >= MAX_PENDING_STYLE_MUTATIONS {+ // Resource refresh is a singleton trigger, not style damage. Keep the+ // bounded safety limit on actual selector/tree/animation invalidations+ // without making a late image discard an exactly-full retained batch.+ let style_damage_len = pending.len() - usize::from(has_resource);+ if !is_resource && style_damage_len >= MAX_PENDING_STYLE_MUTATIONS {return false;}pending.push(mutation);true}+/// Rebuild resource-dependent geometry while retaining the previous computed+/// style graph. Image intrinsic sizes and font metrics can reflow the whole+/// document, but neither changes selector matching or computed declarations.+/// Coalescing this marker also makes one shared image response invalidate once+/// rather than once for every HTMLImageElement waiter.+#[cfg(feature = "render")]+pub(crate) fn invalidate_render_resource_geometry(state: &mut ObscuraState) {+ if state.prepared_render.is_some()+ && !queue_retained_style_mutation(+ &mut state.pending_style_mutations,+ obscura_render::RetainedStyleMutation::Resource,+ )+ {+ state.prepared_render = None;+ state.pending_style_mutations.clear();+ }+ state.resolved_scroll = None;+}+#[cfg(feature = "render")]fn render_timing_enabled() -> bool {static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();@@ -2593,7 +2627,7 @@ mod tests {use super::{ensure_prepared_geometry, ensure_prepared_render, node_is_connected,queue_retained_style_mutation, retained_style_mutation,- shadow_including_connected_nodes, ObscuraState,+ shadow_including_connected_nodes, ObscuraState, MAX_PENDING_STYLE_MUTATIONS,};#[cfg(feature = "render")]use obscura_dom::ShadowRootMode;@@ -2865,22 +2899,58 @@ mod tests {// 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 {+ for raw in 201..=MAX_PENDING_STYLE_MUTATIONS as u32 {assert!(queue_retained_style_mutation(&mut pending,style_mutation(raw),));}- assert_eq!(pending.len(), 256);+ assert_eq!(pending.len(), MAX_PENDING_STYLE_MUTATIONS);assert!(queue_retained_style_mutation(&mut pending,style_mutation(1),));assert!(!queue_retained_style_mutation(&mut pending,- style_mutation(257),+ style_mutation(MAX_PENDING_STYLE_MUTATIONS as u32 + 1),+ ));+ assert_eq!(pending.len(), MAX_PENDING_STYLE_MUTATIONS);+ }++ #[cfg(feature = "render")]+ #[test]+ fn repeated_selector_attribute_writes_keep_only_the_rendered_transition() {+ let node = obscura_dom::tree::NodeId::new(7);+ let mutation = |old: &str, new: &str| {+ obscura_render::RetainedStyleMutation::Attribute(+ obscura_render::AttributeStyleMutation {+ node,+ name: "class".to_string(),+ old_value: Some(old.to_string()),+ new_value: Some(new.to_string()),+ },+ )+ };+ let mut pending = Vec::new();+ assert!(queue_retained_style_mutation(+ &mut pending,+ mutation("before", "intermediate"),+ ));+ assert!(queue_retained_style_mutation(+ &mut pending,+ mutation("intermediate", "after"),));- assert_eq!(pending.len(), 256);+ assert_eq!(+ pending,+ vec![obscura_render::RetainedStyleMutation::Attribute(+ obscura_render::AttributeStyleMutation {+ node,+ name: "class".to_string(),+ old_value: Some("before".to_string()),+ new_value: Some("after".to_string()),+ }+ )]+ );}#[cfg(feature = "render")]@@ -2908,6 +2978,46 @@ mod tests {);}+ #[cfg(feature = "render")]+ #[test]+ fn repeated_resource_changes_share_one_retained_refresh_marker() {+ let mut pending = vec![obscura_render::RetainedStyleMutation::Animation {+ node: obscura_dom::tree::NodeId::new(1),+ }];+ for _ in 0..300 {+ assert!(queue_retained_style_mutation(+ &mut pending,+ obscura_render::RetainedStyleMutation::Resource,+ ));+ }+ assert_eq!(+ pending,+ vec![+ obscura_render::RetainedStyleMutation::Animation {+ node: obscura_dom::tree::NodeId::new(1),+ },+ obscura_render::RetainedStyleMutation::Resource,+ ]+ );++ let mut full_style_batch = (1..=MAX_PENDING_STYLE_MUTATIONS)+ .map(|raw| obscura_render::RetainedStyleMutation::Animation {+ node: obscura_dom::tree::NodeId::new(raw as u32),+ })+ .collect::<Vec<_>>();+ assert!(queue_retained_style_mutation(+ &mut full_style_batch,+ obscura_render::RetainedStyleMutation::Resource,+ ));+ assert_eq!(full_style_batch.len(), MAX_PENDING_STYLE_MUTATIONS + 1);+ assert!(!queue_retained_style_mutation(+ &mut full_style_batch,+ obscura_render::RetainedStyleMutation::Animation {+ node: obscura_dom::tree::NodeId::new(5_000),+ },+ ));+ }+#[cfg(feature = "render")]#[test]fn geometry_consumer_defers_paint_only_sample_until_exact_consumer() {@@ -3675,9 +3785,7 @@ fn op_set_dynamic_fonts(state: &OpState, #[string] registrations: &str) -> boollet mut state = shared.borrow_mut();if state.dynamic_fonts != fonts {state.dynamic_fonts = fonts;- state.prepared_render = None;- state.pending_style_mutations.clear();- state.resolved_scroll = None;+ invalidate_render_resource_geometry(&mut state);}true}@@ -4358,9 +4466,7 @@ fn load_image_metadata_without_page_transport(gs: &mut ObscuraState, node_id: No.to_string();};if dimensions.is_some() && dimensions != previous_dimensions {- gs.prepared_render = None;- gs.pending_style_mutations.clear();- gs.resolved_scroll = None;+ invalidate_render_resource_geometry(gs);}image_metadata_json(current_src, density, true, dimensions)}@@ -4373,7 +4479,7 @@ fn finish_async_image_metadata(expected_url: &str,request_profile: ImageRequestProfile,) -> String {- let mut gs = shared.borrow_mut();+ let gs = shared.borrow();if gs.document_generation != document_generation {return serde_json::json!({ "state": "stale", "currentSrc": expected_url }).to_string();@@ -4395,14 +4501,6 @@ fn finish_async_image_metadata(if current_src != expected_url {return serde_json::json!({ "state": "stale", "currentSrc": current_src }).to_string();}- if known && dimensions.is_some() {- // This request began only because the selected resource was unknown.- // Newly available intrinsic dimensions can dirty ancestor geometry,- // exactly like Gecko's SIZE_AVAILABLE reflow notification.- gs.prepared_render = None;- gs.pending_style_mutations.clear();- gs.resolved_scroll = None;- }image_metadata_json(current_src, density, known, dimensions)}@@ -4582,6 +4680,10 @@ async fn op_load_image_metadata(state: Rc<RefCell<OpState>>, nid: u32) -> Stringrequest_profile,bytes,);+ // The leader owns the unknown-to-known cache+ // transition. Followers only observe this result and+ // must not invalidate the retained render again.+ invalidate_render_resource_geometry(&mut gs);} else {gs.render_resources.seed_image_missing(selected_url.clone(), request_profile);diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 57342a98..47d931c1 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -854,18 +854,17 @@ impl ObscuraJsRuntime {}/// Insert one page-transport resource outcome into the retained renderer- /// cache. A new successful byte body can change intrinsic geometry, so any- /// previously prepared layout is invalidated. A negative outcome cannot- /// change geometry and therefore preserves the retained layout/scroll.+ /// cache. Successful image/font bytes queue one resource-dependent layout+ /// refresh while preserving computed styles and any DOM damage already+ /// queued. A negative outcome cannot change geometry and preserves the+ /// retained layout/scroll.#[cfg(feature = "render")]pub fn seed_render_resource(&mut self, url: String, bytes: Option<Vec<u8>>) {let mut state = self.state.borrow_mut();match bytes {Some(bytes) => {state.render_resources.seed(url, bytes);- state.prepared_render = None;- state.pending_style_mutations.clear();- state.resolved_scroll = None;+ crate::ops::invalidate_render_resource_geometry(&mut state);}None => state.render_resources.seed_missing(url),}@@ -882,9 +881,7 @@ impl ObscuraJsRuntime {match bytes {Some(bytes) if obscura_render::image_intrinsic_dimensions(&bytes).is_some() => {state.render_resources.seed_image(url, profile, bytes);- state.prepared_render = None;- state.pending_style_mutations.clear();- state.resolved_scroll = None;+ crate::ops::invalidate_render_resource_geometry(&mut state);}_ => state.render_resources.seed_image_missing(url, profile),}@@ -4274,8 +4271,12 @@ mod tests {rt.set_dom(dom);rt.set_viewport(1024.0, 768.0);rt.run_page_init();- rt.execute_script("remember-screen", "globalThis.__screenBefore = screen;")- .unwrap();+ rt.execute_script(+ "remember-screen",+ "globalThis.__screenBefore = screen;\+ globalThis.__screenSizeBefore = [screen.width, screen.height];",+ )+ .unwrap();rt.set_screen_size_override(Some((1440.0, 900.0)), true);assert_eq!(@@ -4290,8 +4291,9 @@ mod tests {rt.set_screen_size_override(None, false);assert_eq!(rt.evaluate(- "[innerWidth, innerHeight, screen.width !== 1440,\- screen.height !== 900, screen.availHeight === screen.height - 40,\+ "[innerWidth, innerHeight, screen.width === __screenSizeBefore[0],\+ screen.height === __screenSizeBefore[1],\+ screen.availHeight === screen.height - 40,\screen === __screenBefore]").unwrap(),@@ -7418,9 +7420,16 @@ mod tests {Some(br#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="10"/>"#.to_vec()),);let state = rt.state.borrow();- assert!(- state.prepared_render.is_none(),- "successful bytes can change geometry"+ let prepared = state.prepared_render.as_ref().expect("retained style graph");+ assert_eq!(+ prepared as *const obscura_render::PreparedRender as usize,+ prepared_address,+ "resource arrival waits for the next geometry flush"+ );+ assert_eq!(+ state.pending_style_mutations,+ vec![obscura_render::RetainedStyleMutation::Resource],+ "successful bytes queue one resource-dependent rebuild");assert!(state.resolved_scroll.is_none(),@@ -7428,6 +7437,82 @@ mod tests {);}+ #[cfg(feature = "render")]+ #[test]+ fn image_resource_arrival_retains_styles_and_rebuilds_intrinsic_geometry() {+ let dom = parse_html(+ r#"<html style="margin:0"><body style="margin:0">+ <img id="hero" src="http://example.test/late.png" style="display:block">+ <div id="after" style="height:10px"></div>+ </body></html>"#,+ );+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(dom);+ rt.set_url("http://example.test/page");+ rt.set_viewport(80.0, 60.0);+ rt.state.borrow_mut().render_resources =+ obscura_render::RenderResourceCache::with_loader(|_: &str| None);+ rt.run_page_init();++ let before = rt+ .evaluate("[hero.getBoundingClientRect().height, after.getBoundingClientRect().top]")+ .expect("geometry before image arrival");+ assert_eq!(before, serde_json::json!([0, 0]));+ let prepared_address = {+ let state = rt.state.borrow();+ state+ .prepared_render+ .as_ref()+ .expect("initial prepared render") as *const obscura_render::PreparedRender+ as usize+ };++ // Preserve already queued framework damage and coalesce repeated+ // notification of the same shared resource into one refresh marker.+ rt.evaluate("after.setAttribute('data-ready', 'true')")+ .expect("queued DOM mutation");+ let png = two_by_three_png();+ rt.seed_render_image_resource(+ "http://example.test/late.png".to_string(),+ crate::ops::ImageRequestProfile::NoCorsInclude,+ Some(png.clone()),+ );+ rt.seed_render_image_resource(+ "http://example.test/late.png".to_string(),+ crate::ops::ImageRequestProfile::NoCorsInclude,+ Some(png),+ );+ {+ let state = rt.state.borrow();+ assert_eq!(+ state+ .prepared_render+ .as_ref()+ .expect("style graph remains available")+ as *const obscura_render::PreparedRender as usize,+ prepared_address,+ );+ assert_eq!(+ state+ .pending_style_mutations+ .iter()+ .filter(|mutation| matches!(mutation, obscura_render::RetainedStyleMutation::Resource))+ .count(),+ 1,+ );+ assert!(state.pending_style_mutations.iter().any(|mutation| matches!(+ mutation,+ obscura_render::RetainedStyleMutation::Attribute(_)+ )));+ }++ let after = rt+ .evaluate("[hero.getBoundingClientRect().height, after.getBoundingClientRect().top]")+ .expect("geometry after image arrival");+ assert_eq!(after, serde_json::json!([3, 3]));+ assert!(rt.state.borrow().pending_style_mutations.is_empty());+ }+#[cfg(feature = "render")]#[test]fn document_region_capture_preserves_live_runtime_state_and_resource_cache() {@@ -7584,9 +7669,11 @@ mod tests {{let state = rt.state.borrow();assert_eq!(state.dynamic_fonts.len(), 1);- assert!(- state.prepared_render.is_none(),- "changing the document font registry must invalidate prepared text geometry"+ assert!(state.prepared_render.is_some());+ assert_eq!(+ state.pending_style_mutations,+ vec![obscura_render::RetainedStyleMutation::Resource],+ "font registry changes need reshaping and layout, not a fresh cascade");}@@ -11666,7 +11753,14 @@ mod tests {serde_json::json!([true, 2, 3, ["load"]]));assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);- assert!(rt.state.borrow().prepared_render.is_none());+ {+ let state = rt.state.borrow();+ assert!(state.prepared_render.is_some());+ assert_eq!(+ state.pending_style_mutations,+ vec![obscura_render::RetainedStyleMutation::Resource]+ );+ }// Once the successful dimensions are retained, another loading-form// metadata probe is only a cache hit and must preserve fresh layout.diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 6e7f819b..526dcefa 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -534,7 +534,7 @@ pub enum TreeStyleMutation {},}-/// Mutation input for a retained-style rebuild. Attribute invalidation uses+/// Damage input for a retained-style rebuild. Attribute invalidation uses/// selector-key dependencies; tree invalidation uses parent/sibling scopes.#[derive(Clone, Debug, PartialEq, Eq)]pub enum RetainedStyleMutation {@@ -544,6 +544,11 @@ pub enum RetainedStyleMutation {/// stable. Re-cascade this animation owner and its inheritance-dependent/// subtree while retaining unrelated branches.Animation { node: NodeId },+ /// Cached image or font bytes became available. Resource selection,+ /// intrinsic sizes, shaping, layout, and paint must be rebuilt, but the+ /// DOM, stylesheet, and computed declarations are unchanged, so no style+ /// node is dirty.+ Resource,}impl From<AttributeStyleMutation> for RetainedStyleMutation {@@ -3245,6 +3250,7 @@ fn empty_state_may_have_changed(.filter(|mutation| match mutation {RetainedStyleMutation::Attribute(_) => false,RetainedStyleMutation::Animation { .. } => false,+ RetainedStyleMutation::Resource => false,RetainedStyleMutation::Tree(TreeStyleMutation::Insert {old_parent,new_parent,@@ -3310,6 +3316,9 @@ fn retained_style_plan(let mut dirty = HashSet::new();let mut has_animation_damage = false;for mutation in mutations {+ if matches!(mutation, RetainedStyleMutation::Resource) {+ continue;+ }if let RetainedStyleMutation::Animation { node } = mutation {// Animated color and visibility inherit, keyframe endpoints can// consume inherited custom properties, and generated pseudos are@@ -3809,10 +3818,15 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(let retained = retained.and_then(|mut retained| {// The document cache key intentionally contains only document-scope// sources. Until shadow sheets have their own retained cache keys and- // invalidation maps, reusing any computed styles in a document with a- // native root could preserve stale shadow rules or inherited host- // custom properties after a mutation. Prefer a full correct cascade.- if !shadow_sheets.is_empty() {+ // invalidation maps, reusing computed styles after DOM/style damage in+ // a document with a native root could preserve stale shadow rules or+ // inherited host custom properties. Resource-only damage cannot+ // change either cascade, so its zero-dirty reuse remains sound.+ let resource_only = !mutations.is_empty()+ && mutations+ .iter()+ .all(|mutation| matches!(mutation, RetainedStyleMutation::Resource));+ if !shadow_sheets.is_empty() && !resource_only {return None;}if !stylesheet_cache_hit {diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rsindex a71ad7aa..707f8836 100644--- a/crates/obscura-render/src/lib.rs+++ b/crates/obscura-render/src/lib.rs@@ -1926,8 +1926,9 @@ impl AnimationTimelineState {self.waapi.values().map(|animation| animation.node).collect()}- /// New animation instance epochs must observe a complete cascade. They- /// can be created by DOM mutations which have not yet reached style flush.+ /// New animation instance epochs must reach a style flush. Retained+ /// mutation planning cascades the affected nodes while clean branches keep+ /// their existing instances.pub fn has_pending_start_candidates(&self) -> bool {!self.start_candidates.is_empty() || !self.subtree_start_candidates.is_empty()}diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex e1fee51a..fce22499 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -2195,9 +2195,7 @@ pub fn prepare_dom_with_retained_styles_with_animation_state(&& previous.animation_sample.mode == crate::AnimationSampleMode::DocumentTime&& animation_sample.mode == crate::AnimationSampleMode::DocumentTime&& animation_sample.time.milliseconds >= previous.animation_sample.time.milliseconds;- if sample_changed- && (!forward_document_sample || animation_timeline.has_pending_start_candidates())- {+ if sample_changed && !forward_document_sample {drop(previous);return prepare_dom_with_dynamic_fonts_and_stylesheet_cache_with_animation_state(tree,