The headless browser for AI agents and web scraping
Reduce resource and animation layout churn
SGavrlf99be8b4b442
diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rsindex 01fb7d49..8d20ba8d 100644--- a/crates/obscura-cdp/src/domains/page.rs+++ b/crates/obscura-cdp/src/domains/page.rs@@ -1864,7 +1864,7 @@ mod tests {.expect("semi-transparent override");crate::domains::emulation::handle("setDeviceMetricsOverride",- &json!({"width": 40, "height": 30, "deviceScaleFactor": 2}),+ &json!({"width": 40, "height": 30, "deviceScaleFactor": 2, "mobile": false}),&mut ctx,&session,)diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 03749031..a2299b57 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -711,6 +711,17 @@ pub(crate) fn queue_retained_style_mutation(return true;}}+ if let obscura_render::RetainedStyleMutation::WaapiAnimation { node } = &mutation {+ if pending.iter().any(|queued| {+ matches!(+ queued,+ obscura_render::RetainedStyleMutation::WaapiAnimation { node: current }+ if current == node+ )+ }) {+ return true;+ }+ }if let obscura_render::RetainedStyleMutation::Attribute(next) = &mutation {if let Some(obscura_render::RetainedStyleMutation::Attribute(current)) =pending.iter_mut().find(|queued| {@@ -3972,14 +3983,14 @@ fn waapi_document_time_ms(state: &ObscuraState) -> f32 {#[cfg(feature = "render")]fn invalidate_waapi_render(state: &mut ObscuraState, node: NodeId) {// Adding or controlling one effect changes the animation cascade only for- // its target subtree. Keep the previous style graph available to the+ // its target. Keep the previous style graph available to the// retained planner instead of turning every animation setup into a full// document cascade. The bounded mutation queue remains the safety valve// for genuinely broad animation bursts.if state.prepared_render.is_some()&& !queue_retained_style_mutation(&mut state.pending_style_mutations,- obscura_render::RetainedStyleMutation::Animation { node },+ obscura_render::RetainedStyleMutation::WaapiAnimation { node },){state.prepared_render = None;diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 47d931c1..7ec2286a 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -880,8 +880,17 @@ impl ObscuraJsRuntime {let mut state = self.state.borrow_mut();match bytes {Some(bytes) if obscura_render::image_intrinsic_dimensions(&bytes).is_some() => {+ let needs_geometry = match (&state.prepared_render, &state.dom) {+ (Some(prepared), Some(dom)) => {+ prepared.image_resource_needs_geometry(dom, &url, profile)+ }+ _ => true,+ };state.render_resources.seed_image(url, profile, bytes);- crate::ops::invalidate_render_resource_geometry(&mut state);+ state.activity_generation = state.activity_generation.wrapping_add(1);+ if needs_geometry {+ crate::ops::invalidate_render_resource_geometry(&mut state);+ }}_ => state.render_resources.seed_image_missing(url, profile),}@@ -7513,6 +7522,135 @@ mod tests {assert!(rt.state.borrow().pending_style_mutations.is_empty());}+ #[cfg(feature = "render")]+ #[test]+ fn fixed_image_resource_arrival_repaints_without_rebuilding_geometry() {+ let dom = parse_html(+ r#"<html style="margin:0"><body style="margin:0">+ <img id="hero" src="http://example.test/fixed.png"+ style="display:block;width:20px;height:10px">+ <div id="after" style="height:10px;background:blue"></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();++ assert_eq!(+ rt.evaluate("[hero.offsetWidth, hero.offsetHeight, after.offsetTop]")+ .expect("fixed geometry"),+ serde_json::json!([20, 10, 10])+ );+ let before_png = rt+ .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))+ .expect("capture before image arrival");+ let (prepared_address, resolved_address, activity_before) = {+ let state = rt.state.borrow();+ (+ state.prepared_render.as_ref().unwrap() as *const _ as usize,+ &state.resolved_scroll.as_ref().unwrap().1 as *const _ as usize,+ state.activity_generation,+ )+ };++ rt.seed_render_image_resource(+ "http://example.test/fixed.png".to_string(),+ crate::ops::ImageRequestProfile::NoCorsInclude,+ Some(two_by_three_png()),+ );+ {+ let state = rt.state.borrow();+ assert_eq!(+ state.prepared_render.as_ref().unwrap() as *const _ as usize,+ prepared_address,+ "fixed replaced content must keep the prepared geometry"+ );+ assert_eq!(+ &state.resolved_scroll.as_ref().unwrap().1 as *const _ as usize,+ resolved_address,+ "paint-only resource damage must keep resolved scrolling"+ );+ assert!(state.pending_style_mutations.is_empty());+ assert!(state.activity_generation > activity_before);+ }+ assert_eq!(+ rt.evaluate("[hero.offsetWidth, hero.offsetHeight, after.offsetTop]")+ .expect("retained fixed geometry"),+ serde_json::json!([20, 10, 10])+ );+ let after_png = rt+ .screenshot_prepared((80.0, 60.0), Some("http://example.test/page"))+ .expect("capture after image arrival");+ assert_ne!(after_png, before_png, "new image pixels must reach paint");+ }++ #[cfg(feature = "render")]+ #[test]+ fn fixed_flex_image_resource_arrival_still_rebuilds_geometry() {+ let dom = parse_html(+ r#"<html><body><div style="display:flex">+ <img id="hero" src="http://example.test/flex.png"+ style="width:20px;height:10px">+ </div></body></html>"#,+ );+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(dom);+ rt.set_url("http://example.test/page");+ rt.state.borrow_mut().render_resources =+ obscura_render::RenderResourceCache::with_loader(|_: &str| None);+ rt.run_page_init();+ rt.evaluate("hero.getBoundingClientRect().width")+ .expect("prepare flex geometry");+ assert!(rt.state.borrow().resolved_scroll.is_some());++ rt.seed_render_image_resource(+ "http://example.test/flex.png".to_string(),+ crate::ops::ImageRequestProfile::NoCorsInclude,+ Some(two_by_three_png()),+ );+ let state = rt.state.borrow();+ assert_eq!(+ state.pending_style_mutations,+ vec![obscura_render::RetainedStyleMutation::Resource]+ );+ assert!(state.resolved_scroll.is_none());+ }++ #[cfg(feature = "render")]+ #[test]+ fn fixed_css_content_image_arrival_still_rebuilds_intrinsic_geometry() {+ let dom = parse_html(+ r#"<html><body><img id="hero" src="fallback.png"+ style="display:block;width:20px;height:10px;content:url('http://example.test/content.png')">+ </body></html>"#,+ );+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(dom);+ rt.set_url("http://example.test/page");+ rt.state.borrow_mut().render_resources =+ obscura_render::RenderResourceCache::with_loader(|_: &str| None);+ rt.run_page_init();+ rt.evaluate("hero.getBoundingClientRect().width")+ .expect("prepare CSS replaced content");+ assert!(rt.state.borrow().resolved_scroll.is_some());++ rt.seed_render_image_resource(+ "http://example.test/content.png".to_string(),+ crate::ops::ImageRequestProfile::NoCorsInclude,+ Some(two_by_three_png()),+ );+ let state = rt.state.borrow();+ assert_eq!(+ state.pending_style_mutations,+ vec![obscura_render::RetainedStyleMutation::Resource]+ );+ assert!(state.resolved_scroll.is_none());+ }+#[cfg(feature = "render")]#[test]fn document_region_capture_preserves_live_runtime_state_and_resource_cache() {@@ -8056,7 +8194,9 @@ mod tests {);assert_eq!(state.pending_style_mutations,- vec![obscura_render::RetainedStyleMutation::Animation { node: box_node }]+ vec![obscura_render::RetainedStyleMutation::WaapiAnimation {+ node: box_node+ }]);}let initial = rtdiff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 526dcefa..f2b2a21c 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -544,6 +544,12 @@ pub enum RetainedStyleMutation {/// stable. Re-cascade this animation owner and its inheritance-dependent/// subtree while retaining unrelated branches.Animation { node: NodeId },+ /// A Web Animation sample changed. Obscura's WAAPI surface currently+ /// animates only transform and opacity; neither property inherits, so the+ /// target alone needs a fresh animation cascade. Transform descendants+ /// are moved later by visual-geometry propagation, not by recascading+ /// their declarations.+ WaapiAnimation { 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@@ -3250,6 +3256,7 @@ fn empty_state_may_have_changed(.filter(|mutation| match mutation {RetainedStyleMutation::Attribute(_) => false,RetainedStyleMutation::Animation { .. } => false,+ RetainedStyleMutation::WaapiAnimation { .. } => false,RetainedStyleMutation::Resource => false,RetainedStyleMutation::Tree(TreeStyleMutation::Insert {old_parent,@@ -3328,6 +3335,11 @@ fn retained_style_plan(has_animation_damage = true;continue;}+ if let RetainedStyleMutation::WaapiAnimation { node } = mutation {+ dirty.insert(*node);+ has_animation_damage = true;+ continue;+ }let RetainedStyleMutation::Attribute(mutation) = mutation else {let RetainedStyleMutation::Tree(mutation) = mutation else {unreachable!()@@ -15755,6 +15767,27 @@ mod tests {}}+ #[test]+ fn retained_waapi_restyle_dirties_only_the_non_inherited_effect_target() {+ let tree = parse_html(+ "<main><section id=target><div id=child><span id=grandchild></span></div></section><aside id=clean></aside></main>",+ );+ let target = tree.get_element_by_id("target").unwrap();+ let sheet = crate::css::Stylesheet::parse_for_viewport(&tree, &[], (800.0, 600.0));+ let RetainedStylePlan::Reuse {+ dirty,+ has_animation_damage,+ } = retained_style_plan(+ &tree,+ &sheet,+ &[RetainedStyleMutation::WaapiAnimation { node: target }],+ ) else {+ panic!("WAAPI target damage must remain retainable")+ };+ assert_eq!(dirty, HashSet::from([target]));+ assert!(has_animation_damage);+ }+#[test]fn retained_animation_restyle_reuses_clean_branches_and_matches_full() {let mut clean = String::new();diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex fce22499..ec790fd6 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -1719,6 +1719,70 @@ impl PreparedRender {pub fn selected_image(&self, id: obscura_dom::tree::NodeId) -> Option<&SelectedImage> {self.selected_images.get(&id)}++ /// Whether newly available bytes for one selected image can change box+ /// geometry. A replaced image whose two used axes are authored lengths+ /// does not consult its natural dimensions; resource completion only+ /// changes the pixels painted inside the existing content box.+ ///+ /// Keep flex/grid items on the conservative path. Their intrinsic+ /// contribution participates in sizing algorithms even when the item has+ /// preferred dimensions, and browsers likewise propagate image-size+ /// invalidation through those formatting contexts.+ pub fn image_resource_needs_geometry(+ &self,+ tree: &DomTree,+ url: &str,+ profile: ImageRequestProfile,+ ) -> bool {+ self.selected_images.iter().any(|(id, selected)| {+ if selected.resolved_url != url || selected.profile != profile {+ return false;+ }+ if !tree.get_node(*id).is_some_and(|node| {+ node.as_element()+ .is_some_and(|name| name.local.as_ref() == "img")+ }) {+ return true;+ }+ let Some(style) = self.layout.styles.get(id) else {+ return true;+ };+ // CSS replaced content has its own selected intrinsic metadata;+ // do not mistake an <img> owner for an ordinary fixed source+ // image merely because both selections share the element id.+ if style.content_image.is_some() {+ return true;+ }+ let fixed_box = matches!(style.width, crate::Dimension::Px(_))+ && matches!(style.height, crate::Dimension::Px(_))+ && matches!(style.min_width, crate::Dimension::Auto | crate::Dimension::Px(_))+ && matches!(style.min_height, crate::Dimension::Auto | crate::Dimension::Px(_))+ && matches!(style.max_width, crate::Dimension::Auto | crate::Dimension::Px(_))+ && matches!(style.max_height, crate::Dimension::Auto | crate::Dimension::Px(_))+ && !style.width_fit_content+ && style.size_expressions.iter().all(Option::is_none);+ if !fixed_box {+ return true;+ }++ let mut parent = crate::dom::rendered_parent(tree, *id);+ while let Some(parent_id) = parent {+ let Some(parent_style) = self.layout.styles.get(&parent_id) else {+ parent = crate::dom::rendered_parent(tree, parent_id);+ continue;+ };+ if parent_style.display_contents {+ parent = crate::dom::rendered_parent(tree, parent_id);+ continue;+ }+ return parent_style.display == crate::Display::Grid+ || (parent_style.display == crate::Display::Flex+ && !parent_style.internal_flex_container);+ }+ false+ })+ }}fn css_number(value: f32) -> String {@@ -2208,19 +2272,23 @@ pub fn prepare_dom_with_retained_styles_with_animation_state(animation_timeline,);}- let animation_nodes = sample_changed- .then(|| retained_animation_restyle_nodes(tree, &previous.layout.styles, animation_timeline))+ let sampled_animation_mutations = sample_changed+ .then(|| {+ retained_animation_restyle_mutations(+ tree,+ &previous.layout.styles,+ animation_timeline,+ )+ }).unwrap_or_default();let animation_mutations;- let mutations = if animation_nodes.is_empty() {+ let mutations = if sampled_animation_mutations.is_empty() {mutations} else {animation_mutations = mutations.iter().cloned()- .chain(animation_nodes.into_iter().map(|node| {- crate::dom::RetainedStyleMutation::Animation { node }- }))+ .chain(sampled_animation_mutations).collect::<Vec<_>>();animation_mutations.as_slice()};@@ -2243,24 +2311,35 @@ pub fn prepare_dom_with_retained_styles_with_animation_state()}-fn retained_animation_restyle_nodes(+fn retained_animation_restyle_mutations(tree: &DomTree,styles: &HashMap<obscura_dom::tree::NodeId, crate::LayoutStyle>,animation_timeline: &crate::AnimationTimelineState,-) -> std::collections::HashSet<obscura_dom::tree::NodeId> {- let mut nodes = styles+) -> Vec<crate::dom::RetainedStyleMutation> {+ let connected = |node: obscura_dom::tree::NodeId| {+ tree.get_node(node).is_some()+ && (node == tree.document() || tree.ancestors(node).contains(&tree.document()))+ };+ let mut css_nodes = styles.iter().filter_map(|(node, style)| {(style.animation_name.is_some() && style.animation_has_render_effect).then_some(*node)}).collect::<std::collections::HashSet<_>>();- nodes.extend(animation_timeline.waapi_nodes());- nodes.retain(|node| {- tree.get_node(*node).is_some()- && (*node == tree.document() || tree.ancestors(*node).contains(&tree.document()))- });- nodes+ css_nodes.retain(|node| connected(*node));+ let mut mutations = css_nodes+ .into_iter()+ .map(|node| crate::dom::RetainedStyleMutation::Animation { node })+ .collect::<Vec<_>>();+ mutations.extend(+ animation_timeline+ .waapi_nodes()+ .into_iter()+ .filter(|node| connected(*node))+ .map(|node| crate::dom::RetainedStyleMutation::WaapiAnimation { node }),+ );+ mutations}fn prepare_dom_with_dynamic_fonts_and_stylesheet_cache_internal(@@ -15521,10 +15600,9 @@ mod tests {}#[test]- fn animation_restyle_nodes_deduplicate_waapi_and_filter_disconnected_targets() {- let tree = parse_html(- "<main><div id=connected></div><div id=detached></div></main>",- );+ fn animation_restyle_mutations_deduplicate_waapi_and_filter_disconnected_targets() {+ let tree =+ parse_html("<main><div id=connected></div><div id=detached></div></main>");let connected = tree.get_element_by_id("connected").unwrap();let detached = tree.get_element_by_id("detached").unwrap();tree.remove_child(detached);@@ -15556,10 +15634,12 @@ mod tests {"the timeline accessor must return the exact deduplicated target set");- let nodes = retained_animation_restyle_nodes(&tree, &HashMap::new(), &timeline);+ let mutations = retained_animation_restyle_mutations(&tree, &HashMap::new(), &timeline);assert_eq!(- nodes,- std::collections::HashSet::from([connected]),+ mutations,+ vec![crate::dom::RetainedStyleMutation::WaapiAnimation {+ node: connected+ }],"only connected WAAPI targets may enter retained style damage");}