Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix: clarify renderer exports and preserve allocation-free error handoffs
ldm0f32553ed04e0
diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rsindex 1ece773c8..a606b8993 100644--- a/moli-layout/src/taffy_tree.rs+++ b/moli-layout/src/taffy_tree.rs@@ -3004,6 +3004,177 @@ fn inline_percentage_basis(.or_else(|| (sizing_purpose == SizingPurpose::IntrinsicContribution).then_some(0.0))}+#[derive(Clone, Copy)]+struct AtomicMeasurement {+ output: LayoutOutput,+ margins: taffy::Rect<f32>,+}++#[derive(Clone, Copy)]+struct InlineFloatPlacement {+ child: LayoutBoxId,+ location: Point<f32>,+ output: LayoutOutput,+ order: usize,+ parent_width: Option<f32>,+}++struct InlineMeasurement {+ size: Size<f32>,+ /// Block-end extent of every IFC child used as the single alignment+ /// subject. Unlike `size.height`, this includes non-contained floats+ /// without making them contribute to normal-flow auto height.+ alignment_block_size: f32,+ first_baseline: Option<f32>,+ last_baseline: Option<f32>,+ has_non_phantom_line: bool,+ atomic: Vec<Option<AtomicMeasurement>>,+ floats: Vec<InlineFloatPlacement>,+ percentage_basis: Option<f32>,+ /// Present only for the accepted `PerformLayout` result. Intrinsic probes+ /// retain the numeric line summary but never allocate final placement+ /// vectors that would immediately be discarded.+ line_placements: Option<Vec<InlineLinePlacement>>,+}++impl InlineMeasurement {+ fn translate_block_axis(&mut self, offset: f32) {+ if offset == 0.0 {+ return;+ }+ if let Some(first_baseline) = &mut self.first_baseline {+ *first_baseline += offset;+ }+ if let Some(last_baseline) = &mut self.last_baseline {+ *last_baseline += offset;+ }+ if let Some(line_placements) = &mut self.line_placements {+ for placement in line_placements {+ placement.translate_block_axis(offset);+ }+ }+ for floated in &mut self.floats {+ floated.location.y += offset;+ }+ }+}++/// Returns the offset for one block-axis alignment subject.+///+/// Taffy's block algorithm applies these same single-subject fallbacks to its+/// numeric children. A Parley IFC is exposed to Taffy as one measured leaf, so+/// its line fragments and child placements must consume the alignment value at+/// this adapter boundary instead. This is the leaf equivalent of Chromium's+/// `AlignBlockContent` plus `BoxFragmentBuilder::MoveChildrenInDirection`, not+/// a post-layout paint translation.+pub(crate) fn single_subject_block_alignment_offset(+ alignment: Option<AlignContent>,+ free_space: f32,+) -> f32 {+ let Some(alignment) = alignment else {+ return 0.0;+ };+ let (mut keyword, safe) = match alignment.keyword {+ AlignContentKeyword::Stretch | AlignContentKeyword::SpaceBetween => {+ (AlignContentKeyword::FlexStart, true)+ }+ AlignContentKeyword::SpaceAround | AlignContentKeyword::SpaceEvenly => {+ (AlignContentKeyword::Center, true)+ }+ keyword => (keyword, alignment.safety == AlignmentSafety::Safe),+ };+ if free_space <= 0.0 && safe {+ keyword = AlignContentKeyword::Start;+ }+ match keyword {+ AlignContentKeyword::Start+ | AlignContentKeyword::FlexStart+ | AlignContentKeyword::Stretch+ | AlignContentKeyword::SpaceBetween => 0.0,+ AlignContentKeyword::End | AlignContentKeyword::FlexEnd => free_space,+ AlignContentKeyword::Center+ | AlignContentKeyword::SpaceAround+ | AlignContentKeyword::SpaceEvenly => free_space / 2.0,+ }+}++fn empty_inline_context() -> InlineFormattingContext {+ InlineFormattingContext {+ root_style: LayoutBoxId::from_index(0),+ measurement_layout: Some(parley::Layout::default()),+ laid_out: None,+ content_widths: InlineContentWidthsMemo::default(),+ text_units: Vec::new(),+ source_map: Vec::new(),+ selection: None,+ objects: Vec::new(),+ font_metrics: Vec::new(),+ parent_strut: None,+ uses_quirks_line_height: false,+ root_includes_used_font_metrics: false,+ style_parents: Vec::new(),+ structural_boxes: Vec::new(),+ line_placements: Vec::new(),+ fragments: InlineFragments::default(),+ }+}++fn measure_text(+ text: &str,+ font_size: f32,+ line_height: f32,+ known_dimensions: Size<Option<f32>>,+ available_space: Size<AvailableSpace>,+) -> Size<f32> {+ if text.is_empty() {+ return Size {+ width: known_dimensions.width.unwrap_or(0.0),+ height: known_dimensions.height.unwrap_or(0.0),+ };+ }++ let character_width = (font_size * 0.6).max(0.0);+ let collapsed_words = text.split_whitespace().collect::<Vec<_>>();+ let character_count = if collapsed_words.is_empty() {+ 1.0+ } else {+ let word_characters = collapsed_words+ .iter()+ .map(|word| word.chars().count())+ .sum::<usize>();+ (word_characters + collapsed_words.len().saturating_sub(1)) as f32+ };+ let natural_width = character_count * character_width;+ let longest_word = collapsed_words+ .iter()+ .map(|word| word.chars().count())+ .max()+ .unwrap_or(0) as f32+ * character_width;+ let width_limit = match available_space.width {+ AvailableSpace::Definite(width) => width.max(0.0),+ AvailableSpace::MinContent => longest_word,+ AvailableSpace::MaxContent => natural_width,+ };+ let measured_width = if width_limit > 0.0 {+ natural_width.min(width_limit)+ } else {+ 0.0+ };+ let line_count = if measured_width > 0.0 {+ (natural_width / measured_width).ceil().max(1.0)+ } else {+ 1.0+ };++ Size {+ width: known_dimensions.width.unwrap_or(measured_width),+ height: known_dimensions+ .height+ .unwrap_or(line_height.max(0.0) * line_count),+ }+}+#[cfg(test)]mod tests {use super::{inline_percentage_basis, round_layout_to_css_subpixels};@@ -3191,174 +3362,3 @@ mod tests {);}}--#[derive(Clone, Copy)]-struct AtomicMeasurement {- output: LayoutOutput,- margins: taffy::Rect<f32>,-}--#[derive(Clone, Copy)]-struct InlineFloatPlacement {- child: LayoutBoxId,- location: Point<f32>,- output: LayoutOutput,- order: usize,- parent_width: Option<f32>,-}--struct InlineMeasurement {- size: Size<f32>,- /// Block-end extent of every IFC child used as the single alignment- /// subject. Unlike `size.height`, this includes non-contained floats- /// without making them contribute to normal-flow auto height.- alignment_block_size: f32,- first_baseline: Option<f32>,- last_baseline: Option<f32>,- has_non_phantom_line: bool,- atomic: Vec<Option<AtomicMeasurement>>,- floats: Vec<InlineFloatPlacement>,- percentage_basis: Option<f32>,- /// Present only for the accepted `PerformLayout` result. Intrinsic probes- /// retain the numeric line summary but never allocate final placement- /// vectors that would immediately be discarded.- line_placements: Option<Vec<InlineLinePlacement>>,-}--impl InlineMeasurement {- fn translate_block_axis(&mut self, offset: f32) {- if offset == 0.0 {- return;- }- if let Some(first_baseline) = &mut self.first_baseline {- *first_baseline += offset;- }- if let Some(last_baseline) = &mut self.last_baseline {- *last_baseline += offset;- }- if let Some(line_placements) = &mut self.line_placements {- for placement in line_placements {- placement.translate_block_axis(offset);- }- }- for floated in &mut self.floats {- floated.location.y += offset;- }- }-}--/// Returns the offset for one block-axis alignment subject.-///-/// Taffy's block algorithm applies these same single-subject fallbacks to its-/// numeric children. A Parley IFC is exposed to Taffy as one measured leaf, so-/// its line fragments and child placements must consume the alignment value at-/// this adapter boundary instead. This is the leaf equivalent of Chromium's-/// `AlignBlockContent` plus `BoxFragmentBuilder::MoveChildrenInDirection`, not-/// a post-layout paint translation.-pub(crate) fn single_subject_block_alignment_offset(- alignment: Option<AlignContent>,- free_space: f32,-) -> f32 {- let Some(alignment) = alignment else {- return 0.0;- };- let (mut keyword, safe) = match alignment.keyword {- AlignContentKeyword::Stretch | AlignContentKeyword::SpaceBetween => {- (AlignContentKeyword::FlexStart, true)- }- AlignContentKeyword::SpaceAround | AlignContentKeyword::SpaceEvenly => {- (AlignContentKeyword::Center, true)- }- keyword => (keyword, alignment.safety == AlignmentSafety::Safe),- };- if free_space <= 0.0 && safe {- keyword = AlignContentKeyword::Start;- }- match keyword {- AlignContentKeyword::Start- | AlignContentKeyword::FlexStart- | AlignContentKeyword::Stretch- | AlignContentKeyword::SpaceBetween => 0.0,- AlignContentKeyword::End | AlignContentKeyword::FlexEnd => free_space,- AlignContentKeyword::Center- | AlignContentKeyword::SpaceAround- | AlignContentKeyword::SpaceEvenly => free_space / 2.0,- }-}--fn empty_inline_context() -> InlineFormattingContext {- InlineFormattingContext {- root_style: LayoutBoxId::from_index(0),- measurement_layout: Some(parley::Layout::default()),- laid_out: None,- content_widths: InlineContentWidthsMemo::default(),- text_units: Vec::new(),- source_map: Vec::new(),- selection: None,- objects: Vec::new(),- font_metrics: Vec::new(),- parent_strut: None,- uses_quirks_line_height: false,- root_includes_used_font_metrics: false,- style_parents: Vec::new(),- structural_boxes: Vec::new(),- line_placements: Vec::new(),- fragments: InlineFragments::default(),- }-}--fn measure_text(- text: &str,- font_size: f32,- line_height: f32,- known_dimensions: Size<Option<f32>>,- available_space: Size<AvailableSpace>,-) -> Size<f32> {- if text.is_empty() {- return Size {- width: known_dimensions.width.unwrap_or(0.0),- height: known_dimensions.height.unwrap_or(0.0),- };- }-- let character_width = (font_size * 0.6).max(0.0);- let collapsed_words = text.split_whitespace().collect::<Vec<_>>();- let character_count = if collapsed_words.is_empty() {- 1.0- } else {- let word_characters = collapsed_words- .iter()- .map(|word| word.chars().count())- .sum::<usize>();- (word_characters + collapsed_words.len().saturating_sub(1)) as f32- };- let natural_width = character_count * character_width;- let longest_word = collapsed_words- .iter()- .map(|word| word.chars().count())- .max()- .unwrap_or(0) as f32- * character_width;- let width_limit = match available_space.width {- AvailableSpace::Definite(width) => width.max(0.0),- AvailableSpace::MinContent => longest_word,- AvailableSpace::MaxContent => natural_width,- };- let measured_width = if width_limit > 0.0 {- natural_width.min(width_limit)- } else {- 0.0- };- let line_count = if measured_width > 0.0 {- (natural_width / measured_width).ceil().max(1.0)- } else {- 1.0- };-- Size {- width: known_dimensions.width.unwrap_or(measured_width),- height: known_dimensions- .height- .unwrap_or(line_height.max(0.0) * line_count),- }-}diff --git a/moli-protocol-server/src/cdp_scheduler/actor.rs b/moli-protocol-server/src/cdp_scheduler/actor.rsindex 3d634ecf3..3deebdf24 100644--- a/moli-protocol-server/src/cdp_scheduler/actor.rs+++ b/moli-protocol-server/src/cdp_scheduler/actor.rs@@ -1010,6 +1010,8 @@ async fn fail_runtime_deferred_reply_for_loose_protocol_response()))}+// An unmatched response goes back to the caller for routing, without boxing.+#[allow(clippy::result_large_err)]async fn complete_runtime_deferred_reply_for_renderer_response(scheduler: &mut CdpScheduler,pending_runtime_deferred_replies: &mut VecDeque<PendingRuntimeDeferredReplyState>,diff --git a/moli-protocol-server/src/protocol_server/tests/bidi/extracted.rs b/moli-protocol-server/src/protocol_server/tests/bidi/extracted.rsindex 5f9aea46a..e3aeccf94 100644--- a/moli-protocol-server/src/protocol_server/tests/bidi/extracted.rs+++ b/moli-protocol-server/src/protocol_server/tests/bidi/extracted.rs@@ -1,4 +1,3 @@-use super::super::*;use super::*;mod bidi_commands;diff --git a/moli-protocol/src/conn/fetch_support.rs b/moli-protocol/src/conn/fetch_support.rsindex d0eac91d3..ffc58e837 100644--- a/moli-protocol/src/conn/fetch_support.rs+++ b/moli-protocol/src/conn/fetch_support.rs@@ -155,229 +155,6 @@ impl FetchResourceTypeFilter {}}-#[cfg(test)]-mod tests {- use super::{- FetchInterceptionPattern, FetchRequestStage, FetchResourceTypeFilter,- fetch_subresource_interception_config_for_patterns, matching_fetch_pattern,- };- use crate::automation::DevToolsNetworkResourceType;- use moli_core::page::SubresourceResourceType;- use url::Url;-- #[test]- fn fetch_request_stage_parses_cdp_tokens() {- for (raw, expected) in [- ("Request", FetchRequestStage::Request),- ("Response", FetchRequestStage::Response),- ] {- let parsed =- FetchRequestStage::parse(raw).expect("CDP Fetch requestStage token should parse");- assert_eq!(parsed, expected);- assert_eq!(parsed.label(), raw);- }- assert!(FetchRequestStage::parse("request").is_none());- assert!(FetchRequestStage::parse("Both").is_none());- }-- #[test]- fn fetch_resource_type_filter_parses_cdp_tokens() {- for (raw, expected) in [- ("Document", FetchResourceTypeFilter::Document),- ("Script", FetchResourceTypeFilter::Script),- ("Stylesheet", FetchResourceTypeFilter::Stylesheet),- ("Image", FetchResourceTypeFilter::Image),- ("Media", FetchResourceTypeFilter::Media),- ("TextTrack", FetchResourceTypeFilter::TextTrack),- ("Fetch", FetchResourceTypeFilter::Fetch),- ("EventSource", FetchResourceTypeFilter::EventSource),- ("XHR", FetchResourceTypeFilter::Xhr),- ("Ping", FetchResourceTypeFilter::Ping),- (- "CSPViolationReport",- FetchResourceTypeFilter::CspViolationReport,- ),- ("WebSocket", FetchResourceTypeFilter::WebSocket),- ("Other", FetchResourceTypeFilter::Other),- ] {- let parsed = FetchResourceTypeFilter::parse(raw)- .expect("CDP Fetch resourceType token should parse");- assert_eq!(parsed, expected);- assert_eq!(parsed.label(), raw);- assert!(- parsed.matches_resource_type(- DevToolsNetworkResourceType::from_cdp_type(raw)- .expect("supported Fetch filter should be a CDP network resource type"),- )- );- }- assert!(FetchResourceTypeFilter::parse("xhr").is_none());- }-- #[test]- fn matching_fetch_pattern_filters_by_resource_type_and_url() {- let patterns = vec![- FetchInterceptionPattern {- url_pattern: "*://example.test/script.js".to_owned(),- resource_type_filter: Some(FetchResourceTypeFilter::Script),- request_stage: FetchRequestStage::Request,- },- FetchInterceptionPattern {- url_pattern: "*://example.test/api".to_owned(),- resource_type_filter: Some(FetchResourceTypeFilter::Fetch),- request_stage: FetchRequestStage::Response,- },- ];- let url = Url::parse("https://example.test/api").unwrap();-- let matched =- matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Fetch, &url).unwrap();- assert_eq!(matched.request_stage, FetchRequestStage::Response);- assert!(- matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Image, &url).is_none()- );- let script_url = Url::parse("https://example.test/script.js").unwrap();- assert!(- matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Script, &script_url,)- .is_some()- );- }-- #[test]- fn fetch_like_filters_match_chromiums_shared_xhr_interception_type() {- for filter in [- FetchResourceTypeFilter::Fetch,- FetchResourceTypeFilter::EventSource,- FetchResourceTypeFilter::Xhr,- ] {- for resource_type in [- DevToolsNetworkResourceType::Fetch,- DevToolsNetworkResourceType::EventSource,- DevToolsNetworkResourceType::Xhr,- ] {- assert!(filter.matches_resource_type(resource_type), "{filter:?}");- }- assert!(- !filter.matches_resource_type(DevToolsNetworkResourceType::Script),- "{filter:?}"- );- }- }-- #[test]- fn matching_fetch_pattern_accepts_unfiltered_default_pattern() {- let patterns = vec![FetchInterceptionPattern {- url_pattern: "*".to_owned(),- resource_type_filter: None,- request_stage: FetchRequestStage::Request,- }];- let url = Url::parse("https://example.test/style.css").unwrap();-- assert!(- matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Stylesheet, &url)- .is_some()- );- }-- #[test]- fn fetch_resource_type_support_tracks_implemented_interception_paths() {- assert!(FetchResourceTypeFilter::Script.supports_fetch_enable());- assert_eq!(- FetchResourceTypeFilter::Script.subresource_type(),- Some(SubresourceResourceType::Script)- );- for filter in [- FetchResourceTypeFilter::Stylesheet,- FetchResourceTypeFilter::Media,- FetchResourceTypeFilter::TextTrack,- ] {- assert!(!filter.supports_fetch_enable(), "{filter:?}");- assert_eq!(filter.subresource_type(), None, "{filter:?}");- }- for filter in [- FetchResourceTypeFilter::Document,- FetchResourceTypeFilter::Image,- FetchResourceTypeFilter::Fetch,- FetchResourceTypeFilter::EventSource,- FetchResourceTypeFilter::Xhr,- FetchResourceTypeFilter::Ping,- FetchResourceTypeFilter::CspViolationReport,- FetchResourceTypeFilter::WebSocket,- FetchResourceTypeFilter::Other,- ] {- assert!(filter.supports_fetch_enable(), "{filter:?}");- }- }-- #[test]- fn csp_violation_report_filter_maps_to_csp_report_subresource_type() {- let patterns = vec![FetchInterceptionPattern {- url_pattern: "*".to_owned(),- resource_type_filter: Some(FetchResourceTypeFilter::CspViolationReport),- request_stage: FetchRequestStage::Request,- }];-- assert_eq!(- fetch_subresource_interception_config_for_patterns(true, &patterns),- (true, Some(SubresourceResourceType::CspReport))- );- }-- #[test]- fn other_filter_maps_to_dictionary_subresource_type() {- let patterns = vec![FetchInterceptionPattern {- url_pattern: "*".to_owned(),- resource_type_filter: Some(FetchResourceTypeFilter::Other),- request_stage: FetchRequestStage::Request,- }];-- assert_eq!(- fetch_subresource_interception_config_for_patterns(true, &patterns),- (true, Some(SubresourceResourceType::Dictionary))- );- }-- #[test]- fn image_filter_maps_to_image_subresource_type() {- let patterns = vec![FetchInterceptionPattern {- url_pattern: "*".to_owned(),- resource_type_filter: Some(FetchResourceTypeFilter::Image),- request_stage: FetchRequestStage::Request,- }];-- assert_eq!(- fetch_subresource_interception_config_for_patterns(true, &patterns),- (true, Some(SubresourceResourceType::Image))- );- }-- #[test]- fn fetch_like_patterns_share_one_renderer_interception_type() {- let patterns = [- FetchInterceptionPattern {- url_pattern: "*/fetch".to_owned(),- resource_type_filter: Some(FetchResourceTypeFilter::Fetch),- request_stage: FetchRequestStage::Request,- },- FetchInterceptionPattern {- url_pattern: "*/xhr".to_owned(),- resource_type_filter: Some(FetchResourceTypeFilter::Xhr),- request_stage: FetchRequestStage::Response,- },- FetchInterceptionPattern {- url_pattern: "*/events".to_owned(),- resource_type_filter: Some(FetchResourceTypeFilter::EventSource),- request_stage: FetchRequestStage::Request,- },- ];-- assert_eq!(- fetch_subresource_interception_config_for_patterns(true, &patterns),- (true, Some(SubresourceResourceType::Fetch))- );- }-}-pub fn fetch_subresource_interception_config(fetch_enabled: bool,filter: Option<FetchResourceTypeFilter>,@@ -1123,6 +900,9 @@ impl PausedDocumentTransfer {})}+ // Err returns the unconsumed transfer for another continuation path;+ // keep that ownership handoff allocation-free.+ #[allow(clippy::result_large_err)]pub(crate) async fn continue_response_async(self,conn: &mut CdpConnection,@@ -1509,6 +1289,8 @@ impl DocumentBodySource {}}+ // Preserve the body source on failure without allocating a boxed copy.+ #[allow(clippy::result_large_err)]pub(crate) async fn materialize_body_limited_async(self,limit: usize,@@ -2339,3 +2121,226 @@ impl CdpConnection {.map_err(|error| format!("synthetic websocket close dispatch failed: {error}"))}}++#[cfg(test)]+mod tests {+ use super::{+ FetchInterceptionPattern, FetchRequestStage, FetchResourceTypeFilter,+ fetch_subresource_interception_config_for_patterns, matching_fetch_pattern,+ };+ use crate::automation::DevToolsNetworkResourceType;+ use moli_core::page::SubresourceResourceType;+ use url::Url;++ #[test]+ fn fetch_request_stage_parses_cdp_tokens() {+ for (raw, expected) in [+ ("Request", FetchRequestStage::Request),+ ("Response", FetchRequestStage::Response),+ ] {+ let parsed =+ FetchRequestStage::parse(raw).expect("CDP Fetch requestStage token should parse");+ assert_eq!(parsed, expected);+ assert_eq!(parsed.label(), raw);+ }+ assert!(FetchRequestStage::parse("request").is_none());+ assert!(FetchRequestStage::parse("Both").is_none());+ }++ #[test]+ fn fetch_resource_type_filter_parses_cdp_tokens() {+ for (raw, expected) in [+ ("Document", FetchResourceTypeFilter::Document),+ ("Script", FetchResourceTypeFilter::Script),+ ("Stylesheet", FetchResourceTypeFilter::Stylesheet),+ ("Image", FetchResourceTypeFilter::Image),+ ("Media", FetchResourceTypeFilter::Media),+ ("TextTrack", FetchResourceTypeFilter::TextTrack),+ ("Fetch", FetchResourceTypeFilter::Fetch),+ ("EventSource", FetchResourceTypeFilter::EventSource),+ ("XHR", FetchResourceTypeFilter::Xhr),+ ("Ping", FetchResourceTypeFilter::Ping),+ (+ "CSPViolationReport",+ FetchResourceTypeFilter::CspViolationReport,+ ),+ ("WebSocket", FetchResourceTypeFilter::WebSocket),+ ("Other", FetchResourceTypeFilter::Other),+ ] {+ let parsed = FetchResourceTypeFilter::parse(raw)+ .expect("CDP Fetch resourceType token should parse");+ assert_eq!(parsed, expected);+ assert_eq!(parsed.label(), raw);+ assert!(+ parsed.matches_resource_type(+ DevToolsNetworkResourceType::from_cdp_type(raw)+ .expect("supported Fetch filter should be a CDP network resource type"),+ )+ );+ }+ assert!(FetchResourceTypeFilter::parse("xhr").is_none());+ }++ #[test]+ fn matching_fetch_pattern_filters_by_resource_type_and_url() {+ let patterns = vec![+ FetchInterceptionPattern {+ url_pattern: "*://example.test/script.js".to_owned(),+ resource_type_filter: Some(FetchResourceTypeFilter::Script),+ request_stage: FetchRequestStage::Request,+ },+ FetchInterceptionPattern {+ url_pattern: "*://example.test/api".to_owned(),+ resource_type_filter: Some(FetchResourceTypeFilter::Fetch),+ request_stage: FetchRequestStage::Response,+ },+ ];+ let url = Url::parse("https://example.test/api").unwrap();++ let matched =+ matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Fetch, &url).unwrap();+ assert_eq!(matched.request_stage, FetchRequestStage::Response);+ assert!(+ matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Image, &url).is_none()+ );+ let script_url = Url::parse("https://example.test/script.js").unwrap();+ assert!(+ matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Script, &script_url,)+ .is_some()+ );+ }++ #[test]+ fn fetch_like_filters_match_chromiums_shared_xhr_interception_type() {+ for filter in [+ FetchResourceTypeFilter::Fetch,+ FetchResourceTypeFilter::EventSource,+ FetchResourceTypeFilter::Xhr,+ ] {+ for resource_type in [+ DevToolsNetworkResourceType::Fetch,+ DevToolsNetworkResourceType::EventSource,+ DevToolsNetworkResourceType::Xhr,+ ] {+ assert!(filter.matches_resource_type(resource_type), "{filter:?}");+ }+ assert!(+ !filter.matches_resource_type(DevToolsNetworkResourceType::Script),+ "{filter:?}"+ );+ }+ }++ #[test]+ fn matching_fetch_pattern_accepts_unfiltered_default_pattern() {+ let patterns = vec![FetchInterceptionPattern {+ url_pattern: "*".to_owned(),+ resource_type_filter: None,+ request_stage: FetchRequestStage::Request,+ }];+ let url = Url::parse("https://example.test/style.css").unwrap();++ assert!(+ matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Stylesheet, &url)+ .is_some()+ );+ }++ #[test]+ fn fetch_resource_type_support_tracks_implemented_interception_paths() {+ assert!(FetchResourceTypeFilter::Script.supports_fetch_enable());+ assert_eq!(+ FetchResourceTypeFilter::Script.subresource_type(),+ Some(SubresourceResourceType::Script)+ );+ for filter in [+ FetchResourceTypeFilter::Stylesheet,+ FetchResourceTypeFilter::Media,+ FetchResourceTypeFilter::TextTrack,+ ] {+ assert!(!filter.supports_fetch_enable(), "{filter:?}");+ assert_eq!(filter.subresource_type(), None, "{filter:?}");+ }+ for filter in [+ FetchResourceTypeFilter::Document,+ FetchResourceTypeFilter::Image,+ FetchResourceTypeFilter::Fetch,+ FetchResourceTypeFilter::EventSource,+ FetchResourceTypeFilter::Xhr,+ FetchResourceTypeFilter::Ping,+ FetchResourceTypeFilter::CspViolationReport,+ FetchResourceTypeFilter::WebSocket,+ FetchResourceTypeFilter::Other,+ ] {+ assert!(filter.supports_fetch_enable(), "{filter:?}");+ }+ }++ #[test]+ fn csp_violation_report_filter_maps_to_csp_report_subresource_type() {+ let patterns = vec![FetchInterceptionPattern {+ url_pattern: "*".to_owned(),+ resource_type_filter: Some(FetchResourceTypeFilter::CspViolationReport),+ request_stage: FetchRequestStage::Request,+ }];++ assert_eq!(+ fetch_subresource_interception_config_for_patterns(true, &patterns),+ (true, Some(SubresourceResourceType::CspReport))+ );+ }++ #[test]+ fn other_filter_maps_to_dictionary_subresource_type() {+ let patterns = vec![FetchInterceptionPattern {+ url_pattern: "*".to_owned(),+ resource_type_filter: Some(FetchResourceTypeFilter::Other),+ request_stage: FetchRequestStage::Request,+ }];++ assert_eq!(+ fetch_subresource_interception_config_for_patterns(true, &patterns),+ (true, Some(SubresourceResourceType::Dictionary))+ );+ }++ #[test]+ fn image_filter_maps_to_image_subresource_type() {+ let patterns = vec![FetchInterceptionPattern {+ url_pattern: "*".to_owned(),+ resource_type_filter: Some(FetchResourceTypeFilter::Image),+ request_stage: FetchRequestStage::Request,+ }];++ assert_eq!(+ fetch_subresource_interception_config_for_patterns(true, &patterns),+ (true, Some(SubresourceResourceType::Image))+ );+ }++ #[test]+ fn fetch_like_patterns_share_one_renderer_interception_type() {+ let patterns = [+ FetchInterceptionPattern {+ url_pattern: "*/fetch".to_owned(),+ resource_type_filter: Some(FetchResourceTypeFilter::Fetch),+ request_stage: FetchRequestStage::Request,+ },+ FetchInterceptionPattern {+ url_pattern: "*/xhr".to_owned(),+ resource_type_filter: Some(FetchResourceTypeFilter::Xhr),+ request_stage: FetchRequestStage::Response,+ },+ FetchInterceptionPattern {+ url_pattern: "*/events".to_owned(),+ resource_type_filter: Some(FetchResourceTypeFilter::EventSource),+ request_stage: FetchRequestStage::Request,+ },+ ];++ assert_eq!(+ fetch_subresource_interception_config_for_patterns(true, &patterns),+ (true, Some(SubresourceResourceType::Fetch))+ );+ }+}diff --git a/moli-protocol/src/conn/scheduler_state.rs b/moli-protocol/src/conn/scheduler_state.rsindex 4c943eb87..bbd90f1bd 100644--- a/moli-protocol/src/conn/scheduler_state.rs+++ b/moli-protocol/src/conn/scheduler_state.rs@@ -227,47 +227,6 @@ impl CdpRendererOwnerTurnOutcome {}}-#[cfg(test)]-mod tests {- use super::*;- use crate::automation::AutomationEvent;-- #[test]- fn turn_outcome_raw_protocol_messages_regain_typed_sidecars() {- let outcome = CdpTurnOutcome::new(- vec![json!({- "method": "Page.fileChooserOpened",- "params": {- "frameId": "FRAME",- "backendNodeId": 42,- "mode": "selectSingle"- },- "sessionId": "SID"- })],- Vec::new(),- );-- let (events, scheduler_events) = outcome.into_protocol_event_parts();- assert!(scheduler_events.is_empty());- let [(message, automation_event)] = events- .into_iter()- .map(BackgroundProtocolEvent::into_parts)- .collect::<Vec<_>>()- .try_into()- .expect("expected one protocol event");-- assert_eq!(message["method"], json!("Page.fileChooserOpened"));- assert_eq!(message["sessionId"], json!("SID"));- assert!(matches!(- automation_event,- Some(AutomationEvent::PageFileChooserOpened(event))- if event.frame_id.as_str() == "FRAME"- && event.backend_node_id == 42- && event.mode == "selectSingle"- ));- }-}-#[derive(Default)]pub(super) struct CdpConnectionSchedulerState {pending_navigation_background_events: Vec<NavigationBackgroundEvent>,@@ -351,3 +310,44 @@ impl CdpConnectionSchedulerState {})}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::automation::AutomationEvent;++ #[test]+ fn turn_outcome_raw_protocol_messages_regain_typed_sidecars() {+ let outcome = CdpTurnOutcome::new(+ vec![json!({+ "method": "Page.fileChooserOpened",+ "params": {+ "frameId": "FRAME",+ "backendNodeId": 42,+ "mode": "selectSingle"+ },+ "sessionId": "SID"+ })],+ Vec::new(),+ );++ let (events, scheduler_events) = outcome.into_protocol_event_parts();+ assert!(scheduler_events.is_empty());+ let [(message, automation_event)] = events+ .into_iter()+ .map(BackgroundProtocolEvent::into_parts)+ .collect::<Vec<_>>()+ .try_into()+ .expect("expected one protocol event");++ assert_eq!(message["method"], json!("Page.fileChooserOpened"));+ assert_eq!(message["sessionId"], json!("SID"));+ assert!(matches!(+ automation_event,+ Some(AutomationEvent::PageFileChooserOpened(event))+ if event.frame_id.as_str() == "FRAME"+ && event.backend_node_id == 42+ && event.mode == "selectSingle"+ ));+ }+}diff --git a/moli-protocol/src/domains/network/agent.rs b/moli-protocol/src/domains/network/agent.rsindex 6ec950297..8f0538755 100644--- a/moli-protocol/src/domains/network/agent.rs+++ b/moli-protocol/src/domains/network/agent.rs@@ -1934,856 +1934,674 @@ impl SubresourceNetworkArtifacts {}}-#[cfg(test)]-mod tests {- use moli_core::page::{- ScriptNetworkOutputItem, SubresourceNetworkRecord, SubresourceNetworkRequestHandle,- SubresourceRequestInitiatorType, SubresourceRequestStarted, SubresourceResourceType,- WebSocketFrameDirection, WebSocketFrameOpcode, WebSocketNetworkEvent,- };- use url::Url;+#[derive(Debug, Clone, Default, PartialEq, Eq)]+struct WebSocketNetworkArtifacts {+ observation: WebSocketNetworkObservationArtifacts,+ request_ids: WebSocketRequestIdState,+}- use super::super::output_queue::{- PendingSubresourceNetworkActivity, PendingSubresourceNetworkActivitySession,- PendingWebSocketNetworkActivity, PendingWebSocketNetworkActivitySession,- };- use super::{- CapturedResponseBodyStore, NetworkBacklogPreferredRequestId, NetworkBacklogRequestIdPlan,- TargetNetworkAgentState, WebSocketNetworkArtifacts,- };- use crate::conn::{CapturedBody, CapturedBodyWriter, ConnectionNetworkRequestIdAllocator};+impl WebSocketNetworkArtifacts {+ pub(crate) fn emitted_record_count_for_session(&self, session_id: Option<&str>) -> usize {+ self.observation+ .emitted_record_count_for_session(session_id)+ }- #[test]- fn response_body_store_defaults_to_one_tenth_of_chromium_desktop_budget() {- let store = CapturedResponseBodyStore::default();+ pub(crate) fn emitted_event_count_for_session(&self, session_id: Option<&str>) -> usize {+ self.observation.emitted_event_count_for_session(session_id)+ }- assert_eq!(- store.buffered_bodies.limits(),- moli_bounded_buffer::ByteLimits::new(20_000_000, 2_000_000)- );+ fn minimum_emitted_record_count(&self) -> Option<usize> {+ self.observation+ .emitted_record_counts_by_session+ .values()+ .copied()+ .min()}- #[test]- fn response_body_store_marks_oldest_payload_evicted_when_total_budget_fills() {- let mut store =- CapturedResponseBodyStore::with_limits(moli_bounded_buffer::ByteLimits::new(5, 4));- store.insert_captured_body_with_collector_scope(- "REQ-first".to_owned(),- CapturedBody::from_string("aa".to_owned()),- [None],- std::iter::empty::<String>(),- false,- );- store.insert_captured_body_with_collector_scope(- "REQ-second".to_owned(),- CapturedBody::from_string("bb".to_owned()),- [None],- std::iter::empty::<String>(),- false,- );- store.insert_captured_body_with_collector_scope(- "REQ-third".to_owned(),- CapturedBody::from_string("ccc".to_owned()),- [None],- std::iter::empty::<String>(),- false,- );+ fn minimum_emitted_event_count(&self) -> Option<usize> {+ self.observation+ .emitted_event_counts_by_session+ .values()+ .copied()+ .min()+ }- assert_eq!(store.buffered_body_bytes(), 5);- assert_eq!(- store- .get("REQ-first")- .expect("evicted metadata must remain addressable")- .body_bytes_limited(10)- .expect_err("oldest payload should be evicted")- .to_string(),- "Request content was evicted from inspector cache"- );- assert_eq!(- store- .get("REQ-second")- .expect("second response should remain")- .body_bytes_limited(10)- .expect("second response body should remain readable"),- b"bb"- );- assert_eq!(- store- .get("REQ-third")- .expect("third response should remain")- .body_bytes_limited(10)- .expect("third response body should remain readable"),- b"ccc"+ pub(crate) fn mark_emitted(+ &mut self,+ session_id: Option<&str>,+ record_start_index: usize,+ record_count: usize,+ event_start_index: usize,+ event_count: usize,+ ) {+ self.observation.mark_emitted(+ session_id,+ record_start_index,+ record_count,+ event_start_index,+ event_count,);}- #[test]- fn response_body_store_returns_byte_charge_on_state_and_visibility_removal() {- let mut store =- CapturedResponseBodyStore::with_limits(moli_bounded_buffer::ByteLimits::new(8, 4));- store.insert_captured_body_with_collector_scope(- "REQ-failed".to_owned(),- CapturedBody::from_string("body".to_owned()),- [None],- std::iter::empty::<String>(),- false,- );- assert_eq!(store.buffered_body_bytes(), 4);- store.insert_failed_with_collector_scope(- "REQ-failed".to_owned(),- "network failed".to_owned(),- [None],- std::iter::empty::<String>(),- false,- );- assert_eq!(store.buffered_body_bytes(), 0);+ pub(crate) fn reset_cursors(&mut self) {+ self.observation.reset_cursors();+ }- store.insert_captured_body_with_collector_scope(- "REQ-session".to_owned(),- CapturedBody::from_string("abc".to_owned()),- [Some("SID-1".to_owned())],- std::iter::empty::<String>(),- false,- );- assert_eq!(store.buffered_body_bytes(), 3);- store.remove_session_visibility(Some("SID-1"));- assert_eq!(store.buffered_body_bytes(), 0);- assert!(store.get("REQ-session").is_none());+ pub(crate) fn set_session_cursors(+ &mut self,+ session_id: Option<&str>,+ record_count: usize,+ event_count: usize,+ ) {+ self.observation+ .set_session_cursors(session_id, record_count, event_count);}- fn subresource_record(url: &str) -> SubresourceNetworkRecord {- let url = Url::parse(url).expect("test URL should parse");- SubresourceNetworkRecord::success(- None,- Url::parse("https://example.com/").expect("document URL should parse"),- url.clone(),- "GET".to_owned(),- Vec::new().into(),- None,- SubresourceResourceType::Script,- None,- Vec::new(),- url,- 200,- Vec::new(),- String::new(),- Vec::new(),- )+ pub(crate) fn remove_session_cursors(&mut self, session_id: Option<&str>) {+ self.observation.remove_session_cursors(session_id);}- fn websocket_record(url: &str, socket_id: u64) -> SubresourceNetworkRecord {- let url = Url::parse(url).expect("test URL should parse");- SubresourceNetworkRecord::success(- None,- Url::parse("https://example.com/").expect("document URL should parse"),- url.clone(),- "GET".to_owned(),- vec![("Sec-WebSocket-Version".to_owned(), "13".to_owned())].into(),- None,- SubresourceResourceType::WebSocket,- None,- Vec::new(),- url,- 101,- vec![("Upgrade".to_owned(), b"websocket".to_vec())],- String::new(),- Vec::new(),- )- .with_websocket_socket_id(socket_id)+ pub(crate) fn clear_request_ids(&mut self) {+ self.request_ids.clear();}- fn websocket_event(socket_id: u64, payload_length: usize) -> WebSocketNetworkEvent {- WebSocketNetworkEvent::new(- socket_id,- Url::parse("https://example.com/").expect("document URL should parse"),- Url::parse("wss://example.com/socket").expect("websocket URL should parse"),- WebSocketFrameDirection::Received,- WebSocketFrameOpcode::Text,- payload_length,- )+ pub(crate) fn clear_all(&mut self) {+ self.reset_cursors();+ self.clear_request_ids();}- fn network_output_items(- records: &[SubresourceNetworkRecord],- events: &[WebSocketNetworkEvent],- ) -> Vec<ScriptNetworkOutputItem> {- records- .iter()- .cloned()- .map(|record| ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(record)))- .chain(- events- .iter()- .cloned()- .map(ScriptNetworkOutputItem::WebSocketNetworkEvent),- )- .collect()+ pub(crate) fn register_synthetic_request(+ &mut self,+ request_id: String,+ network_request_id: String,+ socket_id: u64,+ ) {+ self.request_ids+ .register_synthetic_request(request_id, network_request_id, socket_id);}- fn ingest_network_output(- agent: &mut TargetNetworkAgentState,- records: &[SubresourceNetworkRecord],- events: &[WebSocketNetworkEvent],+ pub(crate) fn synthetic_socket_id_for_request(&self, request_id: &str) -> Option<u64> {+ self.request_ids.synthetic_socket_id_for_request(request_id)+ }++ pub(crate) fn request_id_for_socket(&self, socket_id: u64) -> Option<&str> {+ self.request_ids.request_id_for_socket(socket_id)+ }++ pub(crate) fn set_request_id_for_socket_if_absent(+ &mut self,+ socket_id: u64,+ request_id: String,) {- for item in network_output_items(records, events) {- agent.ingest_renderer_output_item(&item, "LOADER-1");- }+ self.request_ids+ .set_request_id_for_socket_if_absent(socket_id, request_id);}+}- #[test]- fn handled_terminal_network_record_retires_staged_request_from_idle_accounting() {- let mut agent = TargetNetworkAgentState::default();- let handle = SubresourceNetworkRequestHandle::new(17);- let document_url = Url::parse("https://example.com/").expect("document URL should parse");- let request_url =- Url::parse("https://example.com/late-xhr").expect("request URL should parse");- let started = ScriptNetworkOutputItem::SubresourceRequestStarted(Box::new(- SubresourceRequestStarted::new(- handle,- None,- document_url,- request_url,- "GET".to_owned(),- Vec::new().into(),- None,- SubresourceResourceType::Xhr,- SubresourceRequestInitiatorType::Script,- None,- ),- ));- agent.ingest_renderer_output_item(&started, "LOADER-1");- assert!(!agent.renderer_subresources_are_idle());-- let terminal = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(- subresource_record("https://example.com/late-xhr").with_request_handle(handle),- ));- agent.ingest_renderer_output_item(&terminal, "LOADER-1");+#[derive(Debug, Clone, Default, PartialEq, Eq)]+struct WebSocketNetworkObservationArtifacts {+ emitted_record_counts_by_session: HashMap<Option<String>, usize>,+ emitted_event_counts_by_session: HashMap<Option<String>, usize>,+}- assert!(- agent.renderer_subresources_are_idle(),- "a handled all-in-one record is terminal for the staged request with the same handle"- );+impl WebSocketNetworkObservationArtifacts {+ pub(crate) fn emitted_record_count_for_session(&self, session_id: Option<&str>) -> usize {+ self.emitted_record_counts_by_session+ .get(&session_id.map(str::to_owned))+ .copied()+ .unwrap_or(0)}- #[test]- fn retiring_keepalive_does_not_require_a_document_bound_terminal() {- fn started(- handle: SubresourceNetworkRequestHandle,- keepalive: bool,- ) -> ScriptNetworkOutputItem {- ScriptNetworkOutputItem::SubresourceRequestStarted(Box::new(- SubresourceRequestStarted::new(- handle,- None,- Url::parse("https://example.com/").expect("document URL should parse"),- Url::parse("https://example.com/collect").expect("request URL should parse"),- "POST".to_owned(),- Vec::new().into(),- None,- SubresourceResourceType::Fetch,- SubresourceRequestInitiatorType::Script,- None,- )- .with_keepalive(keepalive),- ))- }-- let mut keepalive_agent = TargetNetworkAgentState::default();- keepalive_agent.ingest_renderer_output_item(- &started(SubresourceNetworkRequestHandle::new(18), true),- "LOADER-1",- );- assert!(- !keepalive_agent.renderer_subresources_are_idle(),- "a keepalive remains current-document activity until replacement"- );- let retiring_keepalive = keepalive_agent.rotate_document_for_replacement();- assert!(- retiring_keepalive- .unterminated_document_bound_request_diagnostics()- .is_empty(),- "a detached keepalive may outlive its Document without a CDP terminal"- );-- let mut ordinary_agent = TargetNetworkAgentState::default();- ordinary_agent.ingest_renderer_output_item(- &started(SubresourceNetworkRequestHandle::new(19), false),- "LOADER-2",- );- let retiring_ordinary = ordinary_agent.rotate_document_for_replacement();- assert_eq!(- retiring_ordinary.unterminated_document_bound_request_diagnostics(),- vec![(19, None)],- "an ordinary request still requires a terminal before its renderer stream closes"- );+ pub(crate) fn emitted_event_count_for_session(&self, session_id: Option<&str>) -> usize {+ self.emitted_event_counts_by_session+ .get(&session_id.map(str::to_owned))+ .copied()+ .unwrap_or(0)}- fn pending_combined_snapshot(- agent: &mut TargetNetworkAgentState,- preferred_request_id: Option<&str>,- ) -> super::PendingNetworkBacklogDeliverySnapshot {- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- pending_combined_snapshot_with_allocator(- agent,- preferred_request_id,- &mut request_id_allocator,- )+ pub(crate) fn mark_emitted(+ &mut self,+ session_id: Option<&str>,+ record_start_index: usize,+ record_count: usize,+ event_start_index: usize,+ event_count: usize,+ ) {+ let record_cursor = record_start_index+ .checked_add(record_count)+ .expect("websocket emitted record cursor exhausted");+ let event_cursor = event_start_index+ .checked_add(event_count)+ .expect("websocket emitted event cursor exhausted");+ self.set_session_cursors(session_id, record_cursor, event_cursor);}- fn pending_combined_snapshot_with_allocator(- agent: &mut TargetNetworkAgentState,- preferred_request_id: Option<&str>,- request_id_allocator: &mut ConnectionNetworkRequestIdAllocator,- ) -> super::PendingNetworkBacklogDeliverySnapshot {- agent- .pending_network_backlog_delivery_snapshot(- None,- None,- preferred_request_id.map(NetworkBacklogPreferredRequestId::contextual_subresource),- request_id_allocator,- )- .expect("combined network backlog snapshot should be visible")+ pub(crate) fn reset_cursors(&mut self) {+ self.emitted_record_counts_by_session.clear();+ self.emitted_event_counts_by_session.clear();}- fn contextual_preferred_request_id(request_id: &str) -> NetworkBacklogPreferredRequestId<'_> {- NetworkBacklogPreferredRequestId::contextual_subresource(request_id)+ pub(crate) fn set_session_cursors(+ &mut self,+ session_id: Option<&str>,+ record_count: usize,+ event_count: usize,+ ) {+ let session_id = session_id.map(str::to_owned);+ self.emitted_record_counts_by_session+ .insert(session_id.clone(), record_count);+ self.emitted_event_counts_by_session+ .insert(session_id, event_count);}- fn subresource_request_ids(- snapshot: &super::PendingNetworkBacklogDeliverySnapshot,- ) -> Vec<String> {- snapshot- .outputs()- .into_iter()- .filter_map(|item| {- item.as_subresource()- .map(|output| output.request_id().to_owned())- })- .collect()+ pub(crate) fn remove_session_cursors(&mut self, session_id: Option<&str>) {+ let session_id = session_id.map(str::to_owned);+ self.emitted_record_counts_by_session.remove(&session_id);+ self.emitted_event_counts_by_session.remove(&session_id);}+}- fn subresource_urls(snapshot: &super::PendingNetworkBacklogDeliverySnapshot) -> Vec<String> {- snapshot- .outputs()- .into_iter()- .filter_map(|item| {- item.as_subresource()- .map(|output| output.metadata().url().as_str().to_owned())- })- .collect()- }+#[derive(Debug, Clone, Default, PartialEq, Eq)]+struct WebSocketRequestIdState {+ request_ids_by_socket_id: HashMap<u64, String>,+ socket_ids_by_request_id: HashMap<String, u64>,+}- fn websocket_request_ids(- snapshot: &super::PendingNetworkBacklogDeliverySnapshot,- ) -> Vec<String> {- snapshot- .outputs()- .into_iter()- .filter_map(|item| {- item.as_websocket().map(|output| {- output- .as_handshake()- .map(|output| output.request_id())- .or_else(|| output.as_frame().map(|output| output.request_id()))- .expect("test WebSocket output should carry a request id")- .to_owned()- })- })- .collect()+impl WebSocketRequestIdState {+ pub(crate) fn clear(&mut self) {+ self.request_ids_by_socket_id.clear();+ self.socket_ids_by_request_id.clear();}- fn websocket_handshake_request_ids(- snapshot: &super::PendingNetworkBacklogDeliverySnapshot,- ) -> Vec<String> {- snapshot- .outputs()- .into_iter()- .filter_map(|item| {- item.as_websocket()- .and_then(|output| output.as_handshake())- .map(|output| output.request_id().to_owned())- })- .collect()+ pub(crate) fn register_synthetic_request(+ &mut self,+ request_id: String,+ network_request_id: String,+ socket_id: u64,+ ) {+ self.socket_ids_by_request_id.insert(request_id, socket_id);+ self.socket_ids_by_request_id+ .insert(network_request_id.clone(), socket_id);+ self.request_ids_by_socket_id+ .insert(socket_id, network_request_id);}- fn websocket_frame_outputs(- snapshot: &super::PendingNetworkBacklogDeliverySnapshot,- ) -> Vec<(String, usize)> {- snapshot- .outputs()- .into_iter()- .filter_map(|item| {- item.as_websocket()- .and_then(|output| output.as_frame())- .map(|output| (output.request_id().to_owned(), output.payload_length()))- })- .collect()+ pub(crate) fn synthetic_socket_id_for_request(&self, request_id: &str) -> Option<u64> {+ self.socket_ids_by_request_id.get(request_id).copied()}- #[test]- fn target_artifact_reset_clears_response_bodies_and_io_streams_together() {- let mut agent = TargetNetworkAgentState::default();-- agent.record_captured_response_body("REQ-1".to_owned(), "response body".to_owned(), [None]);- agent.insert_io_stream("STREAM-1".to_owned(), b"stream body".to_vec(), 0);- assert!(agent.has_captured_response_body("REQ-1"));- assert!(!agent.io_streams_empty());-- agent.reset_all_target_scoped_artifacts();- assert!(!agent.has_captured_response_body("REQ-1"));- assert!(agent.io_streams_empty());+ pub(crate) fn request_id_for_socket(&self, socket_id: u64) -> Option<&str> {+ self.request_ids_by_socket_id+ .get(&socket_id)+ .map(String::as_str)}- #[test]- fn output_queue_reset_clears_page_local_subresource_request_handle_bindings() {- let mut agent = TargetNetworkAgentState::default();- let handle = SubresourceNetworkRequestHandle::new(5);+ pub(crate) fn set_request_id_for_socket_if_absent(+ &mut self,+ socket_id: u64,+ request_id: String,+ ) {+ self.request_ids_by_socket_id+ .entry(socket_id)+ .or_insert(request_id);+ }+}- agent.record_subresource_request_id_for_handle_if_absent(handle, "REQ-old".to_owned());- agent.record_subresource_request_id_for_handle_if_absent(handle, "REQ-stale".to_owned());- assert_eq!(- agent- .artifacts- .subresource_network_artifacts- .request_id_for_handle(handle),- Some("REQ-old")- );+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct IoStreamState {+ body: CapturedBody,+ pub offset: usize,+}- agent.reset_output_queue();- agent.record_subresource_request_id_for_handle_if_absent(handle, "REQ-new".to_owned());- assert_eq!(- agent- .artifacts- .subresource_network_artifacts- .request_id_for_handle(handle),- Some("REQ-new")- );+impl IoStreamState {+ pub(crate) fn from_bytes(bytes: Vec<u8>, offset: usize) -> Self {+ Self {+ body: CapturedBody::from_bytes_spooled(bytes),+ offset,+ }}- #[test]- fn contextual_preferred_request_id_skips_earlier_unrelated_records() {- let mut agent = TargetNetworkAgentState::default();- let contextual_handle = SubresourceNetworkRequestHandle::new(7);- agent.enable_primary_events();- agent.record_subresource_request_id_for_handle_if_absent(- contextual_handle,- "REQ-contextual".to_owned(),- );- let records = [- subresource_record("https://example.com/earlier.js"),- subresource_record("https://example.com/contextual.js")- .with_request_handle(contextual_handle),- ];- ingest_network_output(&mut agent, &records, &[]);+ pub(crate) fn from_body_source(body: CapturedBody, offset: usize) -> Self {+ Self { body, offset }+ }- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- let snapshot = pending_combined_snapshot_with_allocator(- &mut agent,- Some("REQ-contextual"),- &mut request_id_allocator,- );+ pub(crate) fn len(&self) -> usize {+ self.body.len()+ }- assert_eq!(- subresource_request_ids(&snapshot),- vec!["REQ-1", "REQ-contextual"],- "a contextual id already bound to a request handle must not be consumed by an earlier unrelated backlog record"- );- assert_eq!(- request_id_allocator.next_sequence_for_test(),- 1,- "only the unrelated record should allocate a new request id"- );+ pub(crate) fn read_range(&self, offset: usize, len: usize) -> Vec<u8> {+ self.body.read_range(offset, len).unwrap_or_default()}+}- #[test]- fn body_artifacts_own_io_stream_read_offsets_and_close() {- let mut agent = TargetNetworkAgentState::default();- agent.insert_io_stream("STREAM-1".to_owned(), b"abcdef".to_vec(), 0);+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct TargetIoStreamRead {+ pub(crate) bytes: Vec<u8>,+ pub(crate) eof: bool,+}- let first = agent- .read_io_stream("STREAM-1", None, Some(2))- .expect("stream should exist");- assert_eq!(first.bytes, b"ab");- assert!(!first.eof);+#[derive(Debug, Clone, Default, PartialEq, Eq)]+struct TargetIoStreamArtifacts {+ next_stream_id: u64,+ streams: HashMap<String, IoStreamState>,+}- let second = agent- .read_io_stream("STREAM-1", Some(4), None)- .expect("stream should exist");- assert_eq!(second.bytes, b"ef");- assert!(second.eof);+impl TargetIoStreamArtifacts {+ pub(crate) fn allocate_handle(&mut self) -> String {+ self.next_stream_id = self+ .next_stream_id+ .checked_add(1)+ .expect("IO stream id sequence exhausted");+ format!("STREAM-{}", self.next_stream_id)+ }- assert!(agent.close_io_stream("STREAM-1"));- assert!(agent.read_io_stream("STREAM-1", None, None).is_none());- assert!(!agent.close_io_stream("STREAM-1"));+ pub(crate) fn insert_stream(&mut self, handle: String, bytes: Vec<u8>, offset: usize) {+ self.streams+ .insert(handle, IoStreamState::from_bytes(bytes, offset));}- #[test]- fn body_artifacts_read_io_stream_from_captured_body_source() {- let mut writer = CapturedBodyWriter::new(4);- writer- .append(b"captured body source")- .expect("captured body writer should accept bytes");- let body = writer- .finish()- .expect("captured body writer should finish source");- let mut agent = TargetNetworkAgentState::default();+ pub(crate) fn insert_stream_body_source(+ &mut self,+ handle: String,+ body: CapturedBody,+ offset: usize,+ ) {+ self.streams+ .insert(handle, IoStreamState::from_body_source(body, offset));+ }- agent.insert_io_stream_body_source("STREAM-source".to_owned(), body, 0);+ pub(crate) fn remove(&mut self, handle: &str) -> Option<IoStreamState> {+ self.streams.remove(handle)+ }- let first = agent- .read_io_stream("STREAM-source", None, Some(8))- .expect("source-backed stream should exist");- assert_eq!(first.bytes, b"captured");- assert!(!first.eof);+ pub(crate) fn read(+ &mut self,+ handle: &str,+ offset: Option<usize>,+ size: Option<usize>,+ ) -> Option<TargetIoStreamRead> {+ let stream = self.streams.get_mut(handle)?;+ let stream_len = stream.len();+ let start = offset.unwrap_or(stream.offset).min(stream_len);+ stream.offset = start;+ let requested_len = size.unwrap_or_else(|| stream_len.saturating_sub(start));+ let bytes = stream.read_range(start, requested_len);+ let end = start.saturating_add(bytes.len()).min(stream_len);+ stream.offset = end;+ Some(TargetIoStreamRead {+ bytes,+ eof: end >= stream_len,+ })+ }- let second = agent- .read_io_stream("STREAM-source", None, None)- .expect("source-backed stream should remain readable");- assert_eq!(second.bytes, b" body source");- assert!(second.eof);+ pub(crate) fn clear_streams(&mut self) {+ self.streams.clear();}- #[test]- fn websocket_request_ids_are_owned_by_network_agent() {- let mut agent = TargetNetworkAgentState::default();- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ pub(crate) fn reset_all(&mut self) {+ self.next_stream_id = 0;+ self.streams.clear();+ }- agent.record_websocket_request_id_for_socket_if_absent(7, "REQ-bound".to_owned());- assert_eq!(- agent.websocket_request_id_for_socket_or_allocate_with(7, &mut request_id_allocator),- "REQ-bound"- );- assert_eq!(- request_id_allocator.next_sequence_for_test(),- 0,- "bound request id should not consume a new network id"- );+ #[cfg(test)]+ pub(crate) fn is_empty(&self) -> bool {+ self.streams.is_empty()+ }- let allocated =- agent.websocket_request_id_for_socket_or_allocate_with(8, &mut request_id_allocator);- assert_eq!(allocated, "REQ-1");- assert_eq!(- agent.websocket_request_id_for_socket_or_allocate_with(8, &mut request_id_allocator),- "REQ-1"- );- assert_eq!(- request_id_allocator.next_sequence_for_test(),- 1,- "subsequent lookups should reuse the socket mapping"- );+ #[cfg(test)]+ pub(crate) fn set_next_stream_id_for_test(&mut self, next_stream_id: u64) {+ self.next_stream_id = next_stream_id;}- #[test]- fn synthetic_websocket_request_registration_updates_reverse_socket_mapping() {- let mut agent = TargetNetworkAgentState::default();+ #[cfg(test)]+ pub(crate) fn next_stream_id_for_test(&self) -> u64 {+ self.next_stream_id+ }+}- agent.register_synthetic_websocket_request("FETCH-1".to_owned(), "REQ-first".to_owned(), 7);- agent.register_synthetic_websocket_request(- "FETCH-2".to_owned(),- "REQ-second".to_owned(),- 7,- );+#[cfg(test)]+mod tests {+ use moli_core::page::{+ ScriptNetworkOutputItem, SubresourceNetworkRecord, SubresourceNetworkRequestHandle,+ SubresourceRequestInitiatorType, SubresourceRequestStarted, SubresourceResourceType,+ WebSocketFrameDirection, WebSocketFrameOpcode, WebSocketNetworkEvent,+ };+ use url::Url;++ use super::super::output_queue::{+ PendingSubresourceNetworkActivity, PendingSubresourceNetworkActivitySession,+ PendingWebSocketNetworkActivity, PendingWebSocketNetworkActivitySession,+ };+ use super::{+ CapturedResponseBodyStore, NetworkBacklogPreferredRequestId, NetworkBacklogRequestIdPlan,+ TargetNetworkAgentState, WebSocketNetworkArtifacts,+ };+ use crate::conn::{CapturedBody, CapturedBodyWriter, ConnectionNetworkRequestIdAllocator};++ #[test]+ fn response_body_store_defaults_to_one_tenth_of_chromium_desktop_budget() {+ let store = CapturedResponseBodyStore::default();assert_eq!(- agent.synthetic_websocket_socket_id_for_request("FETCH-1"),- Some(7)- );- assert_eq!(- agent.synthetic_websocket_socket_id_for_request("FETCH-2"),- Some(7)- );- assert_eq!(- agent.websocket_request_id_for_socket_or_allocate(7),- "REQ-second",- "re-registering a synthetic socket must keep the canonical reverse map in sync"+ store.buffered_bodies.limits(),+ moli_bounded_buffer::ByteLimits::new(20_000_000, 2_000_000));}#[test]- fn attached_network_event_sessions_follow_enable_insertion_order() {- let mut agent = TargetNetworkAgentState::default();-- agent.enable_attached_events("SID-z");- agent.enable_attached_events("SID-a");- agent.enable_attached_events("SID-z");+ fn response_body_store_marks_oldest_payload_evicted_when_total_budget_fills() {+ let mut store =+ CapturedResponseBodyStore::with_limits(moli_bounded_buffer::ByteLimits::new(5, 4));+ store.insert_captured_body_with_collector_scope(+ "REQ-first".to_owned(),+ CapturedBody::from_string("aa".to_owned()),+ [None],+ std::iter::empty::<String>(),+ false,+ );+ store.insert_captured_body_with_collector_scope(+ "REQ-second".to_owned(),+ CapturedBody::from_string("bb".to_owned()),+ [None],+ std::iter::empty::<String>(),+ false,+ );+ store.insert_captured_body_with_collector_scope(+ "REQ-third".to_owned(),+ CapturedBody::from_string("ccc".to_owned()),+ [None],+ std::iter::empty::<String>(),+ false,+ );+ assert_eq!(store.buffered_body_bytes(), 5);assert_eq!(- agent.event_session_ids(Some("SID-primary"), Some("SID-primary")),- vec![Some("SID-z".to_owned()), Some("SID-a".to_owned())],- "attached Network listeners should not be sorted by session id"+ store+ .get("REQ-first")+ .expect("evicted metadata must remain addressable")+ .body_bytes_limited(10)+ .expect_err("oldest payload should be evicted")+ .to_string(),+ "Request content was evicted from inspector cache");-- agent.enable_primary_events();assert_eq!(- agent.event_session_ids(Some("SID-primary"), Some("SID-primary")),- vec![- Some("SID-primary".to_owned()),- Some("SID-z".to_owned()),- Some("SID-a".to_owned()),- ],- "primary listener remains first, followed by attached enable order"+ store+ .get("REQ-second")+ .expect("second response should remain")+ .body_bytes_limited(10)+ .expect("second response body should remain readable"),+ b"bb");-- assert!(agent.disable_attached_events("SID-z"));- agent.enable_attached_events("SID-z");assert_eq!(- agent.event_session_ids(Some("SID-primary"), Some("SID-primary")),- vec![- Some("SID-primary".to_owned()),- Some("SID-a".to_owned()),- Some("SID-z".to_owned()),- ],- "disable then re-enable should append the attached session"+ store+ .get("REQ-third")+ .expect("third response should remain")+ .body_bytes_limited(10)+ .expect("third response body should remain readable"),+ b"ccc");}#[test]- fn consecutive_renderer_live_tokens_own_disjoint_ingress_ranges() {- let mut agent = TargetNetworkAgentState::default();- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- agent.enable_primary_events();-- let first = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(- subresource_record("https://example.com/first.js"),- ));- let second = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(- subresource_record("https://example.com/second.js"),- ));- let mut first_delivery = agent.ingest_renderer_output_item_and_prepare_live_delivery(- &first,- "LOADER-1",- None,- None,- None,- &mut request_id_allocator,- );- let mut second_delivery = agent.ingest_renderer_output_item_and_prepare_live_delivery(- &second,- "LOADER-1",- None,- None,- None,- &mut request_id_allocator,+ fn response_body_store_returns_byte_charge_on_state_and_visibility_removal() {+ let mut store =+ CapturedResponseBodyStore::with_limits(moli_bounded_buffer::ByteLimits::new(8, 4));+ store.insert_captured_body_with_collector_scope(+ "REQ-failed".to_owned(),+ CapturedBody::from_string("body".to_owned()),+ [None],+ std::iter::empty::<String>(),+ false,);- assert_eq!(agent.output_queue.retained_delivery_output_count(), 2);-- let first_snapshot = agent- .pending_network_backlog_delivery_snapshot_from_backlog(&mut first_delivery)- .expect("the first renderer fact should own one live delivery range");- assert_eq!(- subresource_urls(&first_snapshot),- vec!["https://example.com/first.js"]+ assert_eq!(store.buffered_body_bytes(), 4);+ store.insert_failed_with_collector_scope(+ "REQ-failed".to_owned(),+ "network failed".to_owned(),+ [None],+ std::iter::empty::<String>(),+ false,);- agent.mark_network_backlog_delivery_snapshot_emitted(&first_snapshot);- assert_eq!(agent.output_queue.retained_delivery_output_count(), 1);+ assert_eq!(store.buffered_body_bytes(), 0);- let second_snapshot = agent- .pending_network_backlog_delivery_snapshot_from_backlog(&mut second_delivery)- .expect("the second renderer fact should own one live delivery range");- assert_eq!(- subresource_urls(&second_snapshot),- vec!["https://example.com/second.js"],- "a later ingress token must not rediscover an earlier unprojected fact from the session cursor"- );- agent.mark_network_backlog_delivery_snapshot_emitted(&second_snapshot);- assert_eq!(agent.output_queue.retained_delivery_output_count(), 0);- assert_eq!(- agent- .artifacts- .emitted_subresource_record_count_for_session(None),- 2+ store.insert_captured_body_with_collector_scope(+ "REQ-session".to_owned(),+ CapturedBody::from_string("abc".to_owned()),+ [Some("SID-1".to_owned())],+ std::iter::empty::<String>(),+ false,);+ assert_eq!(store.buffered_body_bytes(), 3);+ store.remove_session_visibility(Some("SID-1"));+ assert_eq!(store.buffered_body_bytes(), 0);+ assert!(store.get("REQ-session").is_none());}- #[test]- fn renderer_outputs_without_network_listeners_are_not_retained() {- let mut agent = TargetNetworkAgentState::default();- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- let item = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(subresource_record(- "https://example.com/before-enable.js",- )));-- let delivery = agent.ingest_renderer_output_item_and_prepare_live_delivery(- &item,- "LOADER-1",+ fn subresource_record(url: &str) -> SubresourceNetworkRecord {+ let url = Url::parse(url).expect("test URL should parse");+ SubresourceNetworkRecord::success(None,+ Url::parse("https://example.com/").expect("document URL should parse"),+ url.clone(),+ "GET".to_owned(),+ Vec::new().into(),None,+ SubresourceResourceType::Script,None,- &mut request_id_allocator,- );-- assert!(!delivery.has_output());- assert_eq!(agent.output_queue.subresource_record_count(), 1);- assert_eq!(agent.output_queue.retained_delivery_output_count(), 0);+ Vec::new(),+ url,+ 200,+ Vec::new(),+ String::new(),+ Vec::new(),+ )}- #[test]- fn websocket_observation_cursors_and_request_ids_are_separate_artifacts() {- let mut artifacts = WebSocketNetworkArtifacts::default();- artifacts.set_session_cursors(None, 3, 5);- artifacts.set_request_id_for_socket_if_absent(7, "REQ-bound".to_owned());-- artifacts.clear_request_ids();+ fn websocket_record(url: &str, socket_id: u64) -> SubresourceNetworkRecord {+ let url = Url::parse(url).expect("test URL should parse");+ SubresourceNetworkRecord::success(+ None,+ Url::parse("https://example.com/").expect("document URL should parse"),+ url.clone(),+ "GET".to_owned(),+ vec![("Sec-WebSocket-Version".to_owned(), "13".to_owned())].into(),+ None,+ SubresourceResourceType::WebSocket,+ None,+ Vec::new(),+ url,+ 101,+ vec![("Upgrade".to_owned(), b"websocket".to_vec())],+ String::new(),+ Vec::new(),+ )+ .with_websocket_socket_id(socket_id)+ }- assert_eq!(- artifacts.emitted_record_count_for_session(None),- 3,- "clearing WebSocket request ids must not reset record observation cursors"- );- assert_eq!(- artifacts.emitted_event_count_for_session(None),- 5,- "clearing WebSocket request ids must not reset frame observation cursors"- );- assert_eq!(artifacts.request_id_for_socket(7), None);+ fn websocket_event(socket_id: u64, payload_length: usize) -> WebSocketNetworkEvent {+ WebSocketNetworkEvent::new(+ socket_id,+ Url::parse("https://example.com/").expect("document URL should parse"),+ Url::parse("wss://example.com/socket").expect("websocket URL should parse"),+ WebSocketFrameDirection::Received,+ WebSocketFrameOpcode::Text,+ payload_length,+ )+ }- artifacts.clear_all();- assert_eq!(artifacts.emitted_record_count_for_session(None), 0);- assert_eq!(artifacts.emitted_event_count_for_session(None), 0);+ fn network_output_items(+ records: &[SubresourceNetworkRecord],+ events: &[WebSocketNetworkEvent],+ ) -> Vec<ScriptNetworkOutputItem> {+ records+ .iter()+ .cloned()+ .map(|record| ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(record)))+ .chain(+ events+ .iter()+ .cloned()+ .map(ScriptNetworkOutputItem::WebSocketNetworkEvent),+ )+ .collect()}- #[test]- fn subresource_delivery_snapshot_binds_websocket_request_id() {- let mut agent = TargetNetworkAgentState::default();- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- agent.enable_primary_events();- let records = vec![websocket_record("wss://example.com/socket", 7)];- ingest_network_output(&mut agent, &records, &[]);- let snapshot = pending_combined_snapshot_with_allocator(- &mut agent,- Some("REQ-from-subresource"),- &mut request_id_allocator,- );+ fn ingest_network_output(+ agent: &mut TargetNetworkAgentState,+ records: &[SubresourceNetworkRecord],+ events: &[WebSocketNetworkEvent],+ ) {+ for item in network_output_items(records, events) {+ agent.ingest_renderer_output_item(&item, "LOADER-1");+ }+ }- assert_eq!(- subresource_request_ids(&snapshot),- vec!["REQ-from-subresource"]- );- assert_eq!(- agent.websocket_request_id_for_socket_or_allocate(7),- "REQ-from-subresource"- );- assert_eq!(- request_id_allocator.next_sequence_for_test(),- 0,- "subresource output binding should not allocate a second request id"+ #[test]+ fn handled_terminal_network_record_retires_staged_request_from_idle_accounting() {+ let mut agent = TargetNetworkAgentState::default();+ let handle = SubresourceNetworkRequestHandle::new(17);+ let document_url = Url::parse("https://example.com/").expect("document URL should parse");+ let request_url =+ Url::parse("https://example.com/late-xhr").expect("request URL should parse");+ let started = ScriptNetworkOutputItem::SubresourceRequestStarted(Box::new(+ SubresourceRequestStarted::new(+ handle,+ None,+ document_url,+ request_url,+ "GET".to_owned(),+ Vec::new().into(),+ None,+ SubresourceResourceType::Xhr,+ SubresourceRequestInitiatorType::Script,+ None,+ ),+ ));+ agent.ingest_renderer_output_item(&started, "LOADER-1");+ assert!(!agent.renderer_subresources_are_idle());++ let terminal = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(+ subresource_record("https://example.com/late-xhr").with_request_handle(handle),+ ));+ agent.ingest_renderer_output_item(&terminal, "LOADER-1");++ assert!(+ agent.renderer_subresources_are_idle(),+ "a handled all-in-one record is terminal for the staged request with the same handle");}#[test]- fn prepared_backlog_drives_delivery_snapshots_without_recomputing_ranges() {- let mut agent = TargetNetworkAgentState::default();- agent.enable_primary_events();- let records = vec![- subresource_record("https://example.com/app.js"),- websocket_record("wss://example.com/socket", 7),- ];- let events = [websocket_event(7, 12)];- ingest_network_output(&mut agent, &records, &events);+ fn retiring_keepalive_does_not_require_a_document_bound_terminal() {+ fn started(+ handle: SubresourceNetworkRequestHandle,+ keepalive: bool,+ ) -> ScriptNetworkOutputItem {+ ScriptNetworkOutputItem::SubresourceRequestStarted(Box::new(+ SubresourceRequestStarted::new(+ handle,+ None,+ Url::parse("https://example.com/").expect("document URL should parse"),+ Url::parse("https://example.com/collect").expect("request URL should parse"),+ "POST".to_owned(),+ Vec::new().into(),+ None,+ SubresourceResourceType::Fetch,+ SubresourceRequestInitiatorType::Script,+ None,+ )+ .with_keepalive(keepalive),+ ))+ }- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- let mut backlog = agent.backlog_prepared_delivery(- None,- None,- Some(contextual_preferred_request_id("REQ-main")),- &mut request_id_allocator,+ let mut keepalive_agent = TargetNetworkAgentState::default();+ keepalive_agent.ingest_renderer_output_item(+ &started(SubresourceNetworkRequestHandle::new(18), true),+ "LOADER-1",);assert!(- backlog.has_output(),- "prepared backlog should retain one visible Network output for typed backlog items"+ !keepalive_agent.renderer_subresources_are_idle(),+ "a keepalive remains current-document activity until replacement"+ );+ let retiring_keepalive = keepalive_agent.rotate_document_for_replacement();+ assert!(+ retiring_keepalive+ .unterminated_document_bound_request_diagnostics()+ .is_empty(),+ "a detached keepalive may outlive its Document without a CDP terminal");- let snapshot = agent- .pending_network_backlog_delivery_snapshot_from_backlog(&mut backlog)- .expect("prepared combined backlog should build a delivery snapshot");- assert_eq!(snapshot.outputs().len(), 4);- assert_eq!(- subresource_request_ids(&snapshot),- vec!["REQ-main", "REQ-1"],- "WebSocket subresource metadata should bind a stable owner request id while consuming prepared output"+ let mut ordinary_agent = TargetNetworkAgentState::default();+ ordinary_agent.ingest_renderer_output_item(+ &started(SubresourceNetworkRequestHandle::new(19), false),+ "LOADER-2",);+ let retiring_ordinary = ordinary_agent.rotate_document_for_replacement();assert_eq!(- websocket_request_ids(&snapshot),- vec!["REQ-1", "REQ-1"],- "prepared WebSocket delivery should reuse the request id bound by the subresource snapshot"- );- assert!(- !backlog.has_output(),- "prepared backlog outputs should be one-shot delivery inputs"+ retiring_ordinary.unterminated_document_bound_request_diagnostics(),+ vec![(19, None)],+ "an ordinary request still requires a terminal before its renderer stream closes");}- #[test]- fn prepared_backlog_drives_combined_network_delivery_snapshot() {- let mut agent = TargetNetworkAgentState::default();- agent.enable_primary_events();- let script_record = subresource_record("https://example.com/app.js");- let websocket_record = websocket_record("wss://example.com/socket", 7);- let fetch_record = subresource_record("https://example.com/api");- let events = [websocket_event(7, 12)];- let items = vec![- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(script_record)),- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(websocket_record)),- ScriptNetworkOutputItem::WebSocketNetworkEvent(events[0].clone()),- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(fetch_record)),- ];- for item in &items {- agent.ingest_renderer_output_item(item, "LOADER-1");- }-+ fn pending_combined_snapshot(+ agent: &mut TargetNetworkAgentState,+ preferred_request_id: Option<&str>,+ ) -> super::PendingNetworkBacklogDeliverySnapshot {let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- let mut backlog = agent.backlog_prepared_delivery(- None,- None,- Some(contextual_preferred_request_id("REQ-main")),+ pending_combined_snapshot_with_allocator(+ agent,+ preferred_request_id,&mut request_id_allocator,- );- let snapshot = agent- .pending_network_backlog_delivery_snapshot_from_backlog(&mut backlog)- .expect("prepared network backlog should build one combined delivery snapshot");+ )+ }- assert_eq!(snapshot.outputs().len(), 5);- let output_order = snapshot+ fn pending_combined_snapshot_with_allocator(+ agent: &mut TargetNetworkAgentState,+ preferred_request_id: Option<&str>,+ request_id_allocator: &mut ConnectionNetworkRequestIdAllocator,+ ) -> super::PendingNetworkBacklogDeliverySnapshot {+ agent+ .pending_network_backlog_delivery_snapshot(+ None,+ None,+ preferred_request_id.map(NetworkBacklogPreferredRequestId::contextual_subresource),+ request_id_allocator,+ )+ .expect("combined network backlog snapshot should be visible")+ }++ fn contextual_preferred_request_id(request_id: &str) -> NetworkBacklogPreferredRequestId<'_> {+ NetworkBacklogPreferredRequestId::contextual_subresource(request_id)+ }++ fn subresource_request_ids(+ snapshot: &super::PendingNetworkBacklogDeliverySnapshot,+ ) -> Vec<String> {+ snapshot.outputs().into_iter()- .map(|item| {- if let Some(output) = item.as_subresource() {- return format!("sub:{}", output.request_id());- }- let output = item- .as_websocket()- .expect("combined backlog item should be subresource or WebSocket");- if let Some(output) = output.as_handshake() {- format!("ws-handshake:{}", output.request_id())- } else if let Some(output) = output.as_frame() {- format!("ws-frame:{}", output.request_id())- } else {- unreachable!("test WebSocket item should be handshake or frame")- }+ .filter_map(|item| {+ item.as_subresource()+ .map(|output| output.request_id().to_owned())})- .collect::<Vec<_>>();- assert_eq!(- output_order,- vec![- "sub:REQ-main",- "sub:REQ-1",- "ws-handshake:REQ-1",- "ws-frame:REQ-1",- "sub:REQ-2",- ],- "combined backlog snapshot should preserve producer delivery order across families"- );- let subresource_request_ids = snapshot+ .collect()+ }++ fn subresource_urls(snapshot: &super::PendingNetworkBacklogDeliverySnapshot) -> Vec<String> {+ snapshot.outputs().into_iter()- .filter_map(|item| item.as_subresource().map(|output| output.request_id()))- .collect::<Vec<_>>();- assert_eq!(- subresource_request_ids,- vec!["REQ-main", "REQ-1", "REQ-2"],- "WebSocket metadata should bind a request id before WebSocket events are materialized"- );- let websocket_request_ids = snapshot+ .filter_map(|item| {+ item.as_subresource()+ .map(|output| output.metadata().url().as_str().to_owned())+ })+ .collect()+ }++ fn websocket_request_ids(+ snapshot: &super::PendingNetworkBacklogDeliverySnapshot,+ ) -> Vec<String> {+ snapshot.outputs().into_iter().filter_map(|item| {@@ -2792,785 +2610,967 @@ mod tests {.as_handshake().map(|output| output.request_id()).or_else(|| output.as_frame().map(|output| output.request_id()))- .expect("test WebSocket item should carry a request id")+ .expect("test WebSocket output should carry a request id")+ .to_owned()})})- .collect::<Vec<_>>();- assert_eq!(- websocket_request_ids,- vec!["REQ-1", "REQ-1"],- "WebSocket delivery should reuse the request id bound by subresource metadata"- );- assert!(- !backlog.has_output(),- "combined delivery snapshots should consume every prepared backlog family"- );-- agent.mark_network_backlog_delivery_snapshot_emitted(&snapshot);- assert!(- !agent- .backlog_prepared_delivery(- None,- None,- None,- &mut ConnectionNetworkRequestIdAllocator::default()- )- .has_output(),- "combined mark-emitted should advance subresource and WebSocket cursors together"- );+ .collect()}- #[test]- fn prepared_backlog_preserves_preferred_request_id_after_bound_websocket_metadata() {- let mut agent = TargetNetworkAgentState::default();- agent.enable_primary_events();- agent.register_synthetic_websocket_request(- "FETCH-ws".to_owned(),- "REQ-synthetic-ws".to_owned(),- 7,- );- let websocket_record = websocket_record("wss://example.com/socket", 7);- let api_record = subresource_record("https://example.com/api");- let events = [websocket_event(7, 12)];- let items = vec![- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(websocket_record)),- ScriptNetworkOutputItem::WebSocketNetworkEvent(events[0].clone()),- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(api_record)),- ];- for item in &items {- agent.ingest_renderer_output_item(item, "LOADER-1");- }+ fn websocket_handshake_request_ids(+ snapshot: &super::PendingNetworkBacklogDeliverySnapshot,+ ) -> Vec<String> {+ snapshot+ .outputs()+ .into_iter()+ .filter_map(|item| {+ item.as_websocket()+ .and_then(|output| output.as_handshake())+ .map(|output| output.request_id().to_owned())+ })+ .collect()+ }- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- let mut backlog = agent.backlog_prepared_delivery(- None,- None,- Some(contextual_preferred_request_id("REQ-main")),- &mut request_id_allocator,- );- let snapshot = agent- .pending_network_backlog_delivery_snapshot_from_backlog(&mut backlog)- .expect("prepared network backlog should build one combined delivery snapshot");- let output_order = snapshot+ fn websocket_frame_outputs(+ snapshot: &super::PendingNetworkBacklogDeliverySnapshot,+ ) -> Vec<(String, usize)> {+ snapshot.outputs().into_iter()- .map(|item| {- if let Some(output) = item.as_subresource() {- return format!("sub:{}", output.request_id());- }- let output = item- .as_websocket()- .expect("combined backlog item should be subresource or WebSocket");- if let Some(output) = output.as_handshake() {- format!("ws-handshake:{}", output.request_id())- } else if let Some(output) = output.as_frame() {- format!("ws-frame:{}", output.request_id())- } else {- unreachable!("test WebSocket item should be handshake or frame")- }+ .filter_map(|item| {+ item.as_websocket()+ .and_then(|output| output.as_frame())+ .map(|output| (output.request_id().to_owned(), output.payload_length()))})- .collect::<Vec<_>>();+ .collect()+ }++ #[test]+ fn target_artifact_reset_clears_response_bodies_and_io_streams_together() {+ let mut agent = TargetNetworkAgentState::default();++ agent.record_captured_response_body("REQ-1".to_owned(), "response body".to_owned(), [None]);+ agent.insert_io_stream("STREAM-1".to_owned(), b"stream body".to_vec(), 0);+ assert!(agent.has_captured_response_body("REQ-1"));+ assert!(!agent.io_streams_empty());++ agent.reset_all_target_scoped_artifacts();+ assert!(!agent.has_captured_response_body("REQ-1"));+ assert!(agent.io_streams_empty());+ }+ #[test]+ fn output_queue_reset_clears_page_local_subresource_request_handle_bindings() {+ let mut agent = TargetNetworkAgentState::default();+ let handle = SubresourceNetworkRequestHandle::new(5);++ agent.record_subresource_request_id_for_handle_if_absent(handle, "REQ-old".to_owned());+ agent.record_subresource_request_id_for_handle_if_absent(handle, "REQ-stale".to_owned());assert_eq!(- output_order,- vec![- "sub:REQ-synthetic-ws",- "ws-handshake:REQ-synthetic-ws",- "ws-frame:REQ-synthetic-ws",- "sub:REQ-main",- ],- "resolving already-bound WebSocket metadata must not consume the preferred id needed by the next ordinary subresource"+ agent+ .artifacts+ .subresource_network_artifacts+ .request_id_for_handle(handle),+ Some("REQ-old"));++ agent.reset_output_queue();+ agent.record_subresource_request_id_for_handle_if_absent(handle, "REQ-new".to_owned());assert_eq!(- request_id_allocator.next_sequence_for_test(),- 0,- "synthetic WebSocket binding and preferred subresource id should not allocate fallback request ids"+ agent+ .artifacts+ .subresource_network_artifacts+ .request_id_for_handle(handle),+ Some("REQ-new"));}#[test]- fn merged_prepared_backlog_preserves_preferred_request_id_after_bound_websocket_metadata() {+ fn contextual_preferred_request_id_skips_earlier_unrelated_records() {let mut agent = TargetNetworkAgentState::default();+ let contextual_handle = SubresourceNetworkRequestHandle::new(7);agent.enable_primary_events();- agent.register_synthetic_websocket_request(- "FETCH-ws".to_owned(),- "REQ-synthetic-ws".to_owned(),- 7,+ agent.record_subresource_request_id_for_handle_if_absent(+ contextual_handle,+ "REQ-contextual".to_owned(),);- let websocket_record = websocket_record("wss://example.com/socket", 7);- let api_record = subresource_record("https://example.com/api");- let events = [websocket_event(7, 12)];- let items = vec![- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(websocket_record)),- ScriptNetworkOutputItem::WebSocketNetworkEvent(events[0].clone()),- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(api_record)),+ let records = [+ subresource_record("https://example.com/earlier.js"),+ subresource_record("https://example.com/contextual.js")+ .with_request_handle(contextual_handle),];- for item in &items {- agent.ingest_renderer_output_item(item, "LOADER-1");- }+ ingest_network_output(&mut agent, &records, &[]);- let subresource_activity = PendingSubresourceNetworkActivity::from_sessions(vec![- PendingSubresourceNetworkActivitySession::new(None, 0),- ])- .expect("test subresource activity should be visible");- let websocket_activity = PendingWebSocketNetworkActivity::from_sessions(vec![- PendingWebSocketNetworkActivitySession::new(None, 0, 0),- ])- .expect("test websocket activity should be visible");let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- let mut request_ids = NetworkBacklogRequestIdPlan::new(- &mut agent.artifacts.subresource_network_artifacts,- &mut agent.artifacts.websocket_network_artifacts,- Some(contextual_preferred_request_id("REQ-main")),+ let snapshot = pending_combined_snapshot_with_allocator(+ &mut agent,+ Some("REQ-contextual"),&mut request_id_allocator,);- let mut subresource_backlog = agent.output_queue.backlog_prepared_delivery_for_activity(- Some(subresource_activity),- None,- &mut request_ids,- );- let websocket_backlog = agent.output_queue.backlog_prepared_delivery_for_activity(- None,- Some(websocket_activity),- &mut request_ids,- );- subresource_backlog.extend(websocket_backlog);-- let snapshot = agent- .pending_network_backlog_delivery_snapshot_from_backlog(&mut subresource_backlog)- .expect("merged prepared backlog should build one combined delivery snapshot");- let output_order = snapshot- .outputs()- .into_iter()- .map(|item| {- if let Some(output) = item.as_subresource() {- return format!("sub:{}", output.request_id());- }- let output = item- .as_websocket()- .expect("combined backlog item should be subresource or WebSocket");- if let Some(output) = output.as_handshake() {- format!("ws-handshake:{}", output.request_id())- } else if let Some(output) = output.as_frame() {- format!("ws-frame:{}", output.request_id())- } else {- unreachable!("test WebSocket item should be handshake or frame")- }- })- .collect::<Vec<_>>();assert_eq!(- output_order,- vec![- "sub:REQ-synthetic-ws",- "ws-handshake:REQ-synthetic-ws",- "ws-frame:REQ-synthetic-ws",- "sub:REQ-main",- ],- "merged prepared tokens must preserve preferred-id availability across already-bound WebSocket metadata"+ subresource_request_ids(&snapshot),+ vec!["REQ-1", "REQ-contextual"],+ "a contextual id already bound to a request handle must not be consumed by an earlier unrelated backlog record");assert_eq!(request_id_allocator.next_sequence_for_test(),- 0,- "merged synthetic WebSocket binding and preferred subresource id should not allocate fallback request ids"+ 1,+ "only the unrelated record should allocate a new request id");}#[test]- fn websocket_handshake_backlog_survives_caught_up_subresource_cursor() {+ fn body_artifacts_own_io_stream_read_offsets_and_close() {let mut agent = TargetNetworkAgentState::default();- agent.enable_primary_events();- let records = vec![websocket_record("wss://example.com/socket", 7)];- ingest_network_output(&mut agent, &records, &[]);- let snapshot = pending_combined_snapshot(&mut agent, Some("REQ-bound"));- assert_eq!(subresource_request_ids(&snapshot), vec!["REQ-bound"]);- agent.mark_subresource_records_emitted(None, 0, 1);+ agent.insert_io_stream("STREAM-1".to_owned(), b"abcdef".to_vec(), 0);- assert!(- agent- .backlog_prepared_delivery(- None,- None,- None,- &mut ConnectionNetworkRequestIdAllocator::default()- )- .has_output(),- "subresource and websocket handshake cursors must remain independent"- );- let handshake_snapshot = pending_combined_snapshot(&mut agent, None);- assert_eq!(- websocket_handshake_request_ids(&handshake_snapshot),- vec!["REQ-bound"]- );- agent.mark_network_backlog_delivery_snapshot_emitted(&handshake_snapshot);- assert!(- !agent- .backlog_prepared_delivery(- None,- None,- None,- &mut ConnectionNetworkRequestIdAllocator::default()- )- .has_output()- );+ let first = agent+ .read_io_stream("STREAM-1", None, Some(2))+ .expect("stream should exist");+ assert_eq!(first.bytes, b"ab");+ assert!(!first.eof);++ let second = agent+ .read_io_stream("STREAM-1", Some(4), None)+ .expect("stream should exist");+ assert_eq!(second.bytes, b"ef");+ assert!(second.eof);++ assert!(agent.close_io_stream("STREAM-1"));+ assert!(agent.read_io_stream("STREAM-1", None, None).is_none());+ assert!(!agent.close_io_stream("STREAM-1"));}#[test]- fn websocket_frame_backlog_survives_caught_up_handshake_cursor() {+ fn body_artifacts_read_io_stream_from_captured_body_source() {+ let mut writer = CapturedBodyWriter::new(4);+ writer+ .append(b"captured body source")+ .expect("captured body writer should accept bytes");+ let body = writer+ .finish()+ .expect("captured body writer should finish source");let mut agent = TargetNetworkAgentState::default();- agent.enable_primary_events();- let records = vec![websocket_record("wss://example.com/socket", 7)];- let events = [websocket_event(7, 12)];- ingest_network_output(&mut agent, &records, &events);- let handshake_snapshot = pending_combined_snapshot(&mut agent, None);- assert_eq!(- websocket_handshake_request_ids(&handshake_snapshot),- vec!["REQ-1"]- );- agent.mark_websocket_activity_emitted(None, 0, 1, 0, 0);- assert!(- agent- .backlog_prepared_delivery(- None,- None,- None,- &mut ConnectionNetworkRequestIdAllocator::default()- )- .has_output(),- "handshake cursor must not consume subresource or frame backlog"- );- let frame_snapshot = pending_combined_snapshot(&mut agent, None);- assert!(- websocket_handshake_request_ids(&frame_snapshot).is_empty(),- "handshake cursor should hide handshake output from the next combined snapshot"- );- assert_eq!(- websocket_frame_outputs(&frame_snapshot),- vec![("REQ-1".to_owned(), 12)]- );- agent.mark_network_backlog_delivery_snapshot_emitted(&frame_snapshot);- assert!(- !agent- .backlog_prepared_delivery(- None,- None,- None,- &mut ConnectionNetworkRequestIdAllocator::default()- )- .has_output(),- "combined mark should consume the remaining subresource and frame outputs together"- );+ agent.insert_io_stream_body_source("STREAM-source".to_owned(), body, 0);++ let first = agent+ .read_io_stream("STREAM-source", None, Some(8))+ .expect("source-backed stream should exist");+ assert_eq!(first.bytes, b"captured");+ assert!(!first.eof);++ let second = agent+ .read_io_stream("STREAM-source", None, None)+ .expect("source-backed stream should remain readable");+ assert_eq!(second.bytes, b" body source");+ assert!(second.eof);}#[test]- fn websocket_subresource_delivery_reuses_existing_socket_request_id() {+ fn websocket_request_ids_are_owned_by_network_agent() {let mut agent = TargetNetworkAgentState::default();let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- agent.enable_primary_events();- let records = vec![websocket_record("wss://example.com/socket", 7)];- let events = [websocket_event(7, 12)];- ingest_network_output(&mut agent, &records, &events);- let handshake_snapshot =- pending_combined_snapshot_with_allocator(&mut agent, None, &mut request_id_allocator);++ agent.record_websocket_request_id_for_socket_if_absent(7, "REQ-bound".to_owned());assert_eq!(- websocket_handshake_request_ids(&handshake_snapshot),- vec!["REQ-1"]+ agent.websocket_request_id_for_socket_or_allocate_with(7, &mut request_id_allocator),+ "REQ-bound"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 0,+ "bound request id should not consume a new network id");+ let allocated =+ agent.websocket_request_id_for_socket_or_allocate_with(8, &mut request_id_allocator);+ assert_eq!(allocated, "REQ-1");assert_eq!(- subresource_request_ids(&handshake_snapshot),- vec!["REQ-1"],- "websocket subresource delivery must reuse the socket request id instead of inventing a second id"+ agent.websocket_request_id_for_socket_or_allocate_with(8, &mut request_id_allocator),+ "REQ-1");assert_eq!(request_id_allocator.next_sequence_for_test(),1,- "reusing the existing socket request id should not allocate a second request id"- );- assert_eq!(- websocket_frame_outputs(&handshake_snapshot),- vec![("REQ-1".to_owned(), 12)]+ "subsequent lookups should reuse the socket mapping");}#[test]- fn combined_frame_delivery_prefers_visible_subresource_binding() {+ fn synthetic_websocket_request_registration_updates_reverse_socket_mapping() {let mut agent = TargetNetworkAgentState::default();- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- agent.enable_primary_events();- let records = vec![websocket_record("wss://example.com/socket", 7)];- let events = [websocket_event(7, 12)];- ingest_network_output(&mut agent, &records, &events);-- agent.mark_websocket_activity_emitted(None, 0, 1, 0, 0);- let frame_snapshot = pending_combined_snapshot_with_allocator(- &mut agent,- Some("REQ-preferred"),- &mut request_id_allocator,- );- assert!(- websocket_handshake_request_ids(&frame_snapshot).is_empty(),- "record cursor should hide handshake output from the combined snapshot"+ agent.register_synthetic_websocket_request("FETCH-1".to_owned(), "REQ-first".to_owned(), 7);+ agent.register_synthetic_websocket_request(+ "FETCH-2".to_owned(),+ "REQ-second".to_owned(),+ 7,);+assert_eq!(- websocket_frame_outputs(&frame_snapshot),- vec![("REQ-preferred".to_owned(), 12)],- "combined delivery should let the still-visible subresource metadata bind the socket before the frame is materialized"+ agent.synthetic_websocket_socket_id_for_request("FETCH-1"),+ Some(7));assert_eq!(- subresource_request_ids(&frame_snapshot),- vec!["REQ-preferred"],- "visible subresource metadata owns the request id binding in the combined production path"+ agent.synthetic_websocket_socket_id_for_request("FETCH-2"),+ Some(7));assert_eq!(- request_id_allocator.next_sequence_for_test(),- 0,- "preferred subresource binding should not allocate a synthetic WebSocket request id"+ agent.websocket_request_id_for_socket_or_allocate(7),+ "REQ-second",+ "re-registering a synthetic socket must keep the canonical reverse map in sync");}#[test]- fn frame_only_delivery_does_not_consume_preferred_subresource_request_id() {+ fn attached_network_event_sessions_follow_enable_insertion_order() {let mut agent = TargetNetworkAgentState::default();- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();- agent.enable_primary_events();- let websocket_record = websocket_record("wss://example.com/socket", 7);- let api_record = subresource_record("https://example.com/api");- let events = [websocket_event(7, 12)];- let items = vec![- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(websocket_record)),- ScriptNetworkOutputItem::WebSocketNetworkEvent(events[0].clone()),- ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(api_record)),- ];- for item in &items {- agent.ingest_renderer_output_item(item, "LOADER-1");- }- agent.mark_subresource_records_emitted(None, 0, 1);- agent.mark_websocket_activity_emitted(None, 0, 1, 0, 0);+ agent.enable_attached_events("SID-z");+ agent.enable_attached_events("SID-a");+ agent.enable_attached_events("SID-z");- let frame_snapshot = pending_combined_snapshot_with_allocator(- &mut agent,- Some("REQ-preferred"),- &mut request_id_allocator,- );- assert!(- websocket_handshake_request_ids(&frame_snapshot).is_empty(),- "handshake cursor should hide the WebSocket handshake output"- );- assert_eq!(- websocket_frame_outputs(&frame_snapshot),- vec![("REQ-1".to_owned(), 12)],- "frame-only delivery should allocate a socket request id instead of consuming the preferred subresource id"- );- assert_eq!(- subresource_request_ids(&frame_snapshot),- vec!["REQ-preferred"],- "the later ordinary subresource should still consume the preferred request id"- );assert_eq!(- request_id_allocator.next_sequence_for_test(),- 1,- "only the frame-only WebSocket path should allocate a fallback request id"+ agent.event_session_ids(Some("SID-primary"), Some("SID-primary")),+ vec![Some("SID-z".to_owned()), Some("SID-a".to_owned())],+ "attached Network listeners should not be sorted by session id");- }- #[test]- fn websocket_delivery_snapshots_resolve_request_ids_in_network_agent() {- let mut agent = TargetNetworkAgentState::default();- let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();agent.enable_primary_events();- let records = vec![websocket_record("wss://example.com/socket", 7)];- let events = [websocket_event(7, 12)];- ingest_network_output(&mut agent, &records, &events);- assert_eq!(- subresource_request_ids(&pending_combined_snapshot_with_allocator(- &mut agent,- Some("REQ-bound"),- &mut request_id_allocator- )),- vec!["REQ-bound"],- "subresource delivery should bind the preferred request id"- );- let snapshot =- pending_combined_snapshot_with_allocator(&mut agent, None, &mut request_id_allocator);- assert_eq!(- websocket_handshake_request_ids(&snapshot),- vec!["REQ-bound"],- "handshake delivery should reuse the subresource request id"- );assert_eq!(- websocket_frame_outputs(&snapshot),- vec![("REQ-bound".to_owned(), 12)],- "frame delivery should reuse the same owner-resolved request id"+ agent.event_session_ids(Some("SID-primary"), Some("SID-primary")),+ vec![+ Some("SID-primary".to_owned()),+ Some("SID-z".to_owned()),+ Some("SID-a".to_owned()),+ ],+ "primary listener remains first, followed by attached enable order");++ assert!(agent.disable_attached_events("SID-z"));+ agent.enable_attached_events("SID-z");assert_eq!(- request_id_allocator.next_sequence_for_test(),- 0,- "delivery snapshots should not allocate when subresource binding exists"+ agent.event_session_ids(Some("SID-primary"), Some("SID-primary")),+ vec![+ Some("SID-primary".to_owned()),+ Some("SID-a".to_owned()),+ Some("SID-z".to_owned()),+ ],+ "disable then re-enable should append the attached session");}#[test]- fn websocket_delivery_snapshots_allocate_unbound_socket_request_id_once() {+ fn consecutive_renderer_live_tokens_own_disjoint_ingress_ranges() {let mut agent = TargetNetworkAgentState::default();let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();agent.enable_primary_events();- let records = vec![websocket_record("wss://example.com/socket", 7)];- let events = [websocket_event(7, 12)];- ingest_network_output(&mut agent, &records, &events);- assert_eq!(- websocket_handshake_request_ids(&pending_combined_snapshot_with_allocator(- &mut agent,- None,- &mut request_id_allocator- )),- vec!["REQ-1"],- "unbound handshake delivery should allocate a request id"+ let first = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(+ subresource_record("https://example.com/first.js"),+ ));+ let second = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(+ subresource_record("https://example.com/second.js"),+ ));+ let mut first_delivery = agent.ingest_renderer_output_item_and_prepare_live_delivery(+ &first,+ "LOADER-1",+ None,+ None,+ None,+ &mut request_id_allocator,);- assert_eq!(request_id_allocator.next_sequence_for_test(), 1);+ let mut second_delivery = agent.ingest_renderer_output_item_and_prepare_live_delivery(+ &second,+ "LOADER-1",+ None,+ None,+ None,+ &mut request_id_allocator,+ );+ assert_eq!(agent.output_queue.retained_delivery_output_count(), 2);+ let first_snapshot = agent+ .pending_network_backlog_delivery_snapshot_from_backlog(&mut first_delivery)+ .expect("the first renderer fact should own one live delivery range");assert_eq!(- websocket_frame_outputs(&pending_combined_snapshot_with_allocator(- &mut agent,- None,- &mut request_id_allocator- )),- vec![("REQ-1".to_owned(), 12)],- "frame delivery should reuse the request id allocated for the same socket"+ subresource_urls(&first_snapshot),+ vec!["https://example.com/first.js"]);+ agent.mark_network_backlog_delivery_snapshot_emitted(&first_snapshot);+ assert_eq!(agent.output_queue.retained_delivery_output_count(), 1);++ let second_snapshot = agent+ .pending_network_backlog_delivery_snapshot_from_backlog(&mut second_delivery)+ .expect("the second renderer fact should own one live delivery range");assert_eq!(- request_id_allocator.next_sequence_for_test(),- 1,- "frame delivery should not allocate another request id for the same socket"+ subresource_urls(&second_snapshot),+ vec!["https://example.com/second.js"],+ "a later ingress token must not rediscover an earlier unprojected fact from the session cursor"+ );+ agent.mark_network_backlog_delivery_snapshot_emitted(&second_snapshot);+ assert_eq!(agent.output_queue.retained_delivery_output_count(), 0);+ assert_eq!(+ agent+ .artifacts+ .emitted_subresource_record_count_for_session(None),+ 2);}-}-#[derive(Debug, Clone, Default, PartialEq, Eq)]-struct WebSocketNetworkArtifacts {- observation: WebSocketNetworkObservationArtifacts,- request_ids: WebSocketRequestIdState,-}+ #[test]+ fn renderer_outputs_without_network_listeners_are_not_retained() {+ let mut agent = TargetNetworkAgentState::default();+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ let item = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(subresource_record(+ "https://example.com/before-enable.js",+ )));-impl WebSocketNetworkArtifacts {- pub(crate) fn emitted_record_count_for_session(&self, session_id: Option<&str>) -> usize {- self.observation- .emitted_record_count_for_session(session_id)- }+ let delivery = agent.ingest_renderer_output_item_and_prepare_live_delivery(+ &item,+ "LOADER-1",+ None,+ None,+ None,+ &mut request_id_allocator,+ );- pub(crate) fn emitted_event_count_for_session(&self, session_id: Option<&str>) -> usize {- self.observation.emitted_event_count_for_session(session_id)+ assert!(!delivery.has_output());+ assert_eq!(agent.output_queue.subresource_record_count(), 1);+ assert_eq!(agent.output_queue.retained_delivery_output_count(), 0);}- fn minimum_emitted_record_count(&self) -> Option<usize> {- self.observation- .emitted_record_counts_by_session- .values()- .copied()- .min()- }+ #[test]+ fn websocket_observation_cursors_and_request_ids_are_separate_artifacts() {+ let mut artifacts = WebSocketNetworkArtifacts::default();+ artifacts.set_session_cursors(None, 3, 5);+ artifacts.set_request_id_for_socket_if_absent(7, "REQ-bound".to_owned());- fn minimum_emitted_event_count(&self) -> Option<usize> {- self.observation- .emitted_event_counts_by_session- .values()- .copied()- .min()- }+ artifacts.clear_request_ids();- pub(crate) fn mark_emitted(- &mut self,- session_id: Option<&str>,- record_start_index: usize,- record_count: usize,- event_start_index: usize,- event_count: usize,- ) {- self.observation.mark_emitted(- session_id,- record_start_index,- record_count,- event_start_index,- event_count,+ assert_eq!(+ artifacts.emitted_record_count_for_session(None),+ 3,+ "clearing WebSocket request ids must not reset record observation cursors");- }-- pub(crate) fn reset_cursors(&mut self) {- self.observation.reset_cursors();- }+ assert_eq!(+ artifacts.emitted_event_count_for_session(None),+ 5,+ "clearing WebSocket request ids must not reset frame observation cursors"+ );+ assert_eq!(artifacts.request_id_for_socket(7), None);- pub(crate) fn set_session_cursors(- &mut self,- session_id: Option<&str>,- record_count: usize,- event_count: usize,- ) {- self.observation- .set_session_cursors(session_id, record_count, event_count);+ artifacts.clear_all();+ assert_eq!(artifacts.emitted_record_count_for_session(None), 0);+ assert_eq!(artifacts.emitted_event_count_for_session(None), 0);}- pub(crate) fn remove_session_cursors(&mut self, session_id: Option<&str>) {- self.observation.remove_session_cursors(session_id);- }+ #[test]+ fn subresource_delivery_snapshot_binds_websocket_request_id() {+ let mut agent = TargetNetworkAgentState::default();+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ agent.enable_primary_events();+ let records = vec![websocket_record("wss://example.com/socket", 7)];+ ingest_network_output(&mut agent, &records, &[]);+ let snapshot = pending_combined_snapshot_with_allocator(+ &mut agent,+ Some("REQ-from-subresource"),+ &mut request_id_allocator,+ );- pub(crate) fn clear_request_ids(&mut self) {- self.request_ids.clear();+ assert_eq!(+ subresource_request_ids(&snapshot),+ vec!["REQ-from-subresource"]+ );+ assert_eq!(+ agent.websocket_request_id_for_socket_or_allocate(7),+ "REQ-from-subresource"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 0,+ "subresource output binding should not allocate a second request id"+ );}- pub(crate) fn clear_all(&mut self) {- self.reset_cursors();- self.clear_request_ids();- }+ #[test]+ fn prepared_backlog_drives_delivery_snapshots_without_recomputing_ranges() {+ let mut agent = TargetNetworkAgentState::default();+ agent.enable_primary_events();+ let records = vec![+ subresource_record("https://example.com/app.js"),+ websocket_record("wss://example.com/socket", 7),+ ];+ let events = [websocket_event(7, 12)];+ ingest_network_output(&mut agent, &records, &events);- pub(crate) fn register_synthetic_request(- &mut self,- request_id: String,- network_request_id: String,- socket_id: u64,- ) {- self.request_ids- .register_synthetic_request(request_id, network_request_id, socket_id);- }+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ let mut backlog = agent.backlog_prepared_delivery(+ None,+ None,+ Some(contextual_preferred_request_id("REQ-main")),+ &mut request_id_allocator,+ );+ assert!(+ backlog.has_output(),+ "prepared backlog should retain one visible Network output for typed backlog items"+ );- pub(crate) fn synthetic_socket_id_for_request(&self, request_id: &str) -> Option<u64> {- self.request_ids.synthetic_socket_id_for_request(request_id)+ let snapshot = agent+ .pending_network_backlog_delivery_snapshot_from_backlog(&mut backlog)+ .expect("prepared combined backlog should build a delivery snapshot");+ assert_eq!(snapshot.outputs().len(), 4);+ assert_eq!(+ subresource_request_ids(&snapshot),+ vec!["REQ-main", "REQ-1"],+ "WebSocket subresource metadata should bind a stable owner request id while consuming prepared output"+ );+ assert_eq!(+ websocket_request_ids(&snapshot),+ vec!["REQ-1", "REQ-1"],+ "prepared WebSocket delivery should reuse the request id bound by the subresource snapshot"+ );+ assert!(+ !backlog.has_output(),+ "prepared backlog outputs should be one-shot delivery inputs"+ );}- pub(crate) fn request_id_for_socket(&self, socket_id: u64) -> Option<&str> {- self.request_ids.request_id_for_socket(socket_id)- }+ #[test]+ fn prepared_backlog_drives_combined_network_delivery_snapshot() {+ let mut agent = TargetNetworkAgentState::default();+ agent.enable_primary_events();+ let script_record = subresource_record("https://example.com/app.js");+ let websocket_record = websocket_record("wss://example.com/socket", 7);+ let fetch_record = subresource_record("https://example.com/api");+ let events = [websocket_event(7, 12)];+ let items = vec![+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(script_record)),+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(websocket_record)),+ ScriptNetworkOutputItem::WebSocketNetworkEvent(events[0].clone()),+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(fetch_record)),+ ];+ for item in &items {+ agent.ingest_renderer_output_item(item, "LOADER-1");+ }- pub(crate) fn set_request_id_for_socket_if_absent(- &mut self,- socket_id: u64,- request_id: String,- ) {- self.request_ids- .set_request_id_for_socket_if_absent(socket_id, request_id);- }-}--#[derive(Debug, Clone, Default, PartialEq, Eq)]-struct WebSocketNetworkObservationArtifacts {- emitted_record_counts_by_session: HashMap<Option<String>, usize>,- emitted_event_counts_by_session: HashMap<Option<String>, usize>,-}--impl WebSocketNetworkObservationArtifacts {- pub(crate) fn emitted_record_count_for_session(&self, session_id: Option<&str>) -> usize {- self.emitted_record_counts_by_session- .get(&session_id.map(str::to_owned))- .copied()- .unwrap_or(0)- }+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ let mut backlog = agent.backlog_prepared_delivery(+ None,+ None,+ Some(contextual_preferred_request_id("REQ-main")),+ &mut request_id_allocator,+ );+ let snapshot = agent+ .pending_network_backlog_delivery_snapshot_from_backlog(&mut backlog)+ .expect("prepared network backlog should build one combined delivery snapshot");- pub(crate) fn emitted_event_count_for_session(&self, session_id: Option<&str>) -> usize {- self.emitted_event_counts_by_session- .get(&session_id.map(str::to_owned))- .copied()- .unwrap_or(0)- }+ assert_eq!(snapshot.outputs().len(), 5);+ let output_order = snapshot+ .outputs()+ .into_iter()+ .map(|item| {+ if let Some(output) = item.as_subresource() {+ return format!("sub:{}", output.request_id());+ }+ let output = item+ .as_websocket()+ .expect("combined backlog item should be subresource or WebSocket");+ if let Some(output) = output.as_handshake() {+ format!("ws-handshake:{}", output.request_id())+ } else if let Some(output) = output.as_frame() {+ format!("ws-frame:{}", output.request_id())+ } else {+ unreachable!("test WebSocket item should be handshake or frame")+ }+ })+ .collect::<Vec<_>>();+ assert_eq!(+ output_order,+ vec![+ "sub:REQ-main",+ "sub:REQ-1",+ "ws-handshake:REQ-1",+ "ws-frame:REQ-1",+ "sub:REQ-2",+ ],+ "combined backlog snapshot should preserve producer delivery order across families"+ );+ let subresource_request_ids = snapshot+ .outputs()+ .into_iter()+ .filter_map(|item| item.as_subresource().map(|output| output.request_id()))+ .collect::<Vec<_>>();+ assert_eq!(+ subresource_request_ids,+ vec!["REQ-main", "REQ-1", "REQ-2"],+ "WebSocket metadata should bind a request id before WebSocket events are materialized"+ );+ let websocket_request_ids = snapshot+ .outputs()+ .into_iter()+ .filter_map(|item| {+ item.as_websocket().map(|output| {+ output+ .as_handshake()+ .map(|output| output.request_id())+ .or_else(|| output.as_frame().map(|output| output.request_id()))+ .expect("test WebSocket item should carry a request id")+ })+ })+ .collect::<Vec<_>>();+ assert_eq!(+ websocket_request_ids,+ vec!["REQ-1", "REQ-1"],+ "WebSocket delivery should reuse the request id bound by subresource metadata"+ );+ assert!(+ !backlog.has_output(),+ "combined delivery snapshots should consume every prepared backlog family"+ );- pub(crate) fn mark_emitted(- &mut self,- session_id: Option<&str>,- record_start_index: usize,- record_count: usize,- event_start_index: usize,- event_count: usize,- ) {- let record_cursor = record_start_index- .checked_add(record_count)- .expect("websocket emitted record cursor exhausted");- let event_cursor = event_start_index- .checked_add(event_count)- .expect("websocket emitted event cursor exhausted");- self.set_session_cursors(session_id, record_cursor, event_cursor);+ agent.mark_network_backlog_delivery_snapshot_emitted(&snapshot);+ assert!(+ !agent+ .backlog_prepared_delivery(+ None,+ None,+ None,+ &mut ConnectionNetworkRequestIdAllocator::default()+ )+ .has_output(),+ "combined mark-emitted should advance subresource and WebSocket cursors together"+ );}- pub(crate) fn reset_cursors(&mut self) {- self.emitted_record_counts_by_session.clear();- self.emitted_event_counts_by_session.clear();- }+ #[test]+ fn prepared_backlog_preserves_preferred_request_id_after_bound_websocket_metadata() {+ let mut agent = TargetNetworkAgentState::default();+ agent.enable_primary_events();+ agent.register_synthetic_websocket_request(+ "FETCH-ws".to_owned(),+ "REQ-synthetic-ws".to_owned(),+ 7,+ );+ let websocket_record = websocket_record("wss://example.com/socket", 7);+ let api_record = subresource_record("https://example.com/api");+ let events = [websocket_event(7, 12)];+ let items = vec![+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(websocket_record)),+ ScriptNetworkOutputItem::WebSocketNetworkEvent(events[0].clone()),+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(api_record)),+ ];+ for item in &items {+ agent.ingest_renderer_output_item(item, "LOADER-1");+ }- pub(crate) fn set_session_cursors(- &mut self,- session_id: Option<&str>,- record_count: usize,- event_count: usize,- ) {- let session_id = session_id.map(str::to_owned);- self.emitted_record_counts_by_session- .insert(session_id.clone(), record_count);- self.emitted_event_counts_by_session- .insert(session_id, event_count);- }+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ let mut backlog = agent.backlog_prepared_delivery(+ None,+ None,+ Some(contextual_preferred_request_id("REQ-main")),+ &mut request_id_allocator,+ );+ let snapshot = agent+ .pending_network_backlog_delivery_snapshot_from_backlog(&mut backlog)+ .expect("prepared network backlog should build one combined delivery snapshot");+ let output_order = snapshot+ .outputs()+ .into_iter()+ .map(|item| {+ if let Some(output) = item.as_subresource() {+ return format!("sub:{}", output.request_id());+ }+ let output = item+ .as_websocket()+ .expect("combined backlog item should be subresource or WebSocket");+ if let Some(output) = output.as_handshake() {+ format!("ws-handshake:{}", output.request_id())+ } else if let Some(output) = output.as_frame() {+ format!("ws-frame:{}", output.request_id())+ } else {+ unreachable!("test WebSocket item should be handshake or frame")+ }+ })+ .collect::<Vec<_>>();- pub(crate) fn remove_session_cursors(&mut self, session_id: Option<&str>) {- let session_id = session_id.map(str::to_owned);- self.emitted_record_counts_by_session.remove(&session_id);- self.emitted_event_counts_by_session.remove(&session_id);+ assert_eq!(+ output_order,+ vec![+ "sub:REQ-synthetic-ws",+ "ws-handshake:REQ-synthetic-ws",+ "ws-frame:REQ-synthetic-ws",+ "sub:REQ-main",+ ],+ "resolving already-bound WebSocket metadata must not consume the preferred id needed by the next ordinary subresource"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 0,+ "synthetic WebSocket binding and preferred subresource id should not allocate fallback request ids"+ );}-}-#[derive(Debug, Clone, Default, PartialEq, Eq)]-struct WebSocketRequestIdState {- request_ids_by_socket_id: HashMap<u64, String>,- socket_ids_by_request_id: HashMap<String, u64>,-}+ #[test]+ fn merged_prepared_backlog_preserves_preferred_request_id_after_bound_websocket_metadata() {+ let mut agent = TargetNetworkAgentState::default();+ agent.enable_primary_events();+ agent.register_synthetic_websocket_request(+ "FETCH-ws".to_owned(),+ "REQ-synthetic-ws".to_owned(),+ 7,+ );+ let websocket_record = websocket_record("wss://example.com/socket", 7);+ let api_record = subresource_record("https://example.com/api");+ let events = [websocket_event(7, 12)];+ let items = vec![+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(websocket_record)),+ ScriptNetworkOutputItem::WebSocketNetworkEvent(events[0].clone()),+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(api_record)),+ ];+ for item in &items {+ agent.ingest_renderer_output_item(item, "LOADER-1");+ }-impl WebSocketRequestIdState {- pub(crate) fn clear(&mut self) {- self.request_ids_by_socket_id.clear();- self.socket_ids_by_request_id.clear();- }+ let subresource_activity = PendingSubresourceNetworkActivity::from_sessions(vec![+ PendingSubresourceNetworkActivitySession::new(None, 0),+ ])+ .expect("test subresource activity should be visible");+ let websocket_activity = PendingWebSocketNetworkActivity::from_sessions(vec![+ PendingWebSocketNetworkActivitySession::new(None, 0, 0),+ ])+ .expect("test websocket activity should be visible");+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ let mut request_ids = NetworkBacklogRequestIdPlan::new(+ &mut agent.artifacts.subresource_network_artifacts,+ &mut agent.artifacts.websocket_network_artifacts,+ Some(contextual_preferred_request_id("REQ-main")),+ &mut request_id_allocator,+ );+ let mut subresource_backlog = agent.output_queue.backlog_prepared_delivery_for_activity(+ Some(subresource_activity),+ None,+ &mut request_ids,+ );+ let websocket_backlog = agent.output_queue.backlog_prepared_delivery_for_activity(+ None,+ Some(websocket_activity),+ &mut request_ids,+ );+ subresource_backlog.extend(websocket_backlog);- pub(crate) fn register_synthetic_request(- &mut self,- request_id: String,- network_request_id: String,- socket_id: u64,- ) {- self.socket_ids_by_request_id.insert(request_id, socket_id);- self.socket_ids_by_request_id- .insert(network_request_id.clone(), socket_id);- self.request_ids_by_socket_id- .insert(socket_id, network_request_id);- }+ let snapshot = agent+ .pending_network_backlog_delivery_snapshot_from_backlog(&mut subresource_backlog)+ .expect("merged prepared backlog should build one combined delivery snapshot");+ let output_order = snapshot+ .outputs()+ .into_iter()+ .map(|item| {+ if let Some(output) = item.as_subresource() {+ return format!("sub:{}", output.request_id());+ }+ let output = item+ .as_websocket()+ .expect("combined backlog item should be subresource or WebSocket");+ if let Some(output) = output.as_handshake() {+ format!("ws-handshake:{}", output.request_id())+ } else if let Some(output) = output.as_frame() {+ format!("ws-frame:{}", output.request_id())+ } else {+ unreachable!("test WebSocket item should be handshake or frame")+ }+ })+ .collect::<Vec<_>>();- pub(crate) fn synthetic_socket_id_for_request(&self, request_id: &str) -> Option<u64> {- self.socket_ids_by_request_id.get(request_id).copied()+ assert_eq!(+ output_order,+ vec![+ "sub:REQ-synthetic-ws",+ "ws-handshake:REQ-synthetic-ws",+ "ws-frame:REQ-synthetic-ws",+ "sub:REQ-main",+ ],+ "merged prepared tokens must preserve preferred-id availability across already-bound WebSocket metadata"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 0,+ "merged synthetic WebSocket binding and preferred subresource id should not allocate fallback request ids"+ );}- pub(crate) fn request_id_for_socket(&self, socket_id: u64) -> Option<&str> {- self.request_ids_by_socket_id- .get(&socket_id)- .map(String::as_str)- }+ #[test]+ fn websocket_handshake_backlog_survives_caught_up_subresource_cursor() {+ let mut agent = TargetNetworkAgentState::default();+ agent.enable_primary_events();+ let records = vec![websocket_record("wss://example.com/socket", 7)];+ ingest_network_output(&mut agent, &records, &[]);+ let snapshot = pending_combined_snapshot(&mut agent, Some("REQ-bound"));+ assert_eq!(subresource_request_ids(&snapshot), vec!["REQ-bound"]);+ agent.mark_subresource_records_emitted(None, 0, 1);- pub(crate) fn set_request_id_for_socket_if_absent(- &mut self,- socket_id: u64,- request_id: String,- ) {- self.request_ids_by_socket_id- .entry(socket_id)- .or_insert(request_id);+ assert!(+ agent+ .backlog_prepared_delivery(+ None,+ None,+ None,+ &mut ConnectionNetworkRequestIdAllocator::default()+ )+ .has_output(),+ "subresource and websocket handshake cursors must remain independent"+ );+ let handshake_snapshot = pending_combined_snapshot(&mut agent, None);+ assert_eq!(+ websocket_handshake_request_ids(&handshake_snapshot),+ vec!["REQ-bound"]+ );+ agent.mark_network_backlog_delivery_snapshot_emitted(&handshake_snapshot);+ assert!(+ !agent+ .backlog_prepared_delivery(+ None,+ None,+ None,+ &mut ConnectionNetworkRequestIdAllocator::default()+ )+ .has_output()+ );}-}-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct IoStreamState {- body: CapturedBody,- pub offset: usize,-}--impl IoStreamState {- pub(crate) fn from_bytes(bytes: Vec<u8>, offset: usize) -> Self {- Self {- body: CapturedBody::from_bytes_spooled(bytes),- offset,- }- }+ #[test]+ fn websocket_frame_backlog_survives_caught_up_handshake_cursor() {+ let mut agent = TargetNetworkAgentState::default();+ agent.enable_primary_events();+ let records = vec![websocket_record("wss://example.com/socket", 7)];+ let events = [websocket_event(7, 12)];+ ingest_network_output(&mut agent, &records, &events);+ let handshake_snapshot = pending_combined_snapshot(&mut agent, None);+ assert_eq!(+ websocket_handshake_request_ids(&handshake_snapshot),+ vec!["REQ-1"]+ );+ agent.mark_websocket_activity_emitted(None, 0, 1, 0, 0);- pub(crate) fn from_body_source(body: CapturedBody, offset: usize) -> Self {- Self { body, offset }+ assert!(+ agent+ .backlog_prepared_delivery(+ None,+ None,+ None,+ &mut ConnectionNetworkRequestIdAllocator::default()+ )+ .has_output(),+ "handshake cursor must not consume subresource or frame backlog"+ );+ let frame_snapshot = pending_combined_snapshot(&mut agent, None);+ assert!(+ websocket_handshake_request_ids(&frame_snapshot).is_empty(),+ "handshake cursor should hide handshake output from the next combined snapshot"+ );+ assert_eq!(+ websocket_frame_outputs(&frame_snapshot),+ vec![("REQ-1".to_owned(), 12)]+ );+ agent.mark_network_backlog_delivery_snapshot_emitted(&frame_snapshot);+ assert!(+ !agent+ .backlog_prepared_delivery(+ None,+ None,+ None,+ &mut ConnectionNetworkRequestIdAllocator::default()+ )+ .has_output(),+ "combined mark should consume the remaining subresource and frame outputs together"+ );}- pub(crate) fn len(&self) -> usize {- self.body.len()- }+ #[test]+ fn websocket_subresource_delivery_reuses_existing_socket_request_id() {+ let mut agent = TargetNetworkAgentState::default();+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ agent.enable_primary_events();+ let records = vec![websocket_record("wss://example.com/socket", 7)];+ let events = [websocket_event(7, 12)];+ ingest_network_output(&mut agent, &records, &events);+ let handshake_snapshot =+ pending_combined_snapshot_with_allocator(&mut agent, None, &mut request_id_allocator);+ assert_eq!(+ websocket_handshake_request_ids(&handshake_snapshot),+ vec!["REQ-1"]+ );- pub(crate) fn read_range(&self, offset: usize, len: usize) -> Vec<u8> {- self.body.read_range(offset, len).unwrap_or_default()+ assert_eq!(+ subresource_request_ids(&handshake_snapshot),+ vec!["REQ-1"],+ "websocket subresource delivery must reuse the socket request id instead of inventing a second id"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 1,+ "reusing the existing socket request id should not allocate a second request id"+ );+ assert_eq!(+ websocket_frame_outputs(&handshake_snapshot),+ vec![("REQ-1".to_owned(), 12)]+ );}-}--#[derive(Debug, Clone, PartialEq, Eq)]-pub(crate) struct TargetIoStreamRead {- pub(crate) bytes: Vec<u8>,- pub(crate) eof: bool,-}--#[derive(Debug, Clone, Default, PartialEq, Eq)]-struct TargetIoStreamArtifacts {- next_stream_id: u64,- streams: HashMap<String, IoStreamState>,-}-impl TargetIoStreamArtifacts {- pub(crate) fn allocate_handle(&mut self) -> String {- self.next_stream_id = self- .next_stream_id- .checked_add(1)- .expect("IO stream id sequence exhausted");- format!("STREAM-{}", self.next_stream_id)- }+ #[test]+ fn combined_frame_delivery_prefers_visible_subresource_binding() {+ let mut agent = TargetNetworkAgentState::default();+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ agent.enable_primary_events();+ let records = vec![websocket_record("wss://example.com/socket", 7)];+ let events = [websocket_event(7, 12)];+ ingest_network_output(&mut agent, &records, &events);- pub(crate) fn insert_stream(&mut self, handle: String, bytes: Vec<u8>, offset: usize) {- self.streams- .insert(handle, IoStreamState::from_bytes(bytes, offset));- }+ agent.mark_websocket_activity_emitted(None, 0, 1, 0, 0);- pub(crate) fn insert_stream_body_source(- &mut self,- handle: String,- body: CapturedBody,- offset: usize,- ) {- self.streams- .insert(handle, IoStreamState::from_body_source(body, offset));+ let frame_snapshot = pending_combined_snapshot_with_allocator(+ &mut agent,+ Some("REQ-preferred"),+ &mut request_id_allocator,+ );+ assert!(+ websocket_handshake_request_ids(&frame_snapshot).is_empty(),+ "record cursor should hide handshake output from the combined snapshot"+ );+ assert_eq!(+ websocket_frame_outputs(&frame_snapshot),+ vec![("REQ-preferred".to_owned(), 12)],+ "combined delivery should let the still-visible subresource metadata bind the socket before the frame is materialized"+ );+ assert_eq!(+ subresource_request_ids(&frame_snapshot),+ vec!["REQ-preferred"],+ "visible subresource metadata owns the request id binding in the combined production path"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 0,+ "preferred subresource binding should not allocate a synthetic WebSocket request id"+ );}- pub(crate) fn remove(&mut self, handle: &str) -> Option<IoStreamState> {- self.streams.remove(handle)- }+ #[test]+ fn frame_only_delivery_does_not_consume_preferred_subresource_request_id() {+ let mut agent = TargetNetworkAgentState::default();+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ agent.enable_primary_events();+ let websocket_record = websocket_record("wss://example.com/socket", 7);+ let api_record = subresource_record("https://example.com/api");+ let events = [websocket_event(7, 12)];+ let items = vec![+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(websocket_record)),+ ScriptNetworkOutputItem::WebSocketNetworkEvent(events[0].clone()),+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(api_record)),+ ];+ for item in &items {+ agent.ingest_renderer_output_item(item, "LOADER-1");+ }- pub(crate) fn read(- &mut self,- handle: &str,- offset: Option<usize>,- size: Option<usize>,- ) -> Option<TargetIoStreamRead> {- let stream = self.streams.get_mut(handle)?;- let stream_len = stream.len();- let start = offset.unwrap_or(stream.offset).min(stream_len);- stream.offset = start;- let requested_len = size.unwrap_or_else(|| stream_len.saturating_sub(start));- let bytes = stream.read_range(start, requested_len);- let end = start.saturating_add(bytes.len()).min(stream_len);- stream.offset = end;- Some(TargetIoStreamRead {- bytes,- eof: end >= stream_len,- })- }+ agent.mark_subresource_records_emitted(None, 0, 1);+ agent.mark_websocket_activity_emitted(None, 0, 1, 0, 0);- pub(crate) fn clear_streams(&mut self) {- self.streams.clear();+ let frame_snapshot = pending_combined_snapshot_with_allocator(+ &mut agent,+ Some("REQ-preferred"),+ &mut request_id_allocator,+ );+ assert!(+ websocket_handshake_request_ids(&frame_snapshot).is_empty(),+ "handshake cursor should hide the WebSocket handshake output"+ );+ assert_eq!(+ websocket_frame_outputs(&frame_snapshot),+ vec![("REQ-1".to_owned(), 12)],+ "frame-only delivery should allocate a socket request id instead of consuming the preferred subresource id"+ );+ assert_eq!(+ subresource_request_ids(&frame_snapshot),+ vec!["REQ-preferred"],+ "the later ordinary subresource should still consume the preferred request id"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 1,+ "only the frame-only WebSocket path should allocate a fallback request id"+ );}- pub(crate) fn reset_all(&mut self) {- self.next_stream_id = 0;- self.streams.clear();+ #[test]+ fn websocket_delivery_snapshots_resolve_request_ids_in_network_agent() {+ let mut agent = TargetNetworkAgentState::default();+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ agent.enable_primary_events();+ let records = vec![websocket_record("wss://example.com/socket", 7)];+ let events = [websocket_event(7, 12)];+ ingest_network_output(&mut agent, &records, &events);+ assert_eq!(+ subresource_request_ids(&pending_combined_snapshot_with_allocator(+ &mut agent,+ Some("REQ-bound"),+ &mut request_id_allocator+ )),+ vec!["REQ-bound"],+ "subresource delivery should bind the preferred request id"+ );+ let snapshot =+ pending_combined_snapshot_with_allocator(&mut agent, None, &mut request_id_allocator);+ assert_eq!(+ websocket_handshake_request_ids(&snapshot),+ vec!["REQ-bound"],+ "handshake delivery should reuse the subresource request id"+ );+ assert_eq!(+ websocket_frame_outputs(&snapshot),+ vec![("REQ-bound".to_owned(), 12)],+ "frame delivery should reuse the same owner-resolved request id"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 0,+ "delivery snapshots should not allocate when subresource binding exists"+ );}- #[cfg(test)]- pub(crate) fn is_empty(&self) -> bool {- self.streams.is_empty()- }+ #[test]+ fn websocket_delivery_snapshots_allocate_unbound_socket_request_id_once() {+ let mut agent = TargetNetworkAgentState::default();+ let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();+ agent.enable_primary_events();+ let records = vec![websocket_record("wss://example.com/socket", 7)];+ let events = [websocket_event(7, 12)];+ ingest_network_output(&mut agent, &records, &events);- #[cfg(test)]- pub(crate) fn set_next_stream_id_for_test(&mut self, next_stream_id: u64) {- self.next_stream_id = next_stream_id;- }+ assert_eq!(+ websocket_handshake_request_ids(&pending_combined_snapshot_with_allocator(+ &mut agent,+ None,+ &mut request_id_allocator+ )),+ vec!["REQ-1"],+ "unbound handshake delivery should allocate a request id"+ );+ assert_eq!(request_id_allocator.next_sequence_for_test(), 1);- #[cfg(test)]- pub(crate) fn next_stream_id_for_test(&self) -> u64 {- self.next_stream_id+ assert_eq!(+ websocket_frame_outputs(&pending_combined_snapshot_with_allocator(+ &mut agent,+ None,+ &mut request_id_allocator+ )),+ vec![("REQ-1".to_owned(), 12)],+ "frame delivery should reuse the request id allocated for the same socket"+ );+ assert_eq!(+ request_id_allocator.next_sequence_for_test(),+ 1,+ "frame delivery should not allocate another request id for the same socket"+ );}}diff --git a/moli-protocol/src/domains/target/worker_target/dedicated_worker.rs b/moli-protocol/src/domains/target/worker_target/dedicated_worker.rsindex ef0e97b35..bb6cb89bc 100644--- a/moli-protocol/src/domains/target/worker_target/dedicated_worker.rs+++ b/moli-protocol/src/domains/target/worker_target/dedicated_worker.rs@@ -566,6 +566,8 @@ pub(in crate::domains) async fn retire_dedicated_worker_targets_for_replaced_pagevents}+// Non-retirement output is handed back unchanged for the caller to route.+#[allow(clippy::result_large_err)]pub(super) async fn commit_dedicated_worker_retirement_output_async(conn: &mut CdpConnection,output: WorkerTargetLifecycleOutput,diff --git a/moli-renderer-v8/src/host/scripts.rs b/moli-renderer-v8/src/host/scripts.rsindex bcc612d4b..e92c19c8e 100644--- a/moli-renderer-v8/src/host/scripts.rs+++ b/moli-renderer-v8/src/host/scripts.rs@@ -1629,17 +1629,13 @@ impl HostScriptScheduler {#[cfg(test)]pub(crate) fn drain_dynamic_scripts(&mut self) -> DynamicScriptBatch {DynamicScriptBatch {- in_order: self.pending_dynamic_in_order_scripts.drain(..).collect(),- importmap_in_order: self- .pending_dynamic_importmap_in_order_scripts- .drain(..)- .collect(),- module_in_order: self- .pending_dynamic_module_in_order_scripts- .drain(..)- .collect(),- async_scripts: self.pending_dynamic_async_scripts.drain(..).collect(),- failed_scripts: self.pending_failed_dynamic_scripts.drain(..).collect(),+ in_order: std::mem::take(&mut self.pending_dynamic_in_order_scripts),+ importmap_in_order: std::mem::take(+ &mut self.pending_dynamic_importmap_in_order_scripts,+ ),+ module_in_order: std::mem::take(&mut self.pending_dynamic_module_in_order_scripts),+ async_scripts: std::mem::take(&mut self.pending_dynamic_async_scripts),+ failed_scripts: std::mem::take(&mut self.pending_failed_dynamic_scripts),}}diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rsindex 1c3d379e8..eefee8a7a 100644--- a/moli-renderer-v8/src/lib.rs+++ b/moli-renderer-v8/src/lib.rs@@ -4,6 +4,8 @@//! owner/page handles, the native bridge, script and module execution, Web API//! bootstrap, and the renderer-side `ResourceRequestClient` wrapper used by the facade crate.+#![recursion_limit = "256"]+#[path = "planning.rs"]mod script_planning;mod stylesheet_blocking;diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects.rsindex d025bc68d..084896c3b 100644--- a/moli-renderer-v8/src/native_bridge/document/detached_objects.rs+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects.rs@@ -14,27 +14,69 @@ mod state_tree;mod text_content;pub(in crate::native_bridge::document) use self::attributes::*;-pub(in crate::native_bridge::document) use self::builders::*;pub(crate) use self::builders::{build_detached_cdata_section_object, build_detached_document_object_from_dom_host,build_detached_document_object_from_dom_host_with_content_type, is_valid_pi_target,preserve_detached_element_bridge_for_custom_prototype,};+pub(in crate::native_bridge::document) use self::builders::{+ build_detached_comment_object, build_detached_document_fragment_object,+ build_detached_document_object, build_detached_document_type_object,+ build_detached_element_object, build_detached_html_document_object,+ build_detached_processing_instruction_object, build_detached_text_object,+ copy_detached_element_bridge_members, generic_html_element_proxy,+ html_element_constructor_name, mirror_detached_private_slots, new_detached_state_object,+ new_map_object, remove_detached_element_instance_selector_matching_methods,+ select_html_element_proxy,+};pub(in crate::native_bridge::document) use self::clone::*;pub(in crate::native_bridge::document) use self::collections::*;pub(in crate::native_bridge::document) use self::document_state::*;pub(crate) use self::method_forwarders::ensure_detached_document_implementation;-pub(in crate::native_bridge) use self::method_forwarders::*;+pub(in crate::native_bridge) use self::method_forwarders::{+ detached_adopt_node_method_callback, detached_after_method_callback,+ detached_append_child_method_callback, detached_append_method_callback,+ detached_before_method_callback, detached_blur_method_callback, detached_click_method_callback,+ detached_clone_node_method_callback, detached_contains_method_callback,+ detached_create_cdata_section_method_callback, detached_create_comment_method_callback,+ detached_create_document_fragment_method_callback,+ detached_create_processing_instruction_method_callback,+ detached_create_text_node_method_callback, detached_focus_method_callback,+ detached_get_attribute_method_callback, detached_get_attribute_names_method_callback,+ detached_get_attribute_ns_method_callback, detached_get_element_by_id_method_callback,+ detached_get_elements_by_class_name_method_callback,+ detached_get_elements_by_name_method_callback,+ detached_get_elements_by_tag_name_method_callback,+ detached_get_elements_by_tag_name_ns_method_callback, detached_has_attribute_method_callback,+ detached_has_attribute_ns_method_callback, detached_has_child_nodes_method_callback,+ detached_import_node_method_callback, detached_insert_before_method_callback,+ detached_is_equal_node_method_callback, detached_is_same_node_method_callback,+ detached_matches_method_callback, detached_prepend_method_callback,+ detached_query_selector_all_method_callback, detached_query_selector_method_callback,+ detached_remove_attribute_method_callback, detached_remove_attribute_ns_method_callback,+ detached_remove_child_method_callback, detached_replace_child_method_callback,+ detached_replace_children_method_callback, detached_replace_with_method_callback,+ detached_set_attribute_method_callback, detached_set_attribute_ns_method_callback,+};+pub(in crate::native_bridge::document) use self::method_forwarders::{+ detached_compare_document_position_method_callback,+ detached_create_cdata_section_html_method_callback,+ detached_create_html_element_method_callback, detached_create_html_element_ns_method_callback,+ detached_create_node_iterator_method_callback, detached_create_xml_element_method_callback,+ detached_create_xml_element_ns_method_callback, detached_document_implementation_getter,+ detached_get_root_node_method_callback, detached_lookup_namespace_uri_method_callback,+ detached_move_before_method_callback, detached_normalize_method_callback,+ detached_remove_method_callback,+};pub(in crate::native_bridge::document) use self::mutation::*;pub(in crate::native_bridge::document) use self::object_access::*;pub(in crate::native_bridge::document) use self::prototypes::*;-pub(in crate::native_bridge::document) use self::shadow_dom::*;+pub(in crate::native_bridge::document) use self::shadow_dom::build_detached_shadow_root_object_for_native_handle;pub(in crate::native_bridge) use self::shadow_dom::{detached_attach_shadow_method_callback, detached_shadow_root_active_element_value,detached_shadow_root_selection_value,};pub(crate) use self::state_tree::detached_is_connected as detached_node_is_connected;-pub(in crate::native_bridge::document) use self::state_tree::*;pub(crate) use self::state_tree::{DetachedNativeAttributeSnapshot, read_detached_native_attribute,read_detached_native_attribute_names, read_detached_native_attribute_snapshot,@@ -50,6 +92,28 @@ pub(in crate::native_bridge) use self::state_tree::{detached_processing_instruction_target, detached_record_tree_mutation,detached_set_owner_document,};+pub(in crate::native_bridge::document) use self::state_tree::{+ define_detached_state, detached_child_node_objects, detached_contains,+ detached_detach_for_insert, detached_detach_for_insert_appending_to_current_reaction_queue,+ detached_detach_from_parent, detached_detach_from_parent_appending_to_current_reaction_queue,+ detached_element_children_objects, detached_element_sibling_object, detached_has_native_handle,+ detached_is_node, detached_live_delegate_object, detached_native_child_node_objects,+ detached_native_element_runtime_and_handle, detached_native_handle,+ detached_native_mutation_child_node_objects, detached_native_parent_is, detached_node_name,+ detached_node_type, detached_owner_document_object, detached_parent_element_object,+ detached_replace_children_array,+ detached_set_owner_document_appending_to_current_reaction_queue, detached_set_parent,+ detached_sibling_object, detached_state_kind, detached_state_object, detached_state_string,+ detached_tree_query_version, detached_tree_root_object,+ detached_update_existing_children_projection, read_detached_native_text_content,+ sync_detached_native_insert, sync_detached_native_insert_appending_to_current_reaction_queue,+ sync_detached_native_set_attribute, sync_detached_native_set_attribute_ns,+ with_detached_tree_reaction_scope, write_detached_native_text_content,+ write_detached_native_text_content_appending_to_current_reaction_queue,+};+pub(in crate::native_bridge::document) use self::state_tree::{+ detached_is_connected, read_detached_native_attribute_ns, read_detached_native_has_attribute_ns,+};pub(crate) use self::state_tree::{detached_native_handle_for_runtime, detached_native_object_for_handle,detached_record_native_tree_mutations, paired_detached_native_object_for_handle,diff --git a/moli-renderer-v8/src/page_task_queue/owner_sources.rs b/moli-renderer-v8/src/page_task_queue/owner_sources.rsindex 3eed42940..1e5938ccb 100644--- a/moli-renderer-v8/src/page_task_queue/owner_sources.rs+++ b/moli-renderer-v8/src/page_task_queue/owner_sources.rs@@ -2396,6 +2396,111 @@ impl crate::page_resource_completion::RendererPageResourceCompletionTestSource}}+#[cfg(test)]+#[derive(Clone, Debug)]+pub(crate) struct RendererPageModulepreloadStartTestSource {+ sources: Rc<RefCell<RendererPageOwnedTaskSources>>,+}++#[cfg(test)]+impl RendererPageModulepreloadStartTestSource {+ pub(crate) fn enqueue_local_for_test(+ &self,+ root_document: RendererDocumentToken,+ task: crate::frame_owner_model::FrameDocumentModulepreloadFetchTask,+ ) {+ self.sources+ .borrow_mut()+ .modulepreload_start+ .enqueue_local_for_test(root_document, task);+ }++ pub(crate) fn has_ready_task(&self) -> bool {+ self.sources+ .borrow_mut()+ .modulepreload_start+ .has_ready_task()+ }++ pub(crate) fn pop_front(+ &self,+ ) -> Option<(+ RendererPageTaskReadyMetadata,+ RendererPageModulepreloadStartTask,+ )> {+ self.sources.borrow_mut().modulepreload_start.pop_front()+ }++ pub(crate) fn next_ready_metadata(&self) -> Option<RendererPageTaskReadyMetadata> {+ self.sources+ .borrow_mut()+ .modulepreload_start+ .next_ready_metadata()+ }++ pub(crate) fn next_ready_owner(&self) -> Option<super::RendererPageModulepreloadStartOwner> {+ self.sources+ .borrow_mut()+ .modulepreload_start+ .next_ready_owner()+ }+}++#[cfg(test)]+#[derive(Clone, Debug)]+pub(crate) struct RendererPageDynamicImportOwnerActionTestSource {+ sources: Rc<RefCell<RendererPageOwnedTaskSources>>,+}++#[cfg(test)]+impl RendererPageDynamicImportOwnerActionTestSource {+ pub(crate) fn enqueue_local_for_test(+ &self,+ root_document: RendererDocumentToken,+ action: crate::frame_owner_model::FrameDocumentDynamicImportTerminalPreparedAction,+ ) {+ self.sources+ .borrow_mut()+ .dynamic_import_owner_action+ .enqueue_local_for_test(root_document, action);+ }++ pub(crate) fn has_ready_task(&self) -> bool {+ self.sources+ .borrow_mut()+ .dynamic_import_owner_action+ .has_ready_task()+ }++ pub(crate) fn pop_front(+ &self,+ ) -> Option<(+ RendererPageTaskReadyMetadata,+ RendererPageDynamicImportOwnerActionTask,+ )> {+ self.sources+ .borrow_mut()+ .dynamic_import_owner_action+ .pop_front()+ }++ pub(crate) fn next_ready_metadata(&self) -> Option<RendererPageTaskReadyMetadata> {+ self.sources+ .borrow_mut()+ .dynamic_import_owner_action+ .next_ready_metadata()+ }++ pub(crate) fn next_ready_owner(+ &self,+ ) -> Option<super::RendererPageDynamicImportOwnerActionOwner> {+ self.sources+ .borrow_mut()+ .dynamic_import_owner_action+ .next_ready_owner()+ }+}+#[cfg(test)]mod tests {use super::*;@@ -2733,108 +2838,3 @@ mod tests {);}}--#[cfg(test)]-#[derive(Clone, Debug)]-pub(crate) struct RendererPageModulepreloadStartTestSource {- sources: Rc<RefCell<RendererPageOwnedTaskSources>>,-}--#[cfg(test)]-impl RendererPageModulepreloadStartTestSource {- pub(crate) fn enqueue_local_for_test(- &self,- root_document: RendererDocumentToken,- task: crate::frame_owner_model::FrameDocumentModulepreloadFetchTask,- ) {- self.sources- .borrow_mut()- .modulepreload_start- .enqueue_local_for_test(root_document, task);- }-- pub(crate) fn has_ready_task(&self) -> bool {- self.sources- .borrow_mut()- .modulepreload_start- .has_ready_task()- }-- pub(crate) fn pop_front(- &self,- ) -> Option<(- RendererPageTaskReadyMetadata,- RendererPageModulepreloadStartTask,- )> {- self.sources.borrow_mut().modulepreload_start.pop_front()- }-- pub(crate) fn next_ready_metadata(&self) -> Option<RendererPageTaskReadyMetadata> {- self.sources- .borrow_mut()- .modulepreload_start- .next_ready_metadata()- }-- pub(crate) fn next_ready_owner(&self) -> Option<super::RendererPageModulepreloadStartOwner> {- self.sources- .borrow_mut()- .modulepreload_start- .next_ready_owner()- }-}--#[cfg(test)]-#[derive(Clone, Debug)]-pub(crate) struct RendererPageDynamicImportOwnerActionTestSource {- sources: Rc<RefCell<RendererPageOwnedTaskSources>>,-}--#[cfg(test)]-impl RendererPageDynamicImportOwnerActionTestSource {- pub(crate) fn enqueue_local_for_test(- &self,- root_document: RendererDocumentToken,- action: crate::frame_owner_model::FrameDocumentDynamicImportTerminalPreparedAction,- ) {- self.sources- .borrow_mut()- .dynamic_import_owner_action- .enqueue_local_for_test(root_document, action);- }-- pub(crate) fn has_ready_task(&self) -> bool {- self.sources- .borrow_mut()- .dynamic_import_owner_action- .has_ready_task()- }-- pub(crate) fn pop_front(- &self,- ) -> Option<(- RendererPageTaskReadyMetadata,- RendererPageDynamicImportOwnerActionTask,- )> {- self.sources- .borrow_mut()- .dynamic_import_owner_action- .pop_front()- }-- pub(crate) fn next_ready_metadata(&self) -> Option<RendererPageTaskReadyMetadata> {- self.sources- .borrow_mut()- .dynamic_import_owner_action- .next_ready_metadata()- }-- pub(crate) fn next_ready_owner(- &self,- ) -> Option<super::RendererPageDynamicImportOwnerActionOwner> {- self.sources- .borrow_mut()- .dynamic_import_owner_action- .next_ready_owner()- }-}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted.rsindex f0da32b13..e73d0f889 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted.rs@@ -1,4 +1,3 @@-use super::super::*;use super::*;mod animations;diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted.rsindex add3a0b6b..5637925bd 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted.rs@@ -1,4 +1,3 @@-use super::super::*;use super::*;mod child_document_lifecycle;diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom/extracted.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom/extracted.rsindex cc8b3b3a4..ee75c2504 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom/extracted.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom/extracted.rs@@ -1,4 +1,3 @@-use super::super::*;use super::*;mod css_text_and_detached;diff --git a/moli-renderer-v8/src/service_worker_runtime/clients.rs b/moli-renderer-v8/src/service_worker_runtime/clients.rsindex f47b102fd..757cbcfb2 100644--- a/moli-renderer-v8/src/service_worker_runtime/clients.rs+++ b/moli-renderer-v8/src/service_worker_runtime/clients.rs@@ -93,31 +93,6 @@ pub(crate) fn service_worker_current_url_for_creation_url(creation_url: &Url) ->current_url}-#[cfg(test)]-mod exposed_client_identity_tests {- use super::*;-- #[test]- fn replacement_ids_are_fresh_and_not_derived_from_internal_client_id() {- let client_id = ServiceWorkerClientId::from_u64_for_test(7);- let first = allocate_service_worker_exposed_client_id();- let second = allocate_service_worker_exposed_client_id();-- assert_ne!(first, second);- assert_ne!(first, service_worker_exposed_client_id(client_id));- }-- #[test]- fn replacement_id_allocator_rejects_exhaustion_without_wrapping() {- let counter = AtomicU64::new(u64::MAX);- let exhausted =- std::panic::catch_unwind(|| allocate_service_worker_exposed_client_id_from(&counter));-- assert!(exhausted.is_err());- assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);- }-}-#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub(crate) enum ServiceWorkerClientType {Window,@@ -204,3 +179,28 @@ pub(crate) struct ServiceWorkerClientQueryResult {pub(crate) request_id: u64,pub(crate) clients: Vec<ServiceWorkerClientSnapshot>,}++#[cfg(test)]+mod exposed_client_identity_tests {+ use super::*;++ #[test]+ fn replacement_ids_are_fresh_and_not_derived_from_internal_client_id() {+ let client_id = ServiceWorkerClientId::from_u64_for_test(7);+ let first = allocate_service_worker_exposed_client_id();+ let second = allocate_service_worker_exposed_client_id();++ assert_ne!(first, second);+ assert_ne!(first, service_worker_exposed_client_id(client_id));+ }++ #[test]+ fn replacement_id_allocator_rejects_exhaustion_without_wrapping() {+ let counter = AtomicU64::new(u64::MAX);+ let exhausted =+ std::panic::catch_unwind(|| allocate_service_worker_exposed_client_id_from(&counter));++ assert!(exhausted.is_err());+ assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);+ }+}diff --git a/moli-renderer-v8/src/service_worker_runtime/jobs.rs b/moli-renderer-v8/src/service_worker_runtime/jobs.rsindex 6c8855266..7bc2c21a9 100644--- a/moli-renderer-v8/src/service_worker_runtime/jobs.rs+++ b/moli-renderer-v8/src/service_worker_runtime/jobs.rs@@ -223,66 +223,6 @@ impl ServiceWorkerPendingRegisterJob {}}-#[cfg(test)]-mod tests {- use url::Url;-- use super::*;- use crate::service_worker_runtime::snapshots::ServiceWorkerVersionSnapshot;-- fn registration_snapshot() -> ServiceWorkerRegistrationSnapshot {- let script_url = Url::parse("https://example.test/app/sw.js").unwrap();- ServiceWorkerRegistrationSnapshot::new(- ServiceWorkerRegistrationId(1),- Url::parse("https://example.test/app/").unwrap(),- ServiceWorkerUpdateViaCache::Imports,- crate::service_worker_runtime::ServiceWorkerNavigationPreloadState::default(),- Some(ServiceWorkerVersionSnapshot::new(- ServiceWorkerVersionId(1),- script_url,- "installing",- )),- None,- None,- )- }-- #[test]- fn pending_register_job_resolves_when_install_starts() {- let queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();- let mut job = ServiceWorkerPendingRegisterJob::new(vec![ServiceWorkerRegisterJob {- request_id: 1,- document_owner: crate::window_document_identity::WindowDocumentOwner::for_test(1),- completion_tx: queue.sender(),- }]);-- job.start_current_moli_job();- assert_eq!(job.phase(), ServiceWorkerRegisterJobPhase::Update);- let callbacks = job.complete_install_started(registration_snapshot());- assert_eq!(callbacks.len(), 1);- assert_eq!(job.phase(), ServiceWorkerRegisterJobPhase::Install);-- let callbacks = job.complete_install_success(registration_snapshot());- assert!(callbacks.is_empty());- assert_eq!(job.phase(), ServiceWorkerRegisterJobPhase::Complete);- }-- #[test]- fn pending_register_job_abort_before_install_sets_abort_phase() {- let mut job = ServiceWorkerPendingRegisterJob::new(Vec::new());-- job.start_current_moli_job();- assert!(- job.abort_before_install(ServiceWorkerRegistrationError::type_error(- "failed to start"- ))- .is_empty()- );-- assert_eq!(job.phase(), ServiceWorkerRegisterJobPhase::Abort);- }-}-#[derive(Clone, Debug)]pub(super) struct ServiceWorkerUnregisterJob {pub(super) request_id: u64,@@ -768,3 +708,63 @@ impl ServiceWorkerVersionLaunchConfig {}}}++#[cfg(test)]+mod tests {+ use url::Url;++ use super::*;+ use crate::service_worker_runtime::snapshots::ServiceWorkerVersionSnapshot;++ fn registration_snapshot() -> ServiceWorkerRegistrationSnapshot {+ let script_url = Url::parse("https://example.test/app/sw.js").unwrap();+ ServiceWorkerRegistrationSnapshot::new(+ ServiceWorkerRegistrationId(1),+ Url::parse("https://example.test/app/").unwrap(),+ ServiceWorkerUpdateViaCache::Imports,+ crate::service_worker_runtime::ServiceWorkerNavigationPreloadState::default(),+ Some(ServiceWorkerVersionSnapshot::new(+ ServiceWorkerVersionId(1),+ script_url,+ "installing",+ )),+ None,+ None,+ )+ }++ #[test]+ fn pending_register_job_resolves_when_install_starts() {+ let queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();+ let mut job = ServiceWorkerPendingRegisterJob::new(vec![ServiceWorkerRegisterJob {+ request_id: 1,+ document_owner: crate::window_document_identity::WindowDocumentOwner::for_test(1),+ completion_tx: queue.sender(),+ }]);++ job.start_current_moli_job();+ assert_eq!(job.phase(), ServiceWorkerRegisterJobPhase::Update);+ let callbacks = job.complete_install_started(registration_snapshot());+ assert_eq!(callbacks.len(), 1);+ assert_eq!(job.phase(), ServiceWorkerRegisterJobPhase::Install);++ let callbacks = job.complete_install_success(registration_snapshot());+ assert!(callbacks.is_empty());+ assert_eq!(job.phase(), ServiceWorkerRegisterJobPhase::Complete);+ }++ #[test]+ fn pending_register_job_abort_before_install_sets_abort_phase() {+ let mut job = ServiceWorkerPendingRegisterJob::new(Vec::new());++ job.start_current_moli_job();+ assert!(+ job.abort_before_install(ServiceWorkerRegistrationError::type_error(+ "failed to start"+ ))+ .is_empty()+ );++ assert_eq!(job.phase(), ServiceWorkerRegisterJobPhase::Abort);+ }+}diff --git a/moli-xpath/src/value.rs b/moli-xpath/src/value.rsindex f5f1fc4dc..1420bc00d 100644--- a/moli-xpath/src/value.rs+++ b/moli-xpath/src/value.rs@@ -296,7 +296,6 @@ partial_eq_impl!(&str, Value::String(ref v) => v);#[cfg(test)]mod tests {- use std::f64;use crate::dummy_implementation;