Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(cdp): retain exact page owners through deferred work
ldm0a9d01bf34519
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rsindex 2c737485a..3c50b125b 100644--- a/moli-protocol/src/conn.rs+++ b/moli-protocol/src/conn.rs@@ -1183,7 +1183,6 @@ pub struct CdpConnection {next_page_domain_subscription_generation: u64,next_internal_runtime_command_id: u64,network_request_id_allocator: ConnectionNetworkRequestIdAllocator,- none_session_owner_route_override: Option<CdpSessionRoute>,pending_runtime_await_jobs: HashMap<PendingRendererCommandKey, RuntimeAwaitJob>,claimed_pending_inspector_await_owners:HashMap<PendingRendererCommandKey, ClaimedPendingInspectorAwaitOwner>,@@ -1517,7 +1516,6 @@ impl CdpConnection {scheduler_hooks: CdpSchedulerHooks::default(),target_host_lifecycle_observer: None,scheduler_state: CdpConnectionSchedulerState::default(),- none_session_owner_route_override: None,standalone_navigation_engine,}}@@ -1696,11 +1694,7 @@ impl CdpConnection {&self,session_id: Option<&str>,) -> bool {- let none_session_owner_route = self.none_session_owner_route_override();- self.has_pending_document_navigation_for_route(- session_id,- none_session_owner_route.as_ref(),- )+ self.has_pending_document_navigation_for_route(session_id, None)}pub(crate) fn has_pending_document_navigation_for_route(@@ -1799,8 +1793,7 @@ impl CdpConnection {&self,session_id: Option<&str>,) -> Result<(), String> {- let none_session_owner_route = self.none_session_owner_route_override();- self.ensure_document_accessible_for_route(session_id, none_session_owner_route.as_ref())+ self.ensure_document_accessible_for_route(session_id, None)}pub(crate) fn ensure_document_accessible_for_route(@@ -1838,25 +1831,28 @@ impl CdpConnection {source_document: moli_core::RendererDocumentLifecycleIdentity,item: &moli_core::page::ScriptNetworkOutputItem,) -> Option<crate::domains::network::TargetNetworkBacklogPreparedDelivery> {- self.ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_session_owner(+ self.ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_route(session_id,None,+ None,source_document,item,)}- pub(crate) fn ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_session_owner(+ pub(crate) fn ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,source_renderer_page: Option<RendererPageResidenceIdentity>,source_document: moli_core::RendererDocumentLifecycleIdentity,item: &moli_core::page::ScriptNetworkOutputItem,) -> Option<crate::domains::network::TargetNetworkBacklogPreparedDelivery> {- let primary_session_id = self.runtime_session_owner_primary_session_id(session_id);+ let primary_session_id =+ self.runtime_session_owner_primary_session_id_for_route(session_id, owner_route);let mut request_id_allocator = std::mem::take(&mut self.network_request_id_allocator);let delivery = self- .runtime_session_owner_slot_mut(session_id)+ .runtime_session_owner_slot_mut_for_route(session_id, owner_route).ok().and_then(|slot| {slot.ingest_renderer_network_output_item_and_prepare_live_delivery(@@ -1877,11 +1873,7 @@ impl CdpConnection {&mut self,session_id: Option<&str>,) -> Result<&mut Page, String> {- let none_session_owner_route = self.none_session_owner_route_override();- self.loaded_page_mut_for_protocol_access_for_route(- session_id,- none_session_owner_route.as_ref(),- )+ self.loaded_page_mut_for_protocol_access_for_route(session_id, None)}pub(crate) fn loaded_page_mut_for_protocol_access_for_route(@@ -1907,11 +1899,7 @@ impl CdpConnection {&mut self,session_id: Option<&str>,) -> Result<&mut Page, String> {- let none_session_owner_route = self.none_session_owner_route_override();- self.loaded_page_mut_for_target_configuration_for_route(- session_id,- none_session_owner_route.as_ref(),- )+ self.loaded_page_mut_for_target_configuration_for_route(session_id, None)}pub(crate) fn loaded_page_mut_for_target_configuration_for_route(@@ -1935,11 +1923,7 @@ impl CdpConnection {&mut self,session_id: Option<&str>,) -> Result<&mut Page, String> {- let none_session_owner_route = self.none_session_owner_route_override();- self.loaded_page_mut_for_interruptible_protocol_access_for_route(- session_id,- none_session_owner_route.as_ref(),- )+ self.loaded_page_mut_for_interruptible_protocol_access_for_route(session_id, None)}pub(crate) fn loaded_page_mut_for_interruptible_protocol_access_for_route(@@ -1952,14 +1936,6 @@ impl CdpConnection {.ok_or_else(|| "NoDocumentLoaded".to_owned())}- pub(crate) fn start_document_navigation_for_session_owner(- &mut self,- session_id: Option<&str>,- loader_id: String,- ) -> Option<DocumentNavigationToken> {- self.start_document_navigation_for_route(session_id, None, loader_id)- }-pub(crate) fn start_document_navigation_for_route(&mut self,session_id: Option<&str>,@@ -1973,13 +1949,13 @@ impl CdpConnection {.start_document_navigation_for_target(&target_id, loader_id)}- pub(crate) fn commit_document_navigation_for_session_owner_if_matches(+ pub(crate) fn commit_document_navigation_for_owner_if_matches(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,token: &DocumentNavigationToken,) {let Some((browser_context_id, target_id)) =- self.target_owner_identity_for_session(session_id)+ self.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())else {return;};@@ -1991,9 +1967,9 @@ impl CdpConnection {}}- pub(crate) fn bind_renderer_document_lifecycle_for_session_owner(+ pub(crate) fn bind_renderer_document_lifecycle_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,artifacts: moli_core::page::RendererPageCreationArtifacts,navigation: Option<DocumentNavigationToken>,frame_id: String,@@ -2003,7 +1979,10 @@ impl CdpConnection {Vec<moli_core::page::RendererDocumentLifecycleEvent>,) {let (binding, events, document_scope_changed) = {- let Ok(slot) = self.runtime_session_owner_slot_mut(session_id) else {+ let Ok(slot) = self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {return (None, Vec::new());};let previous_document_scope = slot@@ -2027,21 +2006,24 @@ impl CdpConnection {)};if document_scope_changed {- self.retire_javascript_dialogs_for_session_owner(session_id);+ self.retire_javascript_dialogs_for_owner(owner);}(binding, events)}- pub(crate) fn ingest_renderer_document_lifecycle_events_for_session_owner(+ pub(crate) fn ingest_renderer_document_lifecycle_events_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,events: Vec<moli_core::page::RendererDocumentLifecycleEvent>,) -> (Option<CommittedRendererDocumentBinding>,Vec<moli_core::page::RendererDocumentLifecycleEvent>,) {let (binding, events, document_scope_changed, document_input_stream_opened) = {- let Ok(slot) = self.runtime_session_owner_slot_mut(session_id) else {+ let Ok(slot) = self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {return (None, Vec::new());};let previous_document_scope = slot@@ -2069,7 +2051,7 @@ impl CdpConnection {)};if document_scope_changed {- self.retire_javascript_dialogs_for_session_owner(session_id);+ self.retire_javascript_dialogs_for_owner(owner);}if document_input_stream_opened {// The concrete lifecycle record is the authoritative notification@@ -2077,59 +2059,79 @@ impl CdpConnection {// not defer this state transition to a later diagnostics snapshot:// that would make a later owner turn rediscover and settle output// produced by this renderer turn.- self.with_target_owner_state_for_session_mut(session_id, |owner_state| {- owner_state.mark_initial_empty_document_exited();- });+ self.with_target_owner_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |owner_state| owner_state.mark_initial_empty_document_exited(),+ );}(binding, events)}- fn retire_javascript_dialogs_for_session_owner(&mut self, session_id: Option<&str>) {- let event_session_ids = self.page_event_session_ids_for_session_owner(session_id);- if let Ok(slot) = self.runtime_session_owner_slot_mut(session_id) {+ fn retire_javascript_dialogs_for_owner(&mut self, owner: &CommandOwnerScope) {+ let event_session_ids =+ self.page_event_session_ids_for_route(owner.session_id(), owner.session_owner_route());+ if let Ok(slot) = self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) {slot.retire_javascript_dialog_scope();}for event_session_id in event_session_ids {- let _ = self.with_target_devtools_session_state_for_session_mut(+ let event_owner_route = event_session_id+ .is_none()+ .then_some(owner.session_owner_route())+ .flatten();+ let _ = self.with_target_devtools_session_state_for_route_mut(event_session_id.as_deref(),+ event_owner_route,|state| state.page_session_state.javascript_dialog_state.clear(),);}}- pub(crate) fn begin_renderer_document_load_visibility_barrier_for_session_owner(+ pub(crate) fn begin_renderer_document_load_visibility_barrier_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,loader_id: &str,) -> bool {- self.runtime_session_owner_slot_mut(session_id)- .is_ok_and(|slot| {- slot.page_slot_mut()- .begin_renderer_document_load_visibility_barrier(loader_id)- })+ self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ .is_ok_and(|slot| {+ slot.page_slot_mut()+ .begin_renderer_document_load_visibility_barrier(loader_id)+ })}- pub(crate) fn release_renderer_document_load_visibility_barrier_for_session_owner(+ pub(crate) fn release_renderer_document_load_visibility_barrier_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,loader_id: &str,) -> Option<Vec<moli_core::page::RendererDocumentLifecycleEvent>> {- self.runtime_session_owner_slot_mut(session_id)- .ok()?- .page_slot_mut()- .release_renderer_document_load_visibility_barrier(loader_id)+ self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ .ok()?+ .page_slot_mut()+ .release_renderer_document_load_visibility_barrier(loader_id)}- pub(crate) fn cancel_renderer_document_load_visibility_barrier_for_session_owner(+ pub(crate) fn cancel_renderer_document_load_visibility_barrier_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,loader_id: &str,) -> bool {- self.runtime_session_owner_slot_mut(session_id)- .is_ok_and(|slot| {- slot.page_slot_mut()- .cancel_renderer_document_load_visibility_barrier(loader_id)- })+ self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ .is_ok_and(|slot| {+ slot.page_slot_mut()+ .cancel_renderer_document_load_visibility_barrier(loader_id)+ })}#[cfg(test)]@@ -2150,9 +2152,9 @@ impl CdpConnection {))}- pub(crate) fn register_exact_renderer_document_lifecycle_observer_for_session_owner(+ pub(crate) fn register_exact_renderer_document_lifecycle_observer_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,expected_binding: Option<&CommittedRendererDocumentBinding>,milestone: moli_core::page::RendererDocumentLifecycleMilestone,) -> RendererDocumentLifecycleObserver {@@ -2161,7 +2163,10 @@ impl CdpConnection {RendererDocumentLifecycleObservation::Unavailable,);};- let Ok(slot) = self.runtime_session_owner_slot_mut(session_id) else {+ let Ok(slot) = self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {return RendererDocumentLifecycleObserver::resolved(RendererDocumentLifecycleObservation::Unavailable,);@@ -2187,16 +2192,19 @@ impl CdpConnection {))}- pub(crate) fn arm_root_post_load_observation_for_session_owner(+ pub(crate) fn arm_root_post_load_observation_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,loader_id: &str,) -> bool {- self.runtime_session_owner_slot_mut(session_id)- .is_ok_and(|slot| {- slot.page_slot_mut()- .arm_root_post_load_observation(loader_id)- })+ self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ .is_ok_and(|slot| {+ slot.page_slot_mut()+ .arm_root_post_load_observation(loader_id)+ })}/// Consumes the exact stopped-loading fact owned by an armed root post-load@@ -2206,9 +2214,9 @@ impl CdpConnection {/// Having no `Page` subscriber is a normal terminal outcome. The binding/// must still be consumed so enabling `Page` later cannot replay a/// historical event from an earlier navigation.- pub(crate) fn settle_root_frame_stopped_loading_observation(+ pub(crate) fn settle_root_frame_stopped_loading_observation_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Result<crate::domains::activity::RootFrameStoppedLoadingSettlement,crate::domains::activity::RootFrameStoppedLoadingSettlementError,@@ -2219,7 +2227,10 @@ impl CdpConnection {};let binding = self- .runtime_session_owner_slot_mut(session_id)+ .runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).ok().and_then(|slot| {slot.page_slot_mut()@@ -2229,13 +2240,19 @@ impl CdpConnection {return Err(SettlementError::MissingArmedObservation);};if self- .subscribed_page_event_session_ids_for_session_owner(session_id)+ .subscribed_page_event_session_ids_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).is_empty(){return Ok(Settlement::Unobserved);}let attachments = self- .page_event_protocol_attachments_for_session_owner(session_id)+ .page_event_protocol_attachments_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).ok_or(SettlementError::SubscribedAttachmentUnavailable)?;let publish_sequence = self.scheduler_state@@ -2254,28 +2271,37 @@ impl CdpConnection {Ok(Settlement::Published)}- pub(crate) fn emit_root_network_idle_for_session_owner(+ pub(crate) fn emit_root_network_idle_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,out: &mut Vec<BackgroundProtocolEvent>,) -> bool {if !self- .runtime_session_owner_slot(session_id)+ .runtime_session_owner_slot_for_route(owner.session_id(), owner.session_owner_route()).is_ok_and(|slot| slot.renderer_subresources_are_idle()){return false;}let binding = self- .runtime_session_owner_slot_mut(session_id)+ .runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).ok().and_then(|slot| slot.page_slot_mut().take_root_network_idle_binding());let Some(binding) = binding else {return false;};let timestamp = monotonic_timestamp_seconds();- for event_session_id in self.page_event_session_ids_for_session_owner(session_id) {+ for event_session_id in+ self.page_event_session_ids_for_route(owner.session_id(), owner.session_owner_route())+ {+ let event_owner_route = event_session_id+ .is_none()+ .then_some(owner.session_owner_route())+ .flatten();let lifecycle_enabled = self- .target_page_session_state_for_session(event_session_id.as_deref())+ .target_page_session_state_for_route(event_session_id.as_deref(), event_owner_route).is_some_and(|state| state.page_lifecycle_events);crate::domains::page::emit_navigation_network_idle_background_events(out,@@ -2307,7 +2333,7 @@ impl CdpConnection {let route = self.target_session_route_for_target_id(target_id.as_str()).or_else(|| self.target_session_route_for_child_frame_id(target_id.as_str()))?;- return Some(CommandOwnerScope::for_implicit_route(Some(route)));+ return Some(CommandOwnerScope::for_route(route));}Some(CommandOwnerScope::capture(self,@@ -2420,13 +2446,13 @@ impl CdpConnection {})}- pub(crate) fn clear_pending_document_navigation_for_session_owner_if_loader_matches(+ pub(crate) fn clear_pending_document_navigation_for_owner_if_loader_matches(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,loader_id: &str,) {let Some((browser_context_id, target_id)) =- self.target_owner_identity_for_session(session_id)+ self.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())else {return;};@@ -2436,7 +2462,7 @@ impl CdpConnection {loader_id,);}- self.discard_uncommitted_main_document_resource_for_session_owner(session_id, loader_id);+ self.discard_uncommitted_main_document_resource_for_owner(owner, loader_id);}pub fn take_scheduler_events(&mut self) -> Vec<CdpSchedulerEvent> {@@ -2496,15 +2522,6 @@ impl CdpConnection {}));}- pub(crate) fn background_navigation_completion_sender_for_session_owner(- &self,- session_id: Option<&str>,- ) -> Option<- tokio::sync::mpsc::UnboundedSender<crate::domains::page::BackgroundNavigationCompletion>,- > {- self.background_navigation_completion_sender_for_route(session_id, None)- }-pub(crate) fn background_navigation_completion_sender_for_route(&self,session_id: Option<&str>,@@ -2619,10 +2636,8 @@ impl CdpConnection {phase_ms = started.elapsed().as_millis(),);}- let protocol_events = self- .drain_materialized_navigation_completion_background_events(completion, command_context)- .await;- protocol_events+ self.drain_materialized_navigation_completion_background_events(completion, command_context)+ .await}pub(crate) fn replace_standalone_navigation_engine(&mut self, engine: NavigationEngine) {@@ -2672,42 +2687,19 @@ impl CdpConnection {Ok(())}- pub(crate) fn adopt_loaded_navigation_engine_for_session_owner(+ pub(crate) fn adopt_loaded_navigation_engine_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,engine: NavigationEngine,) {- let route = match session_id {- Some(_) => self.session_route(session_id),- None => self.none_session_owner_route_override(),- };- let Some(route) = route else {+ let Some((browser_context_id, Some(target_id))) =+ self.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())+ else {self.replace_standalone_navigation_engine(engine);return;};- let page_owner = match route {- CdpSessionRoute::PageTarget {- browser_context_id,- target_id,- ..- } => Some((browser_context_id, target_id)),- CdpSessionRoute::Browser- | CdpSessionRoute::TabTarget { .. }- | CdpSessionRoute::SharedWorkerTarget { .. }- | CdpSessionRoute::DedicatedWorkerTarget { .. }- | CdpSessionRoute::ServiceWorkerTarget { .. } => None,- CdpSessionRoute::BrowserContext { browser_context_id } => self- .browser_context_by_id(&browser_context_id)- .and_then(|browser_context| browser_context.active_target_id())- .map(str::to_owned)- .map(|target_id| (browser_context_id, target_id)),- };- if let Some((browser_context_id, target_id)) = page_owner {- self.install_page_navigation_engine(&browser_context_id, &target_id, engine)- .expect("page route must install its exact PageTargetHost engine");- } else {- self.replace_standalone_navigation_engine(engine);- }+ self.install_page_navigation_engine(&browser_context_id, &target_id, engine)+ .expect("page owner must install its exact PageTargetHost engine");}pub(crate) fn adopt_loaded_navigation_engine_for_page_owner(@@ -2730,14 +2722,10 @@ impl CdpConnection {);return;}- let owner_scope = admission.owner_scope().clone();let observation_id = self.scheduler_state.allocate_deferred_main_document_load_observation_id();- let completion = {- let mut route_scope = owner_scope.enter(self);- admission.bind_lifecycle_observer(route_scope.conn_mut(), observation_id)- };+ let completion = admission.bind_lifecycle_observer(self, observation_id);let publish_sequence = self.scheduler_state.allocate_protocol_work_publish_sequence();@@ -2835,15 +2823,8 @@ impl CdpConnection {&mut self,completion: CompletedDeferredMainDocumentLoadCompletion,) -> CdpTurnOutcome {- let owner_scope = completion.inner.owner_scope().clone();let mut output = BackgroundProtocolEventBuffer::default();- {- let mut route_scope = owner_scope.enter(self);- completion- .inner- .emit_async(route_scope.conn_mut(), &mut output)- .await;- }+ completion.inner.emit_async(self, &mut output).await;CdpTurnOutcome::new_with_protocol_and_post_response_events(output.into_events(),Vec::new(),@@ -2981,7 +2962,7 @@ impl CdpConnection {crate::domains::page::push_superseded_navigation_result(out, &state);return;}- let navigation_session_id = state.owner.session_id().map(str::to_owned);+ let navigation_owner = state.owner.clone();crate::domains::page::complete_materialized_navigation_into_buffer_async(self,out,@@ -2992,10 +2973,7 @@ impl CdpConnection {).await;if let Some(engine) = engine {- self.adopt_loaded_navigation_engine_for_session_owner(- navigation_session_id.as_deref(),- engine,- );+ self.adopt_loaded_navigation_engine_for_owner(&navigation_owner, engine);}if let Some(started) = timing_started {tracing::info!(@@ -3006,31 +2984,6 @@ impl CdpConnection {}}- pub(crate) fn none_session_owner_route_override(&self) -> Option<CdpSessionRoute> {- self.none_session_owner_route_override.clone()- }-- pub(crate) fn replace_none_session_owner_route_override(- &mut self,- route: Option<CdpSessionRoute>,- ) -> Option<CdpSessionRoute> {- std::mem::replace(&mut self.none_session_owner_route_override, route)- }-- pub(crate) fn scoped_none_session_owner_route_override(- &mut self,- route: CdpSessionRoute,- ) -> NoneSessionOwnerRouteOverrideScope<'_> {- NoneSessionOwnerRouteOverrideScope::enter(self, Some(route))- }-- pub(crate) fn scoped_optional_none_session_owner_route_override(- &mut self,- route: Option<CdpSessionRoute>,- ) -> NoneSessionOwnerRouteOverrideScope<'_> {- NoneSessionOwnerRouteOverrideScope::enter(self, route)- }-pub(crate) fn response_body_materialize_limit(&self) -> usize {self.fetch_config().http_max_response_size()@@ -4170,38 +4123,6 @@ impl CdpConnection {}}-pub(crate) struct NoneSessionOwnerRouteOverrideScope<'a> {- conn: &'a mut CdpConnection,- previous_route: Option<Option<CdpSessionRoute>>,-}--impl<'a> NoneSessionOwnerRouteOverrideScope<'a> {- fn enter(conn: &'a mut CdpConnection, target_route: Option<CdpSessionRoute>) -> Self {- let previous_route = conn.replace_none_session_owner_route_override(target_route);- Self {- conn,- previous_route: Some(previous_route),- }- }-- pub(crate) fn conn_mut(&mut self) -> &mut CdpConnection {- self.conn- }-- pub(crate) fn restore(&mut self) {- if let Some(previous_route) = self.previous_route.take() {- self.conn- .replace_none_session_owner_route_override(previous_route);- }- }-}--impl Drop for NoneSessionOwnerRouteOverrideScope<'_> {- fn drop(&mut self) {- self.restore();- }-}-#[derive(Debug, Clone, PartialEq, Eq)]pub struct BrowserDownloadBehavior {pub behavior: String,diff --git a/moli-protocol/src/conn/activity_source.rs b/moli-protocol/src/conn/activity_source.rsindex b3d1f28d6..d03d2d33b 100644--- a/moli-protocol/src/conn/activity_source.rs+++ b/moli-protocol/src/conn/activity_source.rs@@ -84,15 +84,6 @@ impl CdpConnection {)}- pub(crate) fn start_child_frame_lifecycle_work_for_session_owner(- &mut self,- session_id: Option<&str>,- timeout: std::time::Duration,- ) -> Result<PendingChildFrameLifecycleWork, String> {- let owner = CommandOwnerScope::capture(self, session_id);- self.start_child_frame_lifecycle_work_for_owner(owner, timeout)- }-pub(crate) fn start_child_frame_lifecycle_work_for_owner(&mut self,owner: CommandOwnerScope,diff --git a/moli-protocol/src/conn/bidi_channel_work.rs b/moli-protocol/src/conn/bidi_channel_work.rsindex 53952d9ee..ba42a08e2 100644--- a/moli-protocol/src/conn/bidi_channel_work.rs+++ b/moli-protocol/src/conn/bidi_channel_work.rs@@ -1,6 +1,6 @@use super::{- CdpConnection, CommandOwnerScope, NoneSessionOwnerRouteOverrideScope,- TargetPageProtocolAttachmentIdentity, state::PendingBidiChannelListener,+ CdpConnection, CommandOwnerScope, TargetPageProtocolAttachmentIdentity,+ state::PendingBidiChannelListener,};/// Exact Page attachment that owns one WebDriver BiDi channel listener.@@ -18,16 +18,6 @@ pub(crate) struct BidiChannelPageOwner {}impl BidiChannelPageOwner {- /// Captures the Page currently addressed by `session_id`.- ///- /// Callers using the implicit `None` session must invoke this while the- /// target's owner-route override is installed. `owner_scope` freezes that- /// route, while `attachment` freezes the target Page residence and exact- /// protocol session.- pub(crate) fn capture(conn: &CdpConnection, session_id: Option<&str>) -> Option<Self> {- Self::capture_for_owner(conn, CommandOwnerScope::capture(conn, session_id))- }-pub(crate) fn capture_for_owner(conn: &CdpConnection,owner_scope: CommandOwnerScope,@@ -53,13 +43,6 @@ impl BidiChannelPageOwner {&self.owner_scope}- pub(crate) fn enter<'a>(- &self,- conn: &'a mut CdpConnection,- ) -> NoneSessionOwnerRouteOverrideScope<'a> {- self.owner_scope.enter(conn)- }-/// Checks the captured Page attachment directly.////// The attachment contains its exact context, target, and Page residence,@@ -195,8 +178,11 @@ mod tests {#[test]fn page_owner_rejects_replacement_attachment() {let mut conn = connection_with_page_session();- let owner =- BidiChannelPageOwner::capture(&conn, Some("SID-owner")).expect("test Page attachment");+ let owner = BidiChannelPageOwner::capture_for_owner(+ &conn,+ CommandOwnerScope::for_session("SID-owner"),+ )+ .expect("test Page attachment");assert!(owner.is_current(&conn));conn.runtime_session_owner_slot_mut(Some("SID-owner"))@@ -212,8 +198,11 @@ mod tests {#[test]fn page_owner_rejects_detached_session() {let mut conn = connection_with_page_session();- let owner =- BidiChannelPageOwner::capture(&conn, Some("SID-owner")).expect("test Page attachment");+ let owner = BidiChannelPageOwner::capture_for_owner(+ &conn,+ CommandOwnerScope::for_session("SID-owner"),+ )+ .expect("test Page attachment");assert_eq!(conn.browser_context@@ -231,38 +220,24 @@ mod tests {}#[test]- fn implicit_page_owner_reenters_its_frozen_route_and_restores_the_caller() {- let mut conn = connection_with_page_session();+ fn implicit_page_owner_retains_its_frozen_route() {+ let conn = connection_with_page_session();let owner_route = crate::conn::CdpSessionRoute::PageTarget {browser_context_id: "BID-owner".to_owned(),target_id: "TID-owner".to_owned(),is_attached_session: false,};- let owner = {- let mut scope = conn.scoped_none_session_owner_route_override(owner_route.clone());- BidiChannelPageOwner::capture(scope.conn_mut(), None)- .expect("implicit owner must capture the scoped Page")- };- let caller_route = crate::conn::CdpSessionRoute::Browser;- conn.replace_none_session_owner_route_override(Some(caller_route.clone()));-- {- let mut scope = owner.enter(&mut conn);- assert_eq!(- scope.conn_mut().none_session_owner_route_override(),- Some(owner_route),- "deferred work must not follow the caller's current implicit route"- );- assert!(- owner.is_current(scope.conn_mut()),- "the frozen route must still resolve the captured Page attachment"- );- }+ let owner = BidiChannelPageOwner::capture_for_owner(+ &conn,+ CommandOwnerScope::for_route(owner_route.clone()),+ )+ .expect("implicit owner must capture the scoped Page");assert_eq!(- conn.none_session_owner_route_override(),- Some(caller_route),- "executing exact owner work must restore the surrounding route"+ owner.command_owner().session_owner_route(),+ Some(&owner_route),+ "deferred work must retain its exact Page route");+ assert!(owner.is_current(&conn));}}diff --git a/moli-protocol/src/conn/browser_context/fetch_owner.rs b/moli-protocol/src/conn/browser_context/fetch_owner.rsindex 4dc1edbc5..a489de5ff 100644--- a/moli-protocol/src/conn/browser_context/fetch_owner.rs+++ b/moli-protocol/src/conn/browser_context/fetch_owner.rs@@ -228,13 +228,6 @@ fn remove_network_intercept_from_browser_context(}impl CdpConnection {- pub(crate) fn target_fetch_subresource_interception_snapshot_for_session_owner(- &self,- session_id: Option<&str>,- ) -> Option<TargetFetchSubresourceInterceptionSnapshot> {- self.target_fetch_subresource_interception_snapshot_for_route(session_id, None)- }-pub(crate) fn target_fetch_subresource_interception_snapshot_for_route(&self,session_id: Option<&str>,@@ -252,28 +245,31 @@ impl CdpConnection {.map(|config| config.subresource_interception_snapshot())}- pub(crate) fn target_fetch_event_session_id_for_session_owner(+ pub(crate) fn target_fetch_event_session_id_for_route(&self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> Option<String> {- self.target_session_owner_aggregate_fetch_config(session_id)+ self.target_session_owner_aggregate_fetch_config_for_route(session_id, owner_route).and_then(|config| config.session_id().map(str::to_owned))}- pub(crate) fn target_fetch_handle_auth_requests_for_session_owner(+ pub(crate) fn target_fetch_handle_auth_requests_for_route(&self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> bool {- self.target_session_owner_aggregate_fetch_config(session_id)+ self.target_session_owner_aggregate_fetch_config_for_route(session_id, owner_route).is_some_and(|config| config.handle_auth_requests())}- pub(crate) fn target_fetch_matches_auth_required_for_session_owner(+ pub(crate) fn target_fetch_matches_auth_required_for_route(&self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,url: &url::Url,) -> bool {- self.target_session_owner_aggregate_fetch_config(session_id)+ self.target_session_owner_aggregate_fetch_config_for_route(session_id, owner_route).is_some_and(|config| config.matches_auth_required(url))}@@ -328,14 +324,15 @@ impl CdpConnection {}}- pub(crate) fn allocate_pending_subresource_fetch_request_ids_for_session_owner(+ pub(crate) fn allocate_pending_subresource_fetch_request_ids_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> Result<(String, String), String> {let mut network_request_id_allocator =std::mem::take(&mut self.network_request_id_allocator);let result = self- .runtime_session_owner_slot_mut(session_id)+ .runtime_session_owner_slot_mut_for_route(session_id, owner_route).map(|runtime_slot| {runtime_slot.request_id_allocator()@@ -347,11 +344,12 @@ impl CdpConnection {result}- pub(crate) fn allocate_fetch_navigation_request_id_for_session_owner(+ pub(crate) fn allocate_fetch_navigation_request_id_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> Result<String, String> {- self.runtime_session_owner_slot_mut(session_id)+ self.runtime_session_owner_slot_mut_for_route(session_id, owner_route).map(|runtime_slot| {runtime_slot.request_id_allocator()@@ -376,12 +374,7 @@ impl CdpConnection {session_id: Option<&str>,body: CapturedBody,) -> Result<String, String> {- let none_session_owner_route = self.none_session_owner_route_override();- self.open_io_stream_body_source_for_route(- session_id,- none_session_owner_route.as_ref(),- body,- )+ self.open_io_stream_body_source_for_route(session_id, None, body)}pub(crate) fn open_io_stream_body_source_for_route(@@ -418,14 +411,17 @@ impl CdpConnection {.read_io_stream(handle, offset, size)}- pub(crate) fn register_synthetic_websocket_request_for_session_owner(+ pub(crate) fn register_synthetic_websocket_request_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_id: String,network_request_id: String,socket_id: u64,) -> bool {- let Ok(runtime_slot) = self.runtime_session_owner_slot_mut(session_id) else {+ let Ok(runtime_slot) =+ self.runtime_session_owner_slot_mut_for_route(session_id, owner_route)+ else {return false;};runtime_slot.register_synthetic_websocket_request(@@ -441,7 +437,16 @@ impl CdpConnection {session_id: Option<&str>,request_id: &str,) -> Option<u64> {- self.runtime_session_owner_slot(session_id)+ self.synthetic_websocket_socket_id_for_route(session_id, None, request_id)+ }++ pub(crate) fn synthetic_websocket_socket_id_for_route(+ &self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ request_id: &str,+ ) -> Option<u64> {+ self.runtime_session_owner_slot_for_route(session_id, owner_route).ok().and_then(|runtime_slot| {runtime_slot.synthetic_websocket_socket_id_for_request(request_id)@@ -476,9 +481,10 @@ impl CdpConnection {})}- pub(crate) fn claim_subresource_continue_request_for_session_owner(+ pub(crate) fn claim_subresource_continue_request_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,expected_page_owner: &crate::conn::TargetPageResidenceIdentity,internal_id: u64,allow_pending_completion: bool,@@ -488,7 +494,7 @@ impl CdpConnection {{return None;}- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(session_id, owner_route)?.claim_subresource_continue_request(expected_page_owner,internal_id,@@ -497,32 +503,35 @@ impl CdpConnection {)}- pub(crate) fn consume_pending_request_action_for_session_owner(+ pub(crate) fn consume_pending_request_action_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_id: &str,) -> Option<Result<(), &'static str>> {- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(session_id, owner_route)?.consume_pending_request_action(request_id)}- pub(crate) fn take_pending_fetch_navigation_for_session_owner(+ pub(crate) fn take_pending_fetch_navigation_for_route(&mut self,owner_session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingFetchNavigation> {- self.target_session_owner_mut(owner_session_id)?+ self.target_session_owner_mut_for_route(owner_session_id, owner_route)?.take_pending_fetch_navigation_for_action_session(request_id, action_session_id)}- pub(crate) fn take_pending_fetch_auth_navigation_for_action_session_owner(+ pub(crate) fn take_pending_fetch_auth_navigation_for_route(&mut self,owner_session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingFetchAuthNavigation> {- self.target_session_owner_mut(owner_session_id)?+ self.target_session_owner_mut_for_route(owner_session_id, owner_route)?.take_pending_fetch_auth_navigation_for_action_session(request_id, action_session_id)}@@ -532,7 +541,17 @@ impl CdpConnection {request_id: String,pending: PendingFetchAuthNavigation,) -> bool {- self.target_session_owner_mut(session_id)+ self.register_pending_fetch_auth_navigation_for_route(session_id, None, request_id, pending)+ }++ pub(crate) fn register_pending_fetch_auth_navigation_for_route(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ request_id: String,+ pending: PendingFetchAuthNavigation,+ ) -> bool {+ self.target_session_owner_mut_for_route(session_id, owner_route).is_some_and(|mut owner| {owner.register_pending_fetch_auth_navigation(request_id, pending)})@@ -557,53 +576,58 @@ impl CdpConnection {})}- pub(crate) fn take_pending_fetch_response_transfer_for_terminal_action_for_session_owner(+ pub(crate) fn take_pending_fetch_response_transfer_for_terminal_action_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_id: &str,) -> Option<PausedDocumentTransfer> {- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(session_id, owner_route)?.take_pending_fetch_response_transfer_for_terminal_action(request_id)}- pub(crate) fn take_pending_fetch_response_transfer_for_body_read_for_session_owner(+ pub(crate) fn take_pending_fetch_response_transfer_for_body_read_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_id: &str,) -> Option<PausedDocumentTransfer> {- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(session_id, owner_route)?.take_pending_fetch_response_transfer(request_id)}- pub(crate) fn register_pending_fetch_response_transfer_for_session_owner(+ pub(crate) fn register_pending_fetch_response_transfer_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_id: String,transfer: PausedDocumentTransfer,) -> bool {- self.target_session_owner_mut(session_id)+ self.target_session_owner_mut_for_route(session_id, owner_route).is_some_and(|mut owner| {owner.register_pending_fetch_response_transfer(request_id, transfer)})}- pub(crate) fn pending_subresource_fetch_response_request_for_action_session_owner(+ pub(crate) fn pending_subresource_fetch_response_request_for_route(&mut self,owner_session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingSubresourceFetchResponseRequest> {- self.target_session_owner_mut(owner_session_id)?+ self.target_session_owner_mut_for_route(owner_session_id, owner_route)?.pending_subresource_fetch_response_request(request_id, action_session_id)}- pub(crate) fn mark_pending_subresource_fetch_response_body_taken_as_stream_for_action_session_owner(+ pub(crate) fn mark_pending_subresource_fetch_response_body_taken_as_stream_for_route(&mut self,owner_session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,action_session_id: Option<&str>,request_id: &str,) -> bool {- self.target_session_owner_mut(owner_session_id)+ self.target_session_owner_mut_for_route(owner_session_id, owner_route).is_some_and(|mut owner| {owner.mark_pending_subresource_fetch_response_body_taken_as_stream(request_id,@@ -767,27 +791,29 @@ impl CdpConnection {.then_some(pending)}- pub(crate) fn take_pending_subresource_fetch_request_for_action_session_owner(+ pub(crate) fn take_pending_subresource_fetch_request_for_route(&mut self,owner_session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingSubresourceFetchRequest> {let pending = self- .target_session_owner_mut(owner_session_id)?+ .target_session_owner_mut_for_route(owner_session_id, owner_route)?.take_pending_subresource_fetch_request(request_id, action_session_id)?;self.pending_subresource_fetch_request_residence_is_current(owner_session_id, &pending).then_some(pending)}- pub(crate) fn take_pending_subresource_fetch_auth_request_for_action_session_owner(+ pub(crate) fn take_pending_subresource_fetch_auth_request_for_route(&mut self,owner_session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingSubresourceFetchAuthRequest> {let pending = self- .target_session_owner_mut(owner_session_id)?+ .target_session_owner_mut_for_route(owner_session_id, owner_route)?.take_pending_subresource_fetch_auth_request(request_id, action_session_id)?;self.target_page_residence_identity_is_current_for_session(owner_session_id,@@ -796,14 +822,15 @@ impl CdpConnection {.then_some(pending)}- pub(crate) fn take_pending_subresource_fetch_response_request_for_action_session_owner(+ pub(crate) fn take_pending_subresource_fetch_response_request_for_route(&mut self,owner_session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingSubresourceFetchResponseRequest> {let pending = self- .target_session_owner_mut(owner_session_id)?+ .target_session_owner_mut_for_route(owner_session_id, owner_route)?.take_pending_subresource_fetch_response_request(request_id, action_session_id)?;self.target_page_residence_identity_is_current_for_session(owner_session_id,@@ -812,26 +839,19 @@ impl CdpConnection {.then_some(pending)}- pub(crate) fn take_in_flight_subresource_fetch_request_for_session_owner(+ pub(crate) fn take_in_flight_subresource_fetch_request_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,internal_id: u64,) -> Option<InFlightSubresourceFetchRequest> {let in_flight = self- .target_session_owner_mut(session_id)?+ .target_session_owner_mut_for_route(session_id, owner_route)?.take_in_flight_subresource_fetch_request(internal_id)?;self.installed_subresource_fetch_request_is_current(session_id, &in_flight.pending).then_some(in_flight)}- pub(crate) fn in_flight_subresource_fetch_request_id_for_session_owner(- &mut self,- session_id: Option<&str>,- internal_id: u64,- ) -> Option<String> {- self.in_flight_subresource_fetch_request_id_for_route(session_id, None, internal_id)- }-pub(crate) fn in_flight_subresource_fetch_request_id_for_route(&mut self,session_id: Option<&str>,@@ -850,36 +870,58 @@ impl CdpConnection {session_id: Option<&str>,request_id: String,pending: PendingSubresourceFetchRequest,+ ) -> bool {+ self.register_pending_subresource_fetch_request_for_route(+ session_id, None, request_id, pending,+ )+ }++ pub(crate) fn register_pending_subresource_fetch_request_for_route(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ request_id: String,+ pending: PendingSubresourceFetchRequest,) -> bool {if !self.pending_subresource_fetch_request_residence_is_current(session_id, &pending) {return false;}- self.record_pending_subresource_network_request_identity(session_id, &pending);- self.target_session_owner_mut(session_id)+ self.record_pending_subresource_network_request_identity_for_route(+ session_id,+ owner_route,+ &pending,+ );+ self.target_session_owner_mut_for_route(session_id, owner_route).is_some_and(|mut owner| {owner.register_pending_subresource_fetch_request(request_id, pending)})}- pub(crate) fn register_in_flight_subresource_fetch_request_for_session_owner(+ pub(crate) fn register_in_flight_subresource_fetch_request_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_id: Option<String>,pending: PendingSubresourceFetchRequest,) -> bool {if !self.installed_subresource_fetch_request_is_current(session_id, &pending) {return false;}- self.record_pending_subresource_network_request_identity(session_id, &pending);- self.target_session_owner_mut(session_id)+ self.record_pending_subresource_network_request_identity_for_route(+ session_id,+ owner_route,+ &pending,+ );+ self.target_session_owner_mut_for_route(session_id, owner_route).is_some_and(|mut owner| {owner.register_in_flight_subresource_fetch_request(request_id, pending)})}- pub(crate) fn register_in_flight_response_stage_subresource_fetch_request_for_session_owner(+ pub(crate) fn register_in_flight_response_stage_subresource_fetch_request_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_id: Option<String>,pending: PendingSubresourceFetchRequest,response_stage_blocked_intercepts: Vec<DevToolsNetworkInterceptId>,@@ -887,8 +929,12 @@ impl CdpConnection {if !self.installed_subresource_fetch_request_is_current(session_id, &pending) {return false;}- self.record_pending_subresource_network_request_identity(session_id, &pending);- self.target_session_owner_mut(session_id)+ self.record_pending_subresource_network_request_identity_for_route(+ session_id,+ owner_route,+ &pending,+ );+ self.target_session_owner_mut_for_route(session_id, owner_route).is_some_and(|mut owner| {owner.register_in_flight_response_stage_subresource_fetch_request(request_id,@@ -899,17 +945,22 @@ impl CdpConnection {})}- pub(crate) fn register_in_flight_deferred_response_stage_subresource_fetch_request_for_session_owner(+ pub(crate) fn register_in_flight_deferred_response_stage_subresource_fetch_request_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_id: Option<String>,pending: PendingSubresourceFetchRequest,) -> bool {if !self.installed_subresource_fetch_request_is_current(session_id, &pending) {return false;}- self.record_pending_subresource_network_request_identity(session_id, &pending);- self.target_session_owner_mut(session_id)+ self.record_pending_subresource_network_request_identity_for_route(+ session_id,+ owner_route,+ &pending,+ );+ self.target_session_owner_mut_for_route(session_id, owner_route).is_some_and(|mut owner| {owner.register_in_flight_subresource_fetch_request_with_response_match_policy(request_id,@@ -924,14 +975,30 @@ impl CdpConnection {session_id: Option<&str>,request_id: String,pending: PendingSubresourceFetchAuthRequest,+ ) -> bool {+ self.register_pending_subresource_fetch_auth_request_for_route(+ session_id, None, request_id, pending,+ )+ }++ pub(crate) fn register_pending_subresource_fetch_auth_request_for_route(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ request_id: String,+ pending: PendingSubresourceFetchAuthRequest,) -> bool {if !self.target_page_residence_identity_is_current_for_session(session_id, &pending.page_owner){return false;}- self.record_pending_subresource_auth_network_request_identity(session_id, &pending);- self.target_session_owner_mut(session_id)+ self.record_pending_subresource_auth_network_request_identity_for_route(+ session_id,+ owner_route,+ &pending,+ );+ self.target_session_owner_mut_for_route(session_id, owner_route).is_some_and(|mut owner| {owner.register_pending_subresource_fetch_auth_request(request_id, pending)})@@ -942,28 +1009,47 @@ impl CdpConnection {session_id: Option<&str>,request_id: String,pending: PendingSubresourceFetchResponseRequest,+ ) -> bool {+ self.register_pending_subresource_fetch_response_request_for_route(+ session_id, None, request_id, pending,+ )+ }++ pub(crate) fn register_pending_subresource_fetch_response_request_for_route(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ request_id: String,+ pending: PendingSubresourceFetchResponseRequest,) -> bool {if !self.target_page_residence_identity_is_current_for_session(session_id, &pending.page_owner){return false;}- self.record_pending_subresource_response_network_request_identity(session_id, &pending);- self.target_session_owner_mut(session_id)+ self.record_pending_subresource_response_network_request_identity_for_route(+ session_id,+ owner_route,+ &pending,+ );+ self.target_session_owner_mut_for_route(session_id, owner_route).is_some_and(|mut owner| {owner.register_pending_subresource_fetch_response_request(request_id, pending)})}- fn record_pending_subresource_network_request_identity(+ fn record_pending_subresource_network_request_identity_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,pending: &PendingSubresourceFetchRequest,) {let Some(handle) = pending.network_request_handle else {return;};- if let Ok(runtime_slot) = self.runtime_session_owner_slot_mut(session_id) {+ if let Ok(runtime_slot) =+ self.runtime_session_owner_slot_mut_for_route(session_id, owner_route)+ {runtime_slot.record_subresource_request_id_for_handle_if_absent(handle,pending.network_request_id.clone(),@@ -971,15 +1057,18 @@ impl CdpConnection {}}- fn record_pending_subresource_auth_network_request_identity(+ fn record_pending_subresource_auth_network_request_identity_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,pending: &PendingSubresourceFetchAuthRequest,) {let Some(handle) = pending.network_request_handle else {return;};- if let Ok(runtime_slot) = self.runtime_session_owner_slot_mut(session_id) {+ if let Ok(runtime_slot) =+ self.runtime_session_owner_slot_mut_for_route(session_id, owner_route)+ {runtime_slot.record_subresource_request_id_for_handle_if_absent(handle,pending.network_request_id.clone(),@@ -987,15 +1076,18 @@ impl CdpConnection {}}- fn record_pending_subresource_response_network_request_identity(+ fn record_pending_subresource_response_network_request_identity_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,pending: &PendingSubresourceFetchResponseRequest,) {let Some(handle) = pending.network_request_handle else {return;};- if let Ok(runtime_slot) = self.runtime_session_owner_slot_mut(session_id) {+ if let Ok(runtime_slot) =+ self.runtime_session_owner_slot_mut_for_route(session_id, owner_route)+ {runtime_slot.record_subresource_request_id_for_handle_if_absent(handle,pending.network_request_id.clone(),@@ -1009,7 +1101,18 @@ impl CdpConnection {handle_auth_requests: bool,patterns: Vec<FetchInterceptionPattern>,) -> Result<Option<moli_core::page::PendingPageCommand>, String> {- let Some(mut owner) = self.target_session_owner_mut(session_id) else {+ self.start_enable_fetch_for_route(session_id, None, handle_auth_requests, patterns)+ }++ pub(crate) fn start_enable_fetch_for_route(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ handle_auth_requests: bool,+ patterns: Vec<FetchInterceptionPattern>,+ ) -> Result<Option<moli_core::page::PendingPageCommand>, String> {+ let Some(mut owner) = self.target_session_owner_mut_for_route(session_id, owner_route)+ else {return Err("BrowserContextNotLoaded".to_owned());};let Some((subresource_enabled, subresource_resource_type)) = owner.configure_fetch(@@ -1033,16 +1136,19 @@ impl CdpConnection {.map_err(|error| format!("failed to update page fetch interception: {error}"))}- pub(crate) fn start_add_network_intercept_for_session_owner(+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn start_add_network_intercept_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,intercept_session_id: Option<String>,intercept_id: String,handle_auth_requests: bool,auth_url_patterns: Vec<String>,patterns: Vec<FetchInterceptionPattern>,) -> Result<Option<moli_core::page::PendingPageCommand>, String> {- let Some(mut owner) = self.target_session_owner_mut(session_id) else {+ let Some(mut owner) = self.target_session_owner_mut_for_route(session_id, owner_route)+ else {return Err("BrowserContextNotLoaded".to_owned());};let Some((subresource_enabled, subresource_resource_type)) = owner.add_network_intercept(@@ -1068,13 +1174,15 @@ impl CdpConnection {.map_err(|error| format!("failed to update page fetch interception: {error}"))}- pub(crate) fn start_remove_network_intercept_for_session_owner(+ pub(crate) fn start_remove_network_intercept_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,intercept_id: &str,allow_global_lookup: bool,) -> Result<Option<moli_core::page::PendingPageCommand>, String> {- let Some(mut owner) = self.target_session_owner_mut(session_id) else {+ let Some(mut owner) = self.target_session_owner_mut_for_route(session_id, owner_route)+ else {return Err("BrowserContextNotLoaded".to_owned());};let Some((subresource_enabled, subresource_resource_type)) =@@ -1129,7 +1237,22 @@ impl CdpConnection {)>,String,> {- let Some(mut owner) = self.target_session_owner_mut(session_id) else {+ self.start_disable_fetch_for_route(session_id, None)+ }++ pub(crate) fn start_disable_fetch_for_route(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ ) -> Result<+ Option<(+ SessionOwnerPendingFetchState,+ Option<moli_core::page::PendingPageCommand>,+ )>,+ String,+ > {+ let Some(mut owner) = self.target_session_owner_mut_for_route(session_id, owner_route)+ else {return Ok(None);};let Some((pending, (subresource_enabled, subresource_resource_type), page_update_required)) =diff --git a/moli-protocol/src/conn/browser_context/network_owner.rs b/moli-protocol/src/conn/browser_context/network_owner.rsindex f226fd03a..12e053553 100644--- a/moli-protocol/src/conn/browser_context/network_owner.rs+++ b/moli-protocol/src/conn/browser_context/network_owner.rs@@ -620,22 +620,6 @@ impl CdpConnection {.is_ok_and(|runtime_slot| runtime_slot.has_network_event_listeners())}- pub(crate) fn network_backlog_prepared_delivery_for_session_owner(- &mut self,- session_id: Option<&str>,- trigger_session_id: Option<&str>,- primary_session_id: Option<&str>,- preferred_request_id: Option<NetworkBacklogPreferredRequestId<'_>>,- ) -> Option<TargetNetworkBacklogPreparedDelivery> {- self.network_backlog_prepared_delivery_for_route(- session_id,- None,- trigger_session_id,- primary_session_id,- preferred_request_id,- )- }-pub(crate) fn network_backlog_prepared_delivery_for_route(&mut self,session_id: Option<&str>,@@ -938,9 +922,7 @@ impl CdpConnection {self.session_route(session_id),Some(CdpSessionRoute::Browser));- let is_pre_context_root = session_id.is_none()- && self.none_session_owner_route_override().is_none()- && self.browser_context.is_none();+ let is_pre_context_root = session_id.is_none() && self.browser_context.is_none();if !is_browser_session && !is_pre_context_root {return None;}@@ -1114,15 +1096,13 @@ mod tests {conn.browser_context = Some(browser_context);let (active_fetch_id, active_network_request_id) = conn- .allocate_pending_subresource_fetch_request_ids_for_session_owner(Some("SID-active"))+ .allocate_pending_subresource_fetch_request_ids_for_route(Some("SID-active"), None).expect("active owner should allocate request ids");let (background_fetch_id, background_network_request_id) = conn- .allocate_pending_subresource_fetch_request_ids_for_session_owner(Some(- "SID-background",- ))+ .allocate_pending_subresource_fetch_request_ids_for_route(Some("SID-background"), None).expect("background owner should allocate request ids");let (second_active_fetch_id, second_active_network_request_id) = conn- .allocate_pending_subresource_fetch_request_ids_for_session_owner(Some("SID-active"))+ .allocate_pending_subresource_fetch_request_ids_for_route(Some("SID-active"), None).expect("active owner should allocate a second request id");assert_eq!(active_fetch_id, "INT-SUB-1");diff --git a/moli-protocol/src/conn/browser_context/page_owner.rs b/moli-protocol/src/conn/browser_context/page_owner.rsindex 1cb68abfe..4f4952c39 100644--- a/moli-protocol/src/conn/browser_context/page_owner.rs+++ b/moli-protocol/src/conn/browser_context/page_owner.rs@@ -1,10 +1,9 @@use super::target_session_owner::{TargetSessionOwnerMut, TargetSessionStateMut};use super::*;-use crate::conn::PageScreencastConfig;-use crate::conn::TargetRuntimeSlot;use crate::conn::state::DevToolsSessionState;use crate::conn::state::MainDocumentResourceSnapshot;use crate::conn::state::PerformanceTimeDomain;+use crate::conn::{CommandOwnerScope, PageScreencastConfig, TargetRuntimeSlot};pub(crate) struct PageLifecycleReplayTarget {pub(crate) session_id: String,@@ -550,7 +549,15 @@ impl CdpConnection {&self,session_id: Option<&str>,) -> Option<bool> {- self.target_session_owner_ref(session_id)+ self.page_domain_enabled_for_route(session_id, None)+ }++ pub(crate) fn page_domain_enabled_for_route(+ &self,+ session_id: Option<&str>,+ owner_route: Option<&crate::conn::CdpSessionRoute>,+ ) -> Option<bool> {+ self.target_session_owner_ref_for_route(session_id, owner_route).and_then(|owner| owner.devtools_session_state()).map(devtools_session_page_domain_enabled)}@@ -606,9 +613,9 @@ impl CdpConnection {.is_some()}- pub(crate) fn commit_main_document_resource_for_session_owner(+ pub(crate) fn commit_main_document_resource_for_owner(&mut self,- session_id: Option<&str>,+ owner: &crate::conn::CommandOwnerScope,frame_id: String,loader_id: String,url: url::Url,@@ -617,23 +624,27 @@ impl CdpConnection {body: Option<crate::conn::CapturedBody>,) -> bool {if self- .runtime_session_owner_slot(session_id)+ .runtime_session_owner_slot_for_route(owner.session_id(), owner.session_owner_route()).ok().and_then(TargetRuntimeSlot::committed_document_loader_id)!= Some(loader_id.as_str()){return false;}- self.with_target_owner_state_for_session_mut(session_id, |owner_state| {- owner_state.page_resource_store.commit_main_document(- frame_id,- loader_id,- url,- response_headers,- from_cache,- body,- );- })+ self.with_target_owner_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |owner_state| {+ owner_state.page_resource_store.commit_main_document(+ frame_id,+ loader_id,+ url,+ response_headers,+ from_cache,+ body,+ );+ },+ ).is_some()}@@ -660,16 +671,20 @@ impl CdpConnection {.map(|owner_state| owner_state.has_attached_child_frame_id(frame_id))}- pub(crate) fn discard_uncommitted_main_document_resource_for_session_owner(+ pub(crate) fn discard_uncommitted_main_document_resource_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,loader_id: &str,) {- let _ = self.with_target_owner_state_for_session_mut(session_id, |owner_state| {- owner_state- .page_resource_store- .discard_uncommitted_loader(loader_id);- });+ let _ = self.with_target_owner_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |owner_state| {+ owner_state+ .page_resource_store+ .discard_uncommitted_loader(loader_id);+ },+ );}pub(crate) fn set_page_domain_enabled_for_session_owner(@@ -710,21 +725,41 @@ impl CdpConnection {&mut self,session_id: Option<&str>,enabled: bool,+ ) -> bool {+ let owner = crate::conn::CommandOwnerScope::capture(self, session_id);+ self.set_console_enabled_for_owner(&owner, enabled)+ }++ pub(crate) fn set_console_enabled_for_owner(+ &mut self,+ owner: &crate::conn::CommandOwnerScope,+ enabled: bool,) -> bool {let handled = self- .with_target_session_owner_mut(session_id, |owner| owner.set_console_enabled(enabled))+ .with_target_session_owner_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ |owner| owner.set_console_enabled(enabled),+ ).unwrap_or(false);if handled {let renderer_console_agent_owns_page_console_api_events = enabled&& self- .runtime_session_owner_slot(session_id)+ .runtime_session_owner_slot_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).is_ok_and(|slot| slot.has_loaded_page());- let _ = self.with_target_devtools_session_state_for_session_mut(session_id, |state| {- state- .console_output_session_state- .renderer_console_agent_owns_page_console_api_events =- renderer_console_agent_owns_page_console_api_events;- });+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| {+ state+ .console_output_session_state+ .renderer_console_agent_owns_page_console_api_events =+ renderer_console_agent_owns_page_console_api_events;+ },+ );}handled}@@ -733,8 +768,20 @@ impl CdpConnection {&mut self,session_id: Option<&str>,) -> bool {- self.with_target_session_owner_mut(session_id, |owner| owner.clear_console_messages())- .unwrap_or(false)+ let owner = crate::conn::CommandOwnerScope::capture(self, session_id);+ self.clear_console_messages_for_owner(&owner)+ }++ pub(crate) fn clear_console_messages_for_owner(+ &mut self,+ owner: &crate::conn::CommandOwnerScope,+ ) -> bool {+ self.with_target_session_owner_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ |owner| owner.clear_console_messages(),+ )+ .unwrap_or(false)}pub(crate) fn enable_log_for_session_owner(diff --git a/moli-protocol/src/conn/browser_context/runtime_owner.rs b/moli-protocol/src/conn/browser_context/runtime_owner.rsindex 918aa92b9..d1d204d8c 100644--- a/moli-protocol/src/conn/browser_context/runtime_owner.rs+++ b/moli-protocol/src/conn/browser_context/runtime_owner.rs@@ -83,32 +83,36 @@ impl CdpConnection {SessionOwnerInspectorEnableResult::Handled}- pub(crate) fn set_runtime_frontend_enabled_for_session_owner(+ pub(crate) fn set_runtime_frontend_enabled_for_owner(&mut self,- session_id: Option<&str>,+ owner: &crate::conn::CommandOwnerScope,enabled: bool,) -> SessionOwnerRuntimeFrontendEnableResult {let result = self- .with_target_session_owner_mut(session_id, |owner| {- owner.set_runtime_frontend_enabled(enabled)- })+ .with_target_session_owner_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ |owner| owner.set_runtime_frontend_enabled(enabled),+ ).unwrap_or(SessionOwnerRuntimeFrontendEnableResult::UnknownSession);if matches!(result, SessionOwnerRuntimeFrontendEnableResult::Handled) && !enabled {- let _ = self.set_renderer_runtime_agent_owns_page_console_api_events_for_session_owner(- session_id, false,+ let _ = self+ .set_renderer_runtime_agent_owns_page_console_api_events_for_owner(owner, false);+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.clear_child_default_context_emission_state(),);- let _ = self.with_target_devtools_session_state_for_session_mut(session_id, |state| {- state.clear_child_default_context_emission_state();- });}result}- pub(crate) fn set_renderer_runtime_agent_owns_page_console_api_events_for_session_owner(+ pub(crate) fn set_renderer_runtime_agent_owns_page_console_api_events_for_owner(&mut self,- session_id: Option<&str>,+ owner: &crate::conn::CommandOwnerScope,owns: bool,) -> bool {+ let session_id = owner.session_id();if session_id.is_some_and(|session_id| {self.shared_worker_target_for_session(Some(session_id)).is_some()@@ -120,22 +124,27 @@ impl CdpConnection {}let owns = owns&& self- .runtime_session_owner_slot(session_id)+ .runtime_session_owner_slot_for_route(session_id, owner.session_owner_route()).is_ok_and(|slot| slot.has_loaded_page());- self.with_target_devtools_session_state_for_session_mut(session_id, |state| {- state- .console_output_session_state- .renderer_runtime_agent_owns_page_console_api_events = owns;- })+ self.with_target_devtools_session_state_for_route_mut(+ session_id,+ owner.session_owner_route(),+ |state| {+ state+ .console_output_session_state+ .renderer_runtime_agent_owns_page_console_api_events = owns;+ },+ ).is_some()}- pub(crate) fn merge_v8_inspector_session_state_for_session_owner(+ pub(crate) fn merge_v8_inspector_session_state_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,state: V8InspectorSessionState,) -> bool {- self.with_target_devtools_session_state_for_session_mut(session_id, |session| {+ self.with_target_devtools_session_state_for_route_mut(session_id, owner_route, |session| {session.inspector_session_state.v8_state = Some(state);}).is_some()@@ -145,11 +154,9 @@ impl CdpConnection {let Some(route) = self.target_session_route_for_target_id(target_id) else {return false;};- let mut route_scope = self.scoped_none_session_owner_route_override(route);+ let owner = crate::conn::CommandOwnerScope::for_route(route);let enabled = matches!(- route_scope- .conn_mut()- .set_runtime_frontend_enabled_for_session_owner(None, true),+ self.set_runtime_frontend_enabled_for_owner(&owner, true),SessionOwnerRuntimeFrontendEnableResult::Handled);enabled@@ -196,21 +203,11 @@ impl CdpConnection {.await,);}- let mut route_scope = self.scoped_none_session_owner_route_override(route);- let conn = route_scope.conn_mut();- let _ = conn.set_runtime_frontend_enabled_for_session_owner(None, true);- let outcome = conn- .process_message_with_turn_outcome_async(- &json!({- "id": 0_u64,- "method": "Runtime.enable",- "params": {}- })- .to_string(),- )- .await;- let _ = conn.set_runtime_frontend_enabled_for_session_owner(None, true);- Some(outcome)+ let owner = crate::conn::CommandOwnerScope::for_route(route);+ Some(+ self.execute_page_runtime_listener_command_for_owner(owner, true)+ .await,+ )}pub async fn disable_runtime_listener_for_target(@@ -252,19 +249,43 @@ impl CdpConnection {.await,);}- let previous_route = self.replace_none_session_owner_route_override(Some(route));- let outcome = self- .process_message_with_turn_outcome_async(- &json!({- "id": 0_u64,- "method": "Runtime.disable",- "params": {}- })- .to_string(),- )- .await;- self.replace_none_session_owner_route_override(previous_route);- Some(outcome)+ let owner = crate::conn::CommandOwnerScope::for_route(route);+ Some(+ self.execute_page_runtime_listener_command_for_owner(owner, false)+ .await,+ )+ }++ async fn execute_page_runtime_listener_command_for_owner(+ &mut self,+ owner: crate::conn::CommandOwnerScope,+ enabled: bool,+ ) -> CdpRendererOwnerTurnOutcome {+ let session_id = owner.session_id().map(str::to_owned);+ let plan = crate::domains::runtime::execute_runtime_listener_command_for_owner(+ self,+ owner.clone(),+ enabled,+ )+ .await;+ let mut command_context = crate::conn::CommandDispatchContext::default();+ crate::domains::activity::project_protocol_local_command_outputs(+ self,+ &owner,+ &mut command_context,+ )+ .await;+ match self.complete_with_output_plan(+ &mut command_context,+ plan,+ Some(0),+ session_id.as_deref(),+ ) {+ crate::conn::CdpCommandTaskStep::Complete(outcome) => outcome,+ crate::conn::CdpCommandTaskStep::Pending(_) => {+ unreachable!("a completed Runtime listener plan cannot become pending")+ }+ }}fn service_worker_runtime_listener_session_for_route(diff --git a/moli-protocol/src/conn/browser_context/session_owner.rs b/moli-protocol/src/conn/browser_context/session_owner.rsindex 1a85ae7c3..96a6d0105 100644--- a/moli-protocol/src/conn/browser_context/session_owner.rs+++ b/moli-protocol/src/conn/browser_context/session_owner.rs@@ -37,16 +37,12 @@ impl CdpConnection {&self,session_id: Option<&str>,) -> Option<TargetSessionOwner> {- let none_session_owner_route = self.none_session_owner_route_override();- self.target_session_owner_for_route(session_id, none_session_owner_route.as_ref())+ self.target_session_owner_for_route(session_id, None)}- /// Resolves target ownership from an explicit command route.- ///- /// This is the non-ambient owner boundary used while migrating deferred- /// commands away from `none_session_owner_route_override`. A concrete+ /// Resolves target ownership from an explicit command route. A concrete/// session always resolves through the session registry; `owner_route`- /// only selects the owner of an implicit primary Page attachment.+ /// selects the owner of an internal command without a CDP session.pub(super) fn target_session_owner_for_route(&self,session_id: Option<&str>,diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rsindex 7f74919e7..b2d17f7db 100644--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs@@ -7,8 +7,8 @@ use crate::conn::state::{TargetPageResidenceIdentity, TargetRuntimeSessionState, TargetRuntimeSlot,};use crate::conn::{- BackgroundProtocolEvent, ConnectionNetworkRequestIdAllocator, DocumentStartScript,- EmulatedDeviceMetrics, FetchInterceptionPattern, FetchRequestStage,+ BackgroundProtocolEvent, CommandOwnerScope, ConnectionNetworkRequestIdAllocator,+ DocumentStartScript, EmulatedDeviceMetrics, FetchInterceptionPattern, FetchRequestStage,InitialDocumentPageInstallResult, InitialDocumentPageOwner, LoadedNavigationPageCommit,LoadedNavigationRendererAttachmentCommit, NETWORK_ERROR_PAGE_URL, NetworkErrorPageNavigation,PausedDocumentTransfer, PendingFetchAuthNavigation, PendingFetchNavigation,@@ -1356,22 +1356,6 @@ impl CdpConnection {.and_then(|owner| owner.navigation_initiator_url())}- pub(crate) fn prepare_navigation_request_for_session_owner(- &mut self,- session_id: Option<&str>,- requested_url: &Url,- referrer: Option<&str>,- is_data_url: bool,- ) -> Option<TargetNavigationRequestPreflight> {- self.prepare_navigation_request_for_route(- session_id,- None,- requested_url,- referrer,- is_data_url,- )- }-pub(crate) fn prepare_navigation_request_for_route(&mut self,session_id: Option<&str>,@@ -1401,14 +1385,6 @@ impl CdpConnection {result}- pub(crate) fn register_pending_fetch_navigation_request_for_session_owner(- &mut self,- session_id: Option<&str>,- pending: PendingFetchNavigation,- ) -> Option<()> {- self.register_pending_fetch_navigation_request_for_route(session_id, None, pending)- }-pub(crate) fn register_pending_fetch_navigation_request_for_route(&mut self,session_id: Option<&str>,@@ -1419,32 +1395,32 @@ impl CdpConnection {.register_pending_fetch_navigation_request(pending)}- pub(crate) fn prepare_loaded_navigation_commit_for_session_owner(+ pub(crate) fn prepare_loaded_navigation_commit_for_owner(&mut self,- session_id: Option<&str>,+ owner: &crate::conn::CommandOwnerScope,) -> Option<TargetLoadedNavigationCommitState> {- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(owner.session_id(), owner.session_owner_route())?.prepare_loaded_navigation_commit()}- pub(crate) fn commit_loaded_navigation_target_identity_for_session_owner(+ pub(crate) fn commit_loaded_navigation_target_identity_for_owner(&mut self,- session_id: Option<&str>,+ owner: &crate::conn::CommandOwnerScope,main_document_commit: &RendererMainDocumentCommit,target_url: &Url,) -> Option<()> {- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(owner.session_id(), owner.session_owner_route())?.commit_loaded_navigation_target_identity(main_document_commit, target_url)}- pub(crate) async fn commit_loaded_navigation_page_for_session_owner_async(+ pub(crate) async fn commit_loaded_navigation_page_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &crate::conn::CommandOwnerScope,page: Page,renderer_attachment_commit: LoadedNavigationRendererAttachmentCommit,history_url: &Url,) -> Option<anyhow::Result<LoadedNavigationPageCommit>> {- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(owner.session_id(), owner.session_owner_route())?.commit_loaded_navigation_page_async(page, renderer_attachment_commit, history_url).await}@@ -1514,11 +1490,11 @@ impl CdpConnection {Ok(InitialDocumentPageInstallResult::Installed)}- pub(crate) fn clear_pending_navigation_history_update_for_session_owner(+ pub(crate) fn clear_pending_navigation_history_update_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Option<()> {- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(owner.session_id(), owner.session_owner_route())?.clear_pending_navigation_history_update()}@@ -1532,12 +1508,12 @@ impl CdpConnection {.await}- pub(crate) async fn discard_loaded_page_after_failed_navigation_for_session_owner_async(+ pub(crate) async fn discard_loaded_page_after_failed_navigation_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,final_url: &Url,) -> Option<()> {- self.target_session_owner_mut(session_id)?+ self.target_session_owner_mut_for_route(owner.session_id(), owner.session_owner_route())?.discard_loaded_page_after_failed_navigation_async(final_url).await}@@ -1797,20 +1773,31 @@ impl CdpConnection {.runtime_session_state()}- pub(crate) fn target_runtime_bindings_for_renderer_session_owner(+ pub(crate) fn target_runtime_session_state_for_route(&self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ ) -> Option<&TargetRuntimeSessionState> {+ self.target_session_owner_ref_for_route(session_id, owner_route)?+ .runtime_session_state()+ }++ pub(crate) fn target_runtime_bindings_for_renderer_route(+ &self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> Vec<RuntimeBindingDefinition> {- self.target_session_owner_ref(session_id)+ self.target_session_owner_ref_for_route(session_id, owner_route).map(|owner| owner.runtime_bindings_for_renderer()).unwrap_or_default()}- pub(crate) fn target_runtime_bindings_for_current_inspector_session_owner(+ pub(crate) fn target_runtime_bindings_for_current_inspector_route(&self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> Vec<RuntimeBindingDefinition> {- self.target_session_owner_ref(session_id)+ self.target_session_owner_ref_for_route(session_id, owner_route).and_then(|owner| owner.devtools_session_state()).map(|state| state.runtime_bindings.clone()).unwrap_or_default()@@ -1848,17 +1835,6 @@ impl CdpConnection {.target_owner_state()}- pub(crate) fn target_owner_has_bidi_channel_preload_script_for_session(- &self,- session_id: Option<&str>,- ) -> bool {- let none_session_owner_route = self.none_session_owner_route_override();- self.target_owner_has_bidi_channel_preload_script_for_route(- session_id,- none_session_owner_route.as_ref(),- )- }-pub(crate) fn target_owner_has_bidi_channel_preload_script_for_route(&self,session_id: Option<&str>,@@ -1954,6 +1930,13 @@ impl CdpConnection {session_id: Option<&str>,owner_route: Option<&CdpSessionRoute>,) -> Option<(String, Option<String>)> {+ if session_id.is_none()+ && let Some(CdpSessionRoute::BrowserContext { browser_context_id }) = owner_route+ {+ return self+ .browser_context_by_id(browser_context_id)+ .map(|_| (browser_context_id.clone(), None));+ }self.target_session_owner_ref_for_route(session_id, owner_route)?.owner_identity()}@@ -1969,8 +1952,7 @@ impl CdpConnection {&self,session_id: Option<&str>,) -> Option<TargetPageResidenceIdentity> {- let none_session_owner_route = self.none_session_owner_route_override();- self.target_page_residence_identity_for_route(session_id, none_session_owner_route.as_ref())+ self.target_page_residence_identity_for_route(session_id, None)}pub(crate) fn target_page_residence_identity_for_route(@@ -2006,17 +1988,6 @@ impl CdpConnection {/// before protocol commits that Page into the target slot. The reservation/// therefore owns an explicit attachment id before renderer work starts;/// callers never predict that identity from mutable current-Page state.- pub(crate) fn pending_target_page_residence_identity_for_session(- &self,- session_id: Option<&str>,- ) -> Option<TargetPageResidenceIdentity> {- let none_session_owner_route = self.none_session_owner_route_override();- self.pending_target_page_residence_identity_for_route(- session_id,- none_session_owner_route.as_ref(),- )- }-pub(crate) fn pending_target_page_residence_identity_for_route(&self,session_id: Option<&str>,@@ -2077,17 +2048,12 @@ impl CdpConnection {})}- /// Captures the lifetime of the concrete Page attachment currently- /// addressed by `session_id`.- ///- /// The returned token is owned by that attachment rather than by a numeric- /// slot generation. Moving the whole target slot preserves it; replacing- /// or clearing the installed Page terminates it directly.- pub(crate) fn capture_target_page_residence_token_for_session(+ pub(crate) fn capture_target_page_residence_token_for_route(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> Option<crate::conn::TargetPageResidenceToken> {- self.runtime_session_owner_slot_mut(session_id)+ self.runtime_session_owner_slot_mut_for_route(session_id, owner_route).ok()?.page_slot_mut().page_residence_token()@@ -2115,14 +2081,22 @@ impl CdpConnection {/// Captures the renderer-side identity of the Page currently addressed by/// `session_id`.///- /// Callers must capture this while any `None`-session owner-route override- /// is active. The returned identity is self-contained and must not be- /// reconstructed later from a session that may then address another Page.+ /// The returned identity is self-contained and must not be reconstructed+ /// later from a session that may then address another Page.+ #[cfg(test)]pub(crate) fn renderer_page_residence_identity_for_session_owner(&self,session_id: Option<&str>,) -> Option<crate::conn::RendererPageResidenceIdentity> {- self.runtime_session_owner_slot(session_id)+ self.renderer_page_residence_identity_for_route(session_id, None)+ }++ pub(crate) fn renderer_page_residence_identity_for_route(+ &self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ ) -> Option<crate::conn::RendererPageResidenceIdentity> {+ self.runtime_session_owner_slot_for_route(session_id, owner_route).ok()?.loaded_page().map(crate::conn::RendererPageResidenceIdentity::from_page)@@ -2138,22 +2112,36 @@ impl CdpConnection {/// time. Looking it up again during drain could route an old Page's/// response or notification through a replacement Page or an unrelated/// contextual command session.- pub(crate) fn target_page_protocol_attachment_identity_for_renderer_inspector_route(+ pub(crate) fn target_page_protocol_attachment_identity_for_renderer_inspector_owner(&self,- source_session_id: Option<&str>,+ source_owner: &crate::conn::CommandOwnerScope,renderer_inspector_session_id: Option<&str>,) -> Option<crate::conn::TargetPageProtocolAttachmentIdentity> {- let source =- self.target_page_protocol_attachment_identity_for_session(source_session_id)?;+ let source = self.target_page_protocol_attachment_identity_for_route(+ source_owner.session_id(),+ source_owner.session_owner_route(),+ )?;let protocol_session_id = renderer_inspector_session_id.map(str::to_owned)- .or_else(|| self.runtime_session_owner_primary_session_id(source_session_id));- let attachment = self- .target_page_protocol_attachment_identity_for_session(protocol_session_id.as_deref())?;+ .or_else(|| {+ self.runtime_session_owner_primary_session_id_for_route(+ source_owner.session_id(),+ source_owner.session_owner_route(),+ )+ });+ let protocol_owner_route = protocol_session_id+ .is_none()+ .then(|| source_owner.session_owner_route())+ .flatten();+ let attachment = self.target_page_protocol_attachment_identity_for_route(+ protocol_session_id.as_deref(),+ protocol_owner_route,+ )?;if attachment.page_owner() != source.page_owner()|| self- .target_renderer_runtime_inspector_session_id_for_session(+ .target_renderer_runtime_inspector_session_id_for_route(protocol_session_id.as_deref(),+ protocol_owner_route,).as_deref()!= renderer_inspector_session_id@@ -2169,10 +2157,13 @@ impl CdpConnection {&self,expected: &crate::conn::TargetPageProtocolAttachmentIdentity,) -> bool {- self.target_page_residence_identity_is_current_for_session(- expected.session_id(),- expected.page_owner(),- )+ if let Some(session_id) = expected.session_id() {+ return self+ .target_page_protocol_attachment_identity_for_session(Some(session_id))+ .as_ref()+ == Some(expected);+ }+ self.target_page_residence_identity_is_current_for_session(None, expected.page_owner())}/// Binds renderer-produced child-frame activity to the Page attachment@@ -2220,13 +2211,6 @@ impl CdpConnection {== Some(expected.root_document())}- pub(crate) fn target_root_document_lifecycle_identity_for_session(- &self,- session_id: Option<&str>,- ) -> Option<moli_core::RendererDocumentLifecycleIdentity> {- self.target_root_document_lifecycle_identity_for_route(session_id, None)- }-pub(crate) fn target_root_document_lifecycle_identity_for_route(&self,session_id: Option<&str>,@@ -2327,8 +2311,7 @@ impl CdpConnection {&mut self,session_id: Option<&str>,) -> Result<&mut TargetRuntimeSlot, String> {- let none_session_owner_route = self.none_session_owner_route_override();- self.runtime_session_owner_slot_mut_for_route(session_id, none_session_owner_route.as_ref())+ self.runtime_session_owner_slot_mut_for_route(session_id, None)}pub(crate) fn runtime_session_owner_slot_mut_for_route(@@ -2352,8 +2335,7 @@ impl CdpConnection {&self,session_id: Option<&str>,) -> Result<&TargetRuntimeSlot, String> {- let none_session_owner_route = self.none_session_owner_route_override();- self.runtime_session_owner_slot_for_route(session_id, none_session_owner_route.as_ref())+ self.runtime_session_owner_slot_for_route(session_id, None)}pub(crate) fn runtime_session_owner_slot_for_route(@@ -2439,8 +2421,12 @@ impl CdpConnection {self.page_event_session_ids_for_route(session_id, owner_route).into_iter().filter(|event_session_id| {- self.target_page_session_state_for_session(event_session_id.as_deref())- .is_some_and(|state| state.page_domain_enabled)+ let event_owner_route = event_session_id.is_none().then_some(owner_route).flatten();+ self.target_page_session_state_for_route(+ event_session_id.as_deref(),+ event_owner_route,+ )+ .is_some_and(|state| state.page_domain_enabled)}).collect()}@@ -2453,17 +2439,21 @@ impl CdpConnection {/// identities, but must never call `page_event_session_ids_for_session_owner`/// again: doing so could route an old Page's historical event through a/// replacement Page or a newly active implicit attachment.- pub(crate) fn page_event_protocol_attachments_for_session_owner(+ pub(crate) fn page_event_protocol_attachments_for_route(&self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> Option<Vec<crate::conn::TargetPageProtocolAttachmentIdentity>> {- let source = self.target_page_protocol_attachment_identity_for_session(session_id)?;+ let source =+ self.target_page_protocol_attachment_identity_for_route(session_id, owner_route)?;let attachments = self- .subscribed_page_event_session_ids_for_session_owner(session_id)+ .subscribed_page_event_session_ids_for_route(session_id, owner_route).into_iter().map(|event_session_id| {- self.target_page_protocol_attachment_identity_for_session(+ let event_owner_route = event_session_id.is_none().then_some(owner_route).flatten();+ self.target_page_protocol_attachment_identity_for_route(event_session_id.as_deref(),+ event_owner_route,)}).collect::<Option<Vec<_>>>()?;@@ -2481,21 +2471,29 @@ impl CdpConnection {/// once per Inspector session. Freeze the audience at ingress so a later/// detach, target replacement, or `Runtime.enable` cannot retarget that/// historical fact.- pub(crate) fn runtime_event_protocol_attachments_for_session_owner(+ pub(crate) fn runtime_event_protocol_attachments_for_route(&self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,) -> Option<Vec<crate::conn::TargetPageProtocolAttachmentIdentity>> {- let source = self.target_page_protocol_attachment_identity_for_session(session_id)?;+ let source =+ self.target_page_protocol_attachment_identity_for_route(session_id, owner_route)?;let attachments = self- .page_event_session_ids_for_session_owner(session_id)+ .page_event_session_ids_for_route(session_id, owner_route).into_iter().filter(|event_session_id| {- self.target_runtime_session_state_for_session(event_session_id.as_deref())- .is_some_and(|state| state.runtime_frontend_enabled)+ let event_owner_route = event_session_id.is_none().then_some(owner_route).flatten();+ self.target_runtime_session_state_for_route(+ event_session_id.as_deref(),+ event_owner_route,+ )+ .is_some_and(|state| state.runtime_frontend_enabled)}).map(|event_session_id| {- self.target_page_protocol_attachment_identity_for_session(+ let event_owner_route = event_session_id.is_none().then_some(owner_route).flatten();+ self.target_page_protocol_attachment_identity_for_route(event_session_id.as_deref(),+ event_owner_route,)}).collect::<Option<Vec<_>>>()?;@@ -2590,14 +2588,6 @@ impl CdpConnection {.frame_tree_identity()}- pub(crate) fn target_session_owner_frame_tree_loader_id(- &self,- session_id: Option<&str>,- ) -> Option<String> {- self.target_session_owner_ref(session_id)?- .frame_tree_loader_id()- }-pub(crate) fn target_session_owner_frame_tree_loader_id_for_route(&self,session_id: Option<&str>,@@ -2712,8 +2702,7 @@ impl CdpConnection {&mut self,session_id: Option<&str>,) -> Option<TargetSessionOwnerMut<'_>> {- let none_session_owner_route = self.none_session_owner_route_override();- self.target_session_owner_mut_for_route(session_id, none_session_owner_route.as_ref())+ self.target_session_owner_mut_for_route(session_id, None)}pub(super) fn target_session_owner_mut_for_route(@@ -2744,8 +2733,7 @@ impl CdpConnection {&self,session_id: Option<&str>,) -> Option<TargetSessionOwnerRef<'_>> {- let none_session_owner_route = self.none_session_owner_route_override();- self.target_session_owner_ref_for_route(session_id, none_session_owner_route.as_ref())+ self.target_session_owner_ref_for_route(session_id, None)}pub(super) fn target_session_owner_ref_for_route(@@ -2976,24 +2964,24 @@ mod tests {);let default_route = conn- .target_page_protocol_attachment_identity_for_renderer_inspector_route(- Some("SID-active-aux"),+ .target_page_protocol_attachment_identity_for_renderer_inspector_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-active-aux"),None,).expect("default inspector route should resolve through the target primary session");assert_eq!(default_route.session_id(), Some("SID-active-primary"));let auxiliary_route = conn- .target_page_protocol_attachment_identity_for_renderer_inspector_route(- Some("SID-active-primary"),+ .target_page_protocol_attachment_identity_for_renderer_inspector_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-active-primary"),Some("SID-active-aux"),).expect("auxiliary inspector route should retain its exact protocol attachment");assert_eq!(auxiliary_route.session_id(), Some("SID-active-aux"));assert!(- conn.target_page_protocol_attachment_identity_for_renderer_inspector_route(- Some("SID-active-primary"),+ conn.target_page_protocol_attachment_identity_for_renderer_inspector_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-active-primary"),Some("SID-background-aux"),).is_none(),@@ -3837,8 +3825,11 @@ mod tests {"a reservation must not masquerade as the current Page");assert!(- conn.pending_target_page_residence_identity_for_session(Some("SID-pending-residence"))- .is_some(),+ conn.pending_target_page_residence_identity_for_route(+ Some("SID-pending-residence"),+ None,+ )+ .is_some(),"the future Page attachment should remain explicitly addressable");}@@ -3863,8 +3854,13 @@ mod tests {.expect("browser context").set_active_target_id("TID-replacement");assert!(- !conn.target_page_residence_identity_is_current_for_session(None, &original),- "an implicit route must not let the old Page identity follow a new active target"+ conn.target_page_residence_identity_is_current_for_session(None, &original),+ "changing visibility must not retire the original stable Page residence"+ );+ assert_ne!(+ conn.target_page_residence_identity_for_session(None),+ Some(original),+ "a fresh implicit lookup must follow the new active target without mutating the old identity");}@@ -4005,7 +4001,7 @@ mod tests {}).expect("Runtime-enabled auxiliary session should be mutable");assert_eq!(- conn.runtime_event_protocol_attachments_for_session_owner(Some("SID-runtime-a"))+ conn.runtime_event_protocol_attachments_for_route(Some("SID-runtime-a"), None).expect("the current Page should expose its Runtime audience").into_iter().map(|attachment| attachment.session_id().map(str::to_owned))@@ -4019,7 +4015,7 @@ mod tests {}).expect("Runtime-enabled primary session should be mutable");assert_eq!(- conn.runtime_event_protocol_attachments_for_session_owner(Some("SID-runtime-b"))+ conn.runtime_event_protocol_attachments_for_route(Some("SID-runtime-b"), None).expect("the current Page should expose its Runtime audience").into_iter().map(|attachment| attachment.session_id().map(str::to_owned))diff --git a/moli-protocol/src/conn/command_owner_scope.rs b/moli-protocol/src/conn/command_owner_scope.rsindex 65635223f..5503a0c38 100644--- a/moli-protocol/src/conn/command_owner_scope.rs+++ b/moli-protocol/src/conn/command_owner_scope.rs@@ -1,6 +1,6 @@use super::{- CdpConnection, CdpSessionRoute, NoneSessionOwnerRouteOverrideScope,- TargetPageProtocolAttachmentIdentity,+ CdpConnection, CdpSessionRoute, TargetPageProtocolAttachmentIdentity,+ TargetPageResidenceIdentity,};#[derive(Clone, Debug, PartialEq, Eq)]@@ -11,29 +11,42 @@ pub(crate) struct CommandOwnerScope {#[derive(Clone, Debug, PartialEq, Eq)]enum CommandOwnerIdentity {Session(String),- ImplicitRoute(CdpSessionRoute),- Implicit,+ Route(CdpSessionRoute),}impl CommandOwnerScope {pub(crate) fn capture(conn: &CdpConnection, session_id: Option<&str>) -> Self {- let none_session_owner_route = session_id- .is_none()- .then(|| {- conn.none_session_owner_route_override().or_else(|| {- let browser_context = conn.browser_context.as_ref()?;- let target_id = browser_context.active_target_id_owned()?;- Some(CdpSessionRoute::PageTarget {- browser_context_id: browser_context.id.clone(),- target_id,- is_attached_session: false,- })- })- })- .flatten();match session_id {Some(session_id) => Self::for_session(session_id),- None => Self::for_implicit_route(none_session_owner_route),+ None => Self::for_route(Self::capture_default_route(conn)),+ }+ }++ pub(crate) fn capture_for_route(+ conn: &CdpConnection,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ ) -> Self {+ match (session_id, owner_route) {+ (Some(session_id), _) => Self::for_session(session_id),+ (None, Some(route)) => Self::for_route(route.clone()),+ (None, None) => Self::capture(conn, None),+ }+ }++ fn capture_default_route(conn: &CdpConnection) -> CdpSessionRoute {+ let Some(browser_context) = conn.browser_context.as_ref() else {+ return CdpSessionRoute::Browser;+ };+ match browser_context.active_target_id_owned() {+ Some(target_id) => CdpSessionRoute::PageTarget {+ browser_context_id: browser_context.id.clone(),+ target_id,+ is_attached_session: false,+ },+ None => CdpSessionRoute::BrowserContext {+ browser_context_id: browser_context.id.clone(),+ },}}@@ -43,12 +56,9 @@ impl CommandOwnerScope {}}- pub(crate) fn for_implicit_route(session_owner_route: Option<CdpSessionRoute>) -> Self {+ pub(crate) fn for_route(route: CdpSessionRoute) -> Self {Self {- identity: match session_owner_route {- Some(route) => CommandOwnerIdentity::ImplicitRoute(route),- None => CommandOwnerIdentity::Implicit,- },+ identity: CommandOwnerIdentity::Route(route),}}@@ -56,7 +66,10 @@ impl CommandOwnerScope {if let Some(session_id) = attachment.session_id() {return Self::for_session(session_id);}- let page = attachment.page_owner();+ Self::for_page_residence(attachment.page_owner())+ }++ pub(crate) fn for_page_residence(page: &TargetPageResidenceIdentity) -> Self {let route = match page.target_id() {Some(target_id) => CdpSessionRoute::PageTarget {browser_context_id: page.browser_context_id().to_owned(),@@ -67,35 +80,29 @@ impl CommandOwnerScope {browser_context_id: page.browser_context_id().to_owned(),},};- Self::for_implicit_route(Some(route))+ Self::for_route(route)}pub(crate) fn session_id(&self) -> Option<&str> {match &self.identity {CommandOwnerIdentity::Session(session_id) => Some(session_id),- CommandOwnerIdentity::ImplicitRoute(_) | CommandOwnerIdentity::Implicit => None,+ CommandOwnerIdentity::Route(_) => None,}}- /// Returns the exact route captured for an implicit-session command.+ /// Returns the explicit route captured for a command without a session.////// A concrete CDP session remains authoritative through `session_id`; the- /// route freezes Chromium's implicit primary Page attachment at command- /// admission, so deferred completion cannot follow a later foreground- /// selection.+ /// route freezes Chromium's primary Page attachment at command admission+ /// whenever no more explicit route was supplied. `Browser` and+ /// `BrowserContext` remain explicit authorities rather than a missing+ /// owner that can silently acquire a later active Page.pub(crate) fn session_owner_route(&self) -> Option<&CdpSessionRoute> {match &self.identity {- CommandOwnerIdentity::ImplicitRoute(route) => Some(route),- CommandOwnerIdentity::Session(_) | CommandOwnerIdentity::Implicit => None,+ CommandOwnerIdentity::Route(route) => Some(route),+ CommandOwnerIdentity::Session(_) => None,}}-- pub(crate) fn enter<'a>(- &self,- conn: &'a mut CdpConnection,- ) -> NoneSessionOwnerRouteOverrideScope<'a> {- conn.scoped_optional_none_session_owner_route_override(self.session_owner_route().cloned())- }}#[cfg(test)]@@ -104,7 +111,7 @@ mod tests {use crate::conn::BrowserContext;#[test]- fn implicit_scope_freezes_the_concrete_active_target() {+ fn root_page_scope_freezes_the_concrete_active_target() {let mut conn = CdpConnection::default();let mut browser_context = BrowserContext::new("BID-scope".to_owned());browser_context.set_active_target_id("TID-original");@@ -121,4 +128,28 @@ mod tests {Some(("BID-scope".to_owned(), Some("TID-original".to_owned()))));}++ #[test]+ fn root_scope_without_a_browser_context_has_explicit_browser_authority() {+ let conn = CdpConnection::default();++ let scope = CommandOwnerScope::capture(&conn, None);++ assert_eq!(scope.session_owner_route(), Some(&CdpSessionRoute::Browser));+ }++ #[test]+ fn root_scope_without_a_page_has_explicit_browser_context_authority() {+ let mut conn = CdpConnection::default();+ conn.browser_context = Some(BrowserContext::new("BID-empty".to_owned()));++ let scope = CommandOwnerScope::capture(&conn, None);++ assert_eq!(+ scope.session_owner_route(),+ Some(&CdpSessionRoute::BrowserContext {+ browser_context_id: "BID-empty".to_owned(),+ })+ );+ }}diff --git a/moli-protocol/src/conn/devtools_command.rs b/moli-protocol/src/conn/devtools_command.rsindex 688ebe9f5..5c1c4f8fa 100644--- a/moli-protocol/src/conn/devtools_command.rs+++ b/moli-protocol/src/conn/devtools_command.rs@@ -392,7 +392,7 @@ impl CdpConnection {.is_some_and(|browser_context| {browser_context.has_default_bidi_channel_preload_script()});- let command_owner = CommandOwnerScope::for_implicit_route(Some(route.clone()));+ let command_owner = CommandOwnerScope::for_route(route.clone());let mut initial_runtime_execution_context_ids = Vec::new();let mut renderer_output_predecessor = None;let pending = match self.start_initial_document_page_ensure_for_owner(&command_owner) {@@ -492,39 +492,26 @@ impl CdpConnection {if self.has_pending_javascript_dialog() {return;}- let mut session_id = context+ let session_id = context.session_id.as_ref().map(|session_id| session_id.as_str());- let none_session_owner_route = match context.target_id.as_ref() {+ let owner = match context.target_id.as_ref() {Some(target_id) => {let Some(route) = self.target_session_route_for_target_id(target_id.as_str())else {return;};- session_id = None;- Some(route)+ CommandOwnerScope::for_route(route)}- None => None,+ None => CommandOwnerScope::capture(self, session_id),};- if let Some(route) = none_session_owner_route {- let mut route_scope = self.scoped_none_session_owner_route_override(route);- crate::domains::activity::project_protocol_local_command_outputs(- route_scope.conn_mut(),- session_id,- dispatch_context,- )- .await;- let turn_events = dispatch_context.take_protocol_events();- protocol_events.extend(turn_events);- } else {- crate::domains::activity::project_protocol_local_command_outputs(- self,- session_id,- dispatch_context,- )- .await;- protocol_events.extend(dispatch_context.take_protocol_events());- }+ crate::domains::activity::project_protocol_local_command_outputs(+ self,+ &owner,+ dispatch_context,+ )+ .await;+ protocol_events.extend(dispatch_context.take_protocol_events());}}diff --git a/moli-protocol/src/conn/dispatch.rs b/moli-protocol/src/conn/dispatch.rsindex 3ed8cbe57..7a315aab7 100644--- a/moli-protocol/src/conn/dispatch.rs+++ b/moli-protocol/src/conn/dispatch.rs@@ -8,13 +8,11 @@ use super::*;pub struct PendingCdpCommandDispatch {inner: PendingCdpCommandDispatchKind,- owner_scope: Option<CommandOwnerScope>,scheduler_events: Vec<CdpSchedulerEvent>,}pub struct CompletedCdpCommandDispatch {inner: CompletedCdpCommandDispatchKind,- owner_scope: Option<CommandOwnerScope>,}pub enum CdpCommandTaskStep {@@ -105,31 +103,6 @@ impl PendingCdpCommandDispatchKind {Self::Tracing(_) => "Tracing",}}-- fn owner_scope_capture_session_id(&self) -> Option<Option<&str>> {- match self {- Self::Input(pending) => Some(pending.session_id()),- Self::Dom(pending) => Some(pending.session_id()),- Self::Tracing(pending) => Some(pending.session_id()),- Self::Runtime(_)- | Self::Autofill(_)- | Self::Accessibility(_)- | Self::Css(_)- | Self::DomDebugger(_)- | Self::DomSnapshot(_)- | Self::Performance(_)- | Self::DomStorage(_)- | Self::Page(_)- | Self::Emulation(_)- | Self::Storage(_)- | Self::Fetch(_)- | Self::Io(_)- | Self::Security(_)- | Self::Browser(_)- | Self::Target(_) => None,- Self::Network(pending) => Some(pending.session_id()),- }- }}impl CompletedCdpCommandDispatchKind {@@ -160,20 +133,9 @@ impl CompletedCdpCommandDispatchKind {}impl PendingCdpCommandDispatch {- fn new(- conn: &CdpConnection,- inner: PendingCdpCommandDispatchKind,- scheduler_events: Vec<CdpSchedulerEvent>,- ) -> Self {- let owner_scope = inner- // These domain-local session ids are still used for CDP response- // routing and session-local lookups. Target ownership for their- // pending completion is captured here by the wrapper.- .owner_scope_capture_session_id()- .map(|session_id| CommandOwnerScope::capture(conn, session_id));+ fn new(inner: PendingCdpCommandDispatchKind, scheduler_events: Vec<CdpSchedulerEvent>) -> Self {Self {inner,- owner_scope,scheduler_events,}}@@ -208,6 +170,14 @@ impl PendingCdpCommandDispatch {}}+ #[cfg(test)]+ pub(crate) fn runtime_command_owner_scope(&self) -> Option<&CommandOwnerScope> {+ match &self.inner {+ PendingCdpCommandDispatchKind::Runtime(pending) => Some(pending.owner_scope()),+ _ => None,+ }+ }+pub fn runtime_command_executes_page_javascript(&self) -> bool {match &self.inner {PendingCdpCommandDispatchKind::Runtime(pending) => pending.executes_page_javascript(),@@ -270,7 +240,6 @@ impl PendingCdpCommandDispatch {inner: CompletedCdpCommandDispatchKind::Runtime(Box::new(pending.complete_scheduler_deferred_inspector_reply(conn),)),- owner_scope: None,},_ => {unreachable!(@@ -368,10 +337,7 @@ impl PendingCdpCommandDispatch {elapsed_us = %started.elapsed().as_micros(),);}- CompletedCdpCommandDispatch {- inner,- owner_scope: self.owner_scope,- }+ CompletedCdpCommandDispatch { inner }}}@@ -434,7 +400,7 @@ impl CdpConnection {)}- fn complete_with_output_plan(+ pub(super) fn complete_with_output_plan(&mut self,command_context: &mut CommandDispatchContext,plan: CommandOutputPlan,@@ -455,7 +421,6 @@ impl CdpConnection {fn pending_step(&mut self, inner: PendingCdpCommandDispatchKind) -> CdpCommandTaskStep {let scheduler_events = self.take_scheduler_events();CdpCommandTaskStep::Pending(Box::new(PendingCdpCommandDispatch::new(- self,inner,scheduler_events,)))@@ -917,22 +882,6 @@ impl CdpConnection {}pub async fn complete_pending_command_dispatch_with_context(- &mut self,- mut completed: CompletedCdpCommandDispatch,- command_context: &mut CommandDispatchContext,- ) -> CdpCommandTaskStep {- if let Some(owner_scope) = completed.owner_scope.take() {- let mut scope = owner_scope.enter(self);- return scope- .conn_mut()- .complete_pending_command_dispatch_in_current_owner(completed, command_context)- .await;- }- self.complete_pending_command_dispatch_in_current_owner(completed, command_context)- .await- }-- async fn complete_pending_command_dispatch_in_current_owner(&mut self,completed: CompletedCdpCommandDispatch,command_context: &mut CommandDispatchContext,@@ -1370,6 +1319,7 @@ impl CdpConnection {.ok().and_then(ParsedCdpCommand::command_output_session_id).map(str::to_owned);+ let output_owner = CommandOwnerScope::capture(self, output_session_id.as_deref());let mut protocol_events = Vec::new();let mut post_renderer_output_events = Vec::new();let mut renderer_output_boundary = None;@@ -1431,7 +1381,7 @@ impl CdpConnection {Box::pin(crate::domains::activity::project_protocol_local_command_outputs(self,- output_session_id.as_deref(),+ &output_owner,&mut command_context,),)diff --git a/moli-protocol/src/conn/dispatch_tests.rs b/moli-protocol/src/conn/dispatch_tests.rsindex 3e81f54f8..64a63651d 100644--- a/moli-protocol/src/conn/dispatch_tests.rs+++ b/moli-protocol/src/conn/dispatch_tests.rs@@ -224,19 +224,15 @@ async fn ensure_initial_document_for_target_id_for_test(let route = conn.target_session_route_for_target_id(target_id.as_str()).unwrap_or_else(|| panic!("target route should exist for {}", target_id.as_str()));- let pending = {- let previous_route = conn.replace_none_session_owner_route_override(Some(route));- let pending = conn- .start_initial_document_page_ensure_for_session_owner(None)- .unwrap_or_else(|message| {- panic!(- "target lifecycle ensure should start for {}: {message}",- target_id.as_str()- )- });- conn.replace_none_session_owner_route_override(previous_route);- pending- };+ let owner = CommandOwnerScope::for_route(route);+ let pending = conn+ .start_initial_document_page_ensure_for_owner(&owner)+ .unwrap_or_else(|message| {+ panic!(+ "target lifecycle ensure should start for {}: {message}",+ target_id.as_str()+ )+ });let Some(pending) = pending else {return;};@@ -376,6 +372,27 @@ async fn complete_command_task_for_test(}}+async fn attach_page_session_for_test(conn: &mut CdpConnection, target_id: &str) -> String {+ let raw = serde_json::to_string(&json!({+ "id": 9_900_001,+ "method": "Target.attachToTarget",+ "params": { "targetId": target_id, "flatten": true }+ }))+ .expect("attach command should serialize");+ let messages = match conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(pending) => {+ complete_command_task_for_test(conn, *pending).await+ }+ CdpCommandTaskStep::Complete(outcome) => outcome.into_parts().0,+ };+ messages+ .iter()+ .find(|message| message["id"] == json!(9_900_001))+ .and_then(|message| message["result"]["sessionId"].as_str())+ .unwrap_or_else(|| panic!("attachToTarget should return a session: {messages:?}"))+ .to_owned()+}+#[tokio::test]async fn devtools_browser_context_create_uses_ephemeral_storage_partition() {let initial_storage_owner = StoragePartitionState::open(None).expect("memory partition");@@ -611,16 +628,10 @@ async fn devtools_script_navigation_exact_cursor_rejects_replaced_page_owner_act.conn.target_session_route_for_target_id(target_id.as_str()).expect("created target route");- {- let mut route_scope = ctx- .conn- .scoped_none_session_owner_route_override(route.clone());- route_scope- .conn_mut()- .runtime_session_owner_slot_mut(None)- .expect("created target runtime slot")- .replace_page_attachment_id_for_test();- }+ ctx.conn+ .runtime_session_owner_slot_mut_for_route(None, Some(&route))+ .expect("created target runtime slot")+ .replace_page_attachment_id_for_test();let sent_start = ctx.sent.len();ctx.route_direct_command_renderer_predecessor_for_test(predecessor)@@ -697,8 +708,9 @@ async fn bidi_fetch_control_resolves_background_request_owner() {));conn.browser_context = Some(browser_context);- conn.register_pending_fetch_navigation_request_for_session_owner(+ conn.register_pending_fetch_navigation_request_for_route(Some("SID-background"),+ None,PendingFetchNavigation {fetch_request_id: "FETCH-background".to_owned(),interception_session_id: Some("bidi-session-1".to_owned()),@@ -1576,10 +1588,7 @@ async fn devtools_runtime_command_uses_background_initial_document_without_resollet route = conn.target_session_route_for_target_id(second_target_id.as_str()).expect("background target route");- let previous_route = conn.replace_none_session_owner_route_override(Some(route));- let load_inputs = conn.navigation_load_inputs_for_session_owner(None);- conn.replace_none_session_owner_route_override(previous_route);- load_inputs+ conn.navigation_load_inputs_for_route(None, Some(&route))};assert!(background_load_inputs@@ -1777,23 +1786,21 @@ async fn protocol_neutral_await_promise_keeps_background_owner_route_across_pendlet active_route = conn.target_session_route_for_target_id(first_target_id.as_str()).expect("active target route");- let previous_route = conn.replace_none_session_owner_route_override(Some(active_route));assert!(- !conn.has_pending_inspector_awaits_for_session_owner(None),+ !conn+ .target_devtools_session_state_for_route(None, Some(&active_route))+ .is_some_and(crate::conn::DevToolsSessionState::has_pending_inspector_awaits),"internal id 0 pending await must not be registered on the active owner");- conn.replace_none_session_owner_route_override(previous_route);let background_route = conn.target_session_route_for_target_id(second_target_id.as_str()).expect("background target route");- let previous_route =- conn.replace_none_session_owner_route_override(Some(background_route.clone()));assert!(- conn.has_pending_inspector_awaits_for_session_owner(None),+ conn.target_devtools_session_state_for_route(None, Some(&background_route))+ .is_some_and(crate::conn::DevToolsSessionState::has_pending_inspector_awaits),"internal id 0 pending await must be registered on the targeted background owner");- conn.replace_none_session_owner_route_override(previous_route);let completed = pending.wait().await;let step = conn@@ -1916,28 +1923,22 @@ async fn pending_runtime_binding_page_phase_keeps_background_owner_route_across_"background");- let background_route = conn- .target_session_route_for_target_id(second_target_id.as_str())- .expect("background target route");+ let background_session =+ attach_page_session_for_test(&mut conn, second_target_id.as_str()).await;let raw = serde_json::to_string(&json!({"id": 1269,"method": "Runtime.addBinding",- "params": { "name": "backgroundRouteBinding" }+ "params": { "name": "backgroundRouteBinding" },+ "sessionId": background_session})).unwrap();- let pending = {- let previous_route =- conn.replace_none_session_owner_route_override(Some(background_route.clone()));- let step = conn.start_command_dispatch(&raw);- conn.replace_none_session_owner_route_override(previous_route);- match step {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(outcome) => {- panic!(- "background Runtime.addBinding should pend through renderer binding state apply: {:?}",- outcome.into_parts().0- )- }+ let pending = match conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(pending) => pending,+ CdpCommandTaskStep::Complete(outcome) => {+ panic!(+ "background Runtime.addBinding should pend through renderer binding state apply: {:?}",+ outcome.into_parts().0+ )}};@@ -1956,16 +1957,14 @@ async fn pending_runtime_binding_page_phase_keeps_background_owner_route_across_.all(|binding| binding.name != "backgroundRouteBinding")),"binding state apply completion must not write the active owner");- let previous_route = conn.replace_none_session_owner_route_override(Some(background_route));assert!(- conn.target_devtools_session_state_for_session(None)+ conn.target_devtools_session_state_for_session(Some(&background_session)).is_some_and(|state| state.runtime_bindings.iter().any(|binding| binding.name == "backgroundRouteBinding")),"binding state apply completion should persist on the original background owner");- conn.replace_none_session_owner_route_override(previous_route);assert_eq!(conn.browser_context.as_ref()@@ -1977,7 +1976,7 @@ async fn pending_runtime_binding_page_phase_keeps_background_owner_route_across_}#[tokio::test]-async fn runtime_enable_uses_background_initial_document_without_adapter() {+async fn runtime_enable_uses_background_initial_document_through_attached_session() {let mut conn = CdpConnection::new();let context = DevToolsCommandContext {protocol: DevToolsProtocol::WebDriverBidi,@@ -2023,16 +2022,11 @@ async fn runtime_enable_uses_background_initial_document_without_adapter() {let background_route = conn.target_session_route_for_target_id(second_target_id.as_str()).expect("background target route");- let pending_initial_document = {- let previous_route =- conn.replace_none_session_owner_route_override(Some(background_route.clone()));- let pending = conn- .start_initial_document_page_ensure_for_session_owner(None)- .expect("background target lifecycle ensure should start")- .expect("fresh background target should need an initial document page build");- conn.replace_none_session_owner_route_override(previous_route);- pending- };+ let background_owner = CommandOwnerScope::for_route(background_route.clone());+ let pending_initial_document = conn+ .start_initial_document_page_ensure_for_owner(&background_owner)+ .expect("background target lifecycle ensure should start")+ .expect("fresh background target should need an initial document page build");let completed_initial_document = pending_initial_document.wait().await@@ -2041,24 +2035,21 @@ async fn runtime_enable_uses_background_initial_document_without_adapter() {.await.expect("background initial document should install on captured owner");+ let background_session =+ attach_page_session_for_test(&mut conn, second_target_id.as_str()).await;let raw = serde_json::to_string(&json!({"id": 1270,- "method": "Runtime.enable"+ "method": "Runtime.enable",+ "sessionId": background_session})).unwrap();- let pending = {- let previous_route =- conn.replace_none_session_owner_route_override(Some(background_route.clone()));- let step = conn.start_command_dispatch(&raw);- conn.replace_none_session_owner_route_override(previous_route);- match step {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(outcome) => {- panic!(- "background Runtime.enable should replay the existing initial context through V8: {:?}",- outcome.into_parts().0- )- }+ let pending = match conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(pending) => pending,+ CdpCommandTaskStep::Complete(outcome) => {+ panic!(+ "background Runtime.enable should replay the existing initial context through V8: {:?}",+ outcome.into_parts().0+ )}};@@ -2093,17 +2084,15 @@ async fn runtime_enable_uses_background_initial_document_without_adapter() {.is_none_or(|state| !state.runtime_frontend_enabled),"Runtime.enable completion must not enable Runtime on the active owner");- let previous_route = conn.replace_none_session_owner_route_override(Some(background_route));assert!(- conn.target_runtime_session_state_for_session(None)+ conn.target_runtime_session_state_for_session(Some(&background_session)).is_some_and(|state| state.runtime_frontend_enabled),"Runtime.enable completion should enable Runtime on the original background owner");- conn.replace_none_session_owner_route_override(previous_route);}#[tokio::test]-async fn page_enable_uses_background_initial_document_without_adapter() {+async fn page_enable_uses_background_initial_document_through_attached_session() {let mut conn = CdpConnection::new();let context = DevToolsCommandContext {protocol: DevToolsProtocol::WebDriverBidi,@@ -2149,16 +2138,11 @@ async fn page_enable_uses_background_initial_document_without_adapter() {let background_route = conn.target_session_route_for_target_id(second_target_id.as_str()).expect("background target route");- let pending_initial_document = {- let previous_route =- conn.replace_none_session_owner_route_override(Some(background_route.clone()));- let pending = conn- .start_initial_document_page_ensure_for_session_owner(None)- .expect("background target lifecycle ensure should start")- .expect("fresh background target should need an initial document page build");- conn.replace_none_session_owner_route_override(previous_route);- pending- };+ let background_owner = CommandOwnerScope::for_route(background_route.clone());+ let pending_initial_document = conn+ .start_initial_document_page_ensure_for_owner(&background_owner)+ .expect("background target lifecycle ensure should start")+ .expect("fresh background target should need an initial document page build");let completed_initial_document = pending_initial_document.wait().await@@ -2167,23 +2151,19 @@ async fn page_enable_uses_background_initial_document_without_adapter() {.await.expect("background initial document should install on captured owner");+ let background_session =+ attach_page_session_for_test(&mut conn, second_target_id.as_str()).await;let raw = serde_json::to_string(&json!({"id": 1268,- "method": "Page.enable"+ "method": "Page.enable",+ "sessionId": background_session})).unwrap();- let pending = {- let previous_route = conn.replace_none_session_owner_route_override(Some(background_route));- let step = conn.start_command_dispatch(&raw);- conn.replace_none_session_owner_route_override(previous_route);- match step {- CdpCommandTaskStep::Pending(_) => {- panic!(- "background Page.enable should not start a pending initial document page build"- )- }- CdpCommandTaskStep::Complete(outcome) => outcome,+ let pending = match conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(_) => {+ panic!("background Page.enable should not start a pending initial document page build")}+ CdpCommandTaskStep::Complete(outcome) => outcome,};let messages = pending.into_parts().0;assert!(@@ -2260,20 +2240,12 @@ async fn initial_document_page_ensure_completion_uses_captured_owner() {let background_route = conn.target_session_route_for_target_id(second_target_id.as_str()).expect("background target route");- let pending = {- let previous_route = conn.replace_none_session_owner_route_override(Some(background_route));- let pending = conn- .start_initial_document_page_ensure_for_session_owner(None)- .expect("background initial document page ensure should start")- .expect("background initial document page ensure should pend");- conn.replace_none_session_owner_route_override(previous_route);- pending- };+ let background_owner = CommandOwnerScope::for_route(background_route);+ let pending = conn+ .start_initial_document_page_ensure_for_owner(&background_owner)+ .expect("background initial document page ensure should start")+ .expect("background initial document page ensure should pend");- let active_route = conn- .target_session_route_for_target_id(first_target_id.as_str())- .expect("active target route");- let previous_route = conn.replace_none_session_owner_route_override(Some(active_route));let completed = pending.wait().await@@ -2281,7 +2253,6 @@ async fn initial_document_page_ensure_completion_uses_captured_owner() {conn.complete_initial_document_page_build_for_owner(completed).await.expect("completion should install on captured owner");- conn.replace_none_session_owner_route_override(previous_route);let browser_context = conn.browser_context.as_ref().expect("browser context");assert_eq!(@@ -2408,12 +2379,13 @@ async fn stale_initial_document_page_build_does_not_overwrite_committed_page() {.expect("fresh initial target should pend active initial document page build");let real_page_url = "data:text/html,<title>real-page</title>";let parsed_real_page_url = url::Url::parse(real_page_url).expect("data URL should parse");+ let owner = crate::conn::CommandOwnerScope::capture(&conn, None);let real_page = conn.load_page_via_runtime_async(real_page_url).await.expect("real navigation page should build");- conn.commit_loaded_navigation_page_for_session_owner_async(- None,+ conn.commit_loaded_navigation_page_for_owner_async(+ &owner,real_page,crate::conn::LoadedNavigationRendererAttachmentCommit::Prepare(None),&parsed_real_page_url,@@ -2430,8 +2402,8 @@ async fn stale_initial_document_page_build_does_not_overwrite_committed_page() {secure_context_type: "InsecureScheme".to_owned(),timestamp: 0.0,};- conn.commit_loaded_navigation_target_identity_for_session_owner(- None,+ conn.commit_loaded_navigation_target_identity_for_owner(+ &owner,&real_page_commit,&parsed_real_page_url,)@@ -2676,12 +2648,11 @@ async fn target_lifecycle_ensure_installs_initial_about_blank_page_for_backgrounlet background_route = conn.target_session_route_for_target_id(second_target_id.as_str()).expect("background target route");- let previous_route = conn.replace_none_session_owner_route_override(Some(background_route));+ let background_owner = CommandOwnerScope::for_route(background_route);let pending = conn- .start_initial_document_page_ensure_for_session_owner(None)+ .start_initial_document_page_ensure_for_owner(&background_owner).expect("target lifecycle ensure should start background initial page").expect("fresh background initial target should pend initial document page build");- conn.replace_none_session_owner_route_override(previous_route);let completed = pending.wait()@@ -3219,11 +3190,6 @@ async fn devtools_create_target_can_activate_created_target() {.into_parts();first_realms_before_second_navigation.expect("demoted first target realms should remain readable before second navigation");- assert!(- conn.none_session_owner_route_override().is_none(),- "realm lookup must restore the ambient target route"- );-let (second_navigate, _, _, _) = conn.execute_devtools_command(DevToolsCommand::Navigate(DevToolsNavigateCommand {context: DevToolsCommandContext {@@ -3904,9 +3870,10 @@ async fn bidi_node_remote_value_registers_renderer_shared_node_binding() {ctx.conn.clear_runtime_remote_object_tracking_for_session_owner(None);+ let owner = CommandOwnerScope::capture(&ctx.conn, None);let renderer_binding = ctx.conn- .document_bidi_node_binding_for_session_owner_async(None, shared_id.as_str())+ .document_bidi_node_binding_for_owner_async(&owner, shared_id.as_str()).await.expect("renderer BiDi shared-node binding lookup should run");assert_eq!(@@ -4065,9 +4032,10 @@ async fn bidi_node_remote_value_registers_child_shared_node_bindings() {ctx.conn.clear_runtime_remote_object_tracking_for_session_owner(None);+ let owner = CommandOwnerScope::capture(&ctx.conn, None);let renderer_binding = ctx.conn- .document_bidi_node_binding_for_session_owner_async(None, &child_shared_id)+ .document_bidi_node_binding_for_owner_async(&owner, &child_shared_id).await.expect("child shared-node binding lookup should run");assert!(@@ -4671,11 +4639,9 @@ async fn devtools_command_applies_known_user_context_viewport_default() {let route = conn.target_session_route_for_target_id(create_result.target_id.as_str()).expect("created target route");- let previous_route = conn.replace_none_session_owner_route_override(Some(route));let inherited_metrics = conn- .target_session_owner_emulated_device_metrics(None)+ .target_session_owner_emulated_device_metrics_for_route(None, Some(&route)).expect("new target should inherit userContext default metrics");- conn.replace_none_session_owner_route_override(previous_route);assert_eq!((inherited_metrics.width,@@ -6273,6 +6239,18 @@ async fn devtools_command_executes_user_context_preload_without_default_leakage("custom userContext target",).await;+ let custom_route = ctx+ .conn+ .target_session_route_for_target_id(custom_target.as_str())+ .expect("custom userContext target route");+ assert!(+ ctx.conn+ .navigation_load_inputs_for_route(None, Some(&custom_route))+ .document_start_scripts+ .iter()+ .any(|script| script.source.contains("__bidiUserContextPreload")),+ "custom userContext target navigation inputs should retain its context preload script"+ );let custom_context = DevToolsCommandContext {target_id: Some(custom_target.clone()),..context.clone()@@ -6288,6 +6266,14 @@ async fn devtools_command_executes_user_context_preload_without_default_leakage().await.expect("custom userContext navigation should succeed");+ let custom_location = evaluate_string_through_renderer_fence_for_test(+ &mut ctx,+ custom_context.clone(),+ "location.href",+ "custom preload location",+ )+ .await;+ assert_eq!(custom_location, "data:text/html,user-context-preload");let custom_value = evaluate_string_through_renderer_fence_for_test(&mut ctx,custom_context,@@ -8149,12 +8135,7 @@ async fn pending_emulation_user_agent_loader_keeps_active_owner_route_across_com}};- let background_route = conn- .target_session_route_for_target_id("TID-emulation-ua-background")- .expect("background target route");- let previous_route = conn.replace_none_session_owner_route_override(Some(background_route));let messages = complete_command_task_for_test(&mut conn, *pending).await;- conn.replace_none_session_owner_route_override(previous_route);assert_eq!(messages, vec![json!({ "id": 688, "result": {} })]);let browser_context = conn.browser_context.as_ref().expect("browser context");@@ -8184,6 +8165,92 @@ async fn pending_emulation_user_agent_loader_keeps_active_owner_route_across_com);}+#[tokio::test(flavor = "multi_thread")]+async fn pending_emulation_viewport_keeps_original_page_when_active_target_changes() {+ let mut conn = CdpConnection::new();+ let original_page = conn+ .load_page_via_runtime_async("data:text/html,<title>original viewport owner</title>")+ .await+ .expect("original page should load");+ let replacement_page = conn+ .load_page_via_runtime_async("data:text/html,<title>replacement active page</title>")+ .await+ .expect("replacement page should load");++ let mut browser_context = BrowserContext::new("BID-emulation-viewport-owner".to_owned());+ browser_context.set_active_target_id("TID-emulation-viewport-original".to_owned());+ browser_context+ .active_page_state_mut()+ .runtime_slot+ .set_loaded_page_for_test(original_page);+ browser_context.stage_background_target(+ "TID-emulation-viewport-replacement".to_owned(),+ None,+ "data:text/html,<title>replacement active page</title>".to_owned(),+ None,+ None,+ );+ browser_context+ .background_target_mut("TID-emulation-viewport-replacement")+ .expect("replacement target")+ .replace_loaded_page(Some(replacement_page));+ conn.browser_context = Some(browser_context);++ let raw = serde_json::to_string(&json!({+ "id": 690,+ "method": "Emulation.setDeviceMetricsOverride",+ "params": {+ "width": 640,+ "height": 360,+ "deviceScaleFactor": 2,+ "mobile": false+ }+ }))+ .unwrap();+ let pending = match conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(pending) => pending,+ CdpCommandTaskStep::Complete(outcome) => {+ panic!(+ "live Emulation.setDeviceMetricsOverride should update the original Page: {:?}",+ outcome.into_parts().0+ )+ }+ };++ assert!(+ conn.promote_background_target_to_active_for_connection_async(+ "TID-emulation-viewport-replacement",+ )+ .await+ .expect("target activation should succeed")+ .is_some()+ );+ let messages = complete_command_task_for_test(&mut conn, *pending).await;++ assert_eq!(messages, vec![json!({ "id": 690, "result": {} })]);+ let browser_context = conn.browser_context.as_ref().expect("browser context");+ assert_eq!(+ browser_context.active_target_id(),+ Some("TID-emulation-viewport-replacement")+ );+ assert_eq!(+ browser_context+ .loaded_page()+ .expect("replacement page should remain loaded")+ .document_title(),+ "replacement active page",+ "the original Page completion must not overwrite the newly active Page state"+ );+ assert_eq!(+ browser_context+ .background_target("TID-emulation-viewport-original")+ .and_then(|target| target.loaded_page())+ .expect("original page should remain loaded in its stable target")+ .document_title(),+ "original viewport owner"+ );+}+#[tokio::test(flavor = "multi_thread")]async fn pending_emulation_timezone_keeps_background_owner_route_across_completion() {let mut conn = CdpConnection::new();@@ -8218,36 +8285,35 @@ async fn pending_emulation_timezone_keeps_background_owner_route_across_completilet background_route = conn.target_session_route_for_target_id("TID-emulation-timezone-background").expect("background target route");+ let background_session =+ attach_page_session_for_test(&mut conn, "TID-emulation-timezone-background").await;let raw = serde_json::to_string(&json!({"id": 689,"method": "Emulation.setTimezoneOverride",- "params": { "timezoneId": "UTC" }+ "params": { "timezoneId": "UTC" },+ "sessionId": background_session})).unwrap();- let pending = {- let previous_route =- conn.replace_none_session_owner_route_override(Some(background_route.clone()));- let step = conn.start_command_dispatch(&raw);- conn.replace_none_session_owner_route_override(previous_route);- match step {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(outcome) => {- panic!(- "background Emulation.setTimezoneOverride should update the live background page: {:?}",- outcome.into_parts().0- )- }+ let pending = match conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(pending) => pending,+ CdpCommandTaskStep::Complete(outcome) => {+ panic!(+ "background Emulation.setTimezoneOverride should update the live background page: {:?}",+ outcome.into_parts().0+ )}};- let active_route = conn- .target_session_route_for_target_id("TID-emulation-timezone-active")- .expect("active target route");- let previous_route = conn.replace_none_session_owner_route_override(Some(active_route));let messages = complete_command_task_for_test(&mut conn, *pending).await;- conn.replace_none_session_owner_route_override(previous_route);- assert_eq!(messages, vec![json!({ "id": 689, "result": {} })]);+ assert_eq!(+ messages,+ vec![json!({+ "id": 689,+ "result": {},+ "sessionId": background_session+ })]+ );let browser_context = conn.browser_context.as_ref().expect("browser context");assert_eq!(browser_context@@ -8266,9 +8332,7 @@ async fn pending_emulation_timezone_keeps_background_owner_route_across_completi"background timezone","background Emulation completion should preserve the captured owner");- let previous_route = conn.replace_none_session_owner_route_override(Some(background_route));- let background_inputs = conn.navigation_load_inputs_for_session_owner(None);- conn.replace_none_session_owner_route_override(previous_route);+ let background_inputs = conn.navigation_load_inputs_for_route(None, Some(&background_route));assert_eq!(background_inputs.timezone_override.as_deref(), Some("UTC"));assert!(conn.navigation_load_inputs_for_session_owner(None)@@ -8383,39 +8447,35 @@ async fn pending_security_tls_keeps_background_owner_route_across_completion() {.replace_loaded_page(Some(background_page));conn.browser_context = Some(browser_context);- let background_route = conn- .target_session_route_for_target_id("TID-security-background")- .expect("background target route");+ let background_session =+ attach_page_session_for_test(&mut conn, "TID-security-background").await;let raw = serde_json::to_string(&json!({"id": 687,"method": "Security.setIgnoreCertificateErrors",- "params": { "ignore": true }+ "params": { "ignore": true },+ "sessionId": background_session})).unwrap();- let pending = {- let previous_route =- conn.replace_none_session_owner_route_override(Some(background_route.clone()));- let step = conn.start_command_dispatch(&raw);- conn.replace_none_session_owner_route_override(previous_route);- match step {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(outcome) => {- panic!(- "background Security.setIgnoreCertificateErrors should update the live background page loader: {:?}",- outcome.into_parts().0- )- }+ let pending = match conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(pending) => pending,+ CdpCommandTaskStep::Complete(outcome) => {+ panic!(+ "background Security.setIgnoreCertificateErrors should update the live background page loader: {:?}",+ outcome.into_parts().0+ )}};- let active_route = conn- .target_session_route_for_target_id("TID-security-active")- .expect("active target route");- let previous_route = conn.replace_none_session_owner_route_override(Some(active_route));let messages = complete_command_task_for_test(&mut conn, *pending).await;- conn.replace_none_session_owner_route_override(previous_route);- assert_eq!(messages, vec![json!({ "id": 687, "result": {} })]);+ assert_eq!(+ messages,+ vec![json!({+ "id": 687,+ "result": {},+ "sessionId": background_session+ })]+ );let browser_context = conn.browser_context.as_ref().expect("browser context");assert_eq!(browser_context@@ -8434,7 +8494,20 @@ async fn pending_security_tls_keeps_background_owner_route_across_completion() {"background tls","background Security completion should preserve the original background page snapshot");- assert!(!conn.tls_verify_host());+ assert!(+ conn.tls_verify_host(),+ "the background session override must not change the active target"+ );+ assert_eq!(+ conn.browser_context+ .as_ref()+ .and_then(|browser_context| {+ browser_context.background_target("TID-security-background")+ })+ .and_then(|target| target.tls_verify_host_override),+ Some(false),+ "the attached background session should update only its target"+ );}#[tokio::test(flavor = "multi_thread")]@@ -8658,7 +8731,7 @@ async fn devtools_network_intercept_commands_route_to_fetch_owner() {auth_only_result.expect("auth-only add intercept should succeed");let auth_url = url::Url::parse("https://example.test/protected").unwrap();let preflight = conn- .prepare_navigation_request_for_session_owner(None, &auth_url, None, false)+ .prepare_navigation_request_for_route(None, None, &auth_url, None, false).expect("auth-only intercept should prepare navigation preflight");assert!(preflight.document_auth_required);assert_eq!(diff --git a/moli-protocol/src/conn/fetch_support.rs b/moli-protocol/src/conn/fetch_support.rsindex 4458a9f4a..15b0dc611 100644--- a/moli-protocol/src/conn/fetch_support.rs+++ b/moli-protocol/src/conn/fetch_support.rs@@ -2055,9 +2055,35 @@ impl CdpConnection {headers: Option<Vec<(String, String)>>,intercept_response: bool,handle_auth_requests: bool,+ ) -> Result<PendingSubresourceContinueOutcome, String> {+ self.continue_pending_subresource_fetch_for_route_async(+ session_id,+ None,+ internal_id,+ url,+ method,+ body,+ headers,+ intercept_response,+ handle_auth_requests,+ )+ .await+ }++ pub(crate) async fn continue_pending_subresource_fetch_for_route_async(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ internal_id: u64,+ url: Option<Url>,+ method: Option<String>,+ body: Option<Option<String>>,+ headers: Option<Vec<(String, String)>>,+ intercept_response: bool,+ handle_auth_requests: bool,) -> Result<PendingSubresourceContinueOutcome, String> {let page = self- .runtime_session_owner_slot_mut(session_id)?+ .runtime_session_owner_slot_mut_for_route(session_id, owner_route)?.loaded_page_mut().ok_or_else(|| "NoDocumentLoaded".to_owned())?;page.continue_pending_subresource_fetch_async(@@ -2087,9 +2113,20 @@ impl CdpConnection {session_id: Option<&str>,internal_id: u64,auth: SubresourceAuthCredentials,+ ) -> Result<PendingSubresourceContinueOutcome, String> {+ self.continue_pending_subresource_auth_for_route_async(session_id, None, internal_id, auth)+ .await+ }++ pub(crate) async fn continue_pending_subresource_auth_for_route_async(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ internal_id: u64,+ auth: SubresourceAuthCredentials,) -> Result<PendingSubresourceContinueOutcome, String> {let page = self- .runtime_session_owner_slot_mut(session_id)?+ .runtime_session_owner_slot_mut_for_route(session_id, owner_route)?.loaded_page_mut().ok_or_else(|| "NoDocumentLoaded".to_owned())?;page.continue_pending_subresource_auth_async(internal_id, auth)@@ -2237,9 +2274,27 @@ impl CdpConnection {internal_id: u64,response_code: Option<u16>,response_headers: Option<Vec<(String, String)>>,+ ) -> Result<(), String> {+ self.continue_pending_subresource_response_for_route_async(+ session_id,+ None,+ internal_id,+ response_code,+ response_headers,+ )+ .await+ }++ pub(crate) async fn continue_pending_subresource_response_for_route_async(+ &mut self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ internal_id: u64,+ response_code: Option<u16>,+ response_headers: Option<Vec<(String, String)>>,) -> Result<(), String> {let page = self- .runtime_session_owner_slot_mut(session_id)?+ .runtime_session_owner_slot_mut_for_route(session_id, owner_route)?.loaded_page_mut().ok_or_else(|| "NoDocumentLoaded".to_owned())?;page.continue_pending_subresource_response_async(diff --git a/moli-protocol/src/conn/inspector_route.rs b/moli-protocol/src/conn/inspector_route.rsindex 9ec3e887b..1a358aadd 100644--- a/moli-protocol/src/conn/inspector_route.rs+++ b/moli-protocol/src/conn/inspector_route.rs@@ -7,7 +7,7 @@ use super::state::{CommittedRendererAgentAttachment, FinishedRendererDocumentNavigation,PreparedRendererAgentAttachment, RendererAgentAttachment, RendererPageResidenceIdentity,};-use super::{CdpConnection, DocumentNavigationToken};+use super::{CdpConnection, CommandOwnerScope, DocumentNavigationToken};impl CdpConnection {pub(crate) fn renderer_agent_attachment_is_current_for_session_owner(@@ -21,24 +21,24 @@ impl CdpConnection {.is_some_and(|attachment| attachment.id() == attachment_id)}- pub(crate) fn current_renderer_agent_attachment_id_for_session_owner(+ pub(crate) fn current_renderer_agent_attachment_id_for_owner(&self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Option<RendererAgentAttachmentId> {- self.runtime_session_owner_slot(session_id)+ self.runtime_session_owner_slot_for_route(owner.session_id(), owner.session_owner_route()).ok().and_then(|slot| slot.current_renderer_attachment()).map(RendererAgentAttachment::id)}- pub(crate) fn prepare_renderer_agent_candidate_for_session_owner(+ pub(crate) fn prepare_renderer_agent_candidate_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,token: &DocumentNavigationToken,page: &mut Page,) -> Result<PreparedRendererAgentAttachment, String> {- let candidate = self.prepare_renderer_agent_candidate_token_for_session_owner(- session_id,+ let candidate = self.prepare_renderer_agent_candidate_token_for_owner(+ owner,token,page.renderer_devtools_agent_token(),)?;@@ -46,30 +46,34 @@ impl CdpConnection {Ok(candidate)}- pub(crate) fn prepare_renderer_agent_candidate_token_for_session_owner(+ pub(crate) fn prepare_renderer_agent_candidate_token_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,token: &DocumentNavigationToken,agent_token: RendererDevToolsAgentToken,) -> Result<PreparedRendererAgentAttachment, String> {- self.validate_navigation_target_owner(session_id, token)?;- self.runtime_session_owner_slot(session_id)?- .prepare_renderer_agent_candidate_token(token, agent_token)- .map_err(|error| error.to_string())+ self.validate_navigation_target_owner_for_scope(owner, token)?;+ self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?+ .prepare_renderer_agent_candidate_token(token, agent_token)+ .map_err(|error| error.to_string())}- pub(crate) fn route_current_renderer_inspector_output_for_session_owner(+ pub(crate) fn route_current_renderer_inspector_output_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,batches: Vec<RendererRuntimeInspectorMessageBatch>,) -> Vec<RendererRuntimeInspectorMessageBatch> {- let mut batches =- self.filter_renderer_inspector_batches_for_target_owner(session_id, batches);+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();+ let mut batches = self.filter_renderer_inspector_batches_for_target_owner(owner, batches);if batches.is_empty() {return Vec::new();}let current_attachment = self- .runtime_session_owner_slot(session_id)+ .runtime_session_owner_slot_for_route(session_id, owner_route).ok().and_then(|slot| slot.current_renderer_attachment());if let Some(current_attachment) = current_attachment {@@ -116,20 +120,24 @@ impl CdpConnection {}).collect::<Vec<_>>();match self- .runtime_session_owner_slot_mut(session_id)+ .runtime_session_owner_slot_mut_for_route(session_id, owner_route).and_then(|slot| {slot.route_current_renderer_inspector_output(attachment_id, batches).map_err(|error| error.to_string())}) {Ok(batches) => {- let primary_session_id = self.runtime_session_owner_primary_session_id(session_id);+ let primary_session_id = self+ .runtime_session_owner_primary_session_id_for_route(session_id, owner_route);for (session, state) in state_updates {let state_session_id = match &session {DevToolsSessionKey::Primary => primary_session_id.as_deref(),DevToolsSessionKey::Attached(session_id) => Some(session_id.as_str()),};- let _ = self.merge_v8_inspector_session_state_for_session_owner(+ let state_owner_route =+ state_session_id.is_none().then_some(owner_route).flatten();+ let _ = self.merge_v8_inspector_session_state_for_route(state_session_id,+ state_owner_route,state,);}@@ -146,48 +154,60 @@ impl CdpConnection {}}- pub(crate) fn commit_renderer_agent_candidate_for_session_owner(+ pub(crate) fn commit_renderer_agent_candidate_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,candidate: PreparedRendererAgentAttachment,renderer_page: RendererPageResidenceIdentity,) -> Result<CommittedRendererAgentAttachment, String> {- self.validate_navigation_target_owner(session_id, candidate.navigation())?;+ self.validate_navigation_target_owner_for_scope(owner, candidate.navigation())?;let transaction = self- .runtime_session_owner_slot_mut(session_id)?+ .runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?.commit_renderer_agent_candidate_transaction(candidate, renderer_page).map_err(|error| error.to_string())?;let page_owner = self- .pending_target_page_residence_identity_for_session(session_id)+ .pending_target_page_residence_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).ok_or_else(|| "NavigationTargetOwnerMissing".to_owned())?;self.bind_renderer_page_output_owner(renderer_page, page_owner);Ok(transaction)}- pub(crate) fn rollback_committed_renderer_agent_candidate_for_session_owner(+ pub(crate) fn rollback_committed_renderer_agent_candidate_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,transaction: CommittedRendererAgentAttachment,) -> Result<(), String> {- self.validate_navigation_target_owner(session_id, transaction.navigation())?;- self.runtime_session_owner_slot_mut(session_id)?- .rollback_committed_renderer_agent_candidate(transaction)- .map_err(|error| error.to_string())+ self.validate_navigation_target_owner_for_scope(owner, transaction.navigation())?;+ self.runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?+ .rollback_committed_renderer_agent_candidate(transaction)+ .map_err(|error| error.to_string())}- pub(crate) fn finish_renderer_document_navigation_for_session_owner(+ pub(crate) fn finish_renderer_document_navigation_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,token: &DocumentNavigationToken,) -> Option<FinishedRendererDocumentNavigation> {if self- .validate_navigation_target_owner(session_id, token)+ .validate_navigation_target_owner_for_scope(owner, token).is_err(){return None;}match self- .runtime_session_owner_slot_mut(session_id)+ .runtime_session_owner_slot_mut_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).and_then(|slot| {slot.finish_renderer_document_navigation(token).map_err(|error| error.to_string())@@ -196,7 +216,7 @@ impl CdpConnection {Err(error) => {tracing::debug!(%error,- session_id,+ session_id = owner.session_id(),loader_id = token.loader_id,"renderer channel rejected navigation completion");@@ -207,30 +227,31 @@ impl CdpConnection {fn filter_renderer_inspector_batches_for_target_owner(&self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,batches: Vec<RendererRuntimeInspectorMessageBatch>,) -> Vec<RendererRuntimeInspectorMessageBatch> {- let owner = self.target_owner_identity_for_session(session_id);+ let owner_identity =+ self.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route());batches.into_iter().filter(|batch| match &batch.session {- DevToolsSessionKey::Primary => owner.is_some(),+ DevToolsSessionKey::Primary => owner_identity.is_some(),DevToolsSessionKey::Attached(attached_session_id) => {- owner.is_some()+ owner_identity.is_some()&& self.target_owner_identity_for_session(Some(attached_session_id))- == owner+ == owner_identity}}).collect()}- fn validate_navigation_target_owner(+ fn validate_navigation_target_owner_for_scope(&self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,token: &DocumentNavigationToken,) -> Result<(), String> {let (_, target_id) = self- .target_owner_identity_for_session(session_id)+ .target_owner_identity_for_route(owner.session_id(), owner.session_owner_route()).ok_or_else(|| "NoDocumentLoaded".to_owned())?;if target_id.as_deref() != Some(token.target_id.as_str()) {return Err("renderer channel navigation target owner mismatch".to_owned());@@ -286,7 +307,7 @@ mod tests {conn.browser_context = Some(browser_context);let filtered = conn.filter_renderer_inspector_batches_for_target_owner(- Some("SID-active-primary"),+ &CommandOwnerScope::for_session("SID-active-primary"),vec![batch(DevToolsSessionKey::Primary),batch(DevToolsSessionKey::Attached("SID-active-aux".to_owned())),@@ -337,7 +358,10 @@ mod tests {accepted.bind_renderer_agent_attachment(current.id());assert_eq!(ctx.conn- .route_current_renderer_inspector_output_for_session_owner(None, vec![accepted])+ .route_current_renderer_inspector_output_for_owner(+ &CommandOwnerScope::capture(&ctx.conn, None),+ vec![accepted],+ ).len(),1);@@ -360,8 +384,8 @@ mod tests {auxiliary.bind_renderer_agent_attachment(current.id());assert_eq!(ctx.conn- .route_current_renderer_inspector_output_for_session_owner(- Some("SID-state-primary"),+ .route_current_renderer_inspector_output_for_owner(+ &CommandOwnerScope::for_session("SID-state-primary"),vec![auxiliary],).len(),@@ -389,8 +413,8 @@ mod tests {stale_attachment.bind_renderer_agent_attachment(RendererAgentAttachmentId::allocate());assert!(ctx.conn- .route_current_renderer_inspector_output_for_session_owner(- None,+ .route_current_renderer_inspector_output_for_owner(+ &CommandOwnerScope::capture(&ctx.conn, None),vec![stale_attachment],).is_empty()@@ -401,7 +425,10 @@ mod tests {stale_agent.bind_renderer_agent_attachment(current.id());assert!(ctx.conn- .route_current_renderer_inspector_output_for_session_owner(None, vec![stale_agent],)+ .route_current_renderer_inspector_output_for_owner(+ &CommandOwnerScope::capture(&ctx.conn, None),+ vec![stale_agent],+ ).is_empty());@@ -411,8 +438,8 @@ mod tests {page_creation_batch.v8_state_update = Some(route_completed_state.clone());assert_eq!(ctx.conn- .route_current_renderer_inspector_output_for_session_owner(- None,+ .route_current_renderer_inspector_output_for_owner(+ &CommandOwnerScope::capture(&ctx.conn, None),vec![page_creation_batch],).len(),@@ -438,13 +465,15 @@ mod tests {Vec::new(),);let mut ordered_events = Vec::new();+ let owner = CommandOwnerScope::capture(&ctx.conn, None);assert!(- !ctx.conn.route_renderer_runtime_command_output_into(- output,- Some(77),- None,- &mut ordered_events,- ),+ !ctx.conn+ .route_renderer_runtime_command_output_for_owner_into(+ output,+ Some(77),+ &owner,+ &mut ordered_events,+ ),"a validated state-only response must not invent a frontend completion");assert!(ordered_events.is_empty());diff --git a/moli-protocol/src/conn/output.rs b/moli-protocol/src/conn/output.rsindex 95e1f8410..db3feb769 100644--- a/moli-protocol/src/conn/output.rs+++ b/moli-protocol/src/conn/output.rs@@ -22,7 +22,7 @@ use serde_json::{Value, json};use tokio::sync::mpsc::UnboundedSender;use super::{- CdpConnection, DevToolsDocumentLifecycleWaitKey,+ CdpConnection, CommandOwnerScope, DevToolsDocumentLifecycleWaitKey,state::{BrowserContext, DocumentNavigationToken},};@@ -35,6 +35,7 @@ pub type BackgroundEventSender = UnboundedSender<BackgroundProtocolEvent>;pub struct RuntimeInspectorResponseReady {frontend_command_id: FrontendCommandId,session_key: DevToolsSessionKey,+ owner: Option<CommandOwnerScope>,expected_renderer_call_id: Option<RendererCallId>,response: Result<RendererRuntimeInspectorAsyncCompletion, String>,}@@ -48,6 +49,21 @@ impl RuntimeInspectorResponseReady {Self {frontend_command_id: FrontendCommandId::new(command_id),session_key: DevToolsSessionKey::from_wire_session_id(session_id),+ owner: None,+ expected_renderer_call_id: None,+ response,+ }+ }++ pub(crate) fn for_owner(+ command_id: u64,+ owner: &CommandOwnerScope,+ response: Result<RendererRuntimeInspectorAsyncCompletion, String>,+ ) -> Self {+ Self {+ frontend_command_id: FrontendCommandId::new(command_id),+ session_key: DevToolsSessionKey::from_wire_session_id(owner.session_id()),+ owner: Some(owner.clone()),expected_renderer_call_id: None,response,}@@ -61,6 +77,26 @@ impl RuntimeInspectorResponseReady {self.session_key.wire_session_id()}+ pub(crate) fn owner(&self) -> Option<&CommandOwnerScope> {+ self.owner.as_ref()+ }++ pub(crate) fn bind_owner(&mut self, owner: &CommandOwnerScope) {+ assert_eq!(+ self.session_id(),+ owner.session_id(),+ "runtime Inspector response owner must preserve its wire session"+ );+ if let Some(current) = self.owner.as_ref() {+ assert_eq!(+ current, owner,+ "runtime Inspector response owner cannot change"+ );+ } else {+ self.owner = Some(owner.clone());+ }+ }+pub fn error(&self) -> Option<&str> {self.response.as_ref().err().map(String::as_str)}diff --git a/moli-protocol/src/conn/popup_activation_work.rs b/moli-protocol/src/conn/popup_activation_work.rsindex 2652ab4bc..5e9ddecb9 100644--- a/moli-protocol/src/conn/popup_activation_work.rs+++ b/moli-protocol/src/conn/popup_activation_work.rs@@ -22,11 +22,11 @@ impl PopupTargetActivationAction {) -> Option<Self> {let route = conn.target_session_route_for_target_id(target_id)?;(route.browser_context_id() == Some(browser_context_id)).then(|| Self {- owner_scope: CommandOwnerScope::for_implicit_route(Some(CdpSessionRoute::PageTarget {+ owner_scope: CommandOwnerScope::for_route(CdpSessionRoute::PageTarget {browser_context_id: browser_context_id.to_owned(),target_id: target_id.to_owned(),is_attached_session: false,- })),+ }),browser_context_id: browser_context_id.to_owned(),target_id: target_id.to_owned(),})diff --git a/moli-protocol/src/conn/popup_navigation_work.rs b/moli-protocol/src/conn/popup_navigation_work.rsindex 1ded2b78f..67a56eeb4 100644--- a/moli-protocol/src/conn/popup_navigation_work.rs+++ b/moli-protocol/src/conn/popup_navigation_work.rs@@ -41,11 +41,11 @@ impl PopupTargetNavigationOwnerAction {// Activation has an independent owner action. Unlike a frozen// Stable PageTarget route keeps this exact target addressable if// the independent activation action changes its residence first.- owner_scope: CommandOwnerScope::for_implicit_route(Some(CdpSessionRoute::PageTarget {+ owner_scope: CommandOwnerScope::for_route(CdpSessionRoute::PageTarget {browser_context_id: browser_context_id.to_owned(),target_id: target_id.to_owned(),is_attached_session: false,- })),+ }),browser_context_id: browser_context_id.to_owned(),target_id: target_id.to_owned(),url,diff --git a/moli-protocol/src/conn/protocol_output.rs b/moli-protocol/src/conn/protocol_output.rsindex 3a8a9e175..90f489a5e 100644--- a/moli-protocol/src/conn/protocol_output.rs+++ b/moli-protocol/src/conn/protocol_output.rs@@ -246,9 +246,10 @@ impl CdpConnection {session_id: Option<&str>,) -> CdpTurnOutcome {let mut command_context = super::CommandDispatchContext::default();+ let owner = super::CommandOwnerScope::capture(self, session_id);crate::domains::activity::project_protocol_local_command_outputs(self,- session_id,+ &owner,&mut command_context,).await;diff --git a/moli-protocol/src/conn/runtime_eval.rs b/moli-protocol/src/conn/runtime_eval.rsindex 31bbd3d65..cafbe3273 100644--- a/moli-protocol/src/conn/runtime_eval.rs+++ b/moli-protocol/src/conn/runtime_eval.rs@@ -27,9 +27,9 @@ use crate::conn::state::{};use crate::domains::command_output::protocol_message_background_event;use crate::domains::runtime_context_events::{- RuntimeContextProtocolEvent, apply_runtime_context_protocol_event_side_effects_typed,+ RuntimeContextProtocolEvent, apply_runtime_context_protocol_event_side_effects_for_owner_typed,emit_runtime_context_protocol_background_event_typed,- qualify_runtime_context_protocol_event_for_session_owner_typed,+ qualify_runtime_context_protocol_event_for_owner_typed,};use super::*;@@ -261,13 +261,14 @@ pub(crate) struct OwnerRuntimeResponse {#[derive(Debug)]pub(crate) struct ClaimedPendingInspectorAwait {command_id: u64,+ owner: CommandOwnerScope,entry: PendingInspectorAwait,}#[derive(Debug)]pub(crate) struct ClaimedPendingInspectorAwaitOwner {command_id: u64,- session_id: Option<String>,+ owner: CommandOwnerScope,bidi_channel_object_group: Option<String>,renderer_correlation: Option<RendererCommandCorrelation>,}@@ -276,7 +277,7 @@ impl ClaimedPendingInspectorAwaitOwner {fn from_claimed(claimed: &ClaimedPendingInspectorAwait) -> Self {Self {command_id: claimed.command_id,- session_id: claimed.entry.session_id().map(str::to_owned),+ owner: claimed.owner.clone(),bidi_channel_object_group: claimed.entry.bidi_channel_listener()@@ -286,12 +287,16 @@ impl ClaimedPendingInspectorAwaitOwner {}fn session_id(&self) -> Option<&str> {- self.session_id.as_deref()+ self.owner.session_id()}fn matches_session_owner(&self, session_id: Option<&str>) -> bool {self.session_id() == session_id}++ fn matches_owner(&self, owner: &CommandOwnerScope) -> bool {+ &self.owner == owner+ }}impl OwnerRuntimeResponse {@@ -333,7 +338,7 @@ impl OwnerRuntimeResponse {}pub struct PendingRuntimeProtocolMessageDispatch {- session_id: Option<String>,+ owner: CommandOwnerScope,route: RuntimeProtocolMessagePageRoute,pending: PendingRuntimeProtocolMessageDispatchKind,response_route: RuntimeProtocolResponseRoute,@@ -431,24 +436,24 @@ struct PendingMoliDiagnosticsPageSnapshot {}pub struct PendingRuntimeEnableEventsDispatch {- session_id: Option<String>,+ owner: CommandOwnerScope,route: RuntimeProtocolMessagePageRoute,pending: moli_core::page::PendingPageCommand,}pub struct PendingRuntimeBindingPageCommandDispatch {- session_id: Option<String>,+ owner: CommandOwnerScope,operation: &'static str,pending: moli_core::page::PendingPageCommand,}pub struct PendingRuntimeChildDefaultContextLookupDispatch {- session_id: Option<String>,+ owner: CommandOwnerScope,pending: moli_core::page::PendingPageCommand,}pub struct CompletedRuntimeProtocolMessageDispatch {- session_id: Option<String>,+ owner: CommandOwnerScope,route: RuntimeProtocolMessagePageRoute,completion: moli_core::page::CompletedRuntimeInspectorCommandDispatch,response_route: RuntimeProtocolResponseRoute,@@ -477,7 +482,7 @@ struct CompletedMoliDiagnosticsPageSnapshot {}pub struct CompletedRuntimeEnableEventsDispatch {- session_id: Option<String>,+ owner: CommandOwnerScope,route: RuntimeProtocolMessagePageRoute,completion: moli_core::page::CompletedPageCommand,}@@ -524,13 +529,13 @@ impl RuntimeEnableReplayEvent {}pub struct CompletedRuntimeBindingPageCommandDispatch {- session_id: Option<String>,+ owner: CommandOwnerScope,operation: &'static str,completion: moli_core::page::CompletedPageCommand,}pub struct CompletedRuntimeChildDefaultContextLookupDispatch {- session_id: Option<String>,+ owner: CommandOwnerScope,completion: moli_core::page::CompletedPageCommand,}@@ -606,7 +611,7 @@ impl PendingRuntimeProtocolMessageDispatch {.map_err(|error| format!("runtime inspector dispatch failed: {error}"))?,};Ok(CompletedRuntimeProtocolMessageDispatch {- session_id: self.session_id,+ owner: self.owner,route: self.route,completion,response_route: self.response_route,@@ -639,6 +644,10 @@ impl PendingServiceWorkerRuntimeProtocolMessageDispatch {}impl CompletedRuntimeProtocolMessageDispatch {+ pub(crate) fn owner(&self) -> &CommandOwnerScope {+ &self.owner+ }+pub(crate) fn session_response_succeeded(&self) -> Option<bool> {match &self.completion {moli_core::page::CompletedRuntimeInspectorCommandDispatch::OwnerSessionResponse {@@ -728,7 +737,7 @@ impl PendingRuntimeEnableEventsDispatch {.await.map_err(|error| format!("runtime enable event replay failed: {error}"))?;Ok(CompletedRuntimeEnableEventsDispatch {- session_id: self.session_id,+ owner: self.owner,route: self.route,completion,})@@ -743,7 +752,7 @@ impl PendingRuntimeBindingPageCommandDispatch {.await.map_err(|error| format!("{} failed: {error}", self.operation))?;Ok(CompletedRuntimeBindingPageCommandDispatch {- session_id: self.session_id,+ owner: self.owner,operation: self.operation,completion,})@@ -758,7 +767,7 @@ impl PendingRuntimeChildDefaultContextLookupDispatch {.await.map_err(|error| format!("runtime child default context lookup failed: {error}"))?;Ok(CompletedRuntimeChildDefaultContextLookupDispatch {- session_id: self.session_id,+ owner: self.owner,completion,})}@@ -837,20 +846,22 @@ impl CdpConnection {cdp_request_id: u64,session_id: Option<&str>,) {- self.try_register_pending_inspector_await_with_object_group(+ let owner = CommandOwnerScope::capture(self, session_id);+ self.try_register_pending_inspector_await_with_object_group_for_owner(cdp_request_id,- session_id,+ &owner,None,).expect("pending Inspector await frontend command id must be unique per session");}- pub(crate) fn try_register_pending_inspector_await_with_object_group(+ pub(crate) fn try_register_pending_inspector_await_with_object_group_for_owner(&mut self,cdp_request_id: u64,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_group: Option<&str>,) -> Result<(), DuplicatePendingRendererCommand> {+ let session_id = owner.session_id();if let Some(owner_session_id) = session_id&& let Some(target) = self.shared_worker_target_for_session_mut(session_id){@@ -871,9 +882,13 @@ impl CdpConnection {object_group,);}- self.with_target_devtools_session_state_for_session_mut(session_id, |state| {- state.try_register_pending_inspector_await(cdp_request_id, session_id, object_group)- })+ self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| {+ state.try_register_pending_inspector_await(cdp_request_id, session_id, object_group)+ },+ ).unwrap_or(Ok(()))}@@ -917,6 +932,36 @@ impl CdpConnection {.map_err(|error| error.to_string())}+ fn try_register_renderer_call_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ cdp_request_id: u64,+ dispatched_attachment_id: Option<RendererAgentAttachmentId>,+ descriptor: RendererCommandDescriptor,+ ) -> Result<PreparedRendererCallDispatch, String> {+ if owner.session_id().is_some() {+ return self.try_register_renderer_call_for_session_owner(+ owner.session_id(),+ cdp_request_id,+ dispatched_attachment_id,+ descriptor,+ );+ }+ self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| {+ state.try_register_renderer_call(+ cdp_request_id,+ dispatched_attachment_id,+ descriptor,+ )+ },+ )+ .ok_or_else(|| "UnknownSession".to_owned())?+ .map_err(|error| error.to_string())+ }+pub(crate) fn take_renderer_call_for_frontend_for_session_owner(&mut self,session_id: Option<&str>,@@ -938,6 +983,25 @@ impl CdpConnection {.flatten()}+ pub(crate) fn take_renderer_call_for_frontend_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ cdp_request_id: u64,+ ) -> Option<RendererCommandCorrelation> {+ if owner.session_id().is_some() {+ return self.take_renderer_call_for_frontend_for_session_owner(+ owner.session_id(),+ cdp_request_id,+ );+ }+ self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.take_renderer_call_for_frontend(cdp_request_id),+ )+ .flatten()+ }+fn renderer_call_for_frontend_for_session_owner(&self,session_id: Option<&str>,@@ -975,10 +1039,23 @@ impl CdpConnection {session_id: Option<&str>,cdp_request_id: u64,) -> Option<RendererRuntimeCommandCausalIdentity> {- let correlation =- self.renderer_call_for_frontend_for_session_owner(session_id, cdp_request_id)?;+ self.renderer_runtime_command_cause_for_route(session_id, None, cdp_request_id)+ }++ pub(crate) fn renderer_runtime_command_cause_for_route(+ &self,+ session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,+ cdp_request_id: u64,+ ) -> Option<RendererRuntimeCommandCausalIdentity> {+ let correlation = if session_id.is_some() {+ self.renderer_call_for_frontend_for_session_owner(session_id, cdp_request_id)+ } else {+ self.target_devtools_session_state_for_route(session_id, owner_route)?+ .renderer_call_for_frontend(cdp_request_id)+ }?;Some(RendererRuntimeCommandCausalIdentity::new(- self.target_renderer_runtime_inspector_session_id_for_session(session_id),+ self.target_renderer_runtime_inspector_session_id_for_route(session_id, owner_route),correlation.renderer_call_id().get(),))}@@ -1020,6 +1097,35 @@ impl CdpConnection {.flatten()}+ fn take_renderer_call_for_frontend_if_matches_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ cdp_request_id: u64,+ renderer_call_id: RendererCallId,+ dispatched_attachment_id: Option<RendererAgentAttachmentId>,+ ) -> Option<RendererCommandCorrelation> {+ if owner.session_id().is_some() {+ return self.take_renderer_call_for_frontend_if_matches_for_session_owner(+ owner.session_id(),+ cdp_request_id,+ renderer_call_id,+ dispatched_attachment_id,+ );+ }+ self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| {+ state.take_renderer_call_for_frontend_if_matches(+ cdp_request_id,+ renderer_call_id,+ dispatched_attachment_id,+ )+ },+ )+ .flatten()+ }+pub(crate) fn take_renderer_call_if_correlation_matches_for_session_owner(&mut self,session_id: Option<&str>,@@ -1089,6 +1195,33 @@ impl CdpConnection {.flatten()}+ fn take_frontend_command_for_renderer_if_attachment_matches_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ renderer_call_id: RendererCallId,+ dispatched_attachment_id: Option<RendererAgentAttachmentId>,+ ) -> Option<RendererCommandCorrelation> {+ if owner.session_id().is_some() {+ return self+ .take_frontend_command_for_renderer_if_attachment_matches_for_session_owner(+ owner.session_id(),+ renderer_call_id,+ dispatched_attachment_id,+ );+ }+ self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| {+ state.take_frontend_command_for_renderer_if_attachment_matches(+ renderer_call_id,+ dispatched_attachment_id,+ )+ },+ )+ .flatten()+ }+fn prepare_renderer_call_for_session_owner(&mut self,session_id: Option<&str>,@@ -1142,6 +1275,58 @@ impl CdpConnection {}}+ fn prepare_renderer_call_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ descriptor: RendererCommandDescriptor,+ cdp_request_id: u64,+ dispatched_attachment_id: Option<RendererAgentAttachmentId>,+ ) -> Result<+ (+ RendererCommandCorrelation,+ String,+ RendererRuntimeInspectorResponseSender,+ RuntimeProtocolResponseRoute,+ ),+ String,+ > {+ let raw_json = descriptor.frontend_payload().to_owned();+ let response_delivery = descriptor.response_delivery();+ let prepared = self.try_register_renderer_call_for_owner(+ owner,+ cdp_request_id,+ dispatched_attachment_id,+ descriptor,+ )?;+ let correlation = prepared.correlation();+ match self.rewrite_runtime_inspector_command_for_owner(+ owner,+ &raw_json,+ Some((+ FrontendCommandId::new(cdp_request_id),+ correlation.renderer_call_id(),+ )),+ ) {+ Ok(raw_json) => {+ let (correlation, response_sender, response_receiver) = prepared.into_parts();+ Ok((+ correlation,+ raw_json,+ response_sender,+ RuntimeProtocolResponseRoute::for_registered_delivery(+ response_delivery,+ response_receiver,+ ),+ ))+ }+ Err(error) => {+ let removed = self.take_renderer_call_for_frontend_for_owner(owner, cdp_request_id);+ debug_assert_eq!(removed, Some(correlation));+ Err(error)+ }+ }+ }+fn rewrite_runtime_inspector_command_for_session_owner(&self,session_id: Option<&str>,@@ -1158,14 +1343,41 @@ impl CdpConnection {)}- pub(crate) fn register_runtime_await_job(+ fn rewrite_runtime_inspector_command_for_owner(+ &self,+ owner: &CommandOwnerScope,+ raw_json: &str,+ command_id_rewrite: Option<(FrontendCommandId, RendererCallId)>,+ ) -> Result<String, String> {+ if owner.session_id().is_some() {+ return self.rewrite_runtime_inspector_command_for_session_owner(+ owner.session_id(),+ raw_json,+ command_id_rewrite,+ );+ }+ let owner_target_id = self+ .target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())+ .and_then(|(_, target_id)| target_id);+ rewrite_runtime_inspector_command_for_renderer(+ raw_json,+ command_id_rewrite,+ owner_target_id.as_deref(),+ )+ }++ pub(crate) fn register_runtime_await_job_for_owner(&mut self,cdp_request_id: u64,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_group: Option<&str>,action: &'static str,) {- let owner_route = self.runtime_await_owner_route_for_session(session_id);+ let session_id = owner.session_id();+ let owner_route = owner+ .session_owner_route()+ .cloned()+ .or_else(|| self.session_route(session_id));let job = RuntimeAwaitJob::new(cdp_request_id,session_id,@@ -1287,11 +1499,6 @@ impl CdpConnection {&self,session_id: Option<&str>,) -> Option<CdpSessionRoute> {- if session_id.is_none()- && let Some(route) = self.none_session_owner_route_override()- {- return Some(route);- }if let Some(route) = self.session_route(session_id) {return Some(route);}@@ -1322,6 +1529,7 @@ impl CdpConnection {)}+ #[cfg(test)]pub(crate) fn register_pending_bidi_channel_listener(&mut self,cdp_request_id: u64,@@ -1343,6 +1551,31 @@ impl CdpConnection {});}+ fn register_pending_bidi_channel_listener_for_owner(+ &mut self,+ cdp_request_id: u64,+ owner: &CommandOwnerScope,+ listener: BidiChannelListenerResidence,+ ) {+ assert_eq!(+ listener.owner().command_owner(),+ owner,+ "BiDi listener residence must be registered under its exact Page owner"+ );+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| {+ state.register_pending_bidi_channel_listener(+ cdp_request_id,+ owner.session_id(),+ Some(BIDI_SCRIPT_RESULT_OBJECT_GROUP),+ listener,+ );+ },+ );+ }+pub(crate) fn publish_bidi_channel_listener_start(&mut self,listener: BidiChannelListenerResidence,@@ -1382,18 +1615,29 @@ impl CdpConnection {let _ = self.remove_pending_inspector_await_for_cancellation(cdp_request_id, session_id);}+ pub(crate) fn forget_pending_inspector_await_for_owner(+ &mut self,+ cdp_request_id: u64,+ owner: &CommandOwnerScope,+ ) {+ self.cancel_runtime_await_job(cdp_request_id, owner.session_id(), "forgotten");+ let _ =+ self.remove_pending_inspector_await_for_cancellation_for_owner(cdp_request_id, owner);+ }+pub(crate) fn claim_pending_inspector_await_for_scheduler_deferred_reply(&mut self,cdp_request_id: u64,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Option<ClaimedPendingInspectorAwait> {let claimed = self- .remove_pending_inspector_await(cdp_request_id, session_id)+ .remove_pending_inspector_await_for_owner(cdp_request_id, owner).map(|entry| ClaimedPendingInspectorAwait {command_id: cdp_request_id,+ owner: owner.clone(),entry,})?;- let key = PendingRendererCommandKey::new(session_id, cdp_request_id);+ let key = PendingRendererCommandKey::new(owner.session_id(), cdp_request_id);match self.claimed_pending_inspector_await_owners.entry(key) {Entry::Vacant(entry) => {entry.insert(ClaimedPendingInspectorAwaitOwner::from_claimed(&claimed));@@ -1433,6 +1677,21 @@ impl CdpConnection {.collect()}+ fn drain_claimed_pending_inspector_await_owners_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ ) -> Vec<ClaimedPendingInspectorAwaitOwner> {+ let to_remove = self+ .claimed_pending_inspector_await_owners+ .iter()+ .filter_map(|(key, claimed)| claimed.matches_owner(owner).then_some(key.clone()))+ .collect::<Vec<_>>();+ to_remove+ .into_iter()+ .filter_map(|key| self.claimed_pending_inspector_await_owners.remove(&key))+ .collect()+ }+fn push_claimed_pending_inspector_await_owner_errors(&mut self,background_events: &mut Vec<BackgroundProtocolEvent>,@@ -1442,21 +1701,20 @@ impl CdpConnection {for owner in owners {self.cancel_runtime_await_job(owner.command_id, owner.session_id(), reason);if let Some(correlation) = owner.renderer_correlation {- self.discard_renderer_call_for_session_owner_if_matches(- owner.session_id(),- correlation,+ let _ = self.take_renderer_call_for_frontend_if_matches_for_owner(+ &owner.owner,+ correlation.frontend_command_id().get(),+ correlation.renderer_call_id(),+ correlation.dispatched_attachment_id(),);}if let Some(object_group) = owner.bidi_channel_object_group.as_deref() {- self.unregister_runtime_remote_object_group_for_session_owner(- owner.session_id(),- object_group,- );+ self.unregister_runtime_remote_object_group_for_owner(&owner.owner, object_group);continue;}- let mut response = RuntimeInspectorResponseReady::new(+ let mut response = RuntimeInspectorResponseReady::for_owner(owner.command_id,- owner.session_id(),+ &owner.owner,Err(reason.to_owned()),);if let Some(correlation) = owner.renderer_correlation {@@ -1505,11 +1763,15 @@ impl CdpConnection {let Some(claimed) = claimed else {return;};- let ClaimedPendingInspectorAwait { command_id, entry } = claimed;- let session_id = entry.session_id().map(str::to_owned);+ let ClaimedPendingInspectorAwait {+ command_id,+ owner,+ entry,+ } = claimed;+ let session_id = owner.session_id().map(str::to_owned);self.remove_claimed_pending_inspector_await_owner(command_id, session_id.as_deref());self.complete_runtime_await_job(command_id, session_id.as_deref());- self.apply_completed_pending_inspector_await_entry(entry, protocol_events);+ self.apply_completed_pending_inspector_await_entry(&owner, entry, protocol_events);}pub(crate) fn cancel_claimed_pending_inspector_await_for_scheduler_deferred_reply(@@ -1520,19 +1782,25 @@ impl CdpConnection {let Some(claimed) = claimed else {return;};- let ClaimedPendingInspectorAwait { command_id, entry } = claimed;- let session_id = entry.session_id().map(str::to_owned);+ let ClaimedPendingInspectorAwait {+ command_id,+ owner,+ entry,+ } = claimed;+ let session_id = owner.session_id().map(str::to_owned);self.remove_claimed_pending_inspector_await_owner(command_id, session_id.as_deref());self.cancel_runtime_await_job(command_id, session_id.as_deref(), reason);if let Some(correlation) = entry.renderer_correlation() {- self.discard_renderer_call_for_session_owner_if_matches(- session_id.as_deref(),- correlation,+ let _ = self.take_renderer_call_for_frontend_if_matches_for_owner(+ &owner,+ correlation.frontend_command_id().get(),+ correlation.renderer_call_id(),+ correlation.dispatched_attachment_id(),);}if let Some(listener) = entry.bidi_channel_listener() {- self.unregister_runtime_remote_object_group_for_session_owner(- entry.session_id(),+ self.unregister_runtime_remote_object_group_for_owner(+ &owner,listener.channel_object_group(),);}@@ -1540,23 +1808,23 @@ impl CdpConnection {fn apply_completed_pending_inspector_await_entry(&mut self,+ owner: &CommandOwnerScope,entry: PendingInspectorAwait,protocol_events: &[BackgroundProtocolEvent],) {- let routed_session_id = entry.session_id().map(str::to_owned);if let Some(object_group) = entry.object_group() {for event in protocol_events {if let Some((_, _, BackgroundCommandResponsePayloadRef::Success { result })) =event.command_response_payload_ref(){- self.register_runtime_remote_object_ids_from_value_for_session_owner_with_group(- routed_session_id.as_deref(),+ self.register_runtime_remote_object_ids_from_value_for_owner_with_group(+ owner,result,object_group,);} else if let Some(message) = event.protocol_message() {- self.register_runtime_remote_object_ids_from_value_for_session_owner_with_group(- routed_session_id.as_deref(),+ self.register_runtime_remote_object_ids_from_value_for_owner_with_group(+ owner,message,object_group,);@@ -1567,21 +1835,15 @@ impl CdpConnection {if let Some((_, _, BackgroundCommandResponsePayloadRef::Success { result })) =event.command_response_payload_ref(){- self.register_runtime_remote_object_ids_from_value_for_session_owner(- routed_session_id.as_deref(),- result,- );+ self.register_runtime_remote_object_ids_from_value_for_owner(owner, result);} else if let Some(message) = event.protocol_message() {- self.register_runtime_remote_object_ids_from_value_for_session_owner(- routed_session_id.as_deref(),- message,- );+ self.register_runtime_remote_object_ids_from_value_for_owner(owner, message);}}}if let Some(listener) = entry.bidi_channel_listener() {- self.unregister_runtime_remote_object_group_for_session_owner(- entry.session_id(),+ self.unregister_runtime_remote_object_group_for_owner(+ owner,listener.channel_object_group(),);}@@ -1608,6 +1870,22 @@ impl CdpConnection {.flatten()}+ fn remove_pending_inspector_await_for_owner(+ &mut self,+ cdp_request_id: u64,+ owner: &CommandOwnerScope,+ ) -> Option<PendingInspectorAwait> {+ if owner.session_id().is_some() {+ return self.remove_pending_inspector_await(cdp_request_id, owner.session_id());+ }+ self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.remove_pending_inspector_await(cdp_request_id),+ )+ .flatten()+ }+fn remove_pending_inspector_await_for_cancellation(&mut self,cdp_request_id: u64,@@ -1626,6 +1904,28 @@ impl CdpConnection {entry}+ fn remove_pending_inspector_await_for_cancellation_for_owner(+ &mut self,+ cdp_request_id: u64,+ owner: &CommandOwnerScope,+ ) -> Option<PendingInspectorAwait> {+ let entry = self.remove_pending_inspector_await_for_owner(cdp_request_id, owner);+ if let Some(correlation) = entry+ .as_ref()+ .and_then(PendingInspectorAwait::renderer_correlation)+ {+ let _ = self.take_renderer_call_for_frontend_if_matches_for_owner(+ owner,+ correlation.frontend_command_id().get(),+ correlation.renderer_call_id(),+ correlation.dispatched_attachment_id(),+ );+ } else if entry.is_none() {+ let _ = self.take_renderer_call_for_frontend_for_owner(owner, cdp_request_id);+ }+ entry+ }+fn discard_renderer_call_for_session_owner_if_matches(&mut self,session_id: Option<&str>,@@ -1936,6 +2236,62 @@ impl CdpConnection {push_terminated_renderer_call_error_background_events(out, terminated, session_id, reason);}+ pub(crate) fn fail_pending_inspector_awaits_for_owner_background_events_into(+ &mut self,+ out: &mut Vec<BackgroundProtocolEvent>,+ claimed_background_events: &mut Vec<BackgroundProtocolEvent>,+ owner: &CommandOwnerScope,+ reason: &'static str,+ ) {+ if owner.session_id().is_some() {+ self.fail_pending_inspector_awaits_for_session_owner_background_events_into(+ out,+ claimed_background_events,+ owner.session_id(),+ reason,+ );+ return;+ }++ let claimed = self.drain_claimed_pending_inspector_await_owners_for_owner(owner);+ self.push_claimed_pending_inspector_await_owner_errors(+ claimed_background_events,+ claimed,+ reason,+ );+ let drained = self+ .with_target_devtools_session_state_for_route_mut(+ None,+ owner.session_owner_route(),+ |state| state.drain_pending_inspector_awaits(),+ )+ .unwrap_or_default();+ for (cdp_id, entry) in drained {+ self.cancel_runtime_await_job(cdp_id, entry.session_id(), reason);+ if let Some(listener) = entry.bidi_channel_listener() {+ self.unregister_runtime_remote_object_group_for_owner(+ owner,+ listener.channel_object_group(),+ );+ continue;+ }+ push_pending_inspector_await_error_background_event(+ out,+ cdp_id,+ entry.session_id(),+ reason,+ );+ }+ let terminated = self+ .with_target_devtools_session_state_for_route_mut(+ None,+ owner.session_owner_route(),+ |state| state.terminate_all_renderer_calls(reason),+ )+ .unwrap_or_default();+ push_terminated_renderer_call_error_background_events(out, terminated, None, reason);+ }+pub(crate) fn validate_runtime_remote_object_ids_for_session_owner(&self,session_id: Option<&str>,@@ -1963,6 +2319,35 @@ impl CdpConnection {Ok(())}+ pub(crate) fn validate_runtime_remote_object_ids_for_owner(+ &self,+ owner: &CommandOwnerScope,+ object_ids: &[String],+ ) -> Result<(), String> {+ if owner.session_id().is_some() {+ return self.validate_runtime_remote_object_ids_for_session_owner(+ owner.session_id(),+ object_ids,+ );+ }+ if object_ids.is_empty() {+ return Ok(());+ }+ let Some(owner_identity) = self.runtime_remote_object_owner_identity_for_owner(owner)+ else {+ return Ok(());+ };+ for object_id in object_ids {+ if self.runtime_remote_object_id_known_for_owner(owner, object_id) {+ continue;+ }+ if self.runtime_remote_object_id_known_for_different_owner(&owner_identity, object_id) {+ return Err("Cannot find object with given id".to_owned());+ }+ }+ Ok(())+ }+pub(crate) fn runtime_remote_object_id_known_for_session_owner(&self,session_id: Option<&str>,@@ -1982,6 +2367,22 @@ impl CdpConnection {.is_some_and(|state| state.has_runtime_remote_object_id(object_id))}+ pub(crate) fn runtime_remote_object_id_known_for_owner(+ &self,+ owner: &CommandOwnerScope,+ object_id: &str,+ ) -> bool {+ if owner.session_id().is_some() {+ return self+ .runtime_remote_object_id_known_for_session_owner(owner.session_id(), object_id);+ }+ self.target_devtools_session_state_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ .is_some_and(|state| state.has_runtime_remote_object_id(object_id))+ }+pub(crate) fn register_runtime_remote_object_ids_from_value_for_session_owner(&mut self,session_id: Option<&str>,@@ -2005,6 +2406,25 @@ impl CdpConnection {);}+ pub(crate) fn register_runtime_remote_object_ids_from_value_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ value: &Value,+ ) {+ if owner.session_id().is_some() {+ self.register_runtime_remote_object_ids_from_value_for_session_owner(+ owner.session_id(),+ value,+ );+ return;+ }+ self.register_runtime_remote_object_ids_from_value_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ value,+ );+ }+pub(crate) fn register_runtime_remote_object_ids_from_value_for_session_owner_with_group(&mut self,session_id: Option<&str>,@@ -2034,6 +2454,28 @@ impl CdpConnection {);}+ pub(crate) fn register_runtime_remote_object_ids_from_value_for_owner_with_group(+ &mut self,+ owner: &CommandOwnerScope,+ value: &Value,+ object_group: &str,+ ) {+ if owner.session_id().is_some() {+ self.register_runtime_remote_object_ids_from_value_for_session_owner_with_group(+ owner.session_id(),+ value,+ object_group,+ );+ return;+ }+ self.register_runtime_remote_object_ids_from_value_for_route_with_group(+ owner.session_id(),+ owner.session_owner_route(),+ value,+ object_group,+ );+ }+pub(crate) fn runtime_remote_object_group_for_session_owner(&self,session_id: Option<&str>,@@ -2058,6 +2500,23 @@ impl CdpConnection {.map(str::to_owned)}+ pub(crate) fn runtime_remote_object_group_for_owner(+ &self,+ owner: &CommandOwnerScope,+ object_id: &str,+ ) -> Option<String> {+ if owner.session_id().is_some() {+ return self+ .runtime_remote_object_group_for_session_owner(owner.session_id(), object_id);+ }+ self.target_devtools_session_state_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?+ .runtime_remote_object_group(object_id)+ .map(str::to_owned)+ }+pub(crate) fn runtime_remote_object_realm_for_session_owner(&self,session_id: Option<&str>,@@ -2082,6 +2541,23 @@ impl CdpConnection {.map(str::to_owned)}+ pub(crate) fn runtime_remote_object_realm_for_owner(+ &self,+ owner: &CommandOwnerScope,+ object_id: &str,+ ) -> Option<String> {+ if owner.session_id().is_some() {+ return self+ .runtime_remote_object_realm_for_session_owner(owner.session_id(), object_id);+ }+ self.target_devtools_session_state_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?+ .runtime_remote_object_realm(object_id)+ .map(str::to_owned)+ }+pub(crate) fn runtime_remote_object_alias_for_session_owner(&self,session_id: Option<&str>,@@ -2106,6 +2582,49 @@ impl CdpConnection {.map(str::to_owned)}+ pub(crate) fn runtime_remote_object_alias_for_owner(+ &self,+ owner: &CommandOwnerScope,+ object_id: &str,+ ) -> Option<String> {+ if owner.session_id().is_some() {+ return self+ .runtime_remote_object_alias_for_session_owner(owner.session_id(), object_id);+ }+ self.target_devtools_session_state_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?+ .runtime_remote_object_alias(object_id)+ .map(str::to_owned)+ }++ pub(crate) fn register_runtime_remote_object_alias_for_owner_with_realm(+ &mut self,+ owner: &CommandOwnerScope,+ alias_id: String,+ object_id: String,+ realm_id: &str,+ ) {+ if owner.session_id().is_some() {+ self.register_runtime_remote_object_alias_for_session_owner_with_realm(+ owner.session_id(),+ alias_id,+ object_id,+ realm_id,+ );+ return;+ }+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| {+ state+ .register_runtime_remote_object_alias_with_realm(alias_id, object_id, realm_id);+ },+ );+ }+pub(crate) fn unregister_runtime_remote_object_ids_for_session_owner(&mut self,session_id: Option<&str>,@@ -2131,6 +2650,25 @@ impl CdpConnection {});}+ pub(crate) fn unregister_runtime_remote_object_ids_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ object_ids: &[String],+ ) {+ if owner.session_id().is_some() {+ self.unregister_runtime_remote_object_ids_for_session_owner(+ owner.session_id(),+ object_ids,+ );+ return;+ }+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.unregister_runtime_remote_object_ids(object_ids),+ );+ }+pub(crate) fn unregister_runtime_remote_object_group_for_session_owner(&mut self,session_id: Option<&str>,@@ -2153,6 +2691,25 @@ impl CdpConnection {});}+ pub(crate) fn unregister_runtime_remote_object_group_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ object_group: &str,+ ) {+ if owner.session_id().is_some() {+ self.unregister_runtime_remote_object_group_for_session_owner(+ owner.session_id(),+ object_group,+ );+ return;+ }+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.unregister_runtime_remote_object_group(object_group),+ );+ }+pub(crate) fn clear_runtime_remote_object_tracking_for_session_owner(&mut self,session_id: Option<&str>,@@ -2174,6 +2731,21 @@ impl CdpConnection {});}+ pub(crate) fn clear_runtime_remote_object_tracking_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ ) {+ if owner.session_id().is_some() {+ self.clear_runtime_remote_object_tracking_for_session_owner(owner.session_id());+ return;+ }+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ DevToolsSessionState::clear_runtime_remote_object_tracking,+ );+ }+pub(crate) fn record_runtime_contexts_reported_for_session_owner(&mut self,session_id: Option<&str>,@@ -2195,6 +2767,18 @@ impl CdpConnection {});}+ pub(crate) fn record_runtime_contexts_reported_for_owner(&mut self, owner: &CommandOwnerScope) {+ if owner.session_id().is_some() {+ self.record_runtime_contexts_reported_for_session_owner(owner.session_id());+ return;+ }+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ DevToolsSessionState::record_runtime_contexts_reported_to_frontend,+ );+ }+pub(crate) fn record_runtime_contexts_cleared_for_session_owner(&mut self,session_id: Option<&str>,@@ -2216,6 +2800,18 @@ impl CdpConnection {});}+ pub(crate) fn record_runtime_contexts_cleared_for_owner(&mut self, owner: &CommandOwnerScope) {+ if owner.session_id().is_some() {+ self.record_runtime_contexts_cleared_for_session_owner(owner.session_id());+ return;+ }+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ DevToolsSessionState::record_runtime_contexts_cleared_for_frontend,+ );+ }+pub(crate) fn record_runtime_context_protocol_event_for_session_owner(&mut self,session_id: Option<&str>,@@ -2253,6 +2849,16 @@ impl CdpConnection {}}+ pub(crate) fn record_runtime_context_protocol_event_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ event: &RuntimeContextProtocolEvent,+ ) {+ if owner.session_id().is_some() {+ self.record_runtime_context_protocol_event_for_session_owner(owner.session_id(), event);+ }+ }+pub(crate) fn clear_runtime_remote_objects_for_realm_for_session_owner(&mut self,session_id: Option<&str>,@@ -2275,6 +2881,25 @@ impl CdpConnection {});}+ pub(crate) fn clear_runtime_remote_objects_for_realm_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ realm_id: &str,+ ) {+ if owner.session_id().is_some() {+ self.clear_runtime_remote_objects_for_realm_for_session_owner(+ owner.session_id(),+ realm_id,+ );+ return;+ }+ let _ = self.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.clear_runtime_remote_objects_for_realm(realm_id),+ );+ }+pub(crate) fn register_runtime_remote_object_ids_for_session_owner_with_realm(&mut self,session_id: Option<&str>,@@ -2482,6 +3107,22 @@ impl CdpConnection {})}+ fn runtime_remote_object_owner_identity_for_owner(+ &self,+ owner: &CommandOwnerScope,+ ) -> Option<RuntimeRemoteObjectOwnerIdentity> {+ if owner.session_id().is_some() {+ return self.runtime_remote_object_owner_identity_for_session(owner.session_id());+ }+ let (browser_context_id, target_id) =+ self.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())?;+ Some(RuntimeRemoteObjectOwnerIdentity::Page {+ browser_context_id,+ target_id,+ devtools_session_id: None,+ })+ }+fn runtime_remote_object_id_known_for_different_owner(&self,owner: &RuntimeRemoteObjectOwnerIdentity,@@ -2675,13 +3316,14 @@ impl CdpConnection {response_events: &mut Vec<BackgroundProtocolEvent>,background_events: &mut Vec<BackgroundProtocolEvent>,) -> bool {+ let owner = CommandOwnerScope::capture(self, current_session_id);let mut current_seen = false;for message in messages {current_seen |= self- .route_runtime_inspector_protocol_message_with_background_events_into(+ .route_runtime_inspector_protocol_message_for_owner_with_background_events_into(message,current_cmd_id,- current_session_id,+ &owner,response_events,background_events,);@@ -2689,28 +3331,23 @@ impl CdpConnection {current_seen}- pub(crate) fn route_renderer_runtime_inspector_messages_with_background_events_into(+ pub(crate) fn route_renderer_runtime_inspector_messages_for_owner_with_background_events_into(&mut self,messages: Vec<RendererRuntimeInspectorMessage>,current_cmd_id: Option<u64>,- current_session_id: Option<&str>,+ owner: &CommandOwnerScope,response_events: &mut Vec<BackgroundProtocolEvent>,background_events: &mut Vec<BackgroundProtocolEvent>,) -> bool {+ let current_session_id = owner.session_id();let mut current_seen = false;for message in messages {match message {RendererRuntimeInspectorMessage::RuntimeContext(event) => {let mut event = RuntimeContextProtocolEvent::from_restore_event(event);- qualify_runtime_context_protocol_event_for_session_owner_typed(- self,- &mut event,- current_session_id,- );- apply_runtime_context_protocol_event_side_effects_typed(- self,- &event,- current_session_id,+ qualify_runtime_context_protocol_event_for_owner_typed(self, &mut event, owner);+ apply_runtime_context_protocol_event_side_effects_for_owner_typed(+ self, &event, owner,);let mut runtime_context_events = Vec::new();emit_runtime_context_protocol_background_event_typed(@@ -2726,10 +3363,10 @@ impl CdpConnection {}RendererRuntimeInspectorMessage::Protocol(message) => {current_seen |= self- .route_runtime_inspector_protocol_message_with_background_events_into(+ .route_runtime_inspector_protocol_message_for_owner_with_background_events_into(message.into_value(),current_cmd_id,- current_session_id,+ owner,response_events,background_events,);@@ -2739,21 +3376,24 @@ impl CdpConnection {current_seen}- pub(crate) fn route_renderer_runtime_command_output_into(+ pub(crate) fn route_renderer_runtime_command_output_for_owner_into(&mut self,output: RendererRuntimeCommandOutput,current_cmd_id: Option<u64>,- current_session_id: Option<&str>,+ owner: &CommandOwnerScope,ordered_events: &mut Vec<BackgroundProtocolEvent>,) -> bool {- if let Some(attachment_id) = output.renderer_agent_attachment_id()- && !self.renderer_agent_attachment_is_current_for_session_owner(- current_session_id,- attachment_id,- )- {+ let current_session_id = owner.session_id();+ let attachment_is_current =+ output+ .renderer_agent_attachment_id()+ .is_none_or(|attachment_id| {+ self.current_renderer_agent_attachment_id_for_owner(owner)+ == Some(attachment_id)+ });+ if !attachment_is_current {tracing::debug!(- ?attachment_id,+ attachment_id = ?output.renderer_agent_attachment_id(),session_id = current_session_id,"dropping renderer command output from a stale attachment");@@ -2762,18 +3402,21 @@ impl CdpConnection {if output.renderer_agent_attachment_id().is_some()&& let Some(state) = output.v8_state_update().cloned(){- let _ =- self.merge_v8_inspector_session_state_for_session_owner(current_session_id, state);+ let _ = self.merge_v8_inspector_session_state_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ state,+ );}let mut current_seen = false;for message in output.into_messages() {let mut response_events = Vec::new();let mut background_events = Vec::new();current_seen |= self- .route_renderer_runtime_inspector_messages_with_background_events_into(+ .route_renderer_runtime_inspector_messages_for_owner_with_background_events_into(vec![message],current_cmd_id,- current_session_id,+ owner,&mut response_events,&mut background_events,);@@ -2783,11 +3426,11 @@ impl CdpConnection {current_seen}- pub(crate) fn route_renderer_command_turn_output_into(+ pub(crate) fn route_renderer_command_turn_output_for_owner_into(&mut self,output: RendererCommandTurnOutput,current_cmd_id: Option<u64>,- current_session_id: Option<&str>,+ owner: &CommandOwnerScope,response_flush: &CommandResponseFlushContext,ordered_events: &mut Vec<BackgroundProtocolEvent>,post_response_events: &mut Vec<BackgroundProtocolEvent>,@@ -2801,31 +3444,34 @@ impl CdpConnection {tracing::error!("Runtime command turn completed with a non-Runtime reply");return (false, renderer_output_predecessor);};- (- self.route_renderer_runtime_command_output_into(- output,- current_cmd_id,- current_session_id,- ordered_events,- ),- renderer_output_predecessor,- )+ let response_seen = self.route_renderer_runtime_command_output_for_owner_into(+ output,+ current_cmd_id,+ owner,+ ordered_events,+ );+ (response_seen, renderer_output_predecessor)}- fn route_runtime_inspector_protocol_message_with_background_events_into(+ fn route_runtime_inspector_protocol_message_for_owner_with_background_events_into(&mut self,- mut message: Value,+ message: Value,current_cmd_id: Option<u64>,- current_session_id: Option<&str>,+ owner: &CommandOwnerScope,response_events: &mut Vec<BackgroundProtocolEvent>,background_events: &mut Vec<BackgroundProtocolEvent>,) -> bool {+ let current_session_id = owner.session_id();+ let mut message = message;let id = message.get("id").and_then(Value::as_u64);match id {Some(id) => {- if let Some(entry) = self.remove_pending_inspector_await(id, current_session_id) {- let owner_route =- self.runtime_await_owner_route_for_session(entry.session_id());+ let entry = self.remove_pending_inspector_await_for_owner(id, owner);+ if let Some(entry) = entry {+ let owner_route = owner+ .session_owner_route()+ .cloned()+ .or_else(|| self.runtime_await_owner_route_for_session(entry.session_id()));let response = OwnerRuntimeResponse::from_pending_inspector_await(id,entry,@@ -2840,10 +3486,7 @@ impl CdpConnection {);}if Some(id) == current_cmd_id {- self.register_runtime_remote_object_ids_from_value_for_session_owner(- current_session_id,- &message,- );+ self.register_runtime_remote_object_ids_from_value_for_owner(owner, &message);let response =BackgroundCommandResponsePayload::from_owned_runtime_inspector_message(message,@@ -2894,10 +3537,11 @@ impl CdpConnection {.into_iter().map(str::to_owned).collect::<Vec<_>>();- crate::domains::page::emit_page_window_open_background_events(+ crate::domains::page::emit_page_window_open_background_events_for_route(self,background_events,- current_session_id,+ owner.session_id(),+ owner.session_owner_route(),url,window_name,&window_features,@@ -2905,22 +3549,13 @@ impl CdpConnection {);return false;}- self.register_runtime_remote_object_ids_from_value_for_session_owner(- current_session_id,- &message,- );+ self.register_runtime_remote_object_ids_from_value_for_owner(owner, &message);if let Some(mut event) =RuntimeContextProtocolEvent::from_context_protocol_message(message.clone()){- qualify_runtime_context_protocol_event_for_session_owner_typed(- self,- &mut event,- current_session_id,- );- apply_runtime_context_protocol_event_side_effects_typed(- self,- &event,- current_session_id,+ qualify_runtime_context_protocol_event_for_owner_typed(self, &mut event, owner);+ apply_runtime_context_protocol_event_side_effects_for_owner_typed(+ self, &event, owner,);let mut runtime_context_events = Vec::new();emit_runtime_context_protocol_background_event_typed(@@ -2946,13 +3581,14 @@ impl CdpConnection {false}- pub async fn route_scheduler_deferred_runtime_inspector_response_into(+ pub(crate) async fn route_scheduler_deferred_runtime_inspector_response_into(&mut self,- response: RuntimeInspectorResponseReady,- current_session_id: Option<&str>,+ mut response: RuntimeInspectorResponseReady,+ owner: &CommandOwnerScope,response_events: &mut Vec<BackgroundProtocolEvent>,background_events: &mut Vec<BackgroundProtocolEvent>,) -> (bool, Option<moli_core::RendererOutputFence>) {+ response.bind_owner(owner);let Some(response) = self.resolve_runtime_inspector_response_ready(response) else {return (false, None);};@@ -2965,14 +3601,15 @@ impl CdpConnection {response.into_renderer_command_output();let (renderer_agent_attachment_id, v8_state_update, messages) = output.into_parts();let mut ordered_events = Vec::new();- let current_seen = self.route_renderer_runtime_command_output_into(- RendererRuntimeCommandOutput::from_parts(- renderer_agent_attachment_id,- v8_state_update,- messages,- ),+ let output = RendererRuntimeCommandOutput::from_parts(+ renderer_agent_attachment_id,+ v8_state_update,+ messages,+ );+ let current_seen = self.route_renderer_runtime_command_output_for_owner_into(+ output,Some(current_cmd_id),- current_session_id,+ owner,&mut ordered_events,);response_events.extend(ordered_events);@@ -2982,18 +3619,30 @@ impl CdpConnection {pub fn route_registered_runtime_inspector_response_into(&mut self,- response: RuntimeInspectorResponseReady,+ mut response: RuntimeInspectorResponseReady,response_events: &mut Vec<BackgroundProtocolEvent>,background_events: &mut Vec<BackgroundProtocolEvent>,) {+ let owner = response+ .owner()+ .cloned()+ .or_else(|| response.session_id().map(CommandOwnerScope::for_session));+ let Some(owner) = owner else {+ tracing::debug!(+ command_id = response.command_id(),+ "dropping implicit runtime Inspector response without an exact owner"+ );+ return;+ };+ response.bind_owner(&owner);let Some(response) = self.resolve_runtime_inspector_response_ready(response) else {return;};let message = response.into_protocol_message_for_typed_runtime_route();- self.route_runtime_inspector_protocol_message_with_background_events_into(+ self.route_runtime_inspector_protocol_message_for_owner_with_background_events_into(message,None,- None,+ &owner,response_events,background_events,);@@ -3008,23 +3657,35 @@ impl CdpConnection {}let command_id = response.command_id();let session_id = response.session_id().map(str::to_owned);+ let owner = response.owner().cloned();let correlation = if let Some(renderer_call_id) = response.renderer_call_id() {let dispatched_attachment_id = response.renderer_agent_attachment_id();// A lease can complete immediately before attachment cutover while// its response-ready event is still queued. The registry mapping// proves that this exact old lease won before rotation; requiring// the attachment to remain current here would lose that response.- self.take_renderer_call_for_frontend_if_matches_for_session_owner(- session_id.as_deref(),- command_id,- renderer_call_id,- dispatched_attachment_id,- )+ match owner.as_ref() {+ Some(owner) => self.take_renderer_call_for_frontend_if_matches_for_owner(+ owner,+ command_id,+ renderer_call_id,+ dispatched_attachment_id,+ ),+ None => self.take_renderer_call_for_frontend_if_matches_for_session_owner(+ session_id.as_deref(),+ command_id,+ renderer_call_id,+ dispatched_attachment_id,+ ),+ }} else {- self.take_renderer_call_for_frontend_for_session_owner(- session_id.as_deref(),- command_id,- )+ match owner.as_ref() {+ Some(owner) => self.take_renderer_call_for_frontend_for_owner(owner, command_id),+ None => self.take_renderer_call_for_frontend_for_session_owner(+ session_id.as_deref(),+ command_id,+ ),+ }};let Some(correlation) = correlation else {tracing::debug!(@@ -3078,6 +3739,41 @@ impl CdpConnection {}}+ fn restore_frontend_command_ids_in_runtime_messages_for_owner(+ &mut self,+ owner: &CommandOwnerScope,+ dispatched_attachment_id: Option<RendererAgentAttachmentId>,+ messages: &mut [RendererRuntimeInspectorMessage],+ ) {+ if dispatched_attachment_id.is_some_and(|attachment_id| {+ self.current_renderer_agent_attachment_id_for_owner(owner) != Some(attachment_id)+ }) {+ return;+ }+ for message in messages {+ let RendererRuntimeInspectorMessage::Protocol(message) = message else {+ continue;+ };+ let Some(renderer_call_id) = message.renderer_call_id() else {+ continue;+ };+ let Some(correlation) = self+ .take_frontend_command_for_renderer_if_attachment_matches_for_owner(+ owner,+ renderer_call_id,+ dispatched_attachment_id,+ )+ else {+ continue;+ };+ debug_assert_eq!(+ correlation.dispatched_attachment_id(),+ dispatched_attachment_id+ );+ message.value_mut()["id"] = json!(correlation.frontend_command_id().get());+ }+ }+/// Resolves terminal responses carried by the renderer's concrete/// DevTools session output stream.///@@ -3228,29 +3924,29 @@ impl CdpConnection {fn start_or_enqueue_registered_runtime_inspector_response_ready(&self,command_id: u64,- session_id: Option<&str>,+ owner: &CommandOwnerScope,mut response_rx: RuntimeInspectorResponseReceiver,) -> bool {let Some(response_tx) = self.runtime_inspector_response_ready_sender() else {return false;};- let session_id = session_id.map(str::to_owned);+ let owner = owner.clone();// Keep both completion timings on the same response-ready lane. If the// renderer callback has already completed, enqueue it immediately; if// not, spawn a waiter that will enqueue the same event later.match response_rx.try_recv() {Ok(completion) => {- let _ = response_tx.send(crate::conn::RuntimeInspectorResponseReady::new(+ let _ = response_tx.send(crate::conn::RuntimeInspectorResponseReady::for_owner(command_id,- session_id.as_deref(),+ &owner,Ok(completion),));return true;}Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {- let _ = response_tx.send(crate::conn::RuntimeInspectorResponseReady::new(+ let _ = response_tx.send(crate::conn::RuntimeInspectorResponseReady::for_owner(command_id,- session_id.as_deref(),+ &owner,Err("RuntimeInspectorResponseCanceled".to_owned()),));return true;@@ -3261,10 +3957,8 @@ impl CdpConnection {let response = response_rx.await.map_err(|_| "RuntimeInspectorResponseCanceled".to_owned());- let _ = response_tx.send(crate::conn::RuntimeInspectorResponseReady::new(- command_id,- session_id.as_deref(),- response,+ let _ = response_tx.send(crate::conn::RuntimeInspectorResponseReady::for_owner(+ command_id, &owner, response,));});true@@ -3291,14 +3985,16 @@ impl CdpConnection {}let routed_session_id = response.session_id().map(str::to_owned);if let Some(object_group) = response.object_group() {- self.register_runtime_remote_object_ids_from_value_for_session_owner_with_group(+ self.register_runtime_remote_object_ids_from_value_for_route_with_group(routed_session_id.as_deref(),+ response.owner_route(),&response.message,object_group,);} else {- self.register_runtime_remote_object_ids_from_value_for_session_owner(+ self.register_runtime_remote_object_ids_from_value_for_route(routed_session_id.as_deref(),+ response.owner_route(),&response.message,);}@@ -3408,19 +4104,26 @@ impl CdpConnection {BidiChannelListenerRoute::Event(event)}- pub(crate) async fn document_node_snapshot_for_runtime_remote_object_id_async(+ pub(crate) async fn document_node_snapshot_for_runtime_remote_object_id_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_id: &str,depth: i32,pierce: bool,) -> Result<Option<DocumentNodeObjectSnapshot>, String> {- let include_whitespace =- crate::domains::dom::dom_agent_includes_whitespace_for_session(self, session_id);+ let include_whitespace = crate::domains::dom::dom_agent_includes_whitespace_for_route(+ self,+ owner.session_id(),+ owner.session_owner_route(),+ );+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );let pending = {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.start_document_node_snapshot_for_object_id_in_inspector_session(- session_id.map(str::to_owned),+ inspector_session_id,include_whitespace,object_id,depth,@@ -3432,20 +4135,20 @@ impl CdpConnection {.wait().await.map_err(|error| format!("resolve runtime node snapshot failed: {error}"))?;- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.finish_document_node_snapshot_for_object_id(completion).map_err(|error| format!("resolve runtime node snapshot failed: {error}"))}- pub(crate) async fn document_node_snapshot_for_backend_node_id_async(+ pub(crate) async fn document_node_snapshot_for_backend_node_id_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,backend_node_id: u32,depth: i32,pierce: bool,) -> Result<Option<DocumentNodeObjectSnapshot>, String> {let pending = {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.start_document_node_snapshot_for_backend_node_id(backend_node_id, depth, pierce).map_err(|error| format!("resolve backend node snapshot failed: {error}"))?};@@ -3453,7 +4156,7 @@ impl CdpConnection {.wait().await.map_err(|error| format!("resolve backend node snapshot failed: {error}"))?;- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.finish_document_node_snapshot_for_backend_node_id(completion).map_err(|error| format!("resolve backend node snapshot failed: {error}"))}@@ -3464,10 +4167,23 @@ impl CdpConnection {shared_id: &str,backend_node_id: u32,) -> Result<(), String> {- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);+ let owner = CommandOwnerScope::capture(self, session_id);+ self.register_document_bidi_node_binding_for_owner_async(&owner, shared_id, backend_node_id)+ .await+ }++ pub(crate) async fn register_document_bidi_node_binding_for_owner_async(+ &mut self,+ owner: &CommandOwnerScope,+ shared_id: &str,+ backend_node_id: u32,+ ) -> Result<(), String> {+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );let pending = {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.start_register_document_bidi_node_binding(inspector_session_id,shared_id.to_owned(),@@ -3479,20 +4195,22 @@ impl CdpConnection {.wait().await.map_err(|error| format!("register BiDi node binding failed: {error}"))?;- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.finish_register_document_bidi_node_binding(completion).map_err(|error| format!("register BiDi node binding failed: {error}"))}- pub(crate) async fn document_bidi_node_binding_for_session_owner_async(+ pub(crate) async fn document_bidi_node_binding_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,shared_id: &str,) -> Result<RendererDomBidiNodeBindingResolution, String> {- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );let pending = {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.start_document_bidi_node_binding(inspector_session_id, shared_id.to_owned()).map_err(|error| format!("resolve BiDi node binding failed: {error}"))?};@@ -3500,7 +4218,7 @@ impl CdpConnection {.wait().await.map_err(|error| format!("resolve BiDi node binding failed: {error}"))?;- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.finish_document_bidi_node_binding(completion).map_err(|error| format!("resolve BiDi node binding failed: {error}"))}@@ -3529,17 +4247,19 @@ impl CdpConnection {.map_err(|error| format!("resolve BiDi node shared id failed: {error}"))}- pub(crate) async fn runtime_remote_object_for_backend_node_id_async(+ pub(crate) async fn runtime_remote_object_for_backend_node_id_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,backend_node_id: u32,execution_context_id: Option<i64>,object_group: Option<&str>,) -> Result<Option<Value>, String> {- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );let pending = {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.start_resolve_runtime_object_for_backend_node_id_in_inspector_session(inspector_session_id,backend_node_id,@@ -3552,7 +4272,7 @@ impl CdpConnection {.wait().await.map_err(|error| format!("resolve runtime object for backend node failed: {error}"))?;- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let result = page.finish_resolve_runtime_object_for_backend_node_id(completion).map_err(|error| format!("resolve runtime object for backend node failed: {error}"))?;@@ -3636,29 +4356,32 @@ impl CdpConnection {.await}- pub(crate) fn start_runtime_enable_events_for_session_owner(+ pub(crate) fn start_runtime_enable_events_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Result<PendingRuntimeEnableEventsDispatch, String> {- let route = self.runtime_protocol_message_page_route_for_session_owner(session_id)?;- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);- let page = self.runtime_session_owner_page_mut(session_id)?;+ let route = self.runtime_protocol_message_page_route_for_owner(owner)?;+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let pending = page.start_runtime_enable_events_for_inspector_session(inspector_session_id.as_deref()).map_err(|error| format!("runtime enable event replay failed: {error}"))?;Ok(PendingRuntimeEnableEventsDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),route,pending,})}- pub(crate) fn complete_runtime_enable_events_for_session_owner(+ pub(crate) fn complete_runtime_enable_events(&mut self,completed: CompletedRuntimeEnableEventsDispatch,) -> Result<RuntimeEnableEventsReplay, String> {- let session_id = completed.session_id.as_deref();+ let owner = completed.owner;+ let session_id = owner.session_id();let page = self.runtime_protocol_message_started_page_mut(&completed.route)?;let output = page.finish_runtime_enable_output(completed.completion)@@ -3670,21 +4393,25 @@ impl CdpConnection {);}if let Some(state) = v8_state_update- && !self.merge_v8_inspector_session_state_for_session_owner(session_id, state)+ && !self.merge_v8_inspector_session_state_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ state,+ ){return Err("Runtime.enable completed after session owner disappeared".to_owned());}let mut replay = RuntimeEnableEventsReplay::from_renderer_messages(messages);- let _ = self.set_renderer_runtime_agent_owns_page_console_api_events_for_session_owner(- session_id, true,+ let _ =+ self.set_renderer_runtime_agent_owns_page_console_api_events_for_owner(&owner, true);+ self.ingest_runtime_session_owner_output_updates_for_route(+ owner.session_id(),+ owner.session_owner_route(),);- self.ingest_runtime_session_owner_output_updates(session_id);for event in replay.events_mut() {match event {RuntimeEnableReplayEvent::Context(event) => {- qualify_runtime_context_protocol_event_for_session_owner_typed(- self, event, session_id,- );+ qualify_runtime_context_protocol_event_for_owner_typed(self, event, &owner);}RuntimeEnableReplayEvent::Background(event) => {event.ensure_protocol_session_id(session_id);@@ -3701,11 +4428,24 @@ impl CdpConnection {self.loaded_page_mut_for_protocol_access(session_id)}- fn runtime_session_owner_page_mut_for_interruptible_control(+ fn runtime_session_owner_page_mut_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,+ ) -> Result<&mut Page, String> {+ self.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ }++ fn runtime_session_owner_page_mut_for_interruptible_control_for_owner(+ &mut self,+ owner: &CommandOwnerScope,) -> Result<&mut Page, String> {- self.loaded_page_mut_for_interruptible_protocol_access(session_id)+ self.loaded_page_mut_for_interruptible_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )}fn runtime_protocol_message_page_route_for_session_owner(@@ -3727,6 +4467,28 @@ impl CdpConnection {})}+ fn runtime_protocol_message_page_route_for_owner(+ &self,+ owner: &CommandOwnerScope,+ ) -> Result<RuntimeProtocolMessagePageRoute, String> {+ let (browser_context_id, target_id) = self+ .target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())+ .ok_or_else(|| "NoDocumentLoaded".to_owned())?;+ let slot = self.runtime_session_owner_slot_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?;+ let renderer_agent_attachment_id = slot+ .current_renderer_attachment()+ .ok_or_else(|| "NoDocumentLoaded".to_owned())?+ .id();+ Ok(RuntimeProtocolMessagePageRoute {+ browser_context_id,+ target_id,+ renderer_agent_attachment_id,+ })+ }+fn runtime_protocol_message_started_slot_mut(&mut self,route: &RuntimeProtocolMessagePageRoute,@@ -4351,10 +5113,10 @@ impl CdpConnection {command_id: u64,) -> Result<Vec<RendererRuntimeInspectorMessage>, String> {let descriptor = RendererCommandDescriptor::from_synthesized_payload(raw_json.to_owned())?;- let pending = self- .start_runtime_protocol_message_for_session_owner_with_deferred_response(- session_id, descriptor, command_id,- )?;+ let owner = CommandOwnerScope::capture(self, session_id);+ let pending = self.start_runtime_protocol_message_for_owner_with_deferred_response(+ &owner, descriptor, command_id,+ )?;let completed = pending.wait().await?;self.complete_runtime_helper_protocol_message_for_session_owner_async(completed, command_id).await@@ -4389,47 +5151,48 @@ impl CdpConnection {Some(RendererRuntimeInspectorMessage::protocol(message))}- pub(crate) fn start_runtime_protocol_message_for_session_owner(+ pub(crate) fn start_runtime_protocol_message_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,raw_json: String,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {- self.start_runtime_protocol_message_for_session_owner_with_access(- session_id,+ self.start_runtime_protocol_message_for_owner_with_access(+ owner,raw_json,RendererInspectorCommandRoute::MainThread,)}- pub(crate) fn start_runtime_io_protocol_message_for_session_owner(+ pub(crate) fn start_runtime_io_protocol_message_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,raw_json: String,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {- self.start_runtime_protocol_message_for_session_owner_with_access(- session_id,+ self.start_runtime_protocol_message_for_owner_with_access(+ owner,raw_json,RendererInspectorCommandRoute::Io,)}- fn start_runtime_protocol_message_for_session_owner_with_access(+ fn start_runtime_protocol_message_for_owner_with_access(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,raw_json: String,inspector_route: RendererInspectorCommandRoute,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {- let route = self.runtime_protocol_message_page_route_for_session_owner(session_id)?;- let raw_json =- self.rewrite_runtime_inspector_command_for_session_owner(session_id, &raw_json, None)?;- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);+ let route = self.runtime_protocol_message_page_route_for_owner(owner)?;+ let raw_json = self.rewrite_runtime_inspector_command_for_owner(owner, &raw_json, None)?;+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );let page = match inspector_route {RendererInspectorCommandRoute::MainThread => {- self.runtime_session_owner_page_mut(session_id)?+ self.runtime_session_owner_page_mut_for_owner(owner)?}RendererInspectorCommandRoute::Io => {- self.runtime_session_owner_page_mut_for_interruptible_control(session_id)?+ self.runtime_session_owner_page_mut_for_interruptible_control_for_owner(owner)?}};let pending = match inspector_route {@@ -4445,71 +5208,72 @@ impl CdpConnection {}.map_err(|error| format!("runtime inspector dispatch failed: {error}"))?;Ok(PendingRuntimeProtocolMessageDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),route,pending,response_route: RuntimeProtocolResponseRoute::command_reply_without_receiver(),})}- pub(crate) fn start_runtime_protocol_message_for_session_owner_with_deferred_response(+ pub(crate) fn start_runtime_protocol_message_for_owner_with_deferred_response(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,descriptor: RendererCommandDescriptor,command_id: u64,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {- self.start_runtime_protocol_message_for_session_owner_with_deferred_response_and_access(- session_id,+ self.start_runtime_protocol_message_for_owner_with_deferred_response_and_access(+ owner,descriptor,command_id,RendererInspectorCommandRoute::MainThread,)}- pub(crate) fn start_runtime_io_protocol_message_for_session_owner_with_deferred_response(+ pub(crate) fn start_runtime_io_protocol_message_for_owner_with_deferred_response(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,descriptor: RendererCommandDescriptor,command_id: u64,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {- self.start_runtime_protocol_message_for_session_owner_with_deferred_response_and_access(- session_id,+ self.start_runtime_protocol_message_for_owner_with_deferred_response_and_access(+ owner,descriptor,command_id,RendererInspectorCommandRoute::Io,)}- fn start_runtime_protocol_message_for_session_owner_with_deferred_response_and_access(+ fn start_runtime_protocol_message_for_owner_with_deferred_response_and_access(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,descriptor: RendererCommandDescriptor,command_id: u64,inspector_route: RendererInspectorCommandRoute,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {- let route = self.runtime_protocol_message_page_route_for_session_owner(session_id)?;+ let route = self.runtime_protocol_message_page_route_for_owner(owner)?;let (correlation, raw_json, response_sender, response_route) = self- .prepare_renderer_call_for_session_owner(- session_id,+ .prepare_renderer_call_for_owner(+ owner,descriptor,command_id,Some(route.renderer_agent_attachment_id),)?;- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );let page_result = match inspector_route {RendererInspectorCommandRoute::MainThread => {- self.runtime_session_owner_page_mut(session_id)+ self.runtime_session_owner_page_mut_for_owner(owner)}RendererInspectorCommandRoute::Io => {- self.runtime_session_owner_page_mut_for_interruptible_control(session_id)+ self.runtime_session_owner_page_mut_for_interruptible_control_for_owner(owner)}};let page = match page_result {Ok(page) => page,Err(error) => {- let removed =- self.take_renderer_call_for_frontend_for_session_owner(session_id, command_id);+ let removed = self.take_renderer_call_for_frontend_for_owner(owner, command_id);debug_assert_eq!(removed, Some(correlation));return Err(error);}@@ -4523,32 +5287,32 @@ impl CdpConnection {) {Ok(pending) => pending,Err(error) => {- let removed =- self.take_renderer_call_for_frontend_for_session_owner(session_id, command_id);+ let removed = self.take_renderer_call_for_frontend_for_owner(owner, command_id);debug_assert_eq!(removed, Some(correlation));return Err(format!("runtime inspector dispatch failed: {error}"));}};Ok(PendingRuntimeProtocolMessageDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),route,pending: PendingRuntimeProtocolMessageDispatchKind::Routable(pending),response_route,})}- pub(crate) fn start_runtime_protocol_message_with_context_resolution_for_session_owner(+ pub(crate) fn start_runtime_protocol_message_with_context_resolution_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,action: &str,raw_json: String,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {- let route = self.runtime_protocol_message_page_route_for_session_owner(session_id)?;- let raw_json =- self.rewrite_runtime_inspector_command_for_session_owner(session_id, &raw_json, None)?;- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);- let page = self.runtime_session_owner_page_mut(session_id)?;+ let route = self.runtime_protocol_message_page_route_for_owner(owner)?;+ let raw_json = self.rewrite_runtime_inspector_command_for_owner(owner, &raw_json, None)?;+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let pending = page.start_runtime_protocol_message_for_inspector_session_with_context_resolution(inspector_session_id,@@ -4557,35 +5321,36 @@ impl CdpConnection {).map_err(|error| format!("runtime inspector dispatch failed: {error}"))?;Ok(PendingRuntimeProtocolMessageDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),route,pending: PendingRuntimeProtocolMessageDispatchKind::Page(pending),response_route: RuntimeProtocolResponseRoute::command_reply_without_receiver(),})}- pub(crate) fn start_runtime_protocol_message_with_context_resolution_for_session_owner_with_deferred_response(+ pub(crate) fn start_runtime_protocol_message_with_context_resolution_for_owner_with_deferred_response(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,action: &str,descriptor: RendererCommandDescriptor,command_id: u64,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {- let route = self.runtime_protocol_message_page_route_for_session_owner(session_id)?;+ let route = self.runtime_protocol_message_page_route_for_owner(owner)?;let (correlation, raw_json, response_sender, response_route) = self- .prepare_renderer_call_for_session_owner(- session_id,+ .prepare_renderer_call_for_owner(+ owner,descriptor,command_id,Some(route.renderer_agent_attachment_id),)?;- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);- let page = match self.runtime_session_owner_page_mut(session_id) {+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = match self.runtime_session_owner_page_mut_for_owner(owner) {Ok(page) => page,Err(error) => {- let removed =- self.take_renderer_call_for_frontend_for_session_owner(session_id, command_id);+ let removed = self.take_renderer_call_for_frontend_for_owner(owner, command_id);debug_assert_eq!(removed, Some(correlation));return Err(error);}@@ -4599,25 +5364,25 @@ impl CdpConnection {) {Ok(pending) => pending,Err(error) => {- let removed =- self.take_renderer_call_for_frontend_for_session_owner(session_id, command_id);+ let removed = self.take_renderer_call_for_frontend_for_owner(owner, command_id);debug_assert_eq!(removed, Some(correlation));return Err(format!("runtime inspector dispatch failed: {error}"));}};Ok(PendingRuntimeProtocolMessageDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),route,pending: PendingRuntimeProtocolMessageDispatchKind::Routable(pending),response_route,})}- pub(crate) async fn complete_runtime_protocol_message_for_session_owner_async(+ pub(crate) async fn complete_runtime_protocol_message_async(&mut self,completed: CompletedRuntimeProtocolMessageDispatch,) -> Result<Option<RendererCommandTurnOutput>, String> {let timing_started = moli_trace::cdp_nav_timing_enabled().then(std::time::Instant::now);+ let owner = completed.owner().clone();let completion = match completed.completion {moli_core::page::CompletedRuntimeInspectorCommandDispatch::Owner(completion) => {*completion@@ -4662,8 +5427,8 @@ impl CdpConnection {runtime_messages.bind_renderer_agent_attachment(completed.route.renderer_agent_attachment_id);let runtime_messages = runtime_messages.messages_mut();- self.restore_frontend_command_ids_in_runtime_messages(- completed.session_id.as_deref(),+ self.restore_frontend_command_ids_in_runtime_messages_for_owner(+ &owner,Some(completed.route.renderer_agent_attachment_id),runtime_messages,);@@ -4688,6 +5453,7 @@ impl CdpConnection {let mut events = Vec::new();for replay in replays {let frontend_session_id = replay.frontend_session_id().map(str::to_owned);+ let owner = CommandOwnerScope::capture(self, frontend_session_id.as_deref());let renderer_inspector_session_id =replay.renderer_inspector_session_id().map(str::to_owned);let (correlation, replay, response_delivery, frontend_payload, response_sender) =@@ -4880,7 +5646,7 @@ impl CdpConnection {};let pending = match pending {Ok(pending) => PendingRuntimeProtocolMessageDispatch {- session_id: frontend_session_id.clone(),+ owner,route,pending,response_route:@@ -4914,6 +5680,7 @@ impl CdpConnection {continue;}};+ let completed_owner = completed.owner().clone();let completion = match completed.completion {moli_core::page::CompletedRuntimeInspectorCommandDispatch::Owner(completion) => {*completion@@ -4970,10 +5737,10 @@ impl CdpConnection {let _ = response_sender.send_output(output);continue;}- let _ = self.route_renderer_runtime_command_output_into(+ let _ = self.route_renderer_runtime_command_output_for_owner_into(output,None,- frontend_session_id.as_deref(),+ &completed_owner,&mut events,);}@@ -5064,9 +5831,9 @@ impl CdpConnection {command_id: u64,) -> Result<Vec<RendererRuntimeInspectorMessage>, String> {let response_rx = completed.take_deferred_response_receiver();- let session_id = completed.session_id.clone();+ let session_id = completed.owner().session_id().map(str::to_owned);let output = self- .complete_runtime_protocol_message_for_session_owner_async(completed)+ .complete_runtime_protocol_message_async(completed).await?;let response_in_output = output.as_ref().is_some_and(|output| {renderer_command_turn_frontend_protocol_response(output, command_id).is_some()@@ -5118,8 +5885,7 @@ impl CdpConnection {background_events: &mut Vec<BackgroundProtocolEvent>,) {let (owner, body) = action.into_parts();- let mut route_scope = owner.enter(self);- if !owner.is_current(route_scope.conn_mut()) {+ if !owner.is_current(self) {tracing::debug!(session_id = owner.session_id(),action = ?body,@@ -5127,33 +5893,29 @@ impl CdpConnection {);return;}- let session_id = owner.session_id().map(str::to_owned);+ let command_owner = owner.command_owner().clone();match body {BidiChannelOwnerActionBody::StartListener(listener) => {- route_scope- .conn_mut()- .start_bidi_channel_listener_once_for_session_owner_with_background_events_async(- session_id.as_deref(),- BidiChannelListenerResidence::from_boxed(owner, listener),- background_events,- )- .await;+ self.start_bidi_channel_listener_once_for_owner_with_background_events_async(+ &command_owner,+ BidiChannelListenerResidence::from_boxed(owner, listener),+ background_events,+ )+ .await;}BidiChannelOwnerActionBody::ReleaseObjectGroup(object_group) => {- route_scope- .conn_mut()- .release_bidi_channel_object_group_for_session_owner_best_effort_async(- session_id.as_deref(),- &object_group,- )- .await;+ self.release_bidi_channel_object_group_for_owner_best_effort_async(+ &command_owner,+ &object_group,+ )+ .await;}}}- pub(crate) async fn release_bidi_channel_object_group_for_session_owner_best_effort_async(+ pub(crate) async fn release_bidi_channel_object_group_for_owner_best_effort_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_group: &str,) {let command_id = self.next_internal_runtime_command_id();@@ -5167,16 +5929,13 @@ impl CdpConnection {Ok(descriptor) => descriptor,Err(error) => {tracing::debug!(%error, object_group, "failed to prepare BiDi object group release");- self.unregister_runtime_remote_object_group_for_session_owner(- session_id,- object_group,- );+ self.unregister_runtime_remote_object_group_for_owner(owner, object_group);return;}};let pending = match self- .start_runtime_protocol_message_with_context_resolution_for_session_owner_with_deferred_response(- session_id,+ .start_runtime_protocol_message_with_context_resolution_for_owner_with_deferred_response(+ owner,"releaseObjectGroup",descriptor,command_id,@@ -5188,46 +5947,37 @@ impl CdpConnection {object_group,"failed to start BiDi channel object group release");- self.unregister_runtime_remote_object_group_for_session_owner(- session_id,- object_group,- );+ self.unregister_runtime_remote_object_group_for_owner(owner, object_group);return;}};let mut completed = match pending.wait().await {Ok(completed) => completed,Err(error) => {- self.forget_pending_inspector_await(command_id, session_id);+ self.forget_pending_inspector_await_for_owner(command_id, owner);tracing::debug!(%error,object_group,"BiDi channel object group release dispatch failed");- self.unregister_runtime_remote_object_group_for_session_owner(- session_id,- object_group,- );+ self.unregister_runtime_remote_object_group_for_owner(owner, object_group);return;}};let mut renderer_response_rx = completed.take_deferred_response_receiver();let messages = match self- .complete_runtime_protocol_message_for_session_owner_async(completed)+ .complete_runtime_protocol_message_async(completed).await{Ok(messages) => messages,Err(error) => {- self.forget_pending_inspector_await(command_id, session_id);+ self.forget_pending_inspector_await_for_owner(command_id, owner);tracing::debug!(%error,object_group,"BiDi channel object group release completion failed");- self.unregister_runtime_remote_object_group_for_session_owner(- session_id,- object_group,- );+ self.unregister_runtime_remote_object_group_for_owner(owner, object_group);return;}};@@ -5235,10 +5985,10 @@ impl CdpConnection {let mut release_post_response_events = Vec::new();let response_flush = CommandResponseFlushContext::default();let release_response_seen = if let Some(messages) = messages {- self.route_renderer_command_turn_output_into(+ self.route_renderer_command_turn_output_for_owner_into(messages,Some(command_id),- session_id,+ owner,&response_flush,&mut release_events,&mut release_post_response_events,@@ -5258,9 +6008,9 @@ impl CdpConnection {}release_events.extend(release_post_response_events);if let Some(renderer_response_rx) = renderer_response_rx {- let response = RuntimeInspectorResponseReady::new(+ let response = RuntimeInspectorResponseReady::for_owner(command_id,- session_id,+ owner,renderer_response_rx.await.map_err(|_| "RuntimeInspectorResponseCanceled".to_owned()),@@ -5272,12 +6022,13 @@ impl CdpConnection {renderer_output_predecessor.is_none(),"internal object-group cleanup cannot discard a concrete output cursor");- let release_response_seen = self.route_renderer_runtime_command_output_into(- output,- Some(command_id),- session_id,- &mut release_events,- );+ let release_response_seen = self+ .route_renderer_runtime_command_output_for_owner_into(+ output,+ Some(command_id),+ owner,+ &mut release_events,+ );if !release_response_seen {tracing::debug!(command_id,@@ -5286,19 +6037,19 @@ impl CdpConnection {}}}- self.unregister_runtime_remote_object_group_for_session_owner(session_id, object_group);+ self.unregister_runtime_remote_object_group_for_owner(owner, object_group);}- async fn start_bidi_channel_listener_once_for_session_owner_with_background_events_async(+ async fn start_bidi_channel_listener_once_for_owner_with_background_events_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,residence: BidiChannelListenerResidence,background_events: &mut Vec<BackgroundProtocolEvent>,) {let listener = residence.listener();if self.runtime_inspector_response_ready_sender().is_none() {- self.release_bidi_channel_object_group_for_session_owner_best_effort_async(- session_id,+ self.release_bidi_channel_object_group_for_owner_best_effort_async(+ owner,listener.channel_object_group(),).await;@@ -5310,8 +6061,8 @@ impl CdpConnection {Ok(descriptor) => descriptor,Err(error) => {tracing::debug!(%error, "failed to prepare BiDi channel listener command");- self.release_bidi_channel_object_group_for_session_owner_best_effort_async(- session_id,+ self.release_bidi_channel_object_group_for_owner_best_effort_async(+ owner,listener.channel_object_group(),).await;@@ -5319,8 +6070,8 @@ impl CdpConnection {}};let pending = match self- .start_runtime_protocol_message_with_context_resolution_for_session_owner_with_deferred_response(- session_id,+ .start_runtime_protocol_message_with_context_resolution_for_owner_with_deferred_response(+ owner,"callFunctionOn",descriptor,command_id,@@ -5332,20 +6083,20 @@ impl CdpConnection {channel = %listener.properties().channel,"failed to start BiDi channel listener");- self.release_bidi_channel_object_group_for_session_owner_best_effort_async(- session_id,+ self.release_bidi_channel_object_group_for_owner_best_effort_async(+ owner,listener.channel_object_group(),).await;return;}};- self.register_pending_bidi_channel_listener(command_id, session_id, residence);+ self.register_pending_bidi_channel_listener_for_owner(command_id, owner, residence);let mut completed = match pending.wait().await {Ok(completed) => completed,Err(error) => {let object_group = self- .remove_pending_inspector_await_for_cancellation(command_id, session_id)+ .remove_pending_inspector_await_for_cancellation_for_owner(command_id, owner).and_then(|entry| {entry.bidi_channel_listener()@@ -5353,8 +6104,8 @@ impl CdpConnection {});tracing::debug!(%error, "BiDi channel listener dispatch failed");if let Some(object_group) = object_group {- self.release_bidi_channel_object_group_for_session_owner_best_effort_async(- session_id,+ self.release_bidi_channel_object_group_for_owner_best_effort_async(+ owner,&object_group,).await;@@ -5364,13 +6115,13 @@ impl CdpConnection {};let mut renderer_response_rx = completed.take_deferred_response_receiver();let messages = match self- .complete_runtime_protocol_message_for_session_owner_async(completed)+ .complete_runtime_protocol_message_async(completed).await{Ok(messages) => messages,Err(error) => {let object_group = self- .remove_pending_inspector_await_for_cancellation(command_id, session_id)+ .remove_pending_inspector_await_for_cancellation_for_owner(command_id, owner).and_then(|entry| {entry.bidi_channel_listener()@@ -5378,8 +6129,8 @@ impl CdpConnection {});tracing::debug!(%error, "BiDi channel listener completion failed");if let Some(object_group) = object_group {- self.release_bidi_channel_object_group_for_session_owner_best_effort_async(- session_id,+ self.release_bidi_channel_object_group_for_owner_best_effort_async(+ owner,&object_group,).await;@@ -5391,10 +6142,10 @@ impl CdpConnection {let mut listener_post_response_events = Vec::new();let response_flush = CommandResponseFlushContext::default();let listener_response_seen = if let Some(messages) = messages {- self.route_renderer_command_turn_output_into(+ self.route_renderer_command_turn_output_for_owner_into(messages,Some(command_id),- session_id,+ owner,&response_flush,&mut listener_events,&mut listener_post_response_events,@@ -5433,13 +6184,13 @@ impl CdpConnection {// oneshot is already completed or still pending.if self.start_or_enqueue_registered_runtime_inspector_response_ready(command_id,- session_id,+ owner,renderer_response_rx,) {return;}let object_group = self- .remove_pending_inspector_await_for_cancellation(command_id, session_id)+ .remove_pending_inspector_await_for_cancellation_for_owner(command_id, owner).and_then(|entry| {entry.bidi_channel_listener()@@ -5450,8 +6201,8 @@ impl CdpConnection {"BiDi channel listener started without scheduler runtime response hook");if let Some(object_group) = object_group {- self.release_bidi_channel_object_group_for_session_owner_best_effort_async(- session_id,+ self.release_bidi_channel_object_group_for_owner_best_effort_async(+ owner,&object_group,).await;@@ -5459,14 +6210,14 @@ impl CdpConnection {}}- pub(crate) async fn runtime_realm_inventory_for_session_owner_async(+ pub(crate) async fn runtime_realm_inventory_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Result<Vec<RuntimeExecutionContextEvent>, String> {let target_id = self- .target_owner_identity_for_session(session_id)+ .target_owner_identity_for_route(owner.session_id(), owner.session_owner_route()).and_then(|(_, target_id)| target_id);- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let target_id = target_id.as_deref();let devtools_target_id = target_id.map(DevToolsTargetId::from);let realms = page@@ -5502,16 +6253,6 @@ impl CdpConnection {.map_err(|error| format!("runtime default execution context lookup failed: {error}"))}- pub(crate) async fn runtime_default_or_initial_execution_context_id_for_session_owner_async(- &mut self,- session_id: Option<&str>,- ) -> Result<Option<i64>, String> {- let page = self.runtime_session_owner_page_mut(session_id)?;- page.default_or_initial_execution_context_id_async()- .await- .map_err(|error| format!("runtime default execution context lookup failed: {error}"))- }-pub(crate) async fn runtime_default_or_initial_execution_context_id_for_owner_async(&mut self,owner: &CommandOwnerScope,@@ -5528,16 +6269,16 @@ impl CdpConnection {.map_err(|error| format!("runtime default execution context lookup failed: {error}"))}- pub(crate) async fn runtime_ensure_isolated_world_for_session_owner_async(+ pub(crate) async fn runtime_ensure_isolated_world_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,frame_id: Option<&str>,world_name: &str,) -> Result<i64, String> {let owner_target_id = self- .target_owner_identity_for_session(session_id)+ .target_owner_identity_for_route(owner.session_id(), owner.session_owner_route()).and_then(|(_, target_id)| target_id);- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let result = if let Some(frame_id) = frame_id&& owner_target_id.as_deref() != Some(frame_id){@@ -5585,33 +6326,42 @@ impl CdpConnection {session_id: Option<&str>,frame_id: &str,) -> Result<Option<i64>, String> {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let owner = CommandOwnerScope::capture(self, session_id);+ self.child_default_execution_context_id_for_frame_id_for_owner_async(&owner, frame_id)+ .await+ }++ pub(crate) async fn child_default_execution_context_id_for_frame_id_for_owner_async(+ &mut self,+ owner: &CommandOwnerScope,+ frame_id: &str,+ ) -> Result<Option<i64>, String> {+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.child_default_execution_context_id_for_frame_id_async(frame_id).await.map_err(|error| format!("runtime child default context lookup failed: {error}"))}- pub(crate) fn start_child_default_execution_context_lookup_for_session_owner(+ pub(crate) fn start_child_default_execution_context_lookup_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,execution_context_id: i64,) -> Result<PendingRuntimeChildDefaultContextLookupDispatch, String> {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let pending = page.start_child_frame_id_for_default_execution_context_id(execution_context_id).map_err(|error| format!("runtime child default context lookup failed: {error}"))?;Ok(PendingRuntimeChildDefaultContextLookupDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),pending,})}- pub(crate) fn complete_child_default_execution_context_lookup_for_session_owner(+ pub(crate) fn complete_child_default_execution_context_lookup(&mut self,completed: CompletedRuntimeChildDefaultContextLookupDispatch,) -> Result<bool, String> {- let session_id = completed.session_id.as_deref();- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(&completed.owner)?;page.finish_child_frame_id_for_default_execution_context_id(completed.completion).map(|frame_id| frame_id.is_some()).map_err(|error| format!("runtime child default context lookup failed: {error}"))@@ -5753,35 +6503,41 @@ impl CdpConnection {.map_err(|error| format!("runtime binding install failed: {error}"))}- pub(crate) fn start_install_runtime_binding_for_session_owner(+ pub(crate) fn start_install_runtime_binding_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,name: &str,execution_context_name: Option<&str>,execution_context_id: Option<i64>,) -> Result<PendingRuntimeBindingPageCommandDispatch, String> {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let pending = page.start_install_runtime_binding(name, execution_context_name, execution_context_id).map_err(|error| format!("runtime binding install failed: {error}"))?;Ok(PendingRuntimeBindingPageCommandDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),operation: "runtime binding install",pending,})}- pub(crate) fn start_apply_stored_runtime_bindings_for_session_owner(+ pub(crate) fn start_apply_stored_runtime_bindings_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Result<PendingRuntimeBindingPageCommandDispatch, String> {- let stored_runtime_bindings =- self.target_runtime_bindings_for_renderer_session_owner(session_id);- let session_runtime_bindings =- self.target_runtime_bindings_for_current_inspector_session_owner(session_id);- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);- let page = self.runtime_session_owner_page_mut(session_id)?;+ let stored_runtime_bindings = self.target_runtime_bindings_for_renderer_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let session_runtime_bindings = self.target_runtime_bindings_for_current_inspector_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let pending = page.start_set_runtime_binding_state(inspector_session_id,@@ -5790,7 +6546,7 @@ impl CdpConnection {).map_err(|error| format!("runtime binding state update failed: {error}"))?;Ok(PendingRuntimeBindingPageCommandDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),operation: "runtime binding state update",pending,})@@ -5800,13 +6556,28 @@ impl CdpConnection {&mut self,session_id: Option<&str>,) -> Result<(), String> {- let stored_runtime_bindings =- self.target_runtime_bindings_for_renderer_session_owner(session_id);- let session_runtime_bindings =- self.target_runtime_bindings_for_current_inspector_session_owner(session_id);- let inspector_session_id =- self.target_renderer_runtime_inspector_session_id_for_session(session_id);- let page = self.runtime_session_owner_page_mut(session_id)?;+ let owner = CommandOwnerScope::capture(self, session_id);+ self.apply_runtime_binding_state_for_owner_async(&owner)+ .await+ }++ pub(crate) async fn apply_runtime_binding_state_for_owner_async(+ &mut self,+ owner: &CommandOwnerScope,+ ) -> Result<(), String> {+ let stored_runtime_bindings = self.target_runtime_bindings_for_renderer_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let session_runtime_bindings = self.target_runtime_bindings_for_current_inspector_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let inspector_session_id = self.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;page.set_runtime_binding_state_async(inspector_session_id,&stored_runtime_bindings,@@ -5832,28 +6603,27 @@ impl CdpConnection {.map_err(|error| format!("runtime binding removal failed: {error}"))}- pub(crate) fn start_remove_runtime_binding_for_session_owner(+ pub(crate) fn start_remove_runtime_binding_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,name: &str,) -> Result<PendingRuntimeBindingPageCommandDispatch, String> {- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(owner)?;let pending = page.start_remove_runtime_binding(name).map_err(|error| format!("runtime binding removal failed: {error}"))?;Ok(PendingRuntimeBindingPageCommandDispatch {- session_id: session_id.map(str::to_owned),+ owner: owner.clone(),operation: "runtime binding removal",pending,})}- pub(crate) fn complete_runtime_binding_page_command_for_session_owner(+ pub(crate) fn complete_runtime_binding_page_command(&mut self,completed: CompletedRuntimeBindingPageCommandDispatch,) -> Result<(), String> {- let session_id = completed.session_id.as_deref();- let page = self.runtime_session_owner_page_mut(session_id)?;+ let page = self.runtime_session_owner_page_mut_for_owner(&completed.owner)?;page.finish_unit_runtime_page_command(completed.completion, completed.operation).map_err(|error| format!("{} failed: {error}", completed.operation))}@@ -6870,7 +7640,11 @@ mod tests {channel: &str,) -> BidiChannelListenerResidence {BidiChannelListenerResidence::new(- BidiChannelPageOwner::capture(conn, Some(session_id)).expect("test Page attachment"),+ BidiChannelPageOwner::capture_for_owner(+ conn,+ CommandOwnerScope::for_session(session_id),+ )+ .expect("test Page attachment"),bidi_channel_listener_for_test(channel),)}@@ -7041,9 +7815,15 @@ mod tests {.and_then(|node_id| u32::try_from(node_id).ok()).expect("DOM.describeNode should return backendNodeId");+ let owner = CommandOwnerScope::capture(&ctx.conn, None);let snapshot = ctx.conn- .document_node_snapshot_for_backend_node_id_async(None, backend_node_id, 1, false)+ .document_node_snapshot_for_backend_node_id_for_owner_async(+ &owner,+ backend_node_id,+ 1,+ false,+ ).await.expect("document node id snapshot command should complete").expect("target node snapshot should exist");@@ -7349,12 +8129,25 @@ mod tests {conn.register_pending_inspector_await(1, Some("SID-active"));conn.register_pending_inspector_await(1, Some("SID-bg"));- conn.register_runtime_await_job(1, Some("SID-active"), None, "evaluate");- conn.register_runtime_await_job(1, Some("SID-bg"), None, "evaluate");+ conn.register_runtime_await_job_for_owner(+ 1,+ &CommandOwnerScope::for_session("SID-active"),+ None,+ "evaluate",+ );+ conn.register_runtime_await_job_for_owner(+ 1,+ &CommandOwnerScope::for_session("SID-bg"),+ None,+ "evaluate",+ );assert_eq!(conn.pending_runtime_await_jobs.len(), 2);let claimed = conn- .claim_pending_inspector_await_for_scheduler_deferred_reply(1, Some("SID-active"))+ .claim_pending_inspector_await_for_scheduler_deferred_reply(+ 1,+ &CommandOwnerScope::for_session("SID-active"),+ ).expect("active session await should be independently claimable");assert!(conn.has_claimed_pending_inspector_awaits_for_session_owner(Some("SID-active")));assert!(!conn.has_unclaimed_pending_inspector_awaits_for_session_owner(Some("SID-active")));@@ -7429,9 +8222,9 @@ mod tests {).expect("first renderer command should own the frontend id").correlation();- conn.try_register_pending_inspector_await_with_object_group(+ conn.try_register_pending_inspector_await_with_object_group_for_owner(17,- Some("SID-duplicate-owner"),+ &CommandOwnerScope::for_session("SID-duplicate-owner"),None,).expect("await state is registered before renderer dispatch");@@ -7625,13 +8418,18 @@ mod tests {));conn.browser_context = Some(browser_context);- conn.try_register_pending_inspector_await_with_object_group(+ conn.try_register_pending_inspector_await_with_object_group_for_owner(77,- Some("SID-bg"),+ &CommandOwnerScope::for_session("SID-bg"),Some("runtime-group"),).unwrap();- conn.register_runtime_await_job(77, Some("SID-bg"), Some("runtime-group"), "evaluate");+ conn.register_runtime_await_job_for_owner(+ 77,+ &CommandOwnerScope::for_session("SID-bg"),+ Some("runtime-group"),+ "evaluate",+ );let mut response_events = Vec::new();let mut background_events = Vec::new();diff --git a/moli-protocol/src/conn/runtime_load.rs b/moli-protocol/src/conn/runtime_load.rsindex 00a22e1a8..6427f5dcf 100644--- a/moli-protocol/src/conn/runtime_load.rs+++ b/moli-protocol/src/conn/runtime_load.rs@@ -1553,13 +1553,14 @@ impl CdpConnection {.with_main_document_commit_seed(RendererMainDocumentCommitSeed::from_navigation(navigation))}- pub(crate) fn prepared_document_commit_configuration_for_session_owner(+ pub(crate) fn prepared_document_commit_configuration_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,final_url: &Url,) -> Result<PreparedDocumentPageCommitConfiguration, String> {- let idle_override = self.idle_override_for_navigation(session_id, final_url);- let load_inputs = self.navigation_load_inputs_for_session_owner(session_id);+ let idle_override = self.idle_override_for_navigation(owner, final_url);+ let load_inputs =+ self.navigation_load_inputs_for_route(owner.session_id(), owner.session_owner_route());// The renderer runtime is shared by the BrowserContext, but each Page// target owns its NavigationEngine and may have a different transport// identity. Resolve through that target's engine at the commit@@ -1604,7 +1605,7 @@ impl CdpConnection {fn idle_override_for_navigation(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,final_url: &Url,) -> Option<moli_core::page::EmulatedIdleOverride> {// Chromium stores this override on RenderFrameHostImpl's IdleManager,@@ -1612,7 +1613,7 @@ impl CdpConnection {// navigation can retain that frame-host state; a cross-site renderer// replacement must start with the actual idle state.let page = self- .runtime_session_owner_slot(session_id)+ .runtime_session_owner_slot_for_route(owner.session_id(), owner.session_owner_route()).ok()?.loaded_page()?;moli_site::same_site_urls(page.final_url(), final_url, true)@@ -2219,8 +2220,10 @@ impl CdpConnection {&mut self,raw_url: &str,) -> Result<LoadedNavigation, String> {- let load_inputs = self.navigation_load_inputs_for_session_owner(None);- self.load_navigation_via_runtime_with_load_inputs_async(None, raw_url, load_inputs)+ let owner = CommandOwnerScope::capture(self, None);+ let load_inputs =+ self.navigation_load_inputs_for_route(owner.session_id(), owner.session_owner_route());+ self.load_navigation_via_runtime_with_load_inputs_async(&owner, raw_url, load_inputs).await}@@ -2237,21 +2240,22 @@ impl CdpConnection {session_id: Option<&str>,raw_url: &str,) -> Result<LoadedNavigation, String> {+ let owner = CommandOwnerScope::capture(self, session_id);let load_inputs = self.navigation_fixture_load_inputs_for_session_owner(session_id)?;- self.load_navigation_via_runtime_with_load_inputs_async(session_id, raw_url, load_inputs)+ self.load_navigation_via_runtime_with_load_inputs_async(&owner, raw_url, load_inputs).await}async fn load_navigation_via_runtime_with_load_inputs_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,raw_url: &str,load_inputs: TargetNavigationLoadInputs,) -> Result<LoadedNavigation, String> {let request_headers = load_inputs.extra_http_headers.clone();let navigation = self.load_navigation_request_via_runtime_with_network_events_and_load_inputs_async(- session_id,+ owner,load_inputs,"GET",raw_url,@@ -2260,20 +2264,20 @@ impl CdpConnection {MainDocumentBodyProgressSource::default(),).await?;- self.commit_navigation_load_outcome_for_session_owner_async(session_id, navigation)+ self.commit_navigation_load_outcome_for_owner_async(owner, navigation).await}- async fn commit_navigation_load_outcome_for_session_owner_async(+ async fn commit_navigation_load_outcome_for_owner_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,navigation: NavigationLoadOutcome,) -> Result<LoadedNavigation, String> {match navigation {NavigationLoadOutcome::ResponseCommitReady(navigation) => {let navigation = *navigation;- let configuration = self.prepared_document_commit_configuration_for_session_owner(- session_id,+ let configuration = self.prepared_document_commit_configuration_for_owner(+ owner,navigation.final_url(),)?;navigation@@ -2319,12 +2323,13 @@ impl CdpConnection {body_progress_source: MainDocumentBodyProgressSource,request_load_policy: NavigationRequestLoadPolicy,) -> Result<NavigationLoadOutcome, String> {+ let owner = CommandOwnerScope::capture(self, session_id);let load_inputs = apply_navigation_request_load_policy(- self.navigation_load_inputs_for_session_owner(session_id),+ self.navigation_load_inputs_for_route(owner.session_id(), owner.session_owner_route()),request_load_policy,);self.load_navigation_request_via_runtime_with_network_events_and_load_inputs_async(- session_id,+ &owner,load_inputs,method,raw_url,@@ -2341,7 +2346,7 @@ impl CdpConnection {body_progress_source: MainDocumentBodyProgressSource,) -> Result<NavigationLoadOutcome, String> {self.load_navigation_request_via_runtime_with_network_events_and_load_inputs_async(- navigation.owner.session_id(),+ &navigation.owner,self.navigation_load_inputs_for_navigation(navigation),&navigation.request_method,navigation.requested_url.as_str(),@@ -2355,7 +2360,7 @@ impl CdpConnection {#[allow(clippy::too_many_arguments)]async fn load_navigation_request_via_runtime_with_network_events_and_load_inputs_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,load_inputs: TargetNavigationLoadInputs,method: &str,raw_url: &str,@@ -2395,11 +2400,8 @@ impl CdpConnection {}} else {let mut inline_engine = self.background_navigation_engine_for_load_inputs(&load_inputs);- let page_reservation = self.reserve_renderer_page_for_session_owner(- session_id,- &load_inputs,- &inline_engine,- );+ let page_reservation =+ self.reserve_renderer_page_for_owner(owner, &load_inputs, &inline_engine);if let Some(navigation) = self.load_inline_html_navigation_with_engine_async(&mut inline_engine,@@ -2449,7 +2451,7 @@ impl CdpConnection {).await?;self.build_navigation_from_streaming_raw_response_with_load_inputs_async(- session_id,+ owner,&load_inputs,requested_url,method.to_owned(),@@ -2557,13 +2559,18 @@ impl CdpConnection {/// navigation future is still running. The protocol target therefore must/// own the reservation at job construction time rather than trying to infer/// it from `ResponseCommitReady` after the future completes.- fn reserve_renderer_page_for_session_owner(+ fn reserve_renderer_page_for_owner(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,load_inputs: &TargetNavigationLoadInputs,engine: &NavigationEngine,) -> RendererPageReservationToken {- self.reserve_renderer_page_for_route(session_id, None, load_inputs, engine)+ self.reserve_renderer_page_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ load_inputs,+ engine,+ )}fn reserve_renderer_page_for_route(@@ -2882,12 +2889,13 @@ impl CdpConnection {response_headers: Vec<(String, String)>,response_body: String,) -> Result<LoadedNavigation, String> {+ let owner = CommandOwnerScope::capture(self, session_id);let load_inputs = self.navigation_fixture_load_inputs_for_session_owner(session_id)?;let initial_request_cookie_report =load_inputs.request_cookie_report_for_navigation(&requested_url, &request_method, true);let navigation = self.build_navigation_from_buffered_body_source_with_load_inputs_async(- session_id,+ &owner,&load_inputs,requested_url.clone(),requested_url,@@ -2901,7 +2909,7 @@ impl CdpConnection {MainDocumentBodyProgressSource::default(),).await?;- self.commit_navigation_load_outcome_for_session_owner_async(session_id, navigation)+ self.commit_navigation_load_outcome_for_owner_async(&owner, navigation).await}@@ -2969,7 +2977,7 @@ impl CdpConnection {) -> Result<NavigationLoadOutcome, String> {let load_inputs = self.navigation_load_inputs_for_navigation(navigation);self.build_navigation_from_buffered_body_source_with_load_inputs_async(- navigation.owner.session_id(),+ &navigation.owner,&load_inputs,navigation.requested_url.clone(),final_url,@@ -2988,7 +2996,7 @@ impl CdpConnection {#[allow(clippy::too_many_arguments)]async fn build_navigation_from_buffered_body_source_with_load_inputs_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,load_inputs: &TargetNavigationLoadInputs,requested_url: Url,final_url: Url,@@ -3015,7 +3023,7 @@ impl CdpConnection {negotiated_http_version: None,};self.build_navigation_from_captured_raw_response_with_load_inputs_async(- session_id,+ owner,load_inputs,requested_url,request_method,@@ -3170,9 +3178,10 @@ impl CdpConnection {.map_err(|error| format!("failed to fetch page `{raw_url}`: {error}"))}- pub(crate) async fn fetch_navigation_auth_raw_response_for_session_owner_async(+ pub(crate) async fn fetch_navigation_auth_raw_response_for_route_async(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_load_policy: NavigationRequestLoadPolicy,method: &str,raw_url: &str,@@ -3181,7 +3190,7 @@ impl CdpConnection {auth: SubresourceAuthCredentials,) -> Result<NetworkFetchResult<RawResponse>, String> {let load_inputs = apply_navigation_request_load_policy(- self.navigation_load_inputs_for_session_owner(session_id),+ self.navigation_load_inputs_for_route(session_id, owner_route),request_load_policy,);ensure_url_not_blocked_for_load_inputs(&load_inputs, raw_url)?;@@ -3231,9 +3240,10 @@ impl CdpConnection {.await}- pub(crate) async fn fetch_navigation_streaming_raw_response_for_session_owner_async(+ pub(crate) async fn fetch_navigation_streaming_raw_response_for_route_async(&mut self,session_id: Option<&str>,+ owner_route: Option<&CdpSessionRoute>,request_load_policy: NavigationRequestLoadPolicy,method: &str,raw_url: &str,@@ -3242,7 +3252,7 @@ impl CdpConnection {auth: Option<SubresourceAuthCredentials>,) -> Result<NetworkFetchResult<StreamingRawResponse>, String> {let load_inputs = apply_navigation_request_load_policy(- self.navigation_load_inputs_for_session_owner(session_id),+ self.navigation_load_inputs_for_route(session_id, owner_route),request_load_policy,);self.fetch_navigation_streaming_raw_response_with_load_inputs_async(@@ -3461,9 +3471,11 @@ impl CdpConnection {request_headers: Vec<(String, String)>,response: NetworkFetchResult<RawResponse>,) -> Result<NavigationLoadOutcome, String> {- let load_inputs = self.navigation_load_inputs_for_session_owner(session_id);+ let owner = CommandOwnerScope::capture(self, session_id);+ let load_inputs =+ self.navigation_load_inputs_for_route(owner.session_id(), owner.session_owner_route());self.build_navigation_from_buffered_raw_response_with_load_inputs_async(- session_id,+ &owner,&load_inputs,requested_url,request_method,@@ -3480,7 +3492,7 @@ impl CdpConnection {) -> Result<NavigationLoadOutcome, String> {let load_inputs = self.navigation_load_inputs_for_navigation(navigation);self.build_navigation_from_buffered_raw_response_with_load_inputs_async(- navigation.owner.session_id(),+ &navigation.owner,&load_inputs,navigation.requested_url.clone(),navigation.request_method.clone(),@@ -3492,7 +3504,7 @@ impl CdpConnection {async fn build_navigation_from_buffered_raw_response_with_load_inputs_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,load_inputs: &TargetNavigationLoadInputs,requested_url: Url,request_method: String,@@ -3515,7 +3527,7 @@ impl CdpConnection {let head = response.head();let body = CapturedBody::from_bytes(response.clone_body_bytes());self.build_navigation_from_captured_raw_response_with_load_inputs_async(- session_id,+ owner,load_inputs,requested_url,request_method,@@ -3538,7 +3550,7 @@ impl CdpConnection {) -> Result<NavigationLoadOutcome, String> {let load_inputs = self.navigation_load_inputs_for_navigation(navigation);self.build_navigation_from_captured_raw_response_with_load_inputs_async(- navigation.owner.session_id(),+ &navigation.owner,&load_inputs,navigation.requested_url.clone(),navigation.request_method.clone(),@@ -3554,7 +3566,7 @@ impl CdpConnection {#[allow(clippy::too_many_arguments)]async fn build_navigation_from_captured_raw_response_with_load_inputs_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,load_inputs: &TargetNavigationLoadInputs,requested_url: Url,request_method: String,@@ -3603,8 +3615,7 @@ impl CdpConnection {}let mut engine = self.background_navigation_engine_for_load_inputs(load_inputs);- let page_reservation =- self.reserve_renderer_page_for_session_owner(session_id, load_inputs, &engine);+ let page_reservation = self.reserve_renderer_page_for_owner(owner, load_inputs, &engine);let navigation = prepare_navigation_from_captured_raw_response_with_engine_async(&mut engine,page_reservation,@@ -3654,9 +3665,11 @@ impl CdpConnection {response: NetworkFetchResult<StreamingRawResponse>,body_progress_source: MainDocumentBodyProgressSource,) -> Result<NavigationLoadOutcome, String> {- let load_inputs = self.navigation_load_inputs_for_session_owner(session_id);+ let owner = CommandOwnerScope::capture(self, session_id);+ let load_inputs =+ self.navigation_load_inputs_for_route(owner.session_id(), owner.session_owner_route());self.build_navigation_from_streaming_raw_response_with_load_inputs_async(- session_id,+ &owner,&load_inputs,requested_url,request_method,@@ -3677,7 +3690,7 @@ impl CdpConnection {) -> Result<NavigationLoadOutcome, String> {let load_inputs = self.navigation_load_inputs_for_navigation(navigation);self.build_navigation_from_streaming_raw_response_with_load_inputs_async(- navigation.owner.session_id(),+ &navigation.owner,&load_inputs,navigation.requested_url.clone(),navigation.request_method.clone(),@@ -3700,7 +3713,7 @@ impl CdpConnection {) -> Result<NavigationLoadOutcome, String> {let load_inputs = self.navigation_load_inputs_for_navigation(navigation);self.build_navigation_from_streaming_raw_response_with_load_inputs_async(- navigation.owner.session_id(),+ &navigation.owner,&load_inputs,navigation.requested_url.clone(),navigation.request_method.clone(),@@ -3716,7 +3729,7 @@ impl CdpConnection {#[allow(clippy::too_many_arguments)]async fn build_navigation_from_streaming_raw_response_with_load_inputs_async(&mut self,- session_id: Option<&str>,+ owner: &CommandOwnerScope,load_inputs: &TargetNavigationLoadInputs,requested_url: Url,request_method: String,@@ -3754,8 +3767,7 @@ impl CdpConnection {}let mut engine = self.background_navigation_engine_for_load_inputs(load_inputs);- let page_reservation =- self.reserve_renderer_page_for_session_owner(session_id, load_inputs, &engine);+ let page_reservation = self.reserve_renderer_page_for_owner(owner, load_inputs, &engine);let navigation = build_navigation_from_streaming_raw_response_with_engine_async(&mut engine,page_reservation,diff --git a/moli-protocol/src/conn/state/fetch.rs b/moli-protocol/src/conn/state/fetch.rsindex 5611af758..2845e7b0f 100644--- a/moli-protocol/src/conn/state/fetch.rs+++ b/moli-protocol/src/conn/state/fetch.rs@@ -2375,7 +2375,11 @@ mod tests {navigate_id: Some(1),owner: owner_session_id.map(crate::conn::CommandOwnerScope::for_session)- .unwrap_or_else(|| crate::conn::CommandOwnerScope::for_implicit_route(None)),+ .unwrap_or_else(|| {+ crate::conn::CommandOwnerScope::for_route(+ crate::conn::CdpSessionRoute::Browser,+ )+ }),result_projection: NavigationResultProjection::Cdp(json!({"frameId": "FRAME-1", "loaderId": "LOADER-1"}),),diff --git a/moli-protocol/src/conn/tests/mod.rs b/moli-protocol/src/conn/tests/mod.rsindex 5f4e9f852..a0fee975d 100644--- a/moli-protocol/src/conn/tests/mod.rs+++ b/moli-protocol/src/conn/tests/mod.rs@@ -7,10 +7,9 @@ use super::{BrowserContextFirstCookieRequest, BrowserContextReservedSiteDataOwnerState,BrowserContextSiteDataManagerOwnerState, BrowserContextStructuredCookieCommandVerdict,BrowserContextStructuredCookieWriteBackendStatus,- BrowserContextStructuredCookieWriteReadinessStatus, CdpConnection, CdpSessionRoute,- CommandDispatchContext, CommandResponseFlushContext, NavigationBackgroundEvent,- NavigationDispatchState, NavigationResultProjection, ServiceWorkerTargetState,- SharedWorkerTargetState, build_event,+ BrowserContextStructuredCookieWriteReadinessStatus, CdpConnection, CommandDispatchContext,+ CommandResponseFlushContext, NavigationBackgroundEvent, NavigationDispatchState,+ NavigationResultProjection, ServiceWorkerTargetState, SharedWorkerTargetState, build_event,};use crate::devtools_runtime::{AutomationEvent, DevToolsFrameId, DevToolsLoaderId, DevToolsTargetFilterEntry,@@ -436,12 +435,12 @@ fn background_navigation_completion_sender_routes_explicit_session_owners() {conn.set_background_navigation_completion_sender(sender);assert!(- conn.background_navigation_completion_sender_for_session_owner(Some("SID-active"))+ conn.background_navigation_completion_sender_for_route(Some("SID-active"), None).is_some(),"a command scoped to a concrete target owner can continue navigation work in the background");assert!(- conn.background_navigation_completion_sender_for_session_owner(Some("SID-inactive"))+ conn.background_navigation_completion_sender_for_route(Some("SID-inactive"), None).is_some(),"inactive-context target owners should also be routable by explicit session id");@@ -486,35 +485,6 @@ fn navigation_gate_resolves_websocket_events_to_their_session_target() {);}-#[test]-fn none_session_owner_route_override_scope_restores_previous_route_on_drop() {- let mut conn = CdpConnection::new();- let previous_route = CdpSessionRoute::PageTarget {- browser_context_id: "BID-active".to_owned(),- target_id: "TID-active".to_owned(),- is_attached_session: false,- };- let scoped_route = CdpSessionRoute::PageTarget {- browser_context_id: "BID-background".to_owned(),- target_id: "TID-background".to_owned(),- is_attached_session: false,- };-- conn.replace_none_session_owner_route_override(Some(previous_route.clone()));- {- let mut scope = conn.scoped_none_session_owner_route_override(scoped_route.clone());- assert_eq!(- scope.conn_mut().none_session_owner_route_override(),- Some(scoped_route)- );- }-- assert_eq!(- conn.none_session_owner_route_override(),- Some(previous_route)- );-}-#[test]fn navigation_background_event_queue_drains_current_token() {let mut conn = CdpConnection::new();@@ -1409,7 +1379,7 @@ async fn memory_diagnostics_splits_pending_inspector_await_counts_by_target_owne);assert_eq!(diagnostics["activeBrowserContext"]["targetHosts"]["pendingInspectorAwaitCount"],- json!(1)+ json!(3));}@@ -1681,7 +1651,7 @@ fn materialized_navigation_test_state() -> NavigationDispatchState {NavigationDispatchState {navigate_id,- owner: crate::conn::CommandOwnerScope::for_implicit_route(None),+ owner: crate::conn::CommandOwnerScope::for_route(crate::conn::CdpSessionRoute::Browser),result_projection: NavigationResultProjection::Cdp(json!({ "frameId": "TID-nav", "loaderId": loader_id }),),diff --git a/moli-protocol/src/conn/tests/resource_runtime.rs b/moli-protocol/src/conn/tests/resource_runtime.rsindex b30012cde..2442d112b 100644--- a/moli-protocol/src/conn/tests/resource_runtime.rs+++ b/moli-protocol/src/conn/tests/resource_runtime.rs@@ -1,8 +1,8 @@use super::*;use crate::DevToolsDocumentLifecycleWaitState;use crate::conn::{- CdpInitialStoragePartition, LoadedNavigation, NavigationLoadOutcome, PageTargetHost,- TargetIdentityState, TargetPageSlot,+ CdpInitialStoragePartition, CommandOwnerScope, LoadedNavigation, NavigationLoadOutcome,+ PageTargetHost, TargetIdentityState, TargetPageSlot,};use moli_core::runtime::storage_partition::StoragePartitionState;use std::sync::{@@ -49,8 +49,11 @@ async fn commit_navigation_outcome_for_session_test(NavigationLoadOutcome::ResponseCommitReady(navigation) => {let navigation = *navigation;let configuration = conn- .prepared_document_commit_configuration_for_session_owner(- session_id,+ .prepared_document_commit_configuration_for_owner(+ &match session_id {+ Some(session_id) => CommandOwnerScope::for_session(session_id),+ None => CommandOwnerScope::capture(conn, None),+ },navigation.final_url(),).expect("test navigation commit configuration should resolve");@@ -1577,8 +1580,8 @@ fn devtools_document_lifecycle_wait_key_observes_interruption_and_target_loss()),..started};- let (_, accepted) = conn.bind_renderer_document_lifecycle_for_session_owner(- Some("SID-lifecycle-wait"),+ let (_, accepted) = conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-lifecycle-wait"),moli_core::page::RendererPageCreationArtifacts {active_document: document,active_epoch: epoch,@@ -1661,8 +1664,8 @@ fn devtools_document_lifecycle_wait_key_observes_interruption_and_target_loss()},..started};- let (_, accepted) = conn.ingest_renderer_document_lifecycle_events_for_session_owner(- Some("SID-lifecycle-wait"),+ let (_, accepted) = conn.ingest_renderer_document_lifecycle_events_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-lifecycle-wait"),vec![terminated],);assert_eq!(accepted, vec![terminated]);@@ -1685,8 +1688,8 @@ fn devtools_document_lifecycle_wait_key_observes_interruption_and_target_loss().runtime_slot.set_page_attachment_id_for_test(902);conn.browser_context = Some(replacement_context);- let (_, accepted) = conn.bind_renderer_document_lifecycle_for_session_owner(- Some("SID-lifecycle-wait"),+ let (_, accepted) = conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-lifecycle-wait"),moli_core::page::RendererPageCreationArtifacts {active_document: document,active_epoch: epoch,@@ -1755,7 +1758,6 @@ fn devtools_target_context_resolves_background_page_without_ambient_route() {browser_context_id: None,};- assert_eq!(conn.none_session_owner_route_override(), None);let residence = conn.page_residence_identity_for_devtools_context(&context).expect("explicit target context should resolve its Page");@@ -1764,11 +1766,6 @@ fn devtools_target_context_resolves_background_page_without_ambient_route() {conn.devtools_context_document_navigation_state(&context),crate::DevToolsDocumentNavigationState::PendingNavigation);- assert_eq!(- conn.none_session_owner_route_override(),- None,- "explicit lookup must not mutate connection-global routing state"- );}#[tokio::test]diff --git a/moli-protocol/src/domains/accessibility/tests.rs b/moli-protocol/src/domains/accessibility/tests.rsindex f96dc3c62..291ff9806 100644--- a/moli-protocol/src/domains/accessibility/tests.rs+++ b/moli-protocol/src/domains/accessibility/tests.rs@@ -49,9 +49,10 @@ async fn load_page_async(ctx: &mut TestContext, html: &str) {}async fn complete_child_frame_lifecycle(ctx: &mut TestContext) {+ let owner = crate::conn::CommandOwnerScope::capture(&ctx.conn, None);let pending = ctx.conn- .start_child_frame_lifecycle_work_for_session_owner(None, std::time::Duration::from_secs(2))+ .start_child_frame_lifecycle_work_for_owner(owner, std::time::Duration::from_secs(2)).expect("loaded page should expose child-frame lifecycle work");let completed = pending.wait()diff --git a/moli-protocol/src/domains/activity/contextual_projection.rs b/moli-protocol/src/domains/activity/contextual_projection.rsindex 52031299a..c0c094106 100644--- a/moli-protocol/src/domains/activity/contextual_projection.rs+++ b/moli-protocol/src/domains/activity/contextual_projection.rs@@ -1,6 +1,4 @@-use url::Url;--use crate::conn::{BackgroundProtocolEvent, CommandDispatchContext};+use crate::conn::{BackgroundProtocolEvent, CommandDispatchContext, CommandOwnerScope};use crate::domains::network::{MainDocumentProgressBackgroundEventBarrier, MainDocumentProgressGate,};@@ -11,28 +9,30 @@ use crate::domains::network::{/// command. It cannot inspect renderer state, select Page work, retry a/// producer, or change the output families owned by the batch.pub(in crate::domains) struct ProtocolOutputProjectionContext<'a> {- pub(in crate::domains) session_id: Option<&'a str>,+ owner: &'a CommandOwnerScope,pub(in crate::domains) command: &'a mut CommandDispatchContext,pub(in crate::domains) subresource_frame_id: Option<&'a str>,- pub(in crate::domains) subresource_document_url: Option<&'a Url>,pub(in crate::domains) subresource_timestamp: Option<f64>,pub(in crate::domains) subresource_network_request_id: Option<&'a str>,}impl<'a> ProtocolOutputProjectionContext<'a> {pub(in crate::domains) fn new(- session_id: Option<&'a str>,+ owner: &'a CommandOwnerScope,command: &'a mut CommandDispatchContext,) -> Self {Self {- session_id,+ owner,command,subresource_frame_id: None,- subresource_document_url: None,subresource_timestamp: None,subresource_network_request_id: None,}}++ pub(in crate::domains) fn owner(&self) -> &CommandOwnerScope {+ self.owner+ }}/// Projection guard for main-document background events captured before the@@ -56,28 +56,24 @@ impl<'a> MainDocumentBodyCompleteProjection<'a> {#[cfg(test)]mod tests {- use url::Url;-- use crate::conn::CommandDispatchContext;+ use crate::conn::{CommandDispatchContext, CommandOwnerScope};use super::ProtocolOutputProjectionContext;#[test]fn plans_use_closed_projection_families_with_exact_context() {- let document_url = Url::parse("https://example.test/page").unwrap();+ let owner = CommandOwnerScope::for_session("session-1");let mut command = CommandDispatchContext::default();let context = ProtocolOutputProjectionContext {- session_id: Some("session-1"),+ owner: &owner,command: &mut command,subresource_frame_id: Some("frame-1"),- subresource_document_url: Some(&document_url),subresource_timestamp: Some(12.5),subresource_network_request_id: Some("REQ-1"),};- assert_eq!(context.session_id, Some("session-1"));+ assert_eq!(context.owner().session_id(), Some("session-1"));assert_eq!(context.subresource_frame_id, Some("frame-1"));- assert_eq!(context.subresource_document_url, Some(&document_url));assert_eq!(context.subresource_network_request_id, Some("REQ-1"));assert_eq!(context.subresource_timestamp, Some(12.5));}diff --git a/moli-protocol/src/domains/activity/main_document.rs b/moli-protocol/src/domains/activity/main_document.rsindex 08e410fae..973b4c38b 100644--- a/moli-protocol/src/domains/activity/main_document.rs+++ b/moli-protocol/src/domains/activity/main_document.rs@@ -226,7 +226,7 @@ impl MainDocumentNavigationActivity {page::emit_bound_renderer_document_lifecycle_background_events(conn,&mut renderer_lifecycle_events,- self.state.owner.session_id(),+ &self.state.owner,binding,&initial_renderer_document_lifecycle_events,);@@ -234,8 +234,8 @@ impl MainDocumentNavigationActivity {}if terminated_before_domcontentloaded {- conn.cancel_renderer_document_load_visibility_barrier_for_session_owner(- self.state.owner.session_id(),+ conn.cancel_renderer_document_load_visibility_barrier_for_owner(+ &self.state.owner,&self.state.loader_id,);return;@@ -270,8 +270,8 @@ impl MainDocumentNavigationActivity {let timing_enabled = moli_trace::cdp_nav_timing_enabled();let timing_started = std::time::Instant::now();if !self.is_still_current(conn) {- conn.cancel_renderer_document_load_visibility_barrier_for_session_owner(- self.state.owner.session_id(),+ conn.cancel_renderer_document_load_visibility_barrier_for_owner(+ &self.state.owner,&self.state.loader_id,);if timing_enabled {@@ -288,9 +288,7 @@ impl MainDocumentNavigationActivity {.emit_renderer_load_completion_async(conn, out, renderer_document).await;if post_load_observation_armed {- conn.settle_root_frame_stopped_loading_observation(- self.state.owner.session_id(),- )+ conn.settle_root_frame_stopped_loading_observation_for_owner(&self.state.owner).expect("an armed root post-load observation must settle its exact stopped-loading fact",);@@ -321,8 +319,11 @@ impl MainDocumentNavigationActivity {token,);}- conn.runtime_session_owner_target_url(self.state.owner.session_id())- .is_some_and(|url| url == self.final_url.as_str())+ conn.runtime_session_owner_target_url_for_route(+ self.state.owner.session_id(),+ self.state.owner.session_owner_route(),+ )+ .is_some_and(|url| url == self.final_url.as_str())}async fn emit_download_navigation_commit_into_buffer_async(@@ -474,16 +475,11 @@ impl MainDocumentNavigationActivity {_renderer_document: Option<RendererDocumentLifecycleIdentity>,) -> bool {self.emit_renderer_load_boundary_facts(conn, out);- let armed = conn.arm_root_post_load_observation_for_session_owner(- self.state.owner.session_id(),- &self.state.loader_id,- );+ let armed =+ conn.arm_root_post_load_observation_for_owner(&self.state.owner, &self.state.loader_id);if armed {let mut network_idle_events = Vec::new();- conn.emit_root_network_idle_for_session_owner(- self.state.owner.session_id(),- &mut network_idle_events,- );+ conn.emit_root_network_idle_for_owner(&self.state.owner, &mut network_idle_events);out.extend_background_events(network_idle_events);}armed@@ -506,13 +502,13 @@ impl MainDocumentNavigationActivity {let renderer_events =std::mem::take(&mut self.deferred_initial_renderer_document_lifecycle_events);let (binding, mut accepted_events) = conn- .ingest_renderer_document_lifecycle_events_for_session_owner(- self.state.owner.session_id(),+ .ingest_renderer_document_lifecycle_events_for_owner(+ &self.state.owner,renderer_events,);accepted_events.extend(- conn.release_renderer_document_load_visibility_barrier_for_session_owner(- self.state.owner.session_id(),+ conn.release_renderer_document_load_visibility_barrier_for_owner(+ &self.state.owner,&self.state.loader_id,).unwrap_or_default(),@@ -522,7 +518,7 @@ impl MainDocumentNavigationActivity {page::emit_bound_renderer_document_lifecycle_background_events(conn,&mut renderer_lifecycle_events,- self.state.owner.session_id(),+ &self.state.owner,binding,&accepted_events,);@@ -676,11 +672,16 @@ impl DeferredMainDocumentLoadCompletionAdmission {) -> DeferredMainDocumentLoadCompletionActivity {let is_current = self.is_still_current_for_scheduler(conn);let renderer_page_residence_identity = is_current- .then(|| conn.renderer_page_residence_identity_for_session_owner(self.session_id()))+ .then(|| {+ conn.renderer_page_residence_identity_for_route(+ self.owner_scope().session_id(),+ self.owner_scope().session_owner_route(),+ )+ }).flatten();let lifecycle_observer = if is_current {- conn.register_exact_renderer_document_lifecycle_observer_for_session_owner(- self.session_id(),+ conn.register_exact_renderer_document_lifecycle_observer_for_owner(+ self.owner_scope(),self.state.renderer_document_binding.as_ref(),RendererDocumentLifecycleMilestone::Load,)@@ -838,8 +839,8 @@ impl CompletedDeferredMainDocumentLoadCompletionActivity {}RendererDocumentLifecycleObservation::Superseded| RendererDocumentLifecycleObservation::Unavailable => {- conn.cancel_renderer_document_load_visibility_barrier_for_session_owner(- self.session_id(),+ conn.cancel_renderer_document_load_visibility_barrier_for_owner(+ self.owner_scope(),&self.state.navigation_activity.state.loader_id,);return;@@ -1003,8 +1004,8 @@ mod tests {),..started};- let (binding, accepted) = conn.bind_renderer_document_lifecycle_for_session_owner(- Some("SID-nav"),+ let (binding, accepted) = conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-nav"),moli_core::page::RendererPageCreationArtifacts {active_document: document,active_epoch: epoch,@@ -1480,8 +1481,8 @@ mod tests {#[tokio::test]async fn deferred_load_observer_waits_for_load_not_domcontentloaded() {let (mut conn, binding, started) = connection_with_dcl_only_renderer_lifecycle();- let observer = conn.register_exact_renderer_document_lifecycle_observer_for_session_owner(- Some("SID-nav"),+ let observer = conn.register_exact_renderer_document_lifecycle_observer_for_owner(+ &CommandOwnerScope::for_session("SID-nav"),Some(&binding),RendererDocumentLifecycleMilestone::Load,);@@ -1492,8 +1493,8 @@ mod tests {);let load = renderer_load_event_for_test(started);- let (_, accepted) = conn.ingest_renderer_document_lifecycle_events_for_session_owner(- Some("SID-nav"),+ let (_, accepted) = conn.ingest_renderer_document_lifecycle_events_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-nav"),vec![load],);assert_eq!(accepted, vec![load]);@@ -1511,8 +1512,8 @@ mod tests {let work = take_deferred_load_work_for_test(&mut conn);let load = renderer_load_event_for_test(started);- let _ = conn.ingest_renderer_document_lifecycle_events_for_session_owner(- Some("SID-nav"),+ let _ = conn.ingest_renderer_document_lifecycle_events_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-nav"),vec![load],);let pending = work.start_main_document_load_wait();@@ -1568,8 +1569,8 @@ mod tests {);let load = renderer_load_event_for_test(started);- let _ = conn.ingest_renderer_document_lifecycle_events_for_session_owner(- Some("SID-nav"),+ let _ = conn.ingest_renderer_document_lifecycle_events_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-nav"),vec![load],);assert!(@@ -1596,14 +1597,14 @@ mod tests {#[tokio::test]async fn deferred_load_observer_reports_exact_document_interruption() {let (mut conn, binding, started) = connection_with_dcl_only_renderer_lifecycle();- let observer = conn.register_exact_renderer_document_lifecycle_observer_for_session_owner(- Some("SID-nav"),+ let observer = conn.register_exact_renderer_document_lifecycle_observer_for_owner(+ &CommandOwnerScope::for_session("SID-nav"),Some(&binding),RendererDocumentLifecycleMilestone::Load,);let terminated = renderer_termination_event_for_test(started);- let _ = conn.ingest_renderer_document_lifecycle_events_for_session_owner(- Some("SID-nav"),+ let _ = conn.ingest_renderer_document_lifecycle_events_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-nav"),vec![terminated],);@@ -1616,12 +1617,12 @@ mod tests {#[tokio::test]async fn newer_document_navigation_supersedes_deferred_load_observer() {let (mut conn, binding, _) = connection_with_dcl_only_renderer_lifecycle();- let observer = conn.register_exact_renderer_document_lifecycle_observer_for_session_owner(- Some("SID-nav"),+ let observer = conn.register_exact_renderer_document_lifecycle_observer_for_owner(+ &CommandOwnerScope::for_session("SID-nav"),Some(&binding),RendererDocumentLifecycleMilestone::Load,);- conn.start_document_navigation_for_session_owner(Some("SID-nav"), "LID-2".to_owned())+ conn.start_document_navigation_for_route(Some("SID-nav"), None, "LID-2".to_owned()).expect("replacement navigation token");assert_eq!(@@ -1633,8 +1634,8 @@ mod tests {#[tokio::test]async fn losing_page_slot_terminates_deferred_load_observer() {let (mut conn, binding, _) = connection_with_dcl_only_renderer_lifecycle();- let observer = conn.register_exact_renderer_document_lifecycle_observer_for_session_owner(- Some("SID-nav"),+ let observer = conn.register_exact_renderer_document_lifecycle_observer_for_owner(+ &CommandOwnerScope::for_session("SID-nav"),Some(&binding),RendererDocumentLifecycleMilestone::Load,);@@ -1653,7 +1654,7 @@ mod tests {conn.enqueue_deferred_main_document_load_completion(old_completion);let work = take_deferred_load_work_for_test(&mut conn);- conn.start_document_navigation_for_session_owner(Some("SID-nav"), "LID-2".to_owned())+ conn.start_document_navigation_for_route(Some("SID-nav"), None, "LID-2".to_owned()).expect("replacement navigation token");assert!(diff --git a/moli-protocol/src/domains/activity/output_ingress/mod.rs b/moli-protocol/src/domains/activity/output_ingress/mod.rsindex 78220fbc2..a3329a693 100644--- a/moli-protocol/src/domains/activity/output_ingress/mod.rs+++ b/moli-protocol/src/domains/activity/output_ingress/mod.rs@@ -6,7 +6,7 @@ pub(crate) use ordered_stream::{OrderedRendererOutputIngress, RendererOutputIngrpub(super) use prepared_outputs::PreparedProtocolOutputs;pub(crate) use renderer::ingest_renderer_output_transport_async;-use crate::conn::{CdpConnection, CommandDispatchContext};+use crate::conn::{CdpConnection, CommandDispatchContext, CommandOwnerScope};/// Projects protocol-owned output accumulated at a command boundary.///@@ -16,11 +16,11 @@ use crate::conn::{CdpConnection, CommandDispatchContext};/// concrete publications and exact cursor fences.pub(crate) async fn project_protocol_local_command_outputs(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,command: &mut CommandDispatchContext,) {- PreparedProtocolOutputs::from_protocol_local_command_boundary(conn, session_id)+ PreparedProtocolOutputs::from_protocol_local_command_boundary(conn, owner).await- .project_async(conn, session_id, command)+ .project_async(conn, owner, command).await;}diff --git a/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs b/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rsindex b449d58bd..9241454b8 100644--- a/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs+++ b/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs@@ -7,7 +7,7 @@ use super::super::output_payloads::{ProtocolOutputPayload, ProtocolOutputPayloaduse super::super::output_slot::{ProtocolOutputDelivery, ProtocolOutputResponseOrder, ProtocolOutputSink, ProtocolOutputSlot,};-use crate::conn::{CdpConnection, CommandDispatchContext};+use crate::conn::{CdpConnection, CommandDispatchContext, CommandOwnerScope};use crate::domains::page::{PagePreparedOutputSlot, SLOT_TOP_LEVEL_LOCATION_NAVIGATION};/// One move-owned protocol projection batch prepared from concrete output.@@ -42,14 +42,16 @@ impl PreparedProtocolOutputs {/// and `Log.enable` retain their independent Chromium-compatible policies.pub(in crate::domains::activity) fn from_renderer_network_observation(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_renderer_page: Option<crate::conn::RendererPageResidenceIdentity>,source_document: moli_core::RendererDocumentLifecycleIdentity,item: &moli_core::page::ScriptNetworkOutputItem,) -> Option<Self> {+ let session_id = owner.session_id();let renderer_live = conn- .ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_session_owner(+ .ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_route(session_id,+ owner.session_owner_route(),source_renderer_page,source_document,item,@@ -57,7 +59,7 @@ impl PreparedProtocolOutputs {let mut prepared = Self::empty();crate::domains::observable_output::live_log_prepared_outputs_for_renderer_network_fact(- conn, session_id,+ conn, owner,).append_to_output_sink(&mut prepared);crate::domains::network::NetworkPreparedOutputs::from_renderer_live_delivery(renderer_live)@@ -68,7 +70,7 @@ impl PreparedProtocolOutputs {pub(in crate::domains::activity) fn from_renderer_observation(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_renderer_agent: moli_core::page::RendererDevToolsAgentToken,observation: &RendererProtocolObservation,) -> Self {@@ -97,14 +99,14 @@ impl PreparedProtocolOutputs {),RendererProtocolObservation::RuntimeBinding(call) => {crate::domains::runtime::RuntimePreparedOutputs::- from_renderer_runtime_binding_call(conn, session_id, call.clone())+ from_renderer_runtime_binding_call(conn, owner, call.clone()).append_to_output_sink(&mut prepared);}RendererProtocolObservation::DomMutations(batch) => {crate::domains::dom::DomPreparedOutputs::from_renderer_dom_mutation_event_batches_for_stream(conn,- session_id,+ owner,source_renderer_agent,std::slice::from_ref(batch),)@@ -112,15 +114,15 @@ impl PreparedProtocolOutputs {}RendererProtocolObservation::RuntimeInspector(batch) => {let source_batches = vec![batch.clone()];- let batches = conn.route_current_renderer_inspector_output_for_session_owner(- session_id,+ let batches = conn.route_current_renderer_inspector_output_for_owner(+ owner,source_batches.clone(),);if batches.is_empty() {crate::domains::runtime::RuntimePreparedOutputs::from_retired_renderer_runtime_inspector_session_responses(conn,- session_id,+ owner,&source_batches,).append_to_output_sink(&mut prepared);@@ -129,7 +131,7 @@ impl PreparedProtocolOutputs {crate::domains::runtime::RuntimePreparedOutputs::from_renderer_runtime_inspector_message_batches(conn,- session_id,+ owner,&batches,).append_to_output_sink(&mut prepared);@@ -138,7 +140,7 @@ impl PreparedProtocolOutputs {crate::domains::observable_output::runtime_console_message_prepared_outputs(conn,message.clone(),- session_id,+ owner,).append_to_output_sink(&mut prepared);}@@ -150,14 +152,14 @@ impl PreparedProtocolOutputs {conn,*source_document,issue.clone(),- session_id,+ owner,).append_to_output_sink(&mut prepared);}RendererProtocolObservation::WindowOpen(event) => {crate::domains::page::PagePreparedOutputs::from_renderer_window_open_event(conn,- session_id,+ owner,event.clone(),).append_to_window_open_output_sink(&mut prepared);@@ -170,7 +172,7 @@ impl PreparedProtocolOutputs {conn,text.clone(),*execution_context_id,- session_id,+ owner,).append_to_output_sink(&mut prepared);}@@ -180,25 +182,24 @@ impl PreparedProtocolOutputs {pub(in crate::domains::activity) async fn from_protocol_local_command_boundary(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Self {let mut outputs = Self::empty();- outputs- .append_protocol_local_outputs(conn, session_id)- .await;+ outputs.append_protocol_local_outputs(conn, owner).await;outputs}pub(in crate::domains::activity) async fn from_renderer_owner_action(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,action: RendererOwnerAction,) -> Self {+ let session_id = owner.session_id();let mut prepared = Self::empty();match action {RendererOwnerAction::FileChooser(activation) => {crate::domains::input::InputPreparedOutputs::from_renderer_file_chooser_activation(- conn, session_id, activation,+ conn, owner, activation,).append_to_output_sink(&mut prepared);}@@ -210,13 +211,13 @@ impl PreparedProtocolOutputs {}RendererOwnerAction::JavaScriptDialog(dialog) => {crate::domains::page::PagePreparedOutputs::from_renderer_javascript_dialog(- conn, session_id, dialog,+ conn, owner, dialog,).append_to_javascript_dialog_output_sink(&mut prepared);}RendererOwnerAction::Popup(activation) => {crate::domains::page::PagePreparedOutputs::from_renderer_popup_activation(- conn, session_id, activation,+ conn, owner, activation,).append_to_popup_output_sink(&mut prepared);}@@ -226,7 +227,7 @@ impl PreparedProtocolOutputs {} => {crate::domains::page::PagePreparedOutputs::from_renderer_child_frame_tree_event(conn,- session_id,+ owner,source_document,event,)@@ -239,7 +240,7 @@ impl PreparedProtocolOutputs {crate::domains::page::PagePreparedOutputs::from_renderer_child_frame_document_opened(conn,- session_id,+ owner,source_document,event,)@@ -252,7 +253,7 @@ impl PreparedProtocolOutputs {crate::domains::page::PagePreparedOutputs::from_renderer_child_frame_document_network(conn,- session_id,+ owner,source_document,event,)@@ -264,7 +265,7 @@ impl PreparedProtocolOutputs {} => {crate::domains::page::PagePreparedOutputs::from_renderer_child_frame_load(conn,- session_id,+ owner,source_document,event,)@@ -272,7 +273,7 @@ impl PreparedProtocolOutputs {}RendererOwnerAction::SameDocumentNavigation(navigation) => {crate::domains::page::PagePreparedOutputs::from_renderer_same_document_navigation(- conn, session_id, navigation,+ conn, owner, navigation,).append_to_same_document_navigation_output_sink(&mut prepared);}@@ -280,7 +281,7 @@ impl PreparedProtocolOutputs {crate::domains::page::PagePreparedOutputs::from_renderer_top_level_location_navigation(conn,- session_id,+ owner,navigation,).append_to_top_level_location_navigation_output_sink(&mut prepared);@@ -297,7 +298,7 @@ impl PreparedProtocolOutputs {crate::domains::fetch::subresource_fetch_pause_prepared_outputs_for_renderer_record_async(conn,- session_id,+ owner,source_document,*info,)@@ -311,7 +312,7 @@ impl PreparedProtocolOutputs {crate::domains::network::NetworkPreparedOutputs::from_renderer_subresource_continue(conn,- session_id,+ owner,source_document,*event,)@@ -325,7 +326,7 @@ impl PreparedProtocolOutputs {crate::domains::fetch::detached_parser_script_fetch_pause_prepared_outputs_for_renderer_record_async(conn,- session_id,+ owner,source_document,*info,continuation,@@ -335,7 +336,7 @@ impl PreparedProtocolOutputs {}RendererOwnerAction::SharedWorkerTargetLifecycle(event) => {if let Some((browser_context_id, _)) =- conn.target_owner_identity_for_session(session_id)+ conn.target_owner_identity_for_route(session_id, owner.session_owner_route()){crate::domains::target::shared_worker_target_lifecycle_prepared_outputs_for_event(@@ -350,7 +351,7 @@ impl PreparedProtocolOutputs {}RendererOwnerAction::ServiceWorkerTargetLifecycle(event) => {if let Some((browser_context_id, _)) =- conn.target_owner_identity_for_session(session_id)+ conn.target_owner_identity_for_route(session_id, owner.session_owner_route()){crate::domains::target::service_worker_target_lifecycle_prepared_outputs_for_event(@@ -367,7 +368,7 @@ impl PreparedProtocolOutputs {crate::domains::target::dedicated_worker_target_lifecycle_prepared_outputs_for_event(conn,- session_id,+ owner,event,).append_to_dedicated_worker_target_lifecycle_output_sink(&mut prepared);@@ -423,10 +424,11 @@ impl PreparedProtocolOutputs {async fn project_slots_async(&mut self,conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,command_context: &mut CommandDispatchContext,slots: Vec<ProtocolOutputSlot>,) {+ let session_id = owner.session_id();for slot in slots {let trace_started =moli_trace::cdp_runtime_trace_enabled().then(std::time::Instant::now);@@ -441,7 +443,7 @@ impl PreparedProtocolOutputs {}slot.project_async(conn,- &mut ProtocolOutputProjectionContext::new(session_id, command_context),+ &mut ProtocolOutputProjectionContext::new(owner, command_context),Some(&mut self.payloads),).await;@@ -461,27 +463,24 @@ impl PreparedProtocolOutputs {fn emit_root_network_idle_if_ready(&mut self,conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,command_context: &mut CommandDispatchContext,) {if std::mem::take(&mut self.emit_root_network_idle_after_projection) {- conn.emit_root_network_idle_for_session_owner(- session_id,- command_context.protocol_events_mut(),- );+ conn.emit_root_network_idle_for_owner(owner, command_context.protocol_events_mut());}}pub(in crate::domains::activity) async fn project_async(mut self,conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,command_context: &mut CommandDispatchContext,) {let slots = std::mem::take(&mut self.ordered_slots);- self.project_slots_async(conn, session_id, command_context, slots)+ self.project_slots_async(conn, owner, command_context, slots).await;- self.emit_root_network_idle_if_ready(conn, session_id, command_context);+ self.emit_root_network_idle_if_ready(conn, owner, command_context);}/// Projects output explicitly allowed before a Runtime command response@@ -494,7 +493,7 @@ impl PreparedProtocolOutputs {pub(in crate::domains::activity) async fn project_before_command_response_and_hold_after(mut self,conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,command_context: &mut CommandDispatchContext,) -> Option<Self> {let mut before_response = Vec::new();@@ -505,12 +504,12 @@ impl PreparedProtocolOutputs {ProtocolOutputResponseOrder::AfterResponse => after_response.push(slot),}}- self.project_slots_async(conn, session_id, command_context, before_response)+ self.project_slots_async(conn, owner, command_context, before_response).await;// A concrete body-finished fact can make the exact committed Document// idle. Emit that derived lifecycle event after the corresponding// Network output and at the same pre-response boundary.- self.emit_root_network_idle_if_ready(conn, session_id, command_context);+ self.emit_root_network_idle_if_ready(conn, owner, command_context);self.ordered_slots = after_response;(!self.ordered_slots.is_empty()).then_some(self)}@@ -520,14 +519,14 @@ impl PreparedProtocolOutputs {pub(in crate::domains::activity) async fn project_owner_actions_async(mut self,conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,command_context: &mut CommandDispatchContext,) {let owner_actions = std::mem::take(&mut self.ordered_slots).into_iter().filter(|slot| slot.delivery() == ProtocolOutputDelivery::OwnerAction).collect();- self.project_slots_async(conn, session_id, command_context, owner_actions)+ self.project_slots_async(conn, owner, command_context, owner_actions).await;}@@ -540,10 +539,10 @@ impl PreparedProtocolOutputs {async fn append_protocol_local_outputs(&mut self,conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) {- crate::domains::dom_storage::append_pending_dom_storage_outputs_for_session_owner(- conn, session_id, self,+ crate::domains::dom_storage::append_pending_dom_storage_outputs_for_owner(+ conn, owner, self,);}}diff --git a/moli-protocol/src/domains/activity/output_ingress/renderer.rs b/moli-protocol/src/domains/activity/output_ingress/renderer.rsindex 1e538bfae..e6572cc9a 100644--- a/moli-protocol/src/domains/activity/output_ingress/renderer.rs+++ b/moli-protocol/src/domains/activity/output_ingress/renderer.rs@@ -7,32 +7,40 @@ use super::super::publication_route::RendererPublicationProjection;use super::super::publication_route::RendererPublicationRoute;use super::super::runtime_command_barrier::RuntimeCommandOutputBarriers;use super::prepared_outputs::PreparedProtocolOutputs;-use crate::conn::{BackgroundProtocolEvent, CdpConnection, CommandDispatchContext};+use crate::conn::{+ BackgroundProtocolEvent, CdpConnection, CommandDispatchContext, CommandOwnerScope,+};-fn renderer_owner_action_session_id(+fn renderer_owner_action_owner(conn: &CdpConnection,- publication_session_id: Option<&str>,+ publication_owner: &CommandOwnerScope,renderer_cause: Option<&moli_core::RendererRuntimeCommandCausalIdentity>,-) -> Option<String> {+) -> CommandOwnerScope {if let Some(cause) = renderer_cause&& let Some(attachment) = conn- .target_page_protocol_attachment_identity_for_renderer_inspector_route(- publication_session_id,+ .target_page_protocol_attachment_identity_for_renderer_inspector_owner(+ publication_owner,cause.inspector_session_id(),){- // `None` is a valid exact attachment for a command sent through the- // implicit primary inspector session, so do not replace it by a peer.- return attachment.session_id().map(str::to_owned);+ return CommandOwnerScope::for_page_attachment(&attachment);}- if let Some(session_id) = publication_session_id {- return Some(session_id.to_owned());+ if publication_owner.session_id().is_some() {+ return publication_owner.clone();}- let (browser_context_id, target_id) =- conn.target_owner_identity_for_session(publication_session_id)?;- let target_id = target_id?;+ let Some((browser_context_id, target_id)) = conn.target_owner_identity_for_route(+ publication_owner.session_id(),+ publication_owner.session_owner_route(),+ ) else {+ return publication_owner.clone();+ };+ let Some(target_id) = target_id else {+ return publication_owner.clone();+ };conn.target_page_protocol_attachment_identity_for_target(&browser_context_id, &target_id)- .and_then(|attachment| attachment.session_id().map(str::to_owned))+ .as_ref()+ .map(CommandOwnerScope::for_page_attachment)+ .unwrap_or_else(|| publication_owner.clone())}/// Ingests one renderer transport message against only the exact Runtime@@ -123,9 +131,10 @@ async fn ingest_renderer_output_publication(session_id,projection,} => {+ let owner = CommandOwnerScope::for_session(&session_id);project_renderer_output_records_for_route(conn,- Some(&session_id),+ &owner,records,cursor,projection,@@ -138,10 +147,10 @@ async fn ingest_renderer_output_publication(owner_route,projection,} => {- let mut route_scope = conn.scoped_none_session_owner_route_override(owner_route);+ let owner = CommandOwnerScope::for_route(owner_route);project_renderer_output_records_for_route(- route_scope.conn_mut(),- None,+ conn,+ &owner,records,cursor,projection,@@ -155,7 +164,7 @@ async fn ingest_renderer_output_publication(async fn project_renderer_output_records_for_route(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,records: Vec<moli_core::RendererOutputRecord>,cursor: moli_core::RendererOutputCursor,projection: RendererPublicationProjection,@@ -182,18 +191,18 @@ async fn project_renderer_output_records_for_route(// exact inspector attachment, not merely to the stream's base route.// Asynchronous actions have no command cause; an unbound stream then// selects the target's stable concrete Page attachment.- let action_session_id =- renderer_owner_action_session_id(conn, session_id, renderer_cause.as_ref());+ let action_owner =+ renderer_owner_action_owner(conn, owner, renderer_cause.as_ref());let outputs = PreparedProtocolOutputs::from_renderer_owner_action(conn,- action_session_id.as_deref(),+ &action_owner,action,).await;barriers.route_publication_outputs(conn,- action_session_id.as_deref(),+ &action_owner,renderer_cause.as_ref(),Some(cursor),outputs,@@ -209,7 +218,7 @@ async fn project_renderer_output_records_for_route({let Some(outputs) = PreparedProtocolOutputs::from_renderer_network_observation(conn,- session_id,+ owner,crate::conn::RendererPageResidenceIdentity::from_residence(cursor.stream().residence(),),@@ -222,7 +231,7 @@ async fn project_renderer_output_records_for_route(} else {PreparedProtocolOutputs::from_renderer_observation(conn,- session_id,+ owner,cursor.stream().renderer_agent(),&observation,)@@ -230,7 +239,7 @@ async fn project_renderer_output_records_for_route(barriers.route_publication_outputs(conn,- session_id,+ owner,renderer_cause.as_ref(),Some(cursor),outputs,@@ -246,9 +255,9 @@ async fn project_renderer_output_records_for_route(mod tests {use moli_core::RendererRuntimeCommandCausalIdentity;- use crate::conn::{BrowserContext, CdpConnection};+ use crate::conn::{BrowserContext, CdpConnection, CommandOwnerScope};- use super::renderer_owner_action_session_id;+ use super::renderer_owner_action_owner;#[test]fn unbound_owner_actions_choose_a_stable_attachment_without_overriding_exact_root_cause() {@@ -266,31 +275,39 @@ mod tests {.runtime_slot.set_page_attachment_id_for_test(1);conn.browser_context = Some(browser_context);+ let owner = CommandOwnerScope::capture(&conn, None);assert_eq!(- renderer_owner_action_session_id(&conn, None, None).as_deref(),+ renderer_owner_action_owner(&conn, &owner, None).session_id(),Some("SID-owner-action"),"an asynchronous target action should use its concrete attachment");assert_eq!(- renderer_owner_action_session_id(+ renderer_owner_action_owner(&conn,- None,+ &owner,Some(&RendererRuntimeCommandCausalIdentity::new(Some("SID-owner-action".to_owned()),1,)),)- .as_deref(),+ .session_id(),Some("SID-owner-action"),);+ let implicit = renderer_owner_action_owner(+ &conn,+ &owner,+ Some(&RendererRuntimeCommandCausalIdentity::new(None, 2)),+ );assert_eq!(- renderer_owner_action_session_id(- &conn,- None,- Some(&RendererRuntimeCommandCausalIdentity::new(None, 2)),+ conn.target_owner_identity_for_route(+ implicit.session_id(),+ implicit.session_owner_route(),),- None,+ Some((+ "BID-owner-action".to_owned(),+ Some("TID-owner-action".to_owned()),+ )),"an exact implicit-primary command must not be reassigned to a peer session");}diff --git a/moli-protocol/src/domains/activity/runtime_command_barrier.rs b/moli-protocol/src/domains/activity/runtime_command_barrier.rsindex 1e42837ae..764be1872 100644--- a/moli-protocol/src/domains/activity/runtime_command_barrier.rs+++ b/moli-protocol/src/domains/activity/runtime_command_barrier.rs@@ -173,10 +173,10 @@ impl RuntimeCommandCausalOwner {}impl RuntimeCommandOutputRoute {- fn capture(conn: &CdpConnection, session_id: Option<&str>) -> Option<Self> {+ fn capture_for_scope(conn: &CdpConnection, delivery_scope: CommandOwnerScope) -> Option<Self> {Some(Self {- delivery_scope: CommandOwnerScope::capture(conn, session_id),- causal_owner: RuntimeCommandCausalOwner::capture(conn, session_id)?,+ causal_owner: RuntimeCommandCausalOwner::capture_for_scope(conn, &delivery_scope)?,+ delivery_scope,})}}@@ -223,15 +223,17 @@ impl RuntimeCommandOutputBarriers {pub(super) async fn route_publication_outputs(&mut self,conn: &mut CdpConnection,- session_id: Option<&str>,+ delivery_scope: &CommandOwnerScope,renderer_cause: Option<&RendererRuntimeCommandCausalIdentity>,renderer_output_cursor: Option<RendererOutputCursor>,mut outputs: PreparedProtocolOutputs,command_context: &mut CommandDispatchContext,) {- let Some(route) = RuntimeCommandOutputRoute::capture(conn, session_id) else {+ let Some(route) =+ RuntimeCommandOutputRoute::capture_for_scope(conn, delivery_scope.clone())+ else {outputs- .project_async(conn, session_id, command_context)+ .project_async(conn, delivery_scope, command_context).await;return;};@@ -240,7 +242,7 @@ impl RuntimeCommandOutputBarriers {.cloned();let Some(renderer_cause) = prepared_cause.as_ref().or(renderer_cause) else {outputs- .project_async(conn, session_id, command_context)+ .project_async(conn, delivery_scope, command_context).await;return;};@@ -259,7 +261,7 @@ impl RuntimeCommandOutputBarriers {"one renderer Runtime command cause cannot match multiple active barriers");outputs- .project_async(conn, session_id, command_context)+ .project_async(conn, delivery_scope, command_context).await;return;};@@ -268,7 +270,7 @@ impl RuntimeCommandOutputBarriers {.take_top_level_location_navigation_for_runtime_command(renderer_cause).expect("a prepared Runtime-command navigation cause must retain its exact action");outputs- .project_async(conn, session_id, command_context)+ .project_async(conn, &route.delivery_scope, command_context).await;causal_outputs} else {@@ -276,7 +278,6 @@ impl RuntimeCommandOutputBarriers {};self.hold_for_exact_barrier(conn,- session_id,route,*barrier_id,renderer_output_cursor,@@ -289,7 +290,6 @@ impl RuntimeCommandOutputBarriers {async fn hold_for_exact_barrier(&mut self,conn: &mut CdpConnection,- session_id: Option<&str>,route: RuntimeCommandOutputRoute,barrier_id: RuntimeCommandOutputBarrierId,renderer_output_cursor: Option<RendererOutputCursor>,@@ -297,7 +297,11 @@ impl RuntimeCommandOutputBarriers {command_context: &mut CommandDispatchContext,) {let Some(outputs) = outputs- .project_before_command_response_and_hold_after(conn, session_id, command_context)+ .project_before_command_response_and_hold_after(+ conn,+ &route.delivery_scope,+ command_context,+ ).awaitelse {return;@@ -424,8 +428,6 @@ impl RuntimeCommandOutputBarriers {.pop_front().expect("ready held output came from the route front");let route = self.held_routes[route_index].route.clone();- let mut scope = route.delivery_scope.enter(conn);- let conn = scope.conn_mut();if moli_trace::cdp_runtime_trace_enabled() {tracing::info!(target: "moli_cdp_runtime",@@ -439,14 +441,14 @@ impl RuntimeCommandOutputBarriers {match held.release_mode {HeldOutputReleaseMode::All => {held.outputs- .project_async(conn, route.delivery_scope.session_id(), command_context)+ .project_async(conn, &route.delivery_scope, command_context).await;}HeldOutputReleaseMode::OwnerActionsOnly => {held.outputs.project_owner_actions_async(conn,- route.delivery_scope.session_id(),+ &route.delivery_scope,command_context,).await;@@ -491,7 +493,8 @@ mod tests {use serde_json::Value;use crate::conn::{- BrowserContext, CdpConnection, CommandDispatchContext, RendererCommandDescriptor,+ BrowserContext, CdpConnection, CommandDispatchContext, CommandOwnerScope,+ RendererCommandDescriptor,};use super::{@@ -577,11 +580,12 @@ mod tests {fragment: &str,command_context: &mut CommandDispatchContext,) {+ let command_owner = CommandOwnerScope::for_session(SESSION_ID);let source_document = loaded_page_source_document(conn);let outputs =super::super::output_ingress::PreparedProtocolOutputs::from_renderer_owner_action(conn,- Some(SESSION_ID),+ &command_owner,RendererOwnerAction::SameDocumentNavigation(RendererDocumentSourcedSameDocumentNavigation::new(source_document,@@ -598,7 +602,7 @@ mod tests {barriers.route_publication_outputs(conn,- Some(SESSION_ID),+ &command_owner,renderer_cause.as_ref(),None,outputs,@@ -614,6 +618,7 @@ mod tests {marker: &str,command_context: &mut CommandDispatchContext,) {+ let command_owner = CommandOwnerScope::for_session(SESSION_ID);let cause = renderer_cause_for_permit(conn, permit);let owner = conn.target_page_residence_identity_for_session(Some(SESSION_ID))@@ -630,7 +635,7 @@ mod tests {);barriers- .route_publication_outputs(conn, Some(SESSION_ID), None, None, outputs, command_context)+ .route_publication_outputs(conn, &command_owner, None, None, outputs, command_context).await;}@@ -750,16 +755,17 @@ mod tests {let outputs =super::super::output_ingress::PreparedProtocolOutputs::from_renderer_observation(&mut conn,- Some(SESSION_ID),+ &crate::conn::CommandOwnerScope::for_session(SESSION_ID),agent_token,&observation,);let mut command_context = CommandDispatchContext::default();+ let command_owner = CommandOwnerScope::for_session(SESSION_ID);barriers.route_publication_outputs(&mut conn,- Some(SESSION_ID),+ &command_owner,Some(&cause),None,outputs,@@ -938,11 +944,12 @@ mod tests {),);let mut command_context = CommandDispatchContext::default();+ let command_owner = CommandOwnerScope::for_session(SESSION_ID);barriers.route_publication_outputs(&mut conn,- Some(SESSION_ID),+ &command_owner,None,None,outputs,diff --git a/moli-protocol/src/domains/activity/subresource.rs b/moli-protocol/src/domains/activity/subresource.rsindex ed309c235..ba895e9a4 100644--- a/moli-protocol/src/domains/activity/subresource.rs+++ b/moli-protocol/src/domains/activity/subresource.rs@@ -38,13 +38,14 @@ impl PreparedSubresourceContinueAction {fn capture(conn: &mut CdpConnection,- session_id: Option<&str>,+ command_owner: &CommandOwnerScope,owner: TargetPageResidenceIdentity,event: PendingSubresourceContinueEvent,) -> Self {let internal_id = Self::internal_id(&event);- let request = conn.claim_subresource_continue_request_for_session_owner(- session_id,+ let request = conn.claim_subresource_continue_request_for_route(+ command_owner.session_id(),+ command_owner.session_owner_route(),&owner,internal_id,matches!(&event, PendingSubresourceContinueEvent::Completed { .. }),@@ -62,37 +63,56 @@ impl PreparedSubresourceContinueAction {session_id: Option<&str>,event: PendingSubresourceContinueEvent,) -> Option<Self> {- let owner = conn.target_page_residence_identity_for_session(session_id)?;- Some(Self::capture(conn, session_id, owner, event))+ let command_owner = CommandOwnerScope::capture(conn, session_id);+ let owner = conn.target_page_residence_identity_for_route(+ command_owner.session_id(),+ command_owner.session_owner_route(),+ )?;+ Some(Self::capture(conn, &command_owner, owner, event))}}pub(in crate::domains) fn prepare_subresource_continue_action_for_renderer_record(conn: &mut CdpConnection,- session_id: Option<&str>,+ command_owner: &CommandOwnerScope,source_document: moli_core::RendererDocumentLifecycleIdentity,event: PendingSubresourceContinueEvent,) -> Option<PreparedSubresourceContinueAction> {- if conn.target_root_document_lifecycle_identity_for_session(session_id) != Some(source_document)+ if conn.target_root_document_lifecycle_identity_for_route(+ command_owner.session_id(),+ command_owner.session_owner_route(),+ ) != Some(source_document){return None;}- let owner = conn.target_page_residence_identity_for_session(session_id)?;+ let owner = conn.target_page_residence_identity_for_route(+ command_owner.session_id(),+ command_owner.session_owner_route(),+ )?;Some(PreparedSubresourceContinueAction::capture(- conn, session_id, owner, event,+ conn,+ command_owner,+ owner,+ event,))}pub(in crate::domains) async fn flush_prepared_subresource_continue_actions_background_events_async(conn: &mut CdpConnection,out: &mut Vec<BackgroundProtocolEvent>,- session_id: Option<&str>,+ command_owner: &CommandOwnerScope,actions: Vec<PreparedSubresourceContinueAction>,) {for action in actions {- if conn.target_page_residence_identity_is_current_for_session(session_id, &action.owner) {+ if conn.target_page_residence_identity_is_current_for_session(+ command_owner.session_id(),+ &action.owner,+ ) {flush_prepared_subresource_continue_action_background_events_async(- conn, out, session_id, action,+ conn,+ out,+ command_owner,+ action,).await;}@@ -102,11 +122,13 @@ pub(in crate::domains) async fn flush_prepared_subresource_continue_actions_backasync fn flush_prepared_subresource_continue_action_background_events_async(conn: &mut CdpConnection,out: &mut Vec<BackgroundProtocolEvent>,- session_id: Option<&str>,+ command_owner: &CommandOwnerScope,action: PreparedSubresourceContinueAction,) {+ let session_id = command_owner.session_id();+ let owner_route = command_owner.session_owner_route();let PreparedSubresourceContinueAction { event, request, .. } = action;- let fetch_session_id = conn.target_fetch_event_session_id_for_session_owner(session_id);+ let fetch_session_id = conn.target_fetch_event_session_id_for_route(session_id, owner_route);let fetch_event_session_id = fetch_session_id.as_deref().or(session_id);match event {@@ -122,8 +144,11 @@ async fn flush_prepared_subresource_continue_action_background_events_async(};if let Some(pending) = pending {Box::pin(- flush_post_subresource_fetch_request_activity_background_events_async(- conn, out, session_id, &pending,+ flush_post_subresource_fetch_request_activity_for_owner_background_events_async(+ conn,+ out,+ command_owner,+ &pending,),).await;@@ -135,18 +160,19 @@ async fn flush_prepared_subresource_continue_action_background_events_async(};let Some(request_id) = in_flight.request_id else {let _ = conn- .continue_pending_subresource_response_for_session_owner_async(+ .continue_pending_subresource_response_for_route_async(session_id,+ owner_route,response_info.internal_id,None,None,).await;Box::pin(- flush_post_subresource_fetch_request_activity_background_events_async(+ flush_post_subresource_fetch_request_activity_for_owner_background_events_async(conn,out,- session_id,+ command_owner,&in_flight.pending,),)@@ -157,7 +183,10 @@ async fn flush_prepared_subresource_continue_action_background_events_async(.response_stage_url_match_policy.requires_final_url_match()&& !conn- .target_fetch_subresource_interception_snapshot_for_session_owner(session_id)+ .target_fetch_subresource_interception_snapshot_for_route(+ session_id,+ owner_route,+ ).is_some_and(|snapshot| {snapshot.matches_response_stage(response_info.resource_type.into(),@@ -166,18 +195,19 @@ async fn flush_prepared_subresource_continue_action_background_events_async(}){let _ = conn- .continue_pending_subresource_response_for_session_owner_async(+ .continue_pending_subresource_response_for_route_async(session_id,+ owner_route,response_info.internal_id,None,None,).await;Box::pin(- flush_post_subresource_fetch_request_activity_background_events_async(+ flush_post_subresource_fetch_request_activity_for_owner_background_events_async(conn,out,- session_id,+ command_owner,&in_flight.pending,),)@@ -185,15 +215,18 @@ async fn flush_prepared_subresource_continue_action_background_events_async(return;}let blocked_intercepts = if in_flight.response_stage_blocked_intercepts.is_empty() {- conn.target_fetch_subresource_interception_snapshot_for_session_owner(session_id)- .map(|snapshot| {- snapshot.matching_network_intercepts(- FetchRequestStage::Response,- response_info.resource_type.into(),- &response_info.final_url,- )- })- .unwrap_or_default()+ conn.target_fetch_subresource_interception_snapshot_for_route(+ session_id,+ owner_route,+ )+ .map(|snapshot| {+ snapshot.matching_network_intercepts(+ FetchRequestStage::Response,+ response_info.resource_type.into(),+ &response_info.final_url,+ )+ })+ .unwrap_or_default()} else {in_flight.response_stage_blocked_intercepts.clone()};@@ -215,8 +248,9 @@ async fn flush_prepared_subresource_continue_action_background_events_async(&in_flight.pending.frame_id,).or_else(|| {- conn.target_fetch_subresource_interception_snapshot_for_session_owner(+ conn.target_fetch_subresource_interception_snapshot_for_route(session_id,+ owner_route,)}).map(|snapshot| {@@ -243,8 +277,9 @@ async fn flush_prepared_subresource_continue_action_background_events_async(let mut remaining_sessions = Vec::new();for session in response_stage_sessions.into_iter().skip(1) {let Ok((next_request_id, _)) = conn- .allocate_pending_subresource_fetch_request_ids_for_session_owner(+ .allocate_pending_subresource_fetch_request_ids_for_route(session_id,+ owner_route,)else {return;@@ -270,8 +305,13 @@ async fn flush_prepared_subresource_continue_action_background_events_async(pending_response.action_session_id = response_event_session_id.clone();let pending_owner_session_id = pending_response.owner_session_id.clone();let pending_owner_session_id = pending_owner_session_id.as_deref().or(session_id);- if !conn.register_pending_subresource_fetch_response_request_for_session_owner(+ let pending_owner_route = pending_owner_session_id+ .is_none()+ .then_some(owner_route)+ .flatten();+ if !conn.register_pending_subresource_fetch_response_request_for_route(pending_owner_session_id,+ pending_owner_route,request_id.clone(),pending_response.clone(),) {@@ -292,17 +332,18 @@ async fn flush_prepared_subresource_continue_action_background_events_async(};let Some(request_id) = in_flight.request_id else {let _ = conn- .fail_pending_subresource_auth_for_session_owner_async(+ .fail_pending_subresource_auth_for_route_async(session_id,+ owner_route,auth_info.internal_id,"Fetch auth challenge has no DevTools request".to_owned(),).await;Box::pin(- flush_post_subresource_fetch_request_activity_background_events_async(+ flush_post_subresource_fetch_request_activity_for_owner_background_events_async(conn,out,- session_id,+ command_owner,&in_flight.pending,),)@@ -310,7 +351,7 @@ async fn flush_prepared_subresource_continue_action_background_events_async(return;};let blocked_intercepts = conn- .target_fetch_subresource_interception_snapshot_for_session_owner(session_id)+ .target_fetch_subresource_interception_snapshot_for_route(session_id, owner_route).map(|snapshot| snapshot.matching_auth_required_network_intercepts(&auth_info.url)).unwrap_or_default();let blocked_intercepts = if blocked_intercepts.is_empty() {@@ -335,8 +376,9 @@ async fn flush_prepared_subresource_continue_action_background_events_async(&in_flight.pending.frame_id,).or_else(|| {- conn.target_fetch_subresource_interception_snapshot_for_session_owner(+ conn.target_fetch_subresource_interception_snapshot_for_route(session_id,+ owner_route,)}).map(|snapshot| {@@ -359,8 +401,9 @@ async fn flush_prepared_subresource_continue_action_background_events_async(let mut remaining_sessions = Vec::new();for session in auth_sessions.into_iter().skip(1) {let Ok((next_request_id, _)) = conn- .allocate_pending_subresource_fetch_request_ids_for_session_owner(+ .allocate_pending_subresource_fetch_request_ids_for_route(session_id,+ owner_route,)else {return;@@ -386,8 +429,13 @@ async fn flush_prepared_subresource_continue_action_background_events_async(pending_auth.action_session_id = auth_event_session_id.clone();let pending_owner_session_id = pending_auth.owner_session_id.clone();let pending_owner_session_id = pending_owner_session_id.as_deref().or(session_id);- if !conn.register_pending_subresource_fetch_auth_request_for_session_owner(+ let pending_owner_route = pending_owner_session_id+ .is_none()+ .then_some(owner_route)+ .flatten();+ if !conn.register_pending_subresource_fetch_auth_request_for_route(pending_owner_session_id,+ pending_owner_route,request_id.clone(),pending_auth.clone(),) {diff --git a/moli-protocol/src/domains/console.rs b/moli-protocol/src/domains/console.rsindex 9a5efb88b..c718e4c2d 100644--- a/moli-protocol/src/domains/console.rs+++ b/moli-protocol/src/domains/console.rs@@ -1,4 +1,4 @@-use crate::conn::{CdpConnection, Cmd};+use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};use crate::domains::actions::ConsoleAction;use crate::domains::command_output::CommandOutputPlan;@@ -54,6 +54,27 @@ pub(crate) fn apply_console_output_state_for_session(}}+pub(crate) fn apply_console_output_state_for_owner(+ conn: &mut CdpConnection,+ owner: &CommandOwnerScope,+ action: ConsoleAction,+) -> bool {+ if owner.session_id().is_some_and(|session_id| {+ conn.shared_worker_target_for_session(Some(session_id))+ .is_some()+ || conn+ .service_worker_target_for_session(Some(session_id))+ .is_some()+ }) {+ return apply_console_output_state_for_session(conn, owner.session_id(), action);+ }+ match action {+ ConsoleAction::Enable => conn.set_console_enabled_for_owner(owner, true),+ ConsoleAction::Disable => conn.set_console_enabled_for_owner(owner, false),+ ConsoleAction::ClearMessages => conn.clear_console_messages_for_owner(owner),+ }+}+fn set_console_enabled(conn: &mut CdpConnection, session_id: Option<&str>, enabled: bool) -> bool {if let Some(session_id) = session_id&& let Some(target) = conn.shared_worker_target_for_session_mut(Some(session_id))diff --git a/moli-protocol/src/domains/css.rs b/moli-protocol/src/domains/css.rsindex 65393d2fa..6e4617bf8 100644--- a/moli-protocol/src/domains/css.rs+++ b/moli-protocol/src/domains/css.rs@@ -918,19 +918,39 @@ mod tests {style_sheet_id}- async fn style_sheet_text_for_id_async(ctx: &mut TestContext, style_sheet_id: &str) -> String {- ctx.process_async(json!({+ async fn style_sheet_text_for_id_async(+ ctx: &mut TestContext,+ session_id: Option<&str>,+ style_sheet_id: &str,+ ) -> String {+ let mut command = json!({"id": 44,"method": "CSS.getStyleSheet","params": { "styleSheetId": style_sheet_id }- }))- .await;+ });+ if let Some(session_id) = session_id {+ command["sessionId"] = json!(session_id);+ }+ ctx.process_async(command).await;take_response_by_id(ctx, 44)["result"]["styleSheet"]["text"].as_str().expect("stylesheet text").to_owned()}+ async fn attach_page_session_async(ctx: &mut TestContext, target_id: &str) -> String {+ ctx.process_async(json!({+ "id": 42,+ "method": "Target.attachToTarget",+ "params": { "targetId": target_id, "flatten": true }+ }))+ .await;+ take_response_by_id(ctx, 42)["result"]["sessionId"]+ .as_str()+ .expect("attached Page session id")+ .to_owned()+ }+async fn resolve_node_object_id_async(ctx: &mut TestContext, node_id: u32) -> String {ctx.process_async(json!({"id": 39,@@ -1684,65 +1704,26 @@ mod tests {.replace_loaded_page(Some(background_page));ctx.conn.browser_context = Some(browser_context);- let background_route = ctx- .conn- .target_session_route_for_target_id("TID-css-background")- .expect("background target route");- let active_style_sheet_id = {- let active_route = ctx- .conn- .target_session_route_for_target_id("TID-css-active")- .expect("active target route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(active_route));- let style_sheet_id = inline_style_sheet_id_for_session_async(&mut ctx, None).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);- style_sheet_id- };- let style_sheet_id = {- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route.clone()));- let style_sheet_id = inline_style_sheet_id_for_session_async(&mut ctx, None).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);- style_sheet_id- };+ let background_session = attach_page_session_async(&mut ctx, "TID-css-background").await;+ let active_style_sheet_id = inline_style_sheet_id_for_session_async(&mut ctx, None).await;+ let style_sheet_id =+ inline_style_sheet_id_for_session_async(&mut ctx, Some(&background_session)).await;let raw = json!({"id": 214,"method": "CSS.setStyleSheetText","params": {"styleSheetId": style_sheet_id,"text": "body { color: purple; }"- }+ },+ "sessionId": background_session}).to_string();- let pending = {- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route));- let pending = ctx- .conn- .try_start_pending_command_dispatch(&raw)- .expect("background CSS.setStyleSheetText should start pending");- ctx.conn- .replace_none_session_owner_route_override(previous_route);- pending- };-- let active_route = ctx- .conn- .target_session_route_for_target_id("TID-css-active")- .expect("active target route");- let previous_route = ctx+ let pending = ctx.conn- .replace_none_session_owner_route_override(Some(active_route));+ .try_start_pending_command_dispatch(&raw)+ .expect("background CSS.setStyleSheetText should start pending");let (messages, scheduler_events) =complete_pending_command_task_for_test(&mut ctx, pending).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);assert!(scheduler_events.is_empty(),@@ -1758,36 +1739,15 @@ mod tests {"styleSheetId": style_sheet_id,}));- let active_text = {- let active_route = ctx- .conn- .target_session_route_for_target_id("TID-css-active")- .expect("active target route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(active_route));- let text = style_sheet_text_for_id_async(&mut ctx, &active_style_sheet_id).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);- text- };+ let active_text =+ style_sheet_text_for_id_async(&mut ctx, None, &active_style_sheet_id).await;assert!(active_text.contains("color: red"),"ambient active page must not receive background CSS completion: {active_text}");- let background_text = {- let background_route = ctx- .conn- .target_session_route_for_target_id("TID-css-background")- .expect("background target route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route));- let text = style_sheet_text_for_id_async(&mut ctx, &style_sheet_id).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);- text- };+ let background_text =+ style_sheet_text_for_id_async(&mut ctx, Some(&background_session), &style_sheet_id)+ .await;assert!(background_text.contains("color: purple"),"background CSS completion should use captured owner route: {background_text}"diff --git a/moli-protocol/src/domains/debugger.rs b/moli-protocol/src/domains/debugger.rsindex f774cd560..94d7f2c16 100644--- a/moli-protocol/src/domains/debugger.rs+++ b/moli-protocol/src/domains/debugger.rs@@ -28,7 +28,7 @@ mod tests {use serde_json::{Value, json};- use crate::conn::BrowserContext;+ use crate::conn::{BrowserContext, CommandOwnerScope};use crate::testing::TestContext;async fn with_loaded_document(ctx: &mut TestContext) {@@ -154,11 +154,9 @@ mod tests {let navigation = ctx.conn- .start_document_navigation_for_session_owner(- None,- "LOADER-debugger-interrupt".to_owned(),- )+ .start_document_navigation_for_route(None, None, "LOADER-debugger-interrupt".to_owned()).expect("start cross-Document navigation");+ let navigation_owner = CommandOwnerScope::capture(&ctx.conn, None);assert!(ctx.conn.renderer_document_navigation_is_suspended_for_session_owner(None)@@ -183,10 +181,10 @@ mod tests {let _ = ctx.conn- .finish_renderer_document_navigation_for_session_owner(None, &navigation);+ .finish_renderer_document_navigation_for_owner(&navigation_owner, &navigation);ctx.conn- .clear_pending_document_navigation_for_session_owner_if_loader_matches(- None,+ .clear_pending_document_navigation_for_owner_if_loader_matches(+ &navigation_owner,&navigation.loader_id,);}@@ -328,7 +326,7 @@ mod tests {}#[tokio::test]- async fn debugger_instrumentation_navigation_publishes_new_context_with_bound_origin() {+ async fn debugger_instrumentation_navigation_publishes_new_context_and_tears_down_paused() {let mut ctx = TestContext::new();with_loaded_document(&mut ctx).await;@@ -389,6 +387,11 @@ mod tests {json!("data:text/html,<script>globalThis.__instrumentedNavigation = true</script>"),"the instrumented replacement script must reach V8");++ // Keep the instrumentation pause active. Connection teardown must+ // close the in-flight replacement Document's Inspector target and+ // join its renderer owner without requiring a frontend resume.+ drop(ctx);}#[tokio::test]diff --git a/moli-protocol/src/domains/dom.rs b/moli-protocol/src/domains/dom.rsindex 8142e9a2d..1a78b8acf 100644--- a/moli-protocol/src/domains/dom.rs+++ b/moli-protocol/src/domains/dom.rs@@ -2,8 +2,7 @@use serde_json::Value;-use crate::conn::CdpConnection;-use crate::conn::Cmd;+use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};use crate::domains::actions::DomAction;use crate::domains::command_output::CommandOutputPlan;use chromiumoxide_cdp::cdp::browser_protocol::dom::{EnableIncludeWhitespace, EnableParams};@@ -146,7 +145,15 @@ pub(crate) fn dom_agent_enabled_for_session(conn: &CdpConnection,session_id: Option<&str>,) -> bool {- conn.target_devtools_session_state_for_session(session_id)+ dom_agent_enabled_for_route(conn, session_id, None)+}++pub(crate) fn dom_agent_enabled_for_route(+ conn: &CdpConnection,+ session_id: Option<&str>,+ owner_route: Option<&crate::conn::CdpSessionRoute>,+) -> bool {+ conn.target_devtools_session_state_for_route(session_id, owner_route).is_some_and(|state| state.dom_session_state.enabled)}@@ -172,13 +179,6 @@ fn disable_dom_agent_for_session(conn: &mut CdpConnection, session_id: Option<&s.is_some()}-pub(crate) fn dom_agent_includes_whitespace_for_session(- conn: &CdpConnection,- session_id: Option<&str>,-) -> bool {- dom_agent_includes_whitespace_for_route(conn, session_id, None)-}-pub(crate) fn dom_agent_includes_whitespace_for_route(conn: &CdpConnection,session_id: Option<&str>,@@ -190,28 +190,38 @@ pub(crate) fn dom_agent_includes_whitespace_for_route(})}-fn loaded_page_mut_for_session<'a>(+fn loaded_page_mut_for_owner<'a>(conn: &'a mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Option<&'a mut Page> {- conn.loaded_page_mut_for_protocol_access(session_id).ok()+ conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ .ok()}-fn target_owner_exists_for_session(conn: &CdpConnection, session_id: Option<&str>) -> bool {- conn.target_owner_identity_for_session(session_id).is_some()+fn target_owner_exists_for_owner(conn: &CdpConnection, owner: &CommandOwnerScope) -> bool {+ conn.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())+ .and_then(|(_, target_id)| target_id)+ .is_some()}-fn top_frame_id_for_session(conn: &CdpConnection, session_id: Option<&str>) -> Option<String> {- conn.target_session_owner_frame_tree_identity(session_id)- .map(|(frame_id, _, _, _)| frame_id)+fn top_frame_id_for_owner(conn: &CdpConnection, owner: &CommandOwnerScope) -> Option<String> {+ conn.target_session_owner_frame_tree_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ .map(|(frame_id, _, _, _)| frame_id)}-fn cached_dom_remote_object_node_for_session(+fn cached_dom_remote_object_node_for_owner(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_id: &str,) -> Option<Value> {- let (browser_context_id, target_id) = conn.target_owner_identity_for_session(session_id)?;+ let (browser_context_id, target_id) =+ conn.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())?;let browser_context = conn.browser_context_by_id(&browser_context_id)?;let target_id = target_id.as_deref()@@ -223,13 +233,14 @@ fn cached_dom_remote_object_node_for_session(.cloned()}-fn cache_dom_remote_object_node_for_session(+fn cache_dom_remote_object_node_for_owner(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_id: String,node: Value,) {- let Some((browser_context_id, target_id)) = conn.target_owner_identity_for_session(session_id)+ let Some((browser_context_id, target_id)) =+ conn.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())else {return;};diff --git a/moli-protocol/src/domains/dom/activity.rs b/moli-protocol/src/domains/dom/activity.rsindex 268f99f65..7bd07fa66 100644--- a/moli-protocol/src/domains/dom/activity.rs+++ b/moli-protocol/src/domains/dom/activity.rs@@ -2,7 +2,7 @@ use moli_core::page::{RendererDevToolsAgentToken, RendererDomMutationEvent, RendererDomMutationEventBatch,};-use crate::conn::{BackgroundProtocolEvent, CdpConnection};+use crate::conn::{BackgroundProtocolEvent, CdpConnection, CommandOwnerScope};use crate::domains::activity::{ProtocolOutputPayloads, ProtocolOutputProjectionContext, ProtocolOutputSink, ProtocolOutputSlot,};@@ -68,13 +68,13 @@ fn append_dom_mutation_batches_to_background_events(impl DomPreparedOutputs {pub(in crate::domains) fn from_renderer_dom_mutation_event_batches_for_stream(conn: &CdpConnection,- source_session_id: Option<&str>,+ source_owner: &CommandOwnerScope,source_renderer_agent: RendererDevToolsAgentToken,batches: &[RendererDomMutationEventBatch],) -> Self {Self::from_renderer_dom_mutation_event_batches_with_source_agent(conn,- source_session_id,+ source_owner,source_renderer_agent,batches,)@@ -82,12 +82,15 @@ impl DomPreparedOutputs {fn from_renderer_dom_mutation_event_batches_with_source_agent(conn: &CdpConnection,- source_session_id: Option<&str>,+ source_owner: &CommandOwnerScope,source_renderer_agent: RendererDevToolsAgentToken,batches: &[RendererDomMutationEventBatch],) -> Self {let current_attachment = conn- .runtime_session_owner_slot(source_session_id)+ .runtime_session_owner_slot_for_route(+ source_owner.session_id(),+ source_owner.session_owner_route(),+ ).ok().and_then(|slot| slot.current_renderer_attachment());Self {@@ -113,8 +116,8 @@ impl DomPreparedOutputs {return None;}let attachment = conn- .target_page_protocol_attachment_identity_for_renderer_inspector_route(- source_session_id,+ .target_page_protocol_attachment_identity_for_renderer_inspector_owner(+ source_owner,batch.session.wire_session_id(),)?;Some(DomMutationBatch {diff --git a/moli-protocol/src/domains/dom/resolve.rs b/moli-protocol/src/domains/dom/resolve.rsindex 5bac73aeb..94ef60e50 100644--- a/moli-protocol/src/domains/dom/resolve.rs+++ b/moli-protocol/src/domains/dom/resolve.rs@@ -106,14 +106,14 @@ fn validated_scroll_into_view_rect(pub(crate) struct PendingDomCommandDispatch {pub(super) command_id: Option<u64>,- pub(super) session_id: Option<String>,+ pub(super) owner_scope: CommandOwnerScope,pub(super) kind: PendingDomCommandKind,pub(super) pending: PendingDomCommandWork,}pub(crate) struct CompletedDomCommandDispatch {command_id: Option<u64>,- session_id: Option<String>,+ owner_scope: CommandOwnerScope,kind: PendingDomCommandKind,completed: Result<CompletedDomCommandWork, String>,}@@ -124,7 +124,7 @@ impl CompletedDomCommandDispatch {}pub(crate) fn session_id(&self) -> Option<&str> {- self.session_id.as_deref()+ self.owner_scope.session_id()}pub(crate) fn renderer_output_predecessor(&self) -> Option<moli_core::RendererOutputFence> {@@ -317,9 +317,13 @@ pub(super) fn start_disable_dom_agent_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(cmd.session_id);- let Some(page) = loaded_page_mut_for_session(conn, cmd.session_id) else {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let Some(page) = loaded_page_mut_for_owner(conn, &owner) else {return Ok(None);};let pending = page@@ -327,7 +331,7 @@ pub(super) fn start_disable_dom_agent_command(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id: cmd.id,- session_id: cmd.session_id.map(str::to_owned),+ owner_scope: owner,kind: PendingDomCommandKind::DiscardDomAgentFrontendBindings,pending: PendingDomCommandWork::Page(pending),}))@@ -361,14 +365,12 @@ pub(super) enum PendingDomObjectReferenceOperation {},}-pub(super) fn dom_object_reference_id(+pub(super) fn dom_object_reference_id_for_owner(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_id: &DevToolsRemoteHandleId,) -> String {- if let Some(object_id) =- conn.runtime_remote_object_alias_for_session_owner(session_id, object_id.as_str())- {+ if let Some(object_id) = conn.runtime_remote_object_alias_for_owner(owner, object_id.as_str()) {return object_id;}object_id.as_str().to_owned()@@ -390,10 +392,6 @@ pub(super) enum PendingSetChildNodesAfter {}impl PendingDomCommandDispatch {- pub(crate) fn session_id(&self) -> Option<&str> {- self.session_id.as_deref()- }-pub(crate) async fn wait(self) -> CompletedDomCommandDispatch {let completed = match self.pending {PendingDomCommandWork::Page(pending) => Box::pin(pending.wait())@@ -403,7 +401,7 @@ impl PendingDomCommandDispatch {};CompletedDomCommandDispatch {command_id: self.command_id,- session_id: self.session_id,+ owner_scope: self.owner_scope,kind: self.kind,completed,}@@ -808,19 +806,19 @@ fn start_pending_dom_command(let Some(action) = cmd.parse_action::<DomAction>() else {return Ok(None);};- if action == DomAction::DiscardSearchResults- && !target_owner_exists_for_session(conn, cmd.session_id)- {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ if action == DomAction::DiscardSearchResults && !target_owner_exists_for_owner(conn, &owner) {return Ok(None);}- if !target_owner_exists_for_session(conn, cmd.session_id) {+ if !target_owner_exists_for_owner(conn, &owner) {return Err(PendingDomCommandStartError {code: -31998,message: "BrowserContextNotLoaded".to_owned(),});}if action.requires_document_access()- && let Err(message) = conn.ensure_document_accessible_for_session_owner(cmd.session_id)+ && let Err(message) = conn+ .ensure_document_accessible_for_route(owner.session_id(), owner.session_owner_route()){return Err(PendingDomCommandStartError {code: -32000,@@ -833,10 +831,10 @@ fn start_pending_dom_command(cmd,PendingDomDocumentSnapshotOperation::GetDocument,)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::GetDocument(command),);}@@ -846,55 +844,55 @@ fn start_pending_dom_command(cmd,PendingDomDocumentSnapshotOperation::GetFlattenedDocument,)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::GetDocument(command),);}if action == DomAction::RequestChildNodes {let command = build_cdp_request_child_nodes_command(conn, cmd)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::RequestChildNodes(command),);}if action == DomAction::QuerySelector {let command = build_cdp_query_selector_command(conn, cmd, false)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::QuerySelector(command),);}if action == DomAction::QuerySelectorAll {let command = build_cdp_query_selector_command(conn, cmd, true)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::QuerySelector(command),);}if action == DomAction::PerformSearch {let command = search::build_cdp_perform_search_command(conn, cmd)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::PerformSearch(command),);}if action == DomAction::GetSearchResults {let command = search::build_cdp_get_search_results_command(conn, cmd)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::GetSearchResults(command),);}@@ -902,10 +900,10 @@ fn start_pending_dom_command(let Some(command) = search::build_cdp_discard_search_results_command(conn, cmd) else {return Ok(None);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DiscardSearchResults(command),);}@@ -917,37 +915,37 @@ fn start_pending_dom_command(}if action == DomAction::ResolveNode {let command = build_cdp_resolve_node_command(conn, cmd)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::ResolveNode(command),);}if action == DomAction::GetFrameOwner {let command = build_cdp_get_frame_owner_command(conn, cmd)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::GetFrameOwner(command),);}if action == DomAction::GetAttributes {let command = build_cdp_get_attributes_command(conn, cmd)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::GetAttributes(command),);}if action == DomAction::GetNodeForLocation {let command = build_cdp_get_node_for_location_command(conn, cmd)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::GetNodeForLocation(command),);}@@ -958,10 +956,10 @@ fn start_pending_dom_command(DevToolsDomObjectReferenceOperation::RequestNode,)?.ok_or_else(PendingDomCommandStartError::invalid_params)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DomObjectReference(command),);}@@ -980,17 +978,17 @@ fn start_pending_dom_command(},)?.ok_or_else(PendingDomCommandStartError::invalid_params)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DomObjectReference(command),);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DescribeNode(command),);}@@ -1010,20 +1008,20 @@ fn start_pending_dom_command(else {return Ok(None);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DomObjectReference(command),);}let Some(command) = build_cdp_get_outer_html_command(conn, cmd)? else {return Ok(None);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::GetOuterHtml(command),);}@@ -1042,20 +1040,20 @@ fn start_pending_dom_command(else {return Ok(None);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DomObjectReference(command),);}let Some(command) = build_cdp_scroll_into_view_if_needed_command(conn, cmd)? else {return Ok(None);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::ScrollIntoViewIfNeeded(command),);}@@ -1067,10 +1065,10 @@ fn start_pending_dom_command(else {return set_file_input::start_cdp_set_file_input_files_by_node_reference(conn, cmd);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::SetFileInputFiles(command),);}@@ -1092,10 +1090,10 @@ fn start_pending_dom_command(}if action == DomAction::PushNodesByBackendIdsToFrontend {let command = build_cdp_push_nodes_by_backend_ids_command(conn, cmd)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::PushNodesByBackendIds(command),);}@@ -1113,17 +1111,17 @@ fn start_pending_dom_command(};let command = build_cdp_dom_object_reference_command(conn, cmd, operation)?.ok_or_else(PendingDomCommandStartError::invalid_params)?;- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DomObjectReference(command),);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DomGeometry(command),);}@@ -1131,10 +1129,10 @@ fn start_pending_dom_command(let Some(command) = build_cdp_remove_node_command(conn, cmd)? else {return Ok(None);};- return start_devtools_dom_command(+ return start_devtools_dom_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::RemoveNode(command),);}@@ -1146,6 +1144,7 @@ fn start_cdp_dom_focus_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> Result<PendingDomCommandDispatch, PendingDomCommandStartError> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);let params: NodeReferenceParams = match cmd.get_params() {Ok(Some(params)) => params,Ok(None) => NodeReferenceParams::default(),@@ -1161,7 +1160,7 @@ fn start_cdp_dom_focus_command(return start_dom_object_reference_operation(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsRemoteHandleId::from(object_id),PendingDomObjectReferenceOperation::Focus,)?@@ -1174,18 +1173,18 @@ fn start_cdp_dom_focus_command(return start_document_frontend_node_binding_command(conn,cmd.id,- cmd.session_id,+ &owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForFocus { frontend_node_id },)?.ok_or_else(PendingDomCommandStartError::node_not_found);}- let page = loaded_page_mut_for_session(conn, cmd.session_id)+ let page = loaded_page_mut_for_owner(conn, &owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = start_focus_document_node_for_reference(page, reference)?;Ok(PendingDomCommandDispatch {command_id: cmd.id,- session_id: cmd.session_id.map(str::to_owned),+ owner_scope: owner,kind: PendingDomCommandKind::Focus {missing_node_message: "No node found for given backend id",},@@ -1212,6 +1211,7 @@ fn start_cdp_dom_attribute_mutation_command(cmd: &Cmd<'_>,action: DomAction,) -> Result<PendingDomCommandDispatch, PendingDomCommandStartError> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);let (frontend_node_id, mutation) = match action {DomAction::SetAttributeValue => {let params: SetAttributeValueParams = match cmd.get_params() {@@ -1248,7 +1248,7 @@ fn start_cdp_dom_attribute_mutation_command(start_document_frontend_node_binding_command(conn,cmd.id,- cmd.session_id,+ &owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForMutateAttribute { mutation },)?@@ -1260,17 +1260,21 @@ fn start_cdp_dom_edit_command(cmd: &Cmd<'_>,action: DomAction,) -> Result<PendingDomCommandDispatch, PendingDomCommandStartError> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);let edit = super::edit::renderer_dom_edit_from_cdp(cmd, action)?;- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(cmd.session_id);- let page = loaded_page_mut_for_session(conn, cmd.session_id)+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, &owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = page.start_edit_document_node(renderer_inspector_session_id, edit).map_err(PendingDomCommandStartError::renderer_error)?;Ok(PendingDomCommandDispatch {command_id: cmd.id,- session_id: cmd.session_id.map(str::to_owned),+ owner_scope: owner,kind: PendingDomCommandKind::EditDocumentNode,pending: PendingDomCommandWork::Page(pending),})@@ -1332,24 +1336,24 @@ fn build_cdp_remove_node_command(fn start_devtools_remove_node_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsRemoveNodeCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {if let DevToolsDomNodeReference::FrontendNodeId(frontend_node_id) = command.reference {return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForRemoveNode { frontend_node_id },);}- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = start_remove_document_node_for_reference(page, command.reference)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::RemoveNode,pending: PendingDomCommandWork::Page(pending),}))@@ -1383,14 +1387,14 @@ fn build_cdp_dom_geometry_command(fn start_devtools_dom_geometry_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsDomGeometryCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {if let DevToolsDomNodeReference::FrontendNodeId(frontend_node_id) = command.reference {return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForDomGeometry {frontend_node_id,@@ -1399,12 +1403,12 @@ fn start_devtools_dom_geometry_command();}let reference = command.reference;- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let (pending, kind) = start_client_rect_for_reference(page, reference, command.operation)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind,pending: PendingDomCommandWork::Page(pending),}))@@ -1440,18 +1444,18 @@ fn build_cdp_describe_node_command(fn start_devtools_describe_node_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsDescribeNodeCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {let Some(reference) = command.reference else {return Err(PendingDomCommandStartError::node_not_found());};- let top_frame_id = top_frame_id_for_session(conn, command_session_id);+ let top_frame_id = top_frame_id_for_owner(conn, owner);if let DevToolsDomNodeReference::FrontendNodeId(frontend_node_id) = reference {return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForDescribeNode {frontend_node_id,@@ -1461,10 +1465,17 @@ fn start_devtools_describe_node_command(},);}- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id)+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = start_inspector_document_node_snapshot_for_reference(page,@@ -1476,7 +1487,7 @@ fn start_devtools_describe_node_command()?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::DescribeNodeObjectReference {cached_object_node: None,top_frame_id,@@ -1521,13 +1532,20 @@ fn build_cdp_request_child_nodes_command(fn start_devtools_request_child_nodes_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsRequestChildNodesCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let top_frame_id = top_frame_id_for_session(conn, command_session_id);- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, command_session_id);+ let top_frame_id = top_frame_id_for_owner(conn, owner);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );let next_depth = if command.depth > 0 {command.depth - 1} else {@@ -1538,7 +1556,7 @@ fn start_devtools_request_child_nodes_command(start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForRequestChildNodes {depth: next_depth,@@ -1548,7 +1566,7 @@ fn start_devtools_request_child_nodes_command()}DevToolsDomNodeReference::BackendNodeId(backend_node_id) => {- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let (pending, kind) = start_request_child_nodes_for_reference(page,@@ -1561,7 +1579,7 @@ fn start_devtools_request_child_nodes_command()?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind,pending: PendingDomCommandWork::Page(pending),}))@@ -1653,20 +1671,26 @@ fn build_cdp_query_selector_command(fn start_devtools_query_selector_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsQuerySelectorCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let top_frame_id = top_frame_id_for_session(conn, command_session_id);- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, command_session_id);+ let top_frame_id = top_frame_id_for_owner(conn, owner);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );let Some(reference) = command.root else {- let page = loaded_page_mut_for_session(conn, command_session_id).ok_or_else(|| {- PendingDomCommandStartError {+ let page =+ loaded_page_mut_for_owner(conn, owner).ok_or_else(|| PendingDomCommandStartError {code: -32000,message: "Could not find node with given id".to_owned(),- }- })?;+ })?;let pending = page.start_document_query_selector_for_document_in_inspector_session(renderer_inspector_session_id,@@ -1677,7 +1701,7 @@ fn start_devtools_query_selector_command(.map_err(PendingDomCommandStartError::renderer_error)?;return Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::QuerySelectorLive {multiple: command.multiple,},@@ -1687,7 +1711,7 @@ fn start_devtools_query_selector_command(match reference {DevToolsDomNodeReference::FrontendNodeId(frontend_node_id) => {- if loaded_page_mut_for_session(conn, command_session_id).is_none() {+ if loaded_page_mut_for_owner(conn, owner).is_none() {return Err(PendingDomCommandStartError {code: -32000,message: "Could not find node with given id".to_owned(),@@ -1696,7 +1720,7 @@ fn start_devtools_query_selector_command(start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForQuerySelector {selector: command.selector,@@ -1706,7 +1730,7 @@ fn start_devtools_query_selector_command()}DevToolsDomNodeReference::BackendNodeId(root_backend_node_id) => {- let page = loaded_page_mut_for_session(conn, command_session_id).ok_or_else(|| {+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(|| {PendingDomCommandStartError {code: -32000,message: "Could not find node with given id".to_owned(),@@ -1723,7 +1747,7 @@ fn start_devtools_query_selector_command(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::QuerySelectorLive {multiple: command.multiple,},@@ -1767,113 +1791,74 @@ fn build_cdp_get_document_command(})}-fn start_devtools_dom_command(+fn start_devtools_dom_command_for_owner(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {match command {DevToolsCommand::GetFrameOwner(command) => {- start_devtools_get_frame_owner_command(conn, command_id, command_session_id, command)+ start_devtools_get_frame_owner_command(conn, command_id, owner, command)}DevToolsCommand::GetAttributes(command) => {- start_devtools_get_attributes_command(conn, command_id, command_session_id, command)+ start_devtools_get_attributes_command(conn, command_id, owner, command)}DevToolsCommand::GetText(command) => {- start_devtools_get_text_command(conn, command_id, command_session_id, command)+ start_devtools_get_text_command(conn, command_id, owner, command)}DevToolsCommand::GetProperty(command) => {- start_devtools_get_property_command(conn, command_id, command_session_id, command)+ start_devtools_get_property_command(conn, command_id, owner, command)}DevToolsCommand::GetDocument(command) => {- start_devtools_get_document_command(conn, command_id, command_session_id, command)+ start_devtools_get_document_command(conn, command_id, owner, command)+ }+ DevToolsCommand::RequestChildNodes(command) => {+ start_devtools_request_child_nodes_command(conn, command_id, owner, command)}- DevToolsCommand::RequestChildNodes(command) => start_devtools_request_child_nodes_command(- conn,- command_id,- command_session_id,- command,- ),DevToolsCommand::QuerySelector(command) => {- start_devtools_query_selector_command(conn, command_id, command_session_id, command)+ start_devtools_query_selector_command(conn, command_id, owner, command)+ }+ DevToolsCommand::PerformSearch(command) => {+ search::start_devtools_perform_search_command(conn, command_id, owner, command)}- DevToolsCommand::PerformSearch(command) => search::start_devtools_perform_search_command(- conn,- command_id,- command_session_id,- command,- ),DevToolsCommand::GetSearchResults(command) => {- search::start_devtools_get_search_results_command(- conn,- command_id,- command_session_id,- command,- )+ search::start_devtools_get_search_results_command(conn, command_id, owner, command)}DevToolsCommand::DiscardSearchResults(command) => {- search::start_devtools_discard_search_results_command(- conn,- command_id,- command_session_id,- command,- )+ search::start_devtools_discard_search_results_command(conn, command_id, owner, command)}DevToolsCommand::GetNodeForLocation(command) => {- start_devtools_get_node_for_location_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_get_node_for_location_command(conn, command_id, owner, command)}DevToolsCommand::ResolveNode(command) => {- start_devtools_resolve_node_command(conn, command_id, command_session_id, command)+ start_devtools_resolve_node_command(conn, command_id, owner, command)}DevToolsCommand::DescribeNode(command) => {- start_devtools_describe_node_command(conn, command_id, command_session_id, command)+ start_devtools_describe_node_command(conn, command_id, owner, command)}DevToolsCommand::DomObjectReference(command) => {- start_devtools_dom_object_reference_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_dom_object_reference_command(conn, command_id, owner, command)}DevToolsCommand::SetFileInputFiles(command) => {set_file_input::start_devtools_set_file_input_files_command(- conn,- command_id,- command_session_id,- command,+ conn, command_id, owner, command,)}DevToolsCommand::PushNodesByBackendIds(command) => {- start_devtools_push_nodes_by_backend_ids_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_push_nodes_by_backend_ids_command(conn, command_id, owner, command)}DevToolsCommand::GetOuterHtml(command) => {- start_devtools_get_outer_html_command(conn, command_id, command_session_id, command)+ start_devtools_get_outer_html_command(conn, command_id, owner, command)}DevToolsCommand::DomGeometry(command) => {- start_devtools_dom_geometry_command(conn, command_id, command_session_id, command)+ start_devtools_dom_geometry_command(conn, command_id, owner, command)}DevToolsCommand::ScrollIntoViewIfNeeded(command) => {- start_devtools_scroll_into_view_if_needed_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_scroll_into_view_if_needed_command(conn, command_id, owner, command)}DevToolsCommand::RemoveNode(command) => {- start_devtools_remove_node_command(conn, command_id, command_session_id, command)+ start_devtools_remove_node_command(conn, command_id, owner, command)}_ => Err(PendingDomCommandStartError {code: -32000,@@ -1916,7 +1901,7 @@ fn complete_devtools_dom_command(fn start_devtools_get_document_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsGetDocumentCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {let operation = if command.flattened {@@ -1924,11 +1909,18 @@ fn start_devtools_get_document_command(} else {PendingDomDocumentSnapshotOperation::GetDocument};- let top_frame_id = top_frame_id_for_session(conn, command_session_id);- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id)+ let top_frame_id = top_frame_id_for_owner(conn, owner);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let depth = match operation {PendingDomDocumentSnapshotOperation::GetDocument => command.depth.unwrap_or(2),@@ -1944,7 +1936,7 @@ fn start_devtools_get_document_command(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::DocumentSnapshot {operation,top_frame_id,@@ -1974,24 +1966,26 @@ fn build_cdp_get_frame_owner_command(fn start_devtools_get_frame_owner_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsGetFrameOwnerCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id).ok_or_else(|| {- PendingDomCommandStartError {+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page =+ loaded_page_mut_for_owner(conn, owner).ok_or_else(|| PendingDomCommandStartError {code: -32000,message: "Frame with the given id does not belong to the target.".to_owned(),- }- })?;+ })?;let frame_id = command.frame_id.into_string();let pending = page.start_child_frame_owner_node_reference(&frame_id, renderer_inspector_session_id).map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::GetFrameOwner { frame_id },pending: PendingDomCommandWork::Page(pending),}))@@ -2031,16 +2025,21 @@ fn build_cdp_get_node_for_location_command(fn start_devtools_get_node_for_location_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsGetNodeForLocationCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {let top_frame_id = conn- .target_session_owner_frame_tree_identity(command_session_id)+ .target_session_owner_frame_tree_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).map(|identity| identity.0).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;- let inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id)+ let inspector_session_id = conn.target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = page.start_document_hit_test(@@ -2053,7 +2052,7 @@ fn start_devtools_get_node_for_location_command(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::GetNodeForLocation { top_frame_id },pending: PendingDomCommandWork::Page(pending),}))@@ -2126,18 +2125,21 @@ fn start_resolve_runtime_object_for_reference(fn start_devtools_resolve_node_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsResolveNodeCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {let reference = command.reference;- let top_frame_id = top_frame_id_for_session(conn, command_session_id);- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);+ let top_frame_id = top_frame_id_for_owner(conn, owner);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );if let DevToolsDomNodeReference::FrontendNodeId(frontend_node_id) = reference {return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForResolveNode {frontend_node_id,@@ -2147,7 +2149,7 @@ fn start_devtools_resolve_node_command(},);}- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;if let Some(execution_context_id) = command.execution_context_id {let pending = page@@ -2155,7 +2157,7 @@ fn start_devtools_resolve_node_command(.map_err(PendingDomCommandStartError::renderer_error)?;return Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::ResolveNodeExecutionContextFrame {reference,execution_context_id,@@ -2177,7 +2179,7 @@ fn start_devtools_resolve_node_command(Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::ResolveNode {object_group,cache_top_frame_id: resolution.cache_top_frame_id,@@ -2245,7 +2247,7 @@ fn build_cdp_dom_object_reference_command(fn pending_dom_object_reference_operation_from_devtools(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_id: &str,operation: DevToolsDomObjectReferenceOperation,) -> PendingDomObjectReferenceOperation {@@ -2269,10 +2271,8 @@ fn pending_dom_object_reference_operation_from_devtools(PendingDomObjectReferenceOperation::DescribeNode {depth,pierce,- cached_object_node: cached_dom_remote_object_node_for_session(- conn, session_id, object_id,- ),- top_frame_id: top_frame_id_for_session(conn, session_id),+ cached_object_node: cached_dom_remote_object_node_for_owner(conn, owner, object_id),+ top_frame_id: top_frame_id_for_owner(conn, owner),}}}@@ -2281,36 +2281,37 @@ fn pending_dom_object_reference_operation_from_devtools(fn start_devtools_dom_object_reference_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsDomObjectReferenceCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {let operation = pending_dom_object_reference_operation_from_devtools(conn,- command_session_id,+ owner,command.object_id.as_str(),command.operation,);- start_dom_object_reference_operation(- conn,- command_id,- command_session_id,- command.object_id,- operation,- )+ start_dom_object_reference_operation(conn, command_id, owner, command.object_id, operation)}fn start_dom_object_reference_operation(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,object_id: DevToolsRemoteHandleId,operation: PendingDomObjectReferenceOperation,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let reference = dom_object_reference_id(conn, command_session_id, &object_id);- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id)+ let reference = dom_object_reference_id_for_owner(conn, owner, &object_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let object_id = reference;match operation {@@ -2326,7 +2327,7 @@ fn start_dom_object_reference_operation(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::RequestNodeObjectReference,pending: PendingDomCommandWork::Page(pending),}))@@ -2337,7 +2338,7 @@ fn start_dom_object_reference_operation(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::Focus {missing_node_message: "Could not find node with given id",},@@ -2354,7 +2355,7 @@ fn start_dom_object_reference_operation(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::GetOuterHtmlObjectReference,pending: PendingDomCommandWork::Page(pending),}))@@ -2376,7 +2377,7 @@ fn start_dom_object_reference_operation(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::DescribeNodeObjectReference {cached_object_node,top_frame_id,@@ -2394,7 +2395,7 @@ fn start_dom_object_reference_operation(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::ObjectReferenceLiveClientRect { operation },pending: PendingDomCommandWork::Page(pending),}))@@ -2409,7 +2410,7 @@ fn start_dom_object_reference_operation(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::ScrollIntoViewIfNeededObjectReference,pending: PendingDomCommandWork::Page(pending),}))@@ -2420,12 +2421,15 @@ fn start_dom_object_reference_operation(fn start_devtools_push_nodes_by_backend_ids_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsPushNodesByBackendIdsCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let renderer_runtime_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id)+ let renderer_runtime_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let renderer_backend_positions = (0..command.backend_node_ids.len()).collect::<Vec<_>>();let node_ids = vec![0; command.backend_node_ids.len()];@@ -2439,7 +2443,7 @@ fn start_devtools_push_nodes_by_backend_ids_command(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::PushNodesByBackendIdsToFrontend {backend_node_ids,node_ids,@@ -2452,19 +2456,19 @@ fn start_devtools_push_nodes_by_backend_ids_command(fn start_devtools_get_outer_html_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsGetOuterHtmlCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {let include_shadow_dom = command.include_shadow_dom;let Some(reference) = command.reference else {- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = page.start_outer_html_for_document(include_shadow_dom).map_err(PendingDomCommandStartError::renderer_error)?;return Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::GetOuterHtmlDocument,pending: PendingDomCommandWork::Page(pending),}));@@ -2473,7 +2477,7 @@ fn start_devtools_get_outer_html_command(return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForGetOuterHtml {frontend_node_id,@@ -2481,12 +2485,12 @@ fn start_devtools_get_outer_html_command(},);}- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let (pending, kind) = start_outer_html_for_reference(page, reference, include_shadow_dom)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind,pending: PendingDomCommandWork::Page(pending),}))@@ -2498,7 +2502,8 @@ fn complete_pending_dom_command(out: &mut DomCommandOutput,) -> DomCommandTaskStep {let command_id = completed.command_id;- let session_id = completed.session_id.as_deref();+ let owner_scope = completed.owner_scope.clone();+ let session_id = owner_scope.session_id();let completed_work = match completed.completed {Ok(completion) => completion,Err(error) => {@@ -2508,35 +2513,53 @@ fn complete_pending_dom_command(};let CompletedDomCommandWork::Page(completion) = completed_work;let completion = *completion;- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ session_id,+ owner_scope.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ session_id,+ owner_scope.session_owner_route(),+ );let kind = match completed.kind {PendingDomCommandKind::PerformSearchLive => {- return search::complete_perform_search_live(conn, session_id, completion, out);+ return search::complete_perform_search_live(conn, &owner_scope, completion, out);}PendingDomCommandKind::GetSearchResultsLive => {- return search::complete_get_search_results_live(conn, session_id, completion, out);+ return search::complete_get_search_results_live(conn, &owner_scope, completion, out);}PendingDomCommandKind::DiscardSearchResultsLive => {- return search::complete_discard_search_results_live(conn, session_id, completion, out);+ return search::complete_discard_search_results_live(+ conn,+ &owner_scope,+ completion,+ out,+ );}PendingDomCommandKind::SetNodeStackTracesEnabled => {return stack_traces::complete_set_node_stack_traces_enabled_command(- conn, session_id, completion, out,+ conn,+ &owner_scope,+ completion,+ out,);}PendingDomCommandKind::GetNodeStackTraces => {return stack_traces::complete_get_node_stack_traces_command(- conn, session_id, completion, out,+ conn,+ &owner_scope,+ completion,+ out,);}PendingDomCommandKind::ResolveFrontendNodeForGetAttributes { frontend_node_id } => {return complete_frontend_node_binding_for_get_attributes(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,out,@@ -2546,7 +2569,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_get_text(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,out,@@ -2559,7 +2582,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_get_property(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,name,@@ -2573,7 +2596,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_dom_geometry(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,operation,@@ -2589,7 +2612,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_describe_node(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,depth,@@ -2606,7 +2629,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_request_child_nodes(conn,command_id,- session_id,+ &owner_scope,completion,depth,pierce,@@ -2618,7 +2641,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_remove_node(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,out,@@ -2628,7 +2651,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_focus(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,out,@@ -2636,7 +2659,12 @@ fn complete_pending_dom_command(}PendingDomCommandKind::ResolveFrontendNodeForMutateAttribute { mutation } => {return complete_frontend_node_binding_for_mutate_attribute(- conn, command_id, session_id, completion, mutation, out,+ conn,+ command_id,+ &owner_scope,+ completion,+ mutation,+ out,);}PendingDomCommandKind::ResolveFrontendNodeForQuerySelector {@@ -2647,7 +2675,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_query_selector(conn,command_id,- session_id,+ &owner_scope,completion,selector,multiple,@@ -2664,7 +2692,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_resolve_node(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,requested_execution_context_id,@@ -2680,7 +2708,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_get_outer_html(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,include_shadow_dom,@@ -2694,7 +2722,7 @@ fn complete_pending_dom_command(return complete_frontend_node_binding_for_scroll_into_view_if_needed(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,rect,@@ -2707,7 +2735,14 @@ fn complete_pending_dom_command(append,} => {return set_file_input::complete_bidi_node_binding_for_set_file_input_files(- conn, command_id, session_id, completion, object_id, files, append, out,+ conn,+ command_id,+ &owner_scope,+ completion,+ object_id,+ files,+ append,+ out,);}PendingDomCommandKind::ResolveFrontendNodeForSetFileInputFiles {@@ -2718,7 +2753,7 @@ fn complete_pending_dom_command(return set_file_input::complete_frontend_node_binding_for_set_file_input_files(conn,command_id,- session_id,+ &owner_scope,completion,frontend_node_id,file_paths,@@ -2728,7 +2763,7 @@ fn complete_pending_dom_command(}kind => kind,};- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {out.push_error(-32000, "NoDocumentLoaded");return DomCommandTaskStep::Complete;};@@ -2753,7 +2788,14 @@ fn complete_pending_dom_command(append,} => {return set_file_input::complete_preflight(- page, command_id, session_id, completion, reference, file_paths, append, out,+ page,+ command_id,+ &owner_scope,+ completion,+ reference,+ file_paths,+ append,+ out,);}PendingDomCommandKind::Focus {@@ -3002,7 +3044,7 @@ fn complete_pending_dom_command(Ok(pending) => {DomCommandTaskStep::Pending(Box::new(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner_scope.clone(),kind: PendingDomCommandKind::ResolveNodeCacheSnapshot {remote_object: Box::new(remote_object),object_group,@@ -3021,7 +3063,7 @@ fn complete_pending_dom_command(}};}- push_resolve_node_result(conn, session_id, out, remote_object, object_group);+ push_resolve_node_result(conn, &owner_scope, out, remote_object, object_group);}PendingDomCommandKind::ResolveNodeCacheSnapshot {remote_object,@@ -3032,7 +3074,7 @@ fn complete_pending_dom_command(match page.finish_document_node_snapshot_for_object_id(completion) {Ok(Some(snapshot)) => cache_resolved_node_snapshot(conn,- session_id,+ &owner_scope,cache_object_id,&snapshot.snapshot,top_frame_id.as_deref(),@@ -3043,7 +3085,7 @@ fn complete_pending_dom_command(return DomCommandTaskStep::Complete;}}- push_resolve_node_result(conn, session_id, out, *remote_object, object_group);+ push_resolve_node_result(conn, &owner_scope, out, *remote_object, object_group);}PendingDomCommandKind::ResolveNodeExecutionContextFrame {reference,@@ -3076,7 +3118,7 @@ fn complete_pending_dom_command(Ok(pending) => {DomCommandTaskStep::Pending(Box::new(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner_scope.clone(),kind: PendingDomCommandKind::ResolveNode {object_group,cache_top_frame_id: None,@@ -3107,7 +3149,7 @@ fn complete_pending_dom_command(Ok(resolution) => {DomCommandTaskStep::Pending(Box::new(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner_scope.clone(),kind: PendingDomCommandKind::ResolveNode {object_group,cache_top_frame_id: resolution.cache_top_frame_id,@@ -3171,10 +3213,18 @@ fn complete_pending_dom_command_result(conn: &mut CdpConnection,completed: CompletedDomCommandDispatch,) -> DevToolsDomCommandTaskStep {- let session_id = completed.session_id.as_deref();- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, session_id);+ let owner_scope = completed.owner_scope.clone();+ let session_id = owner_scope.session_id();+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ session_id,+ owner_scope.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ session_id,+ owner_scope.session_owner_route(),+ );let completed_work = match completed.completed {Ok(completion) => completion,Err(error) => {@@ -3192,7 +3242,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_get_attributes_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,);@@ -3201,7 +3251,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_get_text_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,);@@ -3213,7 +3263,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_get_property_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,name,@@ -3226,7 +3276,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_dom_geometry_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,operation,@@ -3241,7 +3291,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_describe_node_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,depth,@@ -3253,7 +3303,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_remove_node_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,);@@ -3266,7 +3316,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_request_child_nodes_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,depth,pierce,@@ -3279,7 +3329,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_query_selector_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,selector,multiple,@@ -3294,7 +3344,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_resolve_node_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,requested_execution_context_id,@@ -3309,7 +3359,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_get_outer_html_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,include_shadow_dom,@@ -3322,7 +3372,7 @@ fn complete_pending_dom_command_result(return complete_frontend_node_binding_for_scroll_into_view_if_needed_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,rect,@@ -3336,7 +3386,7 @@ fn complete_pending_dom_command_result(return set_file_input::complete_bidi_node_binding_for_set_file_input_files_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,object_id,files,@@ -3351,7 +3401,7 @@ fn complete_pending_dom_command_result(return set_file_input::complete_frontend_node_binding_for_set_file_input_files_result(conn,completed.command_id,- session_id,+ &owner_scope,completion,frontend_node_id,file_paths,@@ -3359,7 +3409,7 @@ fn complete_pending_dom_command_result();}PendingDomCommandKind::SetFileInputFiles => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3369,7 +3419,7 @@ fn complete_pending_dom_command_result(.map(|()| DevToolsCommandResult::Empty)}PendingDomCommandKind::SetFileInputFilesObjectReference => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3379,7 +3429,7 @@ fn complete_pending_dom_command_result(.map(|()| DevToolsCommandResult::Empty)}PendingDomCommandKind::GetNodeForLocation { top_frame_id } => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3389,7 +3439,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::GetNodeForLocation)}PendingDomCommandKind::RendererBackendNodeClientRect { operation } => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3403,7 +3453,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::DomGeometry)}PendingDomCommandKind::RendererBackendNodeScrollIntoViewIfNeeded => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3417,7 +3467,7 @@ fn complete_pending_dom_command_result(node_ids,renderer_backend_positions,} => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3435,7 +3485,7 @@ fn complete_pending_dom_command_result(}}PendingDomCommandKind::GetFrameOwner { frame_id } => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3445,7 +3495,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::GetFrameOwner)}PendingDomCommandKind::QuerySelectorLive { multiple } => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3455,7 +3505,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::QuerySelector)}PendingDomCommandKind::QuerySelectorSetChildNodesLive { multiple, .. } => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3465,7 +3515,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::QuerySelector)}PendingDomCommandKind::GetAttributesLive => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3475,7 +3525,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::GetAttributes)}PendingDomCommandKind::GetTextLive => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3484,7 +3534,7 @@ fn complete_pending_dom_command_result(complete_get_text_live_result(page, completion).map(DevToolsCommandResult::GetText)}PendingDomCommandKind::GetPropertyLive => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3498,7 +3548,7 @@ fn complete_pending_dom_command_result(cache_top_frame_id,} => {let remote_object = {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3515,7 +3565,7 @@ fn complete_pending_dom_command_result(.and_then(Value::as_str).map(str::to_owned){- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3531,7 +3581,7 @@ fn complete_pending_dom_command_result(Ok(pending) => {DevToolsDomCommandTaskStep::Pending(Box::new(PendingDomCommandDispatch {command_id: None,- session_id: session_id.map(str::to_owned),+ owner_scope: owner_scope.clone(),kind: PendingDomCommandKind::ResolveNodeCacheSnapshot {remote_object: Box::new(remote_object),object_group,@@ -3548,7 +3598,7 @@ fn complete_pending_dom_command_result(};}Ok(DevToolsCommandResult::ResolveNode(- register_resolve_node_result(conn, session_id, remote_object, object_group),+ register_resolve_node_result(conn, &owner_scope, remote_object, object_group),))}PendingDomCommandKind::ResolveNodeCacheSnapshot {@@ -3558,7 +3608,7 @@ fn complete_pending_dom_command_result(top_frame_id,} => {{- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3567,7 +3617,7 @@ fn complete_pending_dom_command_result(match page.finish_document_node_snapshot_for_object_id(completion) {Ok(Some(snapshot)) => cache_resolved_node_snapshot(conn,- session_id,+ &owner_scope,cache_object_id,&snapshot.snapshot,top_frame_id.as_deref(),@@ -3582,7 +3632,7 @@ fn complete_pending_dom_command_result(}}Ok(DevToolsCommandResult::ResolveNode(- register_resolve_node_result(conn, session_id, *remote_object, object_group),+ register_resolve_node_result(conn, &owner_scope, *remote_object, object_group),))}PendingDomCommandKind::ResolveNodeExecutionContextFrame {@@ -3591,14 +3641,14 @@ fn complete_pending_dom_command_result(object_group,top_frame_id,} => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",)));};return complete_resolve_node_execution_context_frame_result(- session_id,+ &owner_scope,renderer_inspector_session_id.clone(),page,completion,@@ -3613,7 +3663,7 @@ fn complete_pending_dom_command_result("UnsupportedDevToolsCommand",)),PendingDomCommandKind::ObjectReferenceLiveClientRect { operation } => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3623,7 +3673,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::DomGeometry)}PendingDomCommandKind::GetOuterHtmlObjectReference => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3633,7 +3683,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::GetOuterHtml)}PendingDomCommandKind::GetOuterHtmlDocument => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3643,7 +3693,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::GetOuterHtml)}PendingDomCommandKind::GetOuterHtmlBackendNodeReference => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3653,7 +3703,7 @@ fn complete_pending_dom_command_result(.map(DevToolsCommandResult::GetOuterHtml)}PendingDomCommandKind::ScrollIntoViewIfNeededObjectReference => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3666,7 +3716,7 @@ fn complete_pending_dom_command_result(cached_object_node,top_frame_id,} => {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, &owner_scope) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3916,11 +3966,11 @@ fn complete_query_selector_set_child_nodes_live_result(fn complete_frontend_node_binding_reference(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,out: &mut DomCommandOutput,) -> Result<DevToolsDomNodeReference, DomCommandTaskStep> {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, owner) else {out.push_error(-32000, "NoDocumentLoaded");return Err(DomCommandTaskStep::Complete);};@@ -3935,10 +3985,10 @@ fn complete_frontend_node_binding_reference(fn complete_frontend_node_binding_reference_result(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,) -> Result<DevToolsDomNodeReference, DevToolsDomCommandTaskStep> {- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = loaded_page_mut_for_owner(conn, owner) else {return Err(devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -3957,7 +4007,7 @@ fn complete_frontend_node_binding_reference_result(fn complete_frontend_node_binding_followup<F>(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,out: &mut DomCommandOutput,start: F,@@ -3969,19 +4019,18 @@ where)-> Result<(PendingPageCommand, PendingDomCommandKind), PendingDomCommandStartError>,{- let reference =- match complete_frontend_node_binding_reference(conn, session_id, completion, out) {- Ok(reference) => reference,- Err(step) => return step,- };- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let reference = match complete_frontend_node_binding_reference(conn, owner, completion, out) {+ Ok(reference) => reference,+ Err(step) => return step,+ };+ let Some(page) = loaded_page_mut_for_owner(conn, owner) else {out.push_error(-32000, "NoDocumentLoaded");return DomCommandTaskStep::Complete;};match start(page, reference) {Ok((pending, kind)) => DomCommandTaskStep::Pending(Box::new(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind,pending: PendingDomCommandWork::Page(pending),})),@@ -3995,7 +4044,7 @@ wherefn complete_frontend_node_binding_followup_result<F>(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,start: F,) -> DevToolsDomCommandTaskStep@@ -4006,12 +4055,11 @@ where)-> Result<(PendingPageCommand, PendingDomCommandKind), PendingDomCommandStartError>,{- let reference =- match complete_frontend_node_binding_reference_result(conn, session_id, completion) {- Ok(reference) => reference,- Err(step) => return step,- };- let Some(page) = loaded_page_mut_for_session(conn, session_id) else {+ let reference = match complete_frontend_node_binding_reference_result(conn, owner, completion) {+ Ok(reference) => reference,+ Err(step) => return step,+ };+ let Some(page) = loaded_page_mut_for_owner(conn, owner) else {return devtools_dom_command_task_complete(Err(DevToolsError::new(DevToolsErrorKind::Internal,"NoDocumentLoaded",@@ -4021,7 +4069,7 @@ whereOk((pending, kind)) => {DevToolsDomCommandTaskStep::Pending(Box::new(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind,pending: PendingDomCommandWork::Page(pending),}))@@ -4036,7 +4084,7 @@ wherefn complete_frontend_node_binding_for_get_attributes(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,out: &mut DomCommandOutput,@@ -4044,7 +4092,7 @@ fn complete_frontend_node_binding_for_get_attributes(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4057,14 +4105,14 @@ fn complete_frontend_node_binding_for_get_attributes(fn complete_frontend_node_binding_for_get_attributes_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,) -> DevToolsDomCommandTaskStep {complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| {start_document_node_attributes_for_reference(page, reference)@@ -4076,7 +4124,7 @@ fn complete_frontend_node_binding_for_get_attributes_result(fn complete_frontend_node_binding_for_remove_node(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,out: &mut DomCommandOutput,@@ -4084,7 +4132,7 @@ fn complete_frontend_node_binding_for_remove_node(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4097,14 +4145,14 @@ fn complete_frontend_node_binding_for_remove_node(fn complete_frontend_node_binding_for_remove_node_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,) -> DevToolsDomCommandTaskStep {complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| {start_remove_document_node_for_reference(page, reference)@@ -4116,7 +4164,7 @@ fn complete_frontend_node_binding_for_remove_node_result(fn complete_frontend_node_binding_for_focus(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,out: &mut DomCommandOutput,@@ -4124,7 +4172,7 @@ fn complete_frontend_node_binding_for_focus(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4143,7 +4191,7 @@ fn complete_frontend_node_binding_for_focus(fn complete_frontend_node_binding_for_mutate_attribute(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,mutation: RendererDomAttributeMutation,out: &mut DomCommandOutput,@@ -4151,7 +4199,7 @@ fn complete_frontend_node_binding_for_mutate_attribute(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,move |page, reference| start_mutate_document_node_for_reference(page, reference, mutation),@@ -4161,7 +4209,7 @@ fn complete_frontend_node_binding_for_mutate_attribute(fn complete_frontend_node_binding_for_get_text(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,out: &mut DomCommandOutput,@@ -4169,7 +4217,7 @@ fn complete_frontend_node_binding_for_get_text(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4182,14 +4230,14 @@ fn complete_frontend_node_binding_for_get_text(fn complete_frontend_node_binding_for_get_text_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,) -> DevToolsDomCommandTaskStep {complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| {start_document_node_text_for_reference(page, reference)@@ -4201,7 +4249,7 @@ fn complete_frontend_node_binding_for_get_text_result(fn complete_frontend_node_binding_for_get_property(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,name: String,@@ -4210,7 +4258,7 @@ fn complete_frontend_node_binding_for_get_property(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4223,7 +4271,7 @@ fn complete_frontend_node_binding_for_get_property(fn complete_frontend_node_binding_for_get_property_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,name: String,@@ -4231,7 +4279,7 @@ fn complete_frontend_node_binding_for_get_property_result(complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| {start_document_node_property_for_reference(page, reference, &name)@@ -4243,7 +4291,7 @@ fn complete_frontend_node_binding_for_get_property_result(fn complete_frontend_node_binding_for_dom_geometry(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,operation: DevToolsDomGeometryOperation,@@ -4252,7 +4300,7 @@ fn complete_frontend_node_binding_for_dom_geometry(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| start_client_rect_for_reference(page, reference, operation),@@ -4262,7 +4310,7 @@ fn complete_frontend_node_binding_for_dom_geometry(fn complete_frontend_node_binding_for_dom_geometry_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,operation: DevToolsDomGeometryOperation,@@ -4270,7 +4318,7 @@ fn complete_frontend_node_binding_for_dom_geometry_result(complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| start_client_rect_for_reference(page, reference, operation),)@@ -4279,7 +4327,7 @@ fn complete_frontend_node_binding_for_dom_geometry_result(fn complete_frontend_node_binding_for_describe_node(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,depth: i32,@@ -4287,13 +4335,20 @@ fn complete_frontend_node_binding_for_describe_node(top_frame_id: Option<String>,out: &mut DomCommandOutput,) -> DomCommandTaskStep {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4321,20 +4376,27 @@ fn complete_frontend_node_binding_for_describe_node(fn complete_frontend_node_binding_for_describe_node_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,depth: i32,pierce: bool,top_frame_id: Option<String>,) -> DevToolsDomCommandTaskStep {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| {start_inspector_document_node_snapshot_for_reference(@@ -4362,20 +4424,27 @@ fn complete_frontend_node_binding_for_describe_node_result(fn complete_frontend_node_binding_for_request_child_nodes(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,depth: i32,pierce: bool,top_frame_id: Option<String>,out: &mut DomCommandOutput,) -> DomCommandTaskStep {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4395,19 +4464,26 @@ fn complete_frontend_node_binding_for_request_child_nodes(fn complete_frontend_node_binding_for_request_child_nodes_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,depth: i32,pierce: bool,top_frame_id: Option<String>,) -> DevToolsDomCommandTaskStep {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| {start_request_child_nodes_for_reference(@@ -4427,20 +4503,27 @@ fn complete_frontend_node_binding_for_request_child_nodes_result(fn complete_frontend_node_binding_for_query_selector(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,selector: String,multiple: bool,top_frame_id: Option<String>,out: &mut DomCommandOutput,) -> DomCommandTaskStep {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4461,18 +4544,25 @@ fn complete_frontend_node_binding_for_query_selector(fn complete_frontend_node_binding_for_query_selector_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,selector: String,multiple: bool,) -> DevToolsDomCommandTaskStep {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let include_whitespace = dom_agent_includes_whitespace_for_session(conn, session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| {start_query_selector_for_reference(@@ -4516,7 +4606,7 @@ fn start_resolve_node_for_bound_reference(fn complete_frontend_node_binding_for_resolve_node(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,requested_execution_context_id: Option<i64>,@@ -4524,12 +4614,15 @@ fn complete_frontend_node_binding_for_resolve_node(top_frame_id: Option<String>,out: &mut DomCommandOutput,) -> DomCommandTaskStep {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| {@@ -4549,19 +4642,22 @@ fn complete_frontend_node_binding_for_resolve_node(fn complete_frontend_node_binding_for_resolve_node_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,requested_execution_context_id: Option<i64>,object_group: Option<String>,top_frame_id: Option<String>,) -> DevToolsDomCommandTaskStep {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| {start_resolve_node_for_bound_reference(@@ -4579,7 +4675,7 @@ fn complete_frontend_node_binding_for_resolve_node_result(fn complete_frontend_node_binding_for_get_outer_html(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,include_shadow_dom: bool,@@ -4588,7 +4684,7 @@ fn complete_frontend_node_binding_for_get_outer_html(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| start_outer_html_for_reference(page, reference, include_shadow_dom),@@ -4598,7 +4694,7 @@ fn complete_frontend_node_binding_for_get_outer_html(fn complete_frontend_node_binding_for_get_outer_html_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,include_shadow_dom: bool,@@ -4606,7 +4702,7 @@ fn complete_frontend_node_binding_for_get_outer_html_result(complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| start_outer_html_for_reference(page, reference, include_shadow_dom),)@@ -4615,7 +4711,7 @@ fn complete_frontend_node_binding_for_get_outer_html_result(fn complete_frontend_node_binding_for_scroll_into_view_if_needed(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,rect: Option<DomScrollIntoViewRect>,@@ -4624,7 +4720,7 @@ fn complete_frontend_node_binding_for_scroll_into_view_if_needed(complete_frontend_node_binding_followup(conn,command_id,- session_id,+ owner,completion,out,|page, reference| start_scroll_into_view_for_reference(page, reference, rect),@@ -4634,7 +4730,7 @@ fn complete_frontend_node_binding_for_scroll_into_view_if_needed(fn complete_frontend_node_binding_for_scroll_into_view_if_needed_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,rect: Option<DomScrollIntoViewRect>,@@ -4642,7 +4738,7 @@ fn complete_frontend_node_binding_for_scroll_into_view_if_needed_result(complete_frontend_node_binding_followup_result(conn,command_id,- session_id,+ owner,completion,|page, reference| start_scroll_into_view_for_reference(page, reference, rect),)@@ -4758,7 +4854,7 @@ fn complete_resolve_node_page_result(}fn complete_resolve_node_execution_context_frame_result(- session_id: Option<&str>,+ owner: &CommandOwnerScope,renderer_inspector_session_id: Option<String>,page: &mut Page,completion: CompletedPageCommand,@@ -4790,7 +4886,7 @@ fn complete_resolve_node_execution_context_frame_result(Ok(pending) => {DevToolsDomCommandTaskStep::Pending(Box::new(PendingDomCommandDispatch {command_id: None,- session_id: session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::ResolveNode {object_group,cache_top_frame_id: None,@@ -4817,7 +4913,7 @@ fn complete_resolve_node_execution_context_frame_result(Ok(resolution) => {DevToolsDomCommandTaskStep::Pending(Box::new(PendingDomCommandDispatch {command_id: None,- session_id: session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::ResolveNode {object_group,cache_top_frame_id: resolution.cache_top_frame_id,@@ -4860,20 +4956,20 @@ fn complete_object_reference_live_client_rect_result(fn cache_resolved_node_snapshot(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,cache_object_id: String,snapshot: &DocumentNodeSnapshot,top_frame_id: Option<&str>,) {let top_snapshot_node_id = top_snapshot_node_id_for_live_object_snapshot(snapshot);if let Some(cached_node) = node_snapshot_to_cdp(snapshot, top_snapshot_node_id, top_frame_id) {- cache_dom_remote_object_node_for_session(conn, session_id, cache_object_id, cached_node);+ cache_dom_remote_object_node_for_owner(conn, owner, cache_object_id, cached_node);}}fn register_resolve_node_result(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,mut remote_object: Value,object_group: Option<String>,) -> DevToolsResolveNodeResult {@@ -4884,13 +4980,13 @@ fn register_resolve_node_result(}let result = json!({ "object": remote_object.clone() });if let Some(object_group) = object_group.as_deref() {- conn.register_runtime_remote_object_ids_from_value_for_session_owner_with_group(- session_id,+ conn.register_runtime_remote_object_ids_from_value_for_owner_with_group(+ owner,&result,object_group,);} else {- conn.register_runtime_remote_object_ids_from_value_for_session_owner(session_id, &result);+ conn.register_runtime_remote_object_ids_from_value_for_owner(owner, &result);}DevToolsResolveNodeResult {object: remote_object,@@ -5067,7 +5163,7 @@ pub(super) fn push_set_child_nodes_event_from_snapshots(fn push_resolve_node_result(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,out: &mut DomCommandOutput,mut remote_object: Value,object_group: Option<String>,@@ -5079,13 +5175,13 @@ fn push_resolve_node_result(}let result = json!({ "object": remote_object });if let Some(object_group) = object_group.as_deref() {- conn.register_runtime_remote_object_ids_from_value_for_session_owner_with_group(- session_id,+ conn.register_runtime_remote_object_ids_from_value_for_owner_with_group(+ owner,&result,object_group,);} else {- conn.register_runtime_remote_object_ids_from_value_for_session_owner(session_id, &result);+ conn.register_runtime_remote_object_ids_from_value_for_owner(owner, &result);}out.push_result(result);}@@ -5644,25 +5740,25 @@ fn build_cdp_get_attributes_command(fn start_devtools_get_attributes_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsGetAttributesCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {if let DevToolsDomNodeReference::FrontendNodeId(frontend_node_id) = command.reference {return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForGetAttributes { frontend_node_id },);}let reference = command.reference;- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = start_document_node_attributes_for_reference(page, reference)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::GetAttributesLive,pending: PendingDomCommandWork::Page(pending),}))@@ -5680,20 +5776,23 @@ fn flatten_dom_attributes(attributes: Vec<DevToolsDomAttribute>) -> Vec<String>fn start_document_frontend_node_binding_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,frontend_node_id: u32,kind: PendingDomCommandKind,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id)+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = page.start_document_frontend_node_binding(renderer_inspector_session_id, frontend_node_id).map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind,pending: PendingDomCommandWork::Page(pending),}))@@ -5702,25 +5801,25 @@ fn start_document_frontend_node_binding_command(fn start_devtools_get_text_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsGetTextCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {if let DevToolsDomNodeReference::FrontendNodeId(frontend_node_id) = command.reference {return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForGetText { frontend_node_id },);}let reference = command.reference;- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = start_document_node_text_for_reference(page, reference)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::GetTextLive,pending: PendingDomCommandWork::Page(pending),}))@@ -5729,14 +5828,14 @@ fn start_devtools_get_text_command(fn start_devtools_get_property_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsGetPropertyCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {if let DevToolsDomNodeReference::FrontendNodeId(frontend_node_id) = command.reference {return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForGetProperty {frontend_node_id,@@ -5745,12 +5844,12 @@ fn start_devtools_get_property_command();}let reference = command.reference;- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = start_document_node_property_for_reference(page, reference, &command.name)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::GetPropertyLive,pending: PendingDomCommandWork::Page(pending),}))@@ -5760,7 +5859,8 @@ pub(super) fn push_nodes_by_backend_ids_to_frontend(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> Option<CommandOutputPlan> {- if !target_owner_exists_for_session(conn, cmd.session_id) {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ if !target_owner_exists_for_owner(conn, &owner) {return Some(CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"));}match build_cdp_push_nodes_by_backend_ids_command(conn, cmd) {@@ -5794,7 +5894,8 @@ fn build_cdp_push_nodes_by_backend_ids_command(}pub(super) fn get_outer_html(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<CommandOutputPlan> {- if !target_owner_exists_for_session(conn, cmd.session_id) {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ if !target_owner_exists_for_owner(conn, &owner) {return Some(CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"));}None@@ -5832,7 +5933,7 @@ pub(crate) async fn execute_devtools_dom_command_async(command: DevToolsCommand,) -> Result<DevToolsCommandResult, DevToolsError> {let (target_id, command_session_id) = devtools_dom_command_route(&command)?;- if let Some(target_id) = target_id.as_deref() {+ let owner = if let Some(target_id) = target_id.as_deref() {if conn.target_session_route_for_target_id(target_id).is_none() {let result = super::child_frame::execute_devtools_dom_command(conn, target_id, command).await@@ -5842,17 +5943,12 @@ pub(crate) async fn execute_devtools_dom_command_async(let route = conn.target_session_route_for_target_id(target_id).ok_or_else(|| DevToolsError::new(DevToolsErrorKind::NoSuchTarget, "NoSuchTarget"))?;- let mut route_scope = conn.scoped_none_session_owner_route_override(route);- return execute_devtools_dom_command_on_current_route(- route_scope.conn_mut(),- None,- command,- )- .await;- }+ CommandOwnerScope::for_route(route)+ } else {+ CommandOwnerScope::capture(conn, command_session_id.as_deref())+ };- execute_devtools_dom_command_on_current_route(conn, command_session_id.as_deref(), command)- .await+ execute_devtools_dom_command_for_owner(conn, &owner, command).await}fn devtools_dom_command_route(@@ -5899,17 +5995,17 @@ fn devtools_dom_command_route())}-async fn execute_devtools_dom_command_on_current_route(+async fn execute_devtools_dom_command_for_owner(conn: &mut CdpConnection,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsCommand,) -> Result<DevToolsCommandResult, DevToolsError> {match command {DevToolsCommand::QuerySelector(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::QuerySelector(command),).map_err(DevToolsError::from)?@@ -5918,10 +6014,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::GetAttributes(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::GetAttributes(command),).map_err(DevToolsError::from)?@@ -5930,10 +6026,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::GetText(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::GetText(command),).map_err(DevToolsError::from)?@@ -5942,10 +6038,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::GetProperty(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::GetProperty(command),).map_err(DevToolsError::from)?@@ -5954,10 +6050,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::PushNodesByBackendIds(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::PushNodesByBackendIds(command),).map_err(DevToolsError::from)?@@ -5966,10 +6062,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::GetOuterHtml(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::GetOuterHtml(command),).map_err(DevToolsError::from)?@@ -5978,10 +6074,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::DescribeNode(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::DescribeNode(command),).map_err(DevToolsError::from)?@@ -5991,10 +6087,10 @@ async fn execute_devtools_dom_command_on_current_route(}DevToolsCommand::GetFrameOwner(command) => {let immediate_command = command.clone();- let Some(pending) = start_devtools_dom_command(+ let Some(pending) = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::GetFrameOwner(command),).map_err(DevToolsError::from)?@@ -6011,10 +6107,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::ResolveNode(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::ResolveNode(command),).map_err(DevToolsError::from)?@@ -6023,10 +6119,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::ScrollIntoViewIfNeeded(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::ScrollIntoViewIfNeeded(command),).map_err(DevToolsError::from)?@@ -6035,10 +6131,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::DomGeometry(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::DomGeometry(command),).map_err(DevToolsError::from)?@@ -6053,10 +6149,10 @@ async fn execute_devtools_dom_command_on_current_route(| DevToolsDomObjectReferenceOperation::GetContentQuads) =>{- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::DomObjectReference(command),).map_err(DevToolsError::from)?@@ -6065,10 +6161,10 @@ async fn execute_devtools_dom_command_on_current_route(await_pending_devtools_dom_command_result(conn, pending).await}DevToolsCommand::SetFileInputFiles(command) => {- let pending = start_devtools_dom_command(+ let pending = start_devtools_dom_command_for_owner(conn,None,- command_session_id,+ owner,DevToolsCommand::SetFileInputFiles(command),).map_err(DevToolsError::from)?@@ -6142,7 +6238,8 @@ pub(super) fn scroll_into_view_if_needed(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> Option<CommandOutputPlan> {- if !target_owner_exists_for_session(conn, cmd.session_id) {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ if !target_owner_exists_for_owner(conn, &owner) {return Some(CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"));}None@@ -6178,7 +6275,7 @@ fn build_cdp_scroll_into_view_if_needed_command(fn start_devtools_scroll_into_view_if_needed_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsScrollIntoViewIfNeededCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {let Some(reference) = command.reference else {@@ -6188,7 +6285,7 @@ fn start_devtools_scroll_into_view_if_needed_command(return start_document_frontend_node_binding_command(conn,command_id,- command_session_id,+ owner,frontend_node_id,PendingDomCommandKind::ResolveFrontendNodeForScrollIntoViewIfNeeded {frontend_node_id,@@ -6196,12 +6293,12 @@ fn start_devtools_scroll_into_view_if_needed_command(},);}- let page = loaded_page_mut_for_session(conn, command_session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let (pending, kind) = start_scroll_into_view_for_reference(page, reference, command.rect)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind,pending: PendingDomCommandWork::Page(pending),}))@@ -6216,7 +6313,17 @@ mod protocol_neutral_tests {use moli_page_types::DocumentSnapshotNodeId;use serde_json::{Value, json};- use crate::conn::{CdpConnection, Cmd};+ use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};++ fn start_devtools_dom_command(+ conn: &mut CdpConnection,+ command_id: Option<u64>,+ command_session_id: Option<&str>,+ command: DevToolsCommand,+ ) -> Result<Option<super::PendingDomCommandDispatch>, super::PendingDomCommandStartError> {+ let owner = CommandOwnerScope::capture(conn, command_session_id);+ super::start_devtools_dom_command_for_owner(conn, command_id, &owner, command)+ }fn unique_test_file_path(name: &str) -> std::path::PathBuf {let nanos = std::time::SystemTime::now()@@ -6352,7 +6459,7 @@ mod protocol_neutral_tests {panic!("valid getDocument command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -6407,7 +6514,7 @@ mod protocol_neutral_tests {panic!("valid getFrameOwner command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -6472,7 +6579,7 @@ mod protocol_neutral_tests {panic!("valid requestChildNodes command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -6567,7 +6674,7 @@ mod protocol_neutral_tests {panic!("valid getNodeForLocation command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -6693,7 +6800,7 @@ mod protocol_neutral_tests {panic!("valid querySelector command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -6833,7 +6940,7 @@ mod protocol_neutral_tests {panic!("valid resolveNode command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -7228,7 +7335,7 @@ mod protocol_neutral_tests {panic!("valid scrollIntoViewIfNeeded typed node reference command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -7320,7 +7427,7 @@ mod protocol_neutral_tests {panic!("valid getContentQuads typed node reference command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -7378,7 +7485,7 @@ mod protocol_neutral_tests {panic!("valid removeNode command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -7461,7 +7568,7 @@ mod protocol_neutral_tests {panic!("valid describeNode typed node reference command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,@@ -7564,7 +7671,7 @@ mod protocol_neutral_tests {panic!("valid requestNode object reference command");};- let result = super::start_devtools_dom_command(+ let result = start_devtools_dom_command(&mut conn,cmd.id,cmd.session_id,diff --git a/moli-protocol/src/domains/dom/search.rs b/moli-protocol/src/domains/dom/search.rsindex c610f2498..b62f6d4c6 100644--- a/moli-protocol/src/domains/dom/search.rs+++ b/moli-protocol/src/domains/dom/search.rs@@ -80,14 +80,20 @@ pub(super) fn build_cdp_discard_search_results_command(pub(super) fn start_devtools_perform_search_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsPerformSearchCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let include_whitespace =- super::dom_agent_includes_whitespace_for_session(conn, command_session_id);- let Some(page) = super::loaded_page_mut_for_session(conn, command_session_id) else {+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let include_whitespace = super::dom_agent_includes_whitespace_for_route(+ conn,+ owner.session_id(),+ owner.session_owner_route(),+ );+ let Some(page) = super::loaded_page_mut_for_owner(conn, owner) else {return Ok(None);};let pending = page@@ -101,7 +107,7 @@ pub(super) fn start_devtools_perform_search_command(Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::PerformSearchLive,pending: PendingDomCommandWork::Page(pending),}))@@ -110,12 +116,15 @@ pub(super) fn start_devtools_perform_search_command(pub(super) fn start_devtools_get_search_results_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsGetSearchResultsCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let Some(page) = super::loaded_page_mut_for_session(conn, command_session_id) else {+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let Some(page) = super::loaded_page_mut_for_owner(conn, owner) else {return Ok(None);};let pending = page@@ -128,7 +137,7 @@ pub(super) fn start_devtools_get_search_results_command(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::GetSearchResultsLive,pending: PendingDomCommandWork::Page(pending),}))@@ -137,12 +146,15 @@ pub(super) fn start_devtools_get_search_results_command(pub(super) fn start_devtools_discard_search_results_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsDiscardSearchResultsCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let Some(page) = super::loaded_page_mut_for_session(conn, command_session_id) else {+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let Some(page) = super::loaded_page_mut_for_owner(conn, owner) else {return Ok(None);};let pending = page@@ -150,7 +162,7 @@ pub(super) fn start_devtools_discard_search_results_command(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::DiscardSearchResultsLive,pending: PendingDomCommandWork::Page(pending),}))@@ -169,7 +181,8 @@ pub(super) fn complete_non_pending_perform_search_command(}};let session_id = command.context.session_id.as_ref().map(|id| id.as_str());- if super::loaded_page_mut_for_session(conn, session_id).is_some() {+ let owner = CommandOwnerScope::capture(conn, session_id);+ if super::loaded_page_mut_for_owner(conn, &owner).is_some() {out.push_error(-32000, "MissingDomCommand");return true;}@@ -186,12 +199,12 @@ pub(super) fn complete_non_pending_discard_search_results_command(pub(super) fn complete_perform_search_live(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,out: &mut DomCommandOutput,) -> DomCommandTaskStep {let search = {- let Some(page) = super::loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = super::loaded_page_mut_for_owner(conn, owner) else {out.push_error(-32000, "NoDocumentLoaded");return DomCommandTaskStep::Complete;};@@ -212,12 +225,12 @@ pub(super) fn complete_perform_search_live(pub(super) fn complete_get_search_results_live(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,out: &mut DomCommandOutput,) -> DomCommandTaskStep {let resolution = {- let Some(page) = super::loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = super::loaded_page_mut_for_owner(conn, owner) else {out.push_error(-32000, "NoDocumentLoaded");return DomCommandTaskStep::Complete;};@@ -251,11 +264,11 @@ pub(super) fn complete_get_search_results_live(pub(super) fn complete_discard_search_results_live(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,out: &mut DomCommandOutput,) -> DomCommandTaskStep {- let Some(page) = super::loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = super::loaded_page_mut_for_owner(conn, owner) else {out.push_success();return DomCommandTaskStep::Complete;};@@ -275,7 +288,7 @@ mod protocol_neutral_tests {use crate::devtools_runtime::DevToolsProtocol;use serde_json::{Value, json};- use crate::conn::{CdpConnection, Cmd};+ use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};#[test]fn cdp_perform_search_builds_protocol_neutral_command() {@@ -320,12 +333,9 @@ mod protocol_neutral_tests {panic!("valid performSearch command");};- let result = super::start_devtools_perform_search_command(- &mut conn,- cmd.id,- cmd.session_id,- command,- );+ let owner = CommandOwnerScope::for_session("SID-dom");+ let result =+ super::start_devtools_perform_search_command(&mut conn, cmd.id, &owner, command);let Ok(None) = result else {panic!("performSearch without a loaded page should stay on sync empty-result path");diff --git a/moli-protocol/src/domains/dom/set_file_input.rs b/moli-protocol/src/domains/dom/set_file_input.rsindex 68e27cf7f..f76ad5918 100644--- a/moli-protocol/src/domains/dom/set_file_input.rs+++ b/moli-protocol/src/domains/dom/set_file_input.rs@@ -6,15 +6,15 @@ use std::{use serde::Deserialize;-use super::loaded_page_mut_for_session;+use super::loaded_page_mut_for_owner;use super::node_references::{NodeReferenceParams, devtools_node_reference_from_ids};use super::resolve::{DevToolsDomCommandTaskStep, DomCommandOutput, DomCommandTaskStep, PendingDomCommandDispatch,PendingDomCommandKind, PendingDomCommandStartError, PendingDomCommandWork,- devtools_dom_command_task_complete, dom_object_reference_id,+ devtools_dom_command_task_complete, dom_object_reference_id_for_owner,start_document_node_snapshot_for_reference,};-use crate::conn::{CdpConnection, Cmd};+use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};use crate::devtools_runtime::{DevToolsDomNodeReference, DevToolsError, DevToolsErrorKind, DevToolsRemoteHandleId,DevToolsSetFileInputFilesCommand, is_webdriver_bidi_node_shared_id,@@ -60,6 +60,7 @@ pub(super) fn start_cdp_set_file_input_files_by_node_reference(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);let params: SetFileInputFilesParams = match cmd.get_params() {Ok(Some(params)) => params,_ => return Err(PendingDomCommandStartError::invalid_params()),@@ -73,18 +74,18 @@ pub(super) fn start_cdp_set_file_input_files_by_node_reference(return start_set_file_input_files_frontend_node_binding(conn,cmd.id,- cmd.session_id,+ &owner,frontend_node_id,params.files,false,);}- let page = loaded_page_mut_for_session(conn, cmd.session_id)+ let page = loaded_page_mut_for_owner(conn, &owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;start_set_file_input_files_preflight_dispatch(page,cmd.id,- cmd.session_id,+ &owner,reference,params.files,false,@@ -95,14 +96,17 @@ pub(super) fn start_cdp_set_file_input_files_by_node_reference(pub(super) fn start_devtools_set_file_input_files_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsSetFileInputFilesCommand,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {let is_shared_node_id = is_webdriver_bidi_node_shared_id(command.object_id.as_str());if is_shared_node_id {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id)+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = page.start_document_bidi_node_binding(@@ -112,7 +116,7 @@ pub(super) fn start_devtools_set_file_input_files_command(.map_err(PendingDomCommandStartError::renderer_error)?;return Ok(Some(PendingDomCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::ResolveBidiNodeForSetFileInputFiles {object_id: command.object_id,files: command.files,@@ -124,7 +128,7 @@ pub(super) fn start_devtools_set_file_input_files_command(start_set_file_input_files_for_remote_reference(conn,command_id,- command_session_id,+ owner,command.object_id,command.files,command.append,@@ -135,7 +139,7 @@ pub(super) fn start_devtools_set_file_input_files_command(pub(super) fn complete_preflight(page: &mut Page,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,reference: DevToolsDomNodeReference,file_paths: Vec<String>,@@ -169,7 +173,7 @@ pub(super) fn complete_preflight(}};match start_set_file_input_files_for_reference_dispatch(- page, command_id, session_id, reference, files, append,+ page, command_id, owner, reference, files, append,) {Ok(dispatch) => DomCommandTaskStep::Pending(Box::new(dispatch)),Err(error) => {@@ -182,7 +186,7 @@ pub(super) fn complete_preflight(pub(super) fn complete_bidi_node_binding_for_set_file_input_files(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,object_id: DevToolsRemoteHandleId,files: Vec<SelectedFile>,@@ -190,7 +194,7 @@ pub(super) fn complete_bidi_node_binding_for_set_file_input_files(out: &mut DomCommandOutput,) -> DomCommandTaskStep {match start_set_file_input_files_after_bidi_binding_resolution(- conn, command_id, session_id, completion, object_id, files, append,+ conn, command_id, owner, completion, object_id, files, append,) {Ok(dispatch) => DomCommandTaskStep::Pending(Box::new(dispatch)),Err(error) => {@@ -203,14 +207,14 @@ pub(super) fn complete_bidi_node_binding_for_set_file_input_files(pub(super) fn complete_bidi_node_binding_for_set_file_input_files_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,object_id: DevToolsRemoteHandleId,files: Vec<SelectedFile>,append: bool,) -> DevToolsDomCommandTaskStep {match start_set_file_input_files_after_bidi_binding_resolution(- conn, command_id, session_id, completion, object_id, files, append,+ conn, command_id, owner, completion, object_id, files, append,) {Ok(dispatch) => DevToolsDomCommandTaskStep::Pending(Box::new(dispatch)),Err(error) => devtools_dom_command_task_complete(Err(DevToolsError::from(error))),@@ -220,7 +224,7 @@ pub(super) fn complete_bidi_node_binding_for_set_file_input_files_result(pub(super) fn complete_frontend_node_binding_for_set_file_input_files(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,frontend_node_id: u32,file_paths: Vec<String>,@@ -230,7 +234,7 @@ pub(super) fn complete_frontend_node_binding_for_set_file_input_files(match start_set_file_input_files_after_frontend_binding_resolution(conn,command_id,- session_id,+ owner,completion,frontend_node_id,file_paths,@@ -247,7 +251,7 @@ pub(super) fn complete_frontend_node_binding_for_set_file_input_files(pub(super) fn complete_frontend_node_binding_for_set_file_input_files_result(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,frontend_node_id: u32,file_paths: Vec<String>,@@ -256,7 +260,7 @@ pub(super) fn complete_frontend_node_binding_for_set_file_input_files_result(match start_set_file_input_files_after_frontend_binding_resolution(conn,command_id,- session_id,+ owner,completion,frontend_node_id,file_paths,@@ -340,20 +344,20 @@ pub(super) fn complete_set_file_input_files_object_reference_result(fn start_set_file_input_files_after_bidi_binding_resolution(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,object_id: DevToolsRemoteHandleId,files: Vec<SelectedFile>,append: bool,) -> Result<PendingDomCommandDispatch, PendingDomCommandStartError> {- match finish_renderer_bidi_node_binding(conn, session_id, completion)? {+ match finish_renderer_bidi_node_binding(conn, owner, completion)? {RendererDomBidiNodeBindingResolution::BackendNodeId(backend_node_id) => {- let page = loaded_page_mut_for_session(conn, session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;start_set_file_input_files_for_reference_dispatch(page,command_id,- session_id,+ owner,DevToolsDomNodeReference::BackendNodeId(backend_node_id),files,append,@@ -361,7 +365,7 @@ fn start_set_file_input_files_after_bidi_binding_resolution(}RendererDomBidiNodeBindingResolution::NotFound => {start_set_file_input_files_for_remote_reference(- conn, command_id, session_id, object_id, files, append,+ conn, command_id, owner, object_id, files, append,)}}@@ -370,27 +374,27 @@ fn start_set_file_input_files_after_bidi_binding_resolution(fn start_set_file_input_files_after_frontend_binding_resolution(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,frontend_node_id: u32,file_paths: Vec<String>,append: bool,) -> Result<PendingDomCommandDispatch, PendingDomCommandStartError> {let reference =- finish_renderer_frontend_node_binding(conn, session_id, completion, frontend_node_id)?;- let page = loaded_page_mut_for_session(conn, session_id)+ finish_renderer_frontend_node_binding(conn, owner, completion, frontend_node_id)?;+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;start_set_file_input_files_preflight_dispatch(- page, command_id, session_id, reference, file_paths, append,+ page, command_id, owner, reference, file_paths, append,)}fn finish_renderer_bidi_node_binding(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,) -> Result<RendererDomBidiNodeBindingResolution, PendingDomCommandStartError> {- let page = loaded_page_mut_for_session(conn, session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;page.finish_document_bidi_node_binding(completion).map_err(|error| {@@ -402,11 +406,11 @@ fn finish_renderer_bidi_node_binding(fn finish_renderer_frontend_node_binding(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,_frontend_node_id: u32,) -> Result<DevToolsDomNodeReference, PendingDomCommandStartError> {- let page = loaded_page_mut_for_session(conn, session_id)+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;super::frontend_binding::finish_reference(page, completion).map_err(PendingDomCommandStartError::renderer_error)@@ -415,21 +419,24 @@ fn finish_renderer_frontend_node_binding(fn start_set_file_input_files_frontend_node_binding(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,frontend_node_id: u32,file_paths: Vec<String>,append: bool,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(session_id);- let page = loaded_page_mut_for_session(conn, session_id)+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = page.start_document_frontend_node_binding(renderer_inspector_session_id, frontend_node_id).map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::ResolveFrontendNodeForSetFileInputFiles {frontend_node_id,file_paths,@@ -442,21 +449,24 @@ fn start_set_file_input_files_frontend_node_binding(fn start_set_file_input_files_for_remote_reference(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,object_id: DevToolsRemoteHandleId,files: Vec<SelectedFile>,append: bool,) -> Result<PendingDomCommandDispatch, PendingDomCommandStartError> {- let reference = dom_object_reference_id(conn, command_session_id, &object_id);- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(command_session_id);- let page = loaded_page_mut_for_session(conn, command_session_id)+ let reference = dom_object_reference_id_for_owner(conn, owner, &object_id);+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = loaded_page_mut_for_owner(conn, owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let object_id = reference;start_set_file_input_files_for_runtime_object(page,command_id,- command_session_id,+ owner,renderer_inspector_session_id,object_id,files,@@ -467,7 +477,7 @@ fn start_set_file_input_files_for_remote_reference(fn start_set_file_input_files_preflight_dispatch(page: &Page,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,reference: DevToolsDomNodeReference,file_paths: Vec<String>,append: bool,@@ -478,7 +488,7 @@ fn start_set_file_input_files_preflight_dispatch(let pending = start_document_node_snapshot_for_reference(page, reference.clone(), 0, false)?;Ok(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::SetFileInputFilesPreflight {reference,file_paths,@@ -491,7 +501,7 @@ fn start_set_file_input_files_preflight_dispatch(fn start_set_file_input_files_for_reference_dispatch(page: &Page,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,reference: DevToolsDomNodeReference,files: Vec<SelectedFile>,append: bool,@@ -499,7 +509,7 @@ fn start_set_file_input_files_for_reference_dispatch(let pending = start_set_file_input_files_for_reference(page, reference, files, append)?;Ok(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::SetFileInputFiles,pending: PendingDomCommandWork::Page(pending),})@@ -524,7 +534,7 @@ fn start_set_file_input_files_for_reference(fn start_set_file_input_files_for_runtime_object(page: &Page,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,renderer_inspector_session_id: Option<String>,object_id: String,files: Vec<SelectedFile>,@@ -540,7 +550,7 @@ fn start_set_file_input_files_for_runtime_object(.map_err(PendingDomCommandStartError::renderer_error)?;Ok(PendingDomCommandDispatch {command_id,- session_id: session_id.map(str::to_owned),+ owner_scope: owner.clone(),kind: PendingDomCommandKind::SetFileInputFilesObjectReference,pending: PendingDomCommandWork::Page(pending),})diff --git a/moli-protocol/src/domains/dom/stack_traces.rs b/moli-protocol/src/domains/dom/stack_traces.rsindex c29872480..7d5249ca3 100644--- a/moli-protocol/src/domains/dom/stack_traces.rs+++ b/moli-protocol/src/domains/dom/stack_traces.rs@@ -23,20 +23,24 @@ pub(super) fn start_set_node_stack_traces_enabled_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);let params: SetNodeStackTracesEnabledParams = match cmd.get_params() {Ok(Some(params)) => params,_ => return Err(PendingDomCommandStartError::invalid_params()),};- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(cmd.session_id);- let page = super::loaded_page_mut_for_session(conn, cmd.session_id)+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = super::loaded_page_mut_for_owner(conn, &owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = page.start_set_document_node_stack_traces_enabled(renderer_inspector_session_id, params.enable).map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id: cmd.id,- session_id: cmd.session_id.map(str::to_owned),+ owner_scope: owner,kind: PendingDomCommandKind::SetNodeStackTracesEnabled,pending: PendingDomCommandWork::Page(pending),}))@@ -46,20 +50,24 @@ pub(super) fn start_get_node_stack_traces_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> Result<Option<PendingDomCommandDispatch>, PendingDomCommandStartError> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);let params: GetNodeStackTracesParams = match cmd.get_params() {Ok(Some(params)) => params,_ => return Err(PendingDomCommandStartError::invalid_params()),};- let renderer_inspector_session_id =- conn.target_renderer_runtime_inspector_session_id_for_session(cmd.session_id);- let page = super::loaded_page_mut_for_session(conn, cmd.session_id)+ let renderer_inspector_session_id = conn+ .target_renderer_runtime_inspector_session_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );+ let page = super::loaded_page_mut_for_owner(conn, &owner).ok_or_else(PendingDomCommandStartError::no_document_loaded)?;let pending = page.start_document_node_stack_trace(renderer_inspector_session_id, params.node_id).map_err(PendingDomCommandStartError::renderer_error)?;Ok(Some(PendingDomCommandDispatch {command_id: cmd.id,- session_id: cmd.session_id.map(str::to_owned),+ owner_scope: owner,kind: PendingDomCommandKind::GetNodeStackTraces,pending: PendingDomCommandWork::Page(pending),}))@@ -67,11 +75,11 @@ pub(super) fn start_get_node_stack_traces_command(pub(super) fn complete_set_node_stack_traces_enabled_command(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,out: &mut DomCommandOutput,) -> DomCommandTaskStep {- let Some(page) = super::loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = super::loaded_page_mut_for_owner(conn, owner) else {out.push_error(-32000, "NoDocumentLoaded");return DomCommandTaskStep::Complete;};@@ -88,12 +96,12 @@ pub(super) fn complete_set_node_stack_traces_enabled_command(pub(super) fn complete_get_node_stack_traces_command(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completion: CompletedPageCommand,out: &mut DomCommandOutput,) -> DomCommandTaskStep {let resolution = {- let Some(page) = super::loaded_page_mut_for_session(conn, session_id) else {+ let Some(page) = super::loaded_page_mut_for_owner(conn, owner) else {out.push_error(-32000, "NoDocumentLoaded");return DomCommandTaskStep::Complete;};diff --git a/moli-protocol/src/domains/dom_storage.rs b/moli-protocol/src/domains/dom_storage.rsindex 339bb6a5a..0e6ecbcde 100644--- a/moli-protocol/src/domains/dom_storage.rs+++ b/moli-protocol/src/domains/dom_storage.rs@@ -6,7 +6,7 @@ mod params;mod tests;pub(in crate::domains) use activity::{- DomStoragePreparedOutputSlot, append_pending_dom_storage_outputs_for_session_owner,+ DomStoragePreparedOutputSlot, append_pending_dom_storage_outputs_for_owner,project_dom_storage_async,};pub(crate) use commands::{diff --git a/moli-protocol/src/domains/dom_storage/activity.rs b/moli-protocol/src/domains/dom_storage/activity.rsindex e9a1af3f7..1ae178727 100644--- a/moli-protocol/src/domains/dom_storage/activity.rs+++ b/moli-protocol/src/domains/dom_storage/activity.rs@@ -3,7 +3,7 @@ use moli_core::network::{WebStorageAreaKind, WebStorageMutation, WebStorageMutatuse serde_json::{Value, json};use crate::{- conn::{BackgroundProtocolEvent, CdpConnection},+ conn::{BackgroundProtocolEvent, CdpConnection, CommandOwnerScope},domains::{activity::{ProtocolOutputPayloads, ProtocolOutputProjectionContext, ProtocolOutputSink,@@ -54,14 +54,14 @@ impl DomStoragePreparedOutputs {}}-pub(in crate::domains) fn append_pending_dom_storage_outputs_for_session_owner(+pub(in crate::domains) fn append_pending_dom_storage_outputs_for_owner(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,sink: &mut (impl ProtocolOutputSink + ?Sized),) {let mut outputs = DomStoragePreparedOutputs::default();for (event_session_id, subscription) in- dom_storage_subscriptions_for_browser_context_owner(conn, session_id)+ dom_storage_subscriptions_for_browser_context_owner(conn, owner){let records = subscription.drain();outputs.events.extend(@@ -75,13 +75,15 @@ pub(in crate::domains) fn append_pending_dom_storage_outputs_for_session_owner(fn dom_storage_subscriptions_for_browser_context_owner(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Vec<(Option<String>, WebStorageMutationSubscription)> {- let Some((browser_context_id, _)) = conn.target_owner_identity_for_session(session_id) else {- return dom_storage_subscriptions_for_session_owner(conn, session_id);+ let Some((browser_context_id, _)) =+ conn.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())+ else {+ return dom_storage_subscriptions_for_owner(conn, owner);};let Some(browser_context) = conn.browser_context_by_id(&browser_context_id) else {- return dom_storage_subscriptions_for_session_owner(conn, session_id);+ return dom_storage_subscriptions_for_owner(conn, owner);};let mut subscriptions = Vec::new();@@ -110,11 +112,11 @@ fn dom_storage_subscriptions_for_browser_context_owner(subscriptions}-fn dom_storage_subscriptions_for_session_owner(+fn dom_storage_subscriptions_for_owner(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Vec<(Option<String>, WebStorageMutationSubscription)> {- conn.page_event_session_ids_for_session_owner(session_id)+ conn.page_event_session_ids_for_route(owner.session_id(), owner.session_owner_route()).into_iter().filter_map(|event_session_id| {let subscription = conndiff --git a/moli-protocol/src/domains/dom_storage/commands.rs b/moli-protocol/src/domains/dom_storage/commands.rsindex b683f2be3..bc91d7c91 100644--- a/moli-protocol/src/domains/dom_storage/commands.rs+++ b/moli-protocol/src/domains/dom_storage/commands.rs@@ -470,11 +470,7 @@ fn storage_handles_for_session_owner(conn: &CdpConnection,session_id: Option<&str>,) -> Result<BrowserContextPageStorageHandles, CommandOutputPlan> {- let none_session_owner_route = session_id- .is_none()- .then(|| conn.none_session_owner_route_override())- .flatten();- storage_handles_for_route(conn, session_id, none_session_owner_route.as_ref())+ storage_handles_for_route(conn, session_id, None)}fn storage_handles_for_route(diff --git a/moli-protocol/src/domains/emulation.rs b/moli-protocol/src/domains/emulation.rsindex a8750225e..26e9c3fe8 100644--- a/moli-protocol/src/domains/emulation.rs+++ b/moli-protocol/src/domains/emulation.rs@@ -939,7 +939,13 @@ fn start_devtools_set_viewport_command(command: DevToolsSetViewportCommand,owner_route: Option<&CdpSessionRoute>,) -> Result<Option<PendingEmulationCommandDispatch>, DevToolsError> {- let session_id = command.context.session_id.as_ref().map(|id| id.as_str());+ let owner_scope = CommandOwnerScope::capture_for_route(+ conn,+ command.context.session_id.as_ref().map(|id| id.as_str()),+ owner_route,+ );+ let session_id = owner_scope.session_id();+ let owner_route = owner_scope.session_owner_route();if conn.browser_context.is_none()&& conn.target_owner_identity_for_route(session_id, owner_route)@@ -961,9 +967,6 @@ fn start_devtools_set_viewport_command("BrowserContextNotLoaded",));}- let owner_scope = session_id- .map(CommandOwnerScope::for_session)- .unwrap_or_else(|| CommandOwnerScope::for_implicit_route(owner_route.cloned()));let runtime_call_id = conn.next_internal_runtime_command_id();let Some(page) = conn.loaded_page_mut_for_target_configuration_for_route(session_id, owner_route)@@ -2638,7 +2641,7 @@ fn single_pending_emulation_dispatch(fn emulation_command_is_context_wide(conn: &CdpConnection, session_id: Option<&str>) -> bool {match session_id {- None => conn.none_session_owner_route_override().is_none(),+ None => true,Some(session_id) => matches!(conn.session_route(Some(session_id)),Some(CdpSessionRoute::Browser)@@ -2771,6 +2774,9 @@ fn start_session_surface_override_page_command_for_route(session_id: Option<&str>,owner_route: Option<&CdpSessionRoute>,) -> Result<Vec<PendingEmulationPageCommand>, String> {+ let owner_scope = CommandOwnerScope::capture_for_route(conn, session_id, owner_route);+ let session_id = owner_scope.session_id();+ let owner_route = owner_scope.session_owner_route();let script = {let Some((browser_context_id, target_id)) =conn.target_owner_identity_for_route(session_id, owner_route)@@ -2791,9 +2797,6 @@ fn start_session_surface_override_page_command_for_route(let Some(script) = script else {return Ok(Vec::new());};- let owner_scope = session_id- .map(CommandOwnerScope::for_session)- .unwrap_or_else(|| CommandOwnerScope::for_implicit_route(owner_route.cloned()));let runtime_call_id = conn.next_internal_runtime_command_id();let Some(page) = conn.loaded_page_mut_for_target_configuration_for_route(session_id, owner_route)diff --git a/moli-protocol/src/domains/emulation/tests.rs b/moli-protocol/src/domains/emulation/tests.rsindex 93acc26d7..9803a22ca 100644--- a/moli-protocol/src/domains/emulation/tests.rs+++ b/moli-protocol/src/domains/emulation/tests.rs@@ -727,15 +727,16 @@ async fn idle_override_updates_idle_detector_and_clear_restores_actual_state() {}));ctx.conn- .start_document_navigation_for_session_owner(+ .start_document_navigation_for_route(Some("SID-1"),+ None,"LID-idle-cross-document".to_owned(),).expect("cross-Document navigation should enter the pending state");let configuration = ctx.conn- .prepared_document_commit_configuration_for_session_owner(- Some("SID-1"),+ .prepared_document_commit_configuration_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),&url::Url::parse("http://127.0.0.1:65530/same-site-different-origin").unwrap(),).expect("commit configuration should resolve the target resource runtime");@@ -748,8 +749,8 @@ async fn idle_override_updates_idle_detector_and_clear_restores_actual_state() {);let cross_site_configuration = ctx.conn- .prepared_document_commit_configuration_for_session_owner(- Some("SID-1"),+ .prepared_document_commit_configuration_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),&url::Url::parse("http://idle-override-cross-site.test/").unwrap(),).expect("cross-site commit configuration should resolve the target resource runtime");diff --git a/moli-protocol/src/domains/fetch.rs b/moli-protocol/src/domains/fetch.rsindex 1b33eab78..f575cff4d 100644--- a/moli-protocol/src/domains/fetch.rs+++ b/moli-protocol/src/domains/fetch.rs@@ -57,7 +57,6 @@ pub(crate) use subresource::{pub(crate) struct PendingFetchCommandDispatch {command_id: Option<u64>,- session_id: Option<String>,owner_scope: CommandOwnerScope,kind: PendingFetchCommandKind,pending: PendingFetchCommandOperation,@@ -65,7 +64,6 @@ pub(crate) struct PendingFetchCommandDispatch {pub(crate) struct CompletedFetchCommandDispatch {command_id: Option<u64>,- session_id: Option<String>,owner_scope: CommandOwnerScope,kind: PendingFetchCommandKind,completed: CompletedFetchCommandOperation,@@ -229,33 +227,19 @@ impl PendingFetchCommandDispatch {kind: PendingFetchCommandKind,pending: PendingFetchCommandOperation,) -> Self {- // Fetch terminal commands may resume a renderer-initiated navigation.- // Such a navigation has no command session of its own, so once this- // command crosses an async boundary it needs the issuing Page route as- // its implicit owner. Keep that route exact even if another Page or- // BrowserContext becomes active before the completion is processed.- let session_owner_route =- match session_id.and_then(|session_id| conn.session_route(Some(session_id))) {- Some(route @ CdpSessionRoute::PageTarget { .. }) => Some(route),- Some(- CdpSessionRoute::Browser- | CdpSessionRoute::BrowserContext { .. }- | CdpSessionRoute::TabTarget { .. }- | CdpSessionRoute::SharedWorkerTarget { .. }- | CdpSessionRoute::DedicatedWorkerTarget { .. }- | CdpSessionRoute::ServiceWorkerTarget { .. },- ) => None,- None if session_id.is_none() => CommandOwnerScope::capture(conn, None)- .session_owner_route()- .cloned(),- None => None,- };+ let owner = CommandOwnerScope::capture(conn, session_id);+ Self::new_for_owner(command_id, owner, kind, pending)+ }++ fn new_for_owner(+ command_id: Option<u64>,+ owner_scope: CommandOwnerScope,+ kind: PendingFetchCommandKind,+ pending: PendingFetchCommandOperation,+ ) -> Self {Self {command_id,- session_id: session_id.map(str::to_owned),- owner_scope: session_id- .map(CommandOwnerScope::for_session)- .unwrap_or_else(|| CommandOwnerScope::for_implicit_route(session_owner_route)),+ owner_scope,kind,pending,}@@ -278,7 +262,6 @@ impl PendingFetchCommandDispatch {};CompletedFetchCommandDispatch {command_id: self.command_id,- session_id: self.session_id,owner_scope: self.owner_scope,kind: self.kind,completed,@@ -292,7 +275,7 @@ impl CompletedFetchCommandDispatch {}pub(crate) fn session_id(&self) -> Option<&str> {- self.session_id.as_deref()+ self.owner_scope.session_id()}}@@ -364,16 +347,12 @@ pub(crate) async fn execute_devtools_fetch_command_async_with_protocol_events(Ok(session_ids) => session_ids,Err(error) => return DevToolsCommandExecutionOutput::new(Err(error)),};- let step = {- let mut route_scope =- conn.scoped_optional_none_session_owner_route_override(owner_route.clone());- start_devtools_fetch_command(- route_scope.conn_mut(),- None,- owner_session_id.as_deref(),- command,- )- };+ let owner = CommandOwnerScope::capture_for_route(+ conn,+ owner_session_id.as_deref(),+ owner_route.as_ref(),+ );+ let step = start_devtools_fetch_command_for_owner(conn, None, &owner, command);match step {FetchCommandTaskStep::Complete(mut plan) => {let renderer_output_predecessor = plan.take_renderer_output_predecessor();@@ -393,9 +372,7 @@ pub(crate) async fn execute_devtools_fetch_command_async_with_protocol_events(}FetchCommandTaskStep::Pending(pending) => {let completed = pending.wait().await;- let mut route_scope =- conn.scoped_optional_none_session_owner_route_override(owner_route);- complete_pending_devtools_fetch_command(route_scope.conn_mut(), completed)+ complete_pending_devtools_fetch_command(conn, completed).await.into_devtools_result_and_background_events(success_result)}@@ -413,32 +390,27 @@ fn devtools_fetch_success_result(command: &DevToolsCommand) -> DevToolsCommandRe}}-fn start_devtools_fetch_command(+fn start_devtools_fetch_command_for_owner(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsCommand,) -> FetchCommandTaskStep {match &command {DevToolsCommand::AddNetworkIntercept(command) => {- start_devtools_add_network_intercept_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_add_network_intercept_command(conn, command_id, owner, command)}DevToolsCommand::RemoveNetworkIntercept(command) => {start_devtools_remove_network_intercept_command(conn,command_id,- command_session_id,+ owner,command.intercept_id.as_str(),command.context.protocol != DevToolsProtocol::Cdp&& command.context.target_id.is_none(),)}- _ => commands::start_devtools_fetch_command(conn, command_id, command_session_id, command),+ _ => commands::start_devtools_fetch_command_for_owner(conn, command_id, owner, command),}}@@ -549,13 +521,13 @@ fn start_enable_command(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> FetchCommandfn start_devtools_add_network_intercept_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: &DevToolsAddNetworkInterceptCommand,) -> FetchCommandTaskStep {let (handle_auth_requests, auth_url_patterns, patterns) =network_intercept_fetch_config(command);let intercept_session_id = if command.context.protocol == DevToolsProtocol::Cdp {- command_session_id.map(str::to_owned)+ owner.session_id().map(str::to_owned)} else {command.context@@ -563,23 +535,25 @@ fn start_devtools_add_network_intercept_command(.as_ref().map(|session_id| session_id.as_str().to_owned())};- match conn.start_add_network_intercept_for_session_owner(- command_session_id,+ match conn.start_add_network_intercept_for_route(+ owner.session_id(),+ owner.session_owner_route(),intercept_session_id,command.intercept_id.as_str().to_owned(),handle_auth_requests,auth_url_patterns,patterns,) {- Ok(Some(pending)) => FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,- command_id,- command_session_id,- PendingFetchCommandKind::AddNetworkIntercept {- intercept_id: command.intercept_id.as_str().to_owned(),- },- PendingFetchCommandOperation::Page(pending),- )),+ Ok(Some(pending)) => {+ FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(+ command_id,+ owner.clone(),+ PendingFetchCommandKind::AddNetworkIntercept {+ intercept_id: command.intercept_id.as_str().to_owned(),+ },+ PendingFetchCommandOperation::Page(pending),+ ))+ }Ok(None) => FetchCommandTaskStep::Complete(CommandOutputPlan::from_devtools_result(DevToolsCommandResult::AddNetworkIntercept(DevToolsAddNetworkInterceptResult {intercept_id: command.intercept_id.clone(),@@ -595,22 +569,24 @@ fn start_devtools_add_network_intercept_command(fn start_devtools_remove_network_intercept_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,intercept_id: &str,allow_global_lookup: bool,) -> FetchCommandTaskStep {- match conn.start_remove_network_intercept_for_session_owner(- command_session_id,+ match conn.start_remove_network_intercept_for_route(+ owner.session_id(),+ owner.session_owner_route(),intercept_id,allow_global_lookup,) {- Ok(Some(pending)) => FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,- command_id,- command_session_id,- PendingFetchCommandKind::RemoveNetworkIntercept,- PendingFetchCommandOperation::Page(pending),- )),+ Ok(Some(pending)) => {+ FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(+ command_id,+ owner.clone(),+ PendingFetchCommandKind::RemoveNetworkIntercept,+ PendingFetchCommandOperation::Page(pending),+ ))+ }Ok(None) => FetchCommandTaskStep::Complete(CommandOutputPlan::success()),Err(message) if message == "NetworkInterceptNotFound" => FetchCommandTaskStep::Complete(CommandOutputPlan::error(-32000, "NetworkInterceptNotFound"),@@ -695,9 +671,7 @@ async fn complete_pending_fetch_command_output(conn: &mut CdpConnection,completed: CompletedFetchCommandDispatch,) -> FetchCommandOutput {- let owner_scope = completed.owner_scope.clone();- let mut route_scope = owner_scope.enter(conn);- complete_pending_fetch_command_inner(route_scope.conn_mut(), completed).await+ complete_pending_fetch_command_inner(conn, completed).await}async fn complete_pending_fetch_command_inner(@@ -705,6 +679,7 @@ async fn complete_pending_fetch_command_inner(completed: CompletedFetchCommandDispatch,) -> FetchCommandOutput {let mut out = FetchCommandOutput::default();+ let owner_scope = completed.owner_scope.clone();// Every Fetch operation that crossed the renderer Page boundary must make// its concrete publication a predecessor of the frontend response. Keep// this at the one dispatch join point: command-specific finish helpers@@ -739,7 +714,7 @@ async fn complete_pending_fetch_command_inner(} => {complete_disable_command_async(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed.into_page_completion(),*pending_fetch_state,&mut out,@@ -749,7 +724,7 @@ async fn complete_pending_fetch_command_inner(PendingFetchCommandKind::ContinueRequest { state } => {commands::complete_continue_request_command_async(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed.into_page_completion(),*state,&mut out,@@ -759,7 +734,7 @@ async fn complete_pending_fetch_command_inner(PendingFetchCommandKind::ContinueWithAuth { state } => {auth::complete_continue_with_auth_command_async(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed.into_page_completion(),*state,&mut out,@@ -769,7 +744,7 @@ async fn complete_pending_fetch_command_inner(PendingFetchCommandKind::FailRequest { state } => {commands::complete_fail_request_command_async(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed.into_page_completion(),*state,&mut out,@@ -779,7 +754,7 @@ async fn complete_pending_fetch_command_inner(PendingFetchCommandKind::FulfillRequest { state } => {commands::complete_fulfill_request_command_async(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed.into_page_completion(),*state,&mut out,@@ -789,7 +764,7 @@ async fn complete_pending_fetch_command_inner(PendingFetchCommandKind::DispatchWebSocketMessage { operation } => {commands::complete_websocket_page_command(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed.into_page_completion(),operation,&mut out,@@ -798,7 +773,7 @@ async fn complete_pending_fetch_command_inner(PendingFetchCommandKind::CloseWebSocket => {commands::complete_websocket_page_command(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed.into_page_completion(),commands::PendingWebSocketCommandOperation::Close,&mut out,@@ -807,7 +782,7 @@ async fn complete_pending_fetch_command_inner(PendingFetchCommandKind::ContinueResponse { state } => {commands::complete_continue_response_command_async(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed.into_page_completion(),*state,&mut out,@@ -817,7 +792,7 @@ async fn complete_pending_fetch_command_inner(PendingFetchCommandKind::GetResponseBody => {body_stream::complete_get_response_body_from_transfer(conn,- completed.session_id.as_deref(),+ &owner_scope,completed.completed,&mut out,);@@ -838,6 +813,7 @@ fn complete_fetch_config_update_command(completed: CompletedFetchCommandDispatch,result: DevToolsCommandResult,) -> CommandOutputPlan {+ let owner_scope = completed.owner_scope.clone();let Some(completed_page_command) = completed.completed.into_page_completion() else {return CommandOutputPlan::error(-32000, "Missing renderer completion");};@@ -845,7 +821,10 @@ fn complete_fetch_config_update_command(Ok(completion) => completion,Err(error) => return CommandOutputPlan::error(-32000, error),};- let page = match conn.loaded_page_mut_for_protocol_access(completed.session_id.as_deref()) {+ let page = match conn.loaded_page_mut_for_protocol_access_for_route(+ owner_scope.session_id(),+ owner_scope.session_owner_route(),+ ) {Ok(page) => page,Err(message) if message == "NoDocumentLoaded" => {return CommandOutputPlan::from_devtools_result(result);@@ -886,7 +865,7 @@ fn start_disable_command(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> FetchCommanasync fn complete_disable_command_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<moli_core::page::CompletedPageCommand, String>>,pending_fetch_state: FetchDisablePendingState,out: &mut FetchCommandOutput,@@ -902,7 +881,10 @@ async fn complete_disable_command_async(return;}};- match conn.loaded_page_mut_for_protocol_access(session_id) {+ match conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) {Ok(page) => {if let Err(error) = page.finish_set_fetch_subresource_interception(completion) {out.push_error(@@ -974,8 +956,9 @@ async fn complete_disable_command_async(}for (_, pending) in pending_subresource_fetches {if let Ok(predecessor) = conn- .fail_pending_subresource_fetch_for_session_owner_async(- session_id,+ .fail_pending_subresource_fetch_for_route_async(+ owner.session_id(),+ owner.session_owner_route(),pending.internal_id,"Fetch interception disabled".to_owned(),)@@ -988,7 +971,7 @@ async fn complete_disable_command_async(activity::flush_post_subresource_fetch_request_activity_background_events_async(conn,&mut events,- session_id,+ owner.session_id(),&pending,).await;@@ -997,8 +980,9 @@ async fn complete_disable_command_async(}for (_, pending) in pending_subresource_auths {if let Ok(predecessor) = conn- .fail_pending_subresource_auth_for_session_owner_async(- session_id,+ .fail_pending_subresource_auth_for_route_async(+ owner.session_id(),+ owner.session_owner_route(),pending.internal_id,"Fetch interception disabled".to_owned(),)@@ -1011,7 +995,7 @@ async fn complete_disable_command_async(activity::flush_post_subresource_auth_activity_background_events_async(conn,&mut events,- session_id,+ owner.session_id(),&pending,).await;@@ -1020,8 +1004,9 @@ async fn complete_disable_command_async(}for (_, pending) in pending_subresource_responses {if let Ok(predecessor) = conn- .fail_pending_subresource_response_for_session_owner_async(- session_id,+ .fail_pending_subresource_response_for_route_async(+ owner.session_id(),+ owner.session_owner_route(),pending.internal_id,"Fetch interception disabled".to_owned(),)@@ -1034,7 +1019,7 @@ async fn complete_disable_command_async(activity::flush_post_subresource_response_activity_background_events_async(conn,&mut events,- session_id,+ owner.session_id(),&pending,).await;diff --git a/moli-protocol/src/domains/fetch/auth.rs b/moli-protocol/src/domains/fetch/auth.rsindex 39661e494..f60a5148c 100644--- a/moli-protocol/src/domains/fetch/auth.rs+++ b/moli-protocol/src/domains/fetch/auth.rs@@ -1,5 +1,5 @@use crate::conn::{- BackgroundProtocolEvent, CdpConnection, Cmd, PendingFetchAuthNavigation,+ BackgroundProtocolEvent, CdpConnection, Cmd, CommandOwnerScope, PendingFetchAuthNavigation,PendingFetchNavigation, PendingSubresourceFetchAuthRequest, PendingSubresourceFetchRequest,};use crate::devtools_runtime::{@@ -106,21 +106,18 @@ fn devtools_auth_action_from_cdp(pub(super) fn start_devtools_continue_with_auth_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: &DevToolsContinueWithAuthCommand,) -> FetchCommandTaskStep {- if let Some(step) = start_devtools_continue_with_auth_command_for_pending(- conn,- command_id,- command_session_id,- command,- ) {+ if let Some(step) =+ start_devtools_continue_with_auth_command_for_pending(conn, command_id, owner, command)+ {return step;}FetchCommandTaskStep::Complete(pending_request_action_output_plan_with_id_validation(conn,- command_session_id,+ owner,command.request_id.as_str(),command.context.protocol == DevToolsProtocol::Cdp,))@@ -129,9 +126,10 @@ pub(super) fn start_devtools_continue_with_auth_command(pub(super) fn start_devtools_continue_with_auth_command_for_pending(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: &DevToolsContinueWithAuthCommand,) -> Option<FetchCommandTaskStep> {+ let command_session_id = owner.session_id();let request_id = command.request_id.as_str().to_owned();let action_session_id = action_session_id_for_devtools_context(command_session_id,@@ -140,7 +138,7 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending();if let Some(pending) = take_pending_subresource_auth_request_for_action_session(conn,- command_session_id,+ owner,action_session_id,&request_id,) {@@ -156,59 +154,61 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending(}match command.action {DevToolsAuthChallengeAction::Default | DevToolsAuthChallengeAction::Cancel => {- let cancel_correlation = if matches!(- command.action,- DevToolsAuthChallengeAction::Cancel- ) && pending.intercept_response- {- let continued = continued_subresource_request(&pending);- match PreparedSubresourceCorrelation::prepare(- conn,- command_session_id,- &request_id,- &continued,- true,- ) {- Some(correlation) => Some(correlation),- None => {- conn.register_pending_subresource_fetch_auth_request_for_session_owner(- command_session_id,- request_id,- pending,- );- return Some(FetchCommandTaskStep::Complete(CommandOutputPlan::error(- -32000,- "RequestNotFound",- )));- }- }- } else {- None- };- let pending_page =- match conn.loaded_page_mut_for_protocol_access(command_session_id) {- Ok(page) => (match command.action {- DevToolsAuthChallengeAction::Default => page- .start_fail_pending_subresource_auth(- pending.internal_id,- "Fetch auth challenge aborted".to_owned(),- ),- DevToolsAuthChallengeAction::Cancel => {- page.start_cancel_pending_subresource_auth(pending.internal_id)+ let cancel_correlation =+ if matches!(command.action, DevToolsAuthChallengeAction::Cancel)+ && pending.intercept_response+ {+ let continued = continued_subresource_request(&pending);+ match PreparedSubresourceCorrelation::prepare(+ conn,+ owner,+ &request_id,+ &continued,+ true,+ ) {+ Some(correlation) => Some(correlation),+ None => {+ conn.register_pending_subresource_fetch_auth_request_for_route(+ command_session_id,+ owner.session_owner_route(),+ request_id,+ pending,+ );+ return Some(FetchCommandTaskStep::Complete(+ CommandOutputPlan::error(-32000, "RequestNotFound"),+ ));}- DevToolsAuthChallengeAction::ProvideCredentials => unreachable!(),- })- .map_err(|error| error.to_string()),- Err(message) => Err(message.to_owned()),+ }+ } else {+ None};+ let pending_page = match conn.loaded_page_mut_for_protocol_access_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {+ Ok(page) => (match command.action {+ DevToolsAuthChallengeAction::Default => page+ .start_fail_pending_subresource_auth(+ pending.internal_id,+ "Fetch auth challenge aborted".to_owned(),+ ),+ DevToolsAuthChallengeAction::Cancel => {+ page.start_cancel_pending_subresource_auth(pending.internal_id)+ }+ DevToolsAuthChallengeAction::ProvideCredentials => unreachable!(),+ })+ .map_err(|error| error.to_string()),+ Err(message) => Err(message.to_owned()),+ };let pending_page = match pending_page {Ok(pending_page) => pending_page,Err(error) => {if let Some(correlation) = cancel_correlation {- correlation.rollback(conn, command_session_id);+ correlation.rollback(conn);}- conn.register_pending_subresource_fetch_auth_request_for_session_owner(+ conn.register_pending_subresource_fetch_auth_request_for_route(command_session_id,+ owner.session_owner_route(),request_id,pending,);@@ -233,10 +233,9 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending(DevToolsAuthChallengeAction::ProvideCredentials => unreachable!(),};return Some(FetchCommandTaskStep::Pending(- PendingFetchCommandDispatch::new(- conn,+ PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueWithAuth {state: Box::new(state),},@@ -250,8 +249,9 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending(command.username.as_deref().unwrap_or_default(),command.password.as_deref().unwrap_or_default(),) else {- conn.register_pending_subresource_fetch_auth_request_for_session_owner(+ conn.register_pending_subresource_fetch_auth_request_for_route(command_session_id,+ owner.session_owner_route(),request_id.clone(),pending,);@@ -263,15 +263,16 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending(let continued = continued_subresource_request(&pending);let correlation = match PreparedSubresourceCorrelation::prepare(conn,- command_session_id,+ owner,&request_id,&continued,true,) {Some(correlation) => correlation,None => {- conn.register_pending_subresource_fetch_auth_request_for_session_owner(+ conn.register_pending_subresource_fetch_auth_request_for_route(command_session_id,+ owner.session_owner_route(),request_id,pending,);@@ -281,19 +282,22 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending()));}};- let pending_page =- match conn.loaded_page_mut_for_protocol_access(command_session_id) {- Ok(page) => page- .start_continue_pending_subresource_auth(pending.internal_id, auth)- .map_err(|error| format!("subresource auth continue failed: {error}")),- Err(message) => Err(message.to_owned()),- };+ let pending_page = match conn.loaded_page_mut_for_protocol_access_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {+ Ok(page) => page+ .start_continue_pending_subresource_auth(pending.internal_id, auth)+ .map_err(|error| format!("subresource auth continue failed: {error}")),+ Err(message) => Err(message.to_owned()),+ };let pending_page = match pending_page {Ok(pending_page) => pending_page,Err(message) => {- correlation.rollback(conn, command_session_id);- conn.register_pending_subresource_fetch_auth_request_for_session_owner(+ correlation.rollback(conn);+ conn.register_pending_subresource_fetch_auth_request_for_route(command_session_id,+ owner.session_owner_route(),request_id,pending,);@@ -303,10 +307,9 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending(}};return Some(FetchCommandTaskStep::Pending(- PendingFetchCommandDispatch::new(- conn,+ PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueWithAuth {state: Box::new(PendingContinueWithAuthState::SubresourceAuthContinue {@@ -322,7 +325,7 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending(}let pending = take_pending_auth_navigation_for_action_session(conn,- command_session_id,+ owner,action_session_id,&request_id,)?;@@ -339,10 +342,9 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending()}DevToolsAuthChallengeAction::Default => {- FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueWithAuth {state: Box::new(PendingContinueWithAuthState::NavigationFail {pending: Box::new(pending),@@ -352,10 +354,9 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending())}DevToolsAuthChallengeAction::Cancel => {- FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueWithAuth {state: Box::new(PendingContinueWithAuthState::NavigationCancel {pending: Box::new(pending),@@ -370,8 +371,9 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending(command.username.as_deref().unwrap_or_default(),command.password.as_deref().unwrap_or_default(),) else {- conn.register_pending_fetch_auth_navigation_for_session_owner(+ conn.register_pending_fetch_auth_navigation_for_route(command_session_id,+ owner.session_owner_route(),request_id.clone(),pending,);@@ -380,10 +382,9 @@ pub(super) fn start_devtools_continue_with_auth_command_for_pending("NotImplemented",)));};- FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueWithAuth {state: Box::new(PendingContinueWithAuthState::NavigationContinue {pending: Box::new(pending),@@ -521,7 +522,7 @@ fn next_chained_subresource_auth_required_event(pub(super) async fn complete_continue_with_auth_command_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,state: PendingContinueWithAuthState,out: &mut FetchCommandOutput,@@ -533,7 +534,7 @@ pub(super) async fn complete_continue_with_auth_command_async(} => {complete_subresource_auth_terminal_async(conn,- session_id,+ owner,completed,*pending,true,@@ -544,13 +545,13 @@ pub(super) async fn complete_continue_with_auth_command_async(}PendingContinueWithAuthState::SubresourceAuthFail { pending } => {complete_subresource_auth_terminal_async(- conn, session_id, completed, *pending, false, None, out,+ conn, owner, completed, *pending, false, None, out,).await;}PendingContinueWithAuthState::SubresourceAuthContinue { correlation } => {- if let Err(error) = finish_continue_subresource_auth(conn, session_id, completed) {- correlation.rollback(conn, session_id);+ if let Err(error) = finish_continue_subresource_auth(conn, owner, completed) {+ correlation.rollback(conn);out.push_error(-32000, error);return;}@@ -608,17 +609,21 @@ pub(super) async fn complete_continue_with_auth_command_async(async fn complete_subresource_auth_terminal_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,pending: crate::conn::PendingSubresourceFetchAuthRequest,expose_challenged_response: bool,correlation: Option<PreparedSubresourceCorrelation>,out: &mut FetchCommandOutput,) {- let activity_session_id = pending.owner_session_id.as_deref().or(session_id);+ let activity_session_id = pending.owner_session_id.as_deref().or(owner.session_id());+ let activity_owner_route = activity_session_id+ .is_none()+ .then(|| owner.session_owner_route())+ .flatten();let Some(completed) = completed else {if let Some(correlation) = correlation {- correlation.rollback(conn, activity_session_id);+ correlation.rollback(conn);}out.push_error(-32000, "Missing renderer completion");return;@@ -627,13 +632,15 @@ async fn complete_subresource_auth_terminal_async(Ok(completion) => completion,Err(error) => {if let Some(correlation) = correlation {- correlation.rollback(conn, activity_session_id);+ correlation.rollback(conn);}out.push_error(-32000, error);return;}};- let result = match conn.loaded_page_mut_for_protocol_access(activity_session_id) {+ let result = match conn+ .loaded_page_mut_for_protocol_access_for_route(activity_session_id, activity_owner_route)+ {Ok(page) if expose_challenged_response => page.finish_cancel_pending_subresource_auth(completion).map(|_| ()),@@ -642,7 +649,7 @@ async fn complete_subresource_auth_terminal_async(.map(|_| ()),Err(message) => {if let Some(correlation) = correlation {- correlation.rollback(conn, activity_session_id);+ correlation.rollback(conn);}out.push_error(-32000, message);return;@@ -650,7 +657,7 @@ async fn complete_subresource_auth_terminal_async(};if let Err(error) = result {if let Some(correlation) = correlation {- correlation.rollback(conn, activity_session_id);+ correlation.rollback(conn);}out.push_error(-32000,@@ -672,11 +679,14 @@ async fn complete_subresource_auth_terminal_async(fn finish_continue_subresource_auth(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,) -> Result<(), String> {let completion = completed.ok_or_else(|| "Missing renderer completion".to_owned())??;- let page = conn.loaded_page_mut_for_protocol_access(session_id)?;+ let page = conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?;page.finish_continue_pending_subresource_auth(completion).map(|_| ()).map_err(|error| format!("subresource auth continue failed: {error}"))diff --git a/moli-protocol/src/domains/fetch/body_stream.rs b/moli-protocol/src/domains/fetch/body_stream.rsindex 81cd09c4f..5de5adfb4 100644--- a/moli-protocol/src/domains/fetch/body_stream.rs+++ b/moli-protocol/src/domains/fetch/body_stream.rs@@ -1,4 +1,4 @@-use crate::conn::{CdpConnection, Cmd};+use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};use crate::domains::command_output::CommandOutputPlan;use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};use serde_json::json;@@ -20,6 +20,7 @@ pub(super) fn start_get_response_body_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> FetchCommandTaskStep {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);let params: RequestIdParam = match cmd.get_params() {Ok(Some(params)) => params,_ => {@@ -29,16 +30,14 @@ pub(super) fn start_get_response_body_command());}};- if let Some(transfer) = conn- .take_pending_fetch_response_transfer_for_body_read_for_session_owner(- cmd.session_id,- ¶ms.request_id,- )- {- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ if let Some(transfer) = conn.take_pending_fetch_response_transfer_for_body_read_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ¶ms.request_id,+ ) {+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(cmd.id,- cmd.session_id,+ owner,PendingFetchCommandKind::GetResponseBody,PendingFetchCommandOperation::MaterializeResponseBody {request_id: params.request_id,@@ -49,18 +48,21 @@ pub(super) fn start_get_response_body_command(}FetchCommandTaskStep::Complete(get_response_body_without_transfer_command_output_plan(conn,- cmd.session_id,+ &owner,¶ms.request_id,))}fn get_response_body_without_transfer_command_output_plan(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: &str,) -> CommandOutputPlan {if let Some(pending) = pending_subresource_response_request_for_action_session(- conn, session_id, session_id, request_id,+ conn,+ owner,+ owner.session_id(),+ request_id,) {if pending.response_body_taken_as_stream {return CommandOutputPlan::error(@@ -78,7 +80,7 @@ fn get_response_body_without_transfer_command_output_plan(};return response_body_command_output_plan(bytes);}- pending_request_action_output_plan(conn, session_id, request_id)+ pending_request_action_output_plan(conn, owner, request_id)}fn encode_response_body(bytes: Vec<u8>) -> (String, bool) {@@ -98,7 +100,7 @@ fn response_body_command_output_plan(bytes: Vec<u8>) -> CommandOutputPlan {pub(super) fn complete_get_response_body_from_transfer(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: CompletedFetchCommandOperation,out: &mut super::FetchCommandOutput,) {@@ -112,22 +114,29 @@ pub(super) fn complete_get_response_body_from_transfer(};let plan = match *result {Ok((Some(bytes), transfer)) => {- conn.register_pending_fetch_response_transfer_for_session_owner(- session_id, request_id, transfer,+ conn.register_pending_fetch_response_transfer_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ request_id,+ transfer,);response_body_command_output_plan(bytes)}Ok((None, transfer)) => {- conn.register_pending_fetch_response_transfer_for_session_owner(- session_id,+ conn.register_pending_fetch_response_transfer_for_route(+ owner.session_id(),+ owner.session_owner_route(),request_id.clone(),transfer,);- get_response_body_without_transfer_command_output_plan(conn, session_id, &request_id)+ get_response_body_without_transfer_command_output_plan(conn, owner, &request_id)}Err((message, transfer)) => {- conn.register_pending_fetch_response_transfer_for_session_owner(- session_id, request_id, transfer,+ conn.register_pending_fetch_response_transfer_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ request_id,+ transfer,);CommandOutputPlan::error(-32000, message)}@@ -139,6 +148,7 @@ pub(super) fn take_response_body_as_stream_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> CommandOutputPlan {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);let params: RequestIdParam = match cmd.get_params() {Ok(Some(params)) => params,_ => {@@ -156,7 +166,7 @@ pub(super) fn take_response_body_as_stream_command(}if let Some(pending) = pending_subresource_response_request_for_action_session(conn,- cmd.session_id,+ &owner,cmd.session_id,¶ms.request_id,) {@@ -172,7 +182,7 @@ pub(super) fn take_response_body_as_stream_command(Ok(handle) => {mark_pending_subresource_response_body_taken_as_stream_for_action_session(conn,- cmd.session_id,+ &owner,cmd.session_id,¶ms.request_id,);@@ -183,7 +193,7 @@ pub(super) fn take_response_body_as_stream_command(}}}- pending_request_action_output_plan(conn, cmd.session_id, ¶ms.request_id)+ pending_request_action_output_plan(conn, &owner, ¶ms.request_id)}fn open_pending_response_navigation_body_stream(diff --git a/moli-protocol/src/domains/fetch/commands.rs b/moli-protocol/src/domains/fetch/commands.rsindex c1a3440e9..154224623 100644--- a/moli-protocol/src/domains/fetch/commands.rs+++ b/moli-protocol/src/domains/fetch/commands.rs@@ -1,6 +1,6 @@use crate::conn::{- BackgroundNavigationBodyCompletionSink, CapturedBody, CdpConnection, Cmd, DEFAULT_LOADER_ID,- PendingStreamingDocumentResponseNavigation, monotonic_timestamp_seconds,+ BackgroundNavigationBodyCompletionSink, CapturedBody, CdpConnection, Cmd, CommandOwnerScope,+ DEFAULT_LOADER_ID, PendingStreamingDocumentResponseNavigation, monotonic_timestamp_seconds,};use crate::devtools_runtime::{DevToolsAuthChallengeAction, DevToolsCommand, DevToolsContinueInterceptedRequestCommand,@@ -55,47 +55,34 @@ pub(super) fn start_devtools_fetch_command(command_id: Option<u64>,command_session_id: Option<&str>,command: DevToolsCommand,+) -> FetchCommandTaskStep {+ let owner = CommandOwnerScope::capture(conn, command_session_id);+ start_devtools_fetch_command_for_owner(conn, command_id, &owner, command)+}++pub(super) fn start_devtools_fetch_command_for_owner(+ conn: &mut CdpConnection,+ command_id: Option<u64>,+ owner: &CommandOwnerScope,+ command: DevToolsCommand,) -> FetchCommandTaskStep {match command {DevToolsCommand::ContinueInterceptedRequest(command) => {- start_devtools_continue_intercepted_request_command(- conn,- command_id,- command_session_id,- &command,- )+ start_devtools_continue_intercepted_request_command(conn, command_id, owner, &command)}DevToolsCommand::ContinueInterceptedResponse(command) => {- start_devtools_continue_intercepted_response_command(- conn,- command_id,- command_session_id,- &command,- )+ start_devtools_continue_intercepted_response_command(conn, command_id, owner, &command)}DevToolsCommand::ContinueWithAuth(command) => {super::auth::start_devtools_continue_with_auth_command(- conn,- command_id,- command_session_id,- &command,+ conn, command_id, owner, &command,)}DevToolsCommand::FailInterceptedRequest(command) => {- start_devtools_fail_intercepted_request_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_fail_intercepted_request_command(conn, command_id, owner, command)}DevToolsCommand::FulfillInterceptedRequest(command) => {- start_devtools_fulfill_intercepted_request_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_fulfill_intercepted_request_command(conn, command_id, owner, command)}_ => FetchCommandTaskStep::Complete(CommandOutputPlan::error(-32000,@@ -212,9 +199,10 @@ fn parsed_continue_request_url(fn start_devtools_continue_intercepted_request_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: &DevToolsContinueInterceptedRequestCommand,) -> FetchCommandTaskStep {+ let command_session_id = owner.session_id();let parsed_url = match parsed_continue_request_url(command) {Ok(parsed_url) => parsed_url,Err(()) => {@@ -232,7 +220,7 @@ fn start_devtools_continue_intercepted_request_command();if let Some(pending) = take_pending_subresource_fetch_request_for_action_session(conn,- command_session_id,+ owner,action_session_id,&request_id,) {@@ -272,7 +260,10 @@ fn start_devtools_continue_intercepted_request_command(let headers = command.headers.clone().or(chain_headers);pending.request_stage_chain = None;let configured_response_stage = conn- .target_fetch_subresource_interception_snapshot_for_session_owner(command_session_id)+ .target_fetch_subresource_interception_snapshot_for_route(+ command_session_id,+ owner.session_owner_route(),+ ).is_some_and(|snapshot| {snapshot.has_response_stage_candidate(pending.resource_type.into())});@@ -286,21 +277,23 @@ fn start_devtools_continue_intercepted_request_command(}return FetchCommandTaskStep::Complete(CommandOutputPlan::success());}- let handle_auth_requests =- conn.target_fetch_handle_auth_requests_for_session_owner(command_session_id);+ let handle_auth_requests = conn.target_fetch_handle_auth_requests_for_route(+ command_session_id,+ owner.session_owner_route(),+ );let should_register =pending.resource_type != SubresourceResourceType::WebSocket || intercept_response;let correlation = match if configured_response_stage && !command.intercept_response {PreparedSubresourceCorrelation::prepare_deferred_response_stage(conn,- command_session_id,+ owner,&request_id,&pending,)} else {PreparedSubresourceCorrelation::prepare(conn,- command_session_id,+ owner,&request_id,&pending,should_register,@@ -308,8 +301,9 @@ fn start_devtools_continue_intercepted_request_command(} {Some(correlation) => correlation,None => {- conn.register_pending_subresource_fetch_request_for_session_owner(+ conn.register_pending_subresource_fetch_request_for_route(command_session_id,+ owner.session_owner_route(),request_id,pending,);@@ -319,7 +313,10 @@ fn start_devtools_continue_intercepted_request_command());}};- let pending_page = match conn.loaded_page_mut_for_protocol_access(command_session_id) {+ let pending_page = match conn.loaded_page_mut_for_protocol_access_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {Ok(page) => page.start_continue_pending_subresource_fetch(pending.internal_id,@@ -336,27 +333,26 @@ fn start_devtools_continue_intercepted_request_command(let pending_page = match pending_page {Ok(pending_page) => pending_page,Err(message) => {- correlation.rollback(conn, command_session_id);- conn.register_pending_subresource_fetch_request_for_session_owner(+ correlation.rollback(conn);+ conn.register_pending_subresource_fetch_request_for_route(command_session_id,+ owner.session_owner_route(),request_id,pending,);return FetchCommandTaskStep::Complete(CommandOutputPlan::error(-32000, message));}};- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueRequest {state: Box::new(PendingContinueRequestState::SubresourceFetch { correlation }),},PendingFetchCommandOperation::Page(pending_page),));}- if let Some(mut pending) =- take_pending_navigation(conn, command_session_id, action_session_id, &request_id)+ if let Some(mut pending) = take_pending_navigation(conn, owner, action_session_id, &request_id){if command.intercept_response {pending.intercept_response = true;@@ -384,10 +380,9 @@ fn start_devtools_continue_intercepted_request_command(pending.navigation.request_load_policy,None,);- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueRequest {state: Box::new(PendingContinueRequestState::Navigation {pending: Box::new(pending),@@ -398,7 +393,7 @@ fn start_devtools_continue_intercepted_request_command(}pending_request_action_output_plan(conn,- command_session_id,+ owner,&request_id,command.context.protocol == DevToolsProtocol::Cdp,)@@ -409,15 +404,15 @@ fn start_devtools_continue_intercepted_request_command(pub(super) async fn complete_continue_request_command_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,state: PendingContinueRequestState,out: &mut FetchCommandOutput,) {match state {PendingContinueRequestState::SubresourceFetch { correlation } => {- if let Err(error) = finish_continue_subresource_request(conn, session_id, completed) {- correlation.rollback(conn, session_id);+ if let Err(error) = finish_continue_subresource_request(conn, owner, completed) {+ correlation.rollback(conn);out.push_error(-32000, error);return;}@@ -435,11 +430,14 @@ pub(super) async fn complete_continue_request_command_async(fn finish_continue_subresource_request(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,) -> Result<(), String> {let completion = completed.ok_or_else(|| "Missing renderer completion".to_owned())??;- let page = conn.loaded_page_mut_for_protocol_access(session_id)?;+ let page = conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?;page.finish_continue_pending_subresource_fetch(completion).map(|_| ()).map_err(|error| format!("subresource fetch continue failed: {error}"))@@ -504,9 +502,10 @@ fn build_cdp_fail_intercepted_request_command(fn start_devtools_fail_intercepted_request_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsFailInterceptedRequestCommand,) -> FetchCommandTaskStep {+ let command_session_id = owner.session_id();let validate_request_id = command.context.protocol == DevToolsProtocol::Cdp;let request_id = command.request_id.into_string();let error_text = command.error_text;@@ -516,13 +515,10 @@ fn start_devtools_fail_intercepted_request_command(command.context.session_id.as_ref(),);- if let Some(pending) =- take_pending_navigation(conn, command_session_id, action_session_id, &request_id)- {- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ if let Some(pending) = take_pending_navigation(conn, owner, action_session_id, &request_id) {+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::FailRequest {state: Box::new(PendingFailRequestState::Navigation {pending: Box::new(pending),@@ -535,7 +531,7 @@ fn start_devtools_fail_intercepted_request_command(if let Some(pending) = take_pending_subresource_fetch_request_for_action_session(conn,- command_session_id,+ owner,action_session_id,&request_id,) {@@ -550,7 +546,10 @@ fn start_devtools_fail_intercepted_request_command(let mut plan = CommandOutputPlan::success();let mut events = Vec::new();let loader_id = conn- .current_document_loader_id_for_session_owner(command_session_id)+ .current_document_loader_id_for_route(+ command_session_id,+ owner.session_owner_route(),+ ).unwrap_or_else(|| DEFAULT_LOADER_ID.to_owned());network::emit_loading_failed(&mut events,@@ -565,7 +564,10 @@ fn start_devtools_fail_intercepted_request_command(plan.extend_background_events(events);return FetchCommandTaskStep::Complete(plan);}- let page = match conn.loaded_page_mut_for_protocol_access(command_session_id) {+ let page = match conn.loaded_page_mut_for_protocol_access_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {Ok(page) => page,Err(message) if message == "NoDocumentLoaded" => {return FetchCommandTaskStep::Complete(CommandOutputPlan::error(@@ -588,10 +590,9 @@ fn start_devtools_fail_intercepted_request_command());}};- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::FailRequest {state: Box::new(PendingFailRequestState::SubresourceFetch {pending: Box::new(pending),@@ -603,11 +604,14 @@ fn start_devtools_fail_intercepted_request_command(if let Some(pending) = take_pending_subresource_response_request_for_action_session(conn,- command_session_id,+ owner,action_session_id,&request_id,) {- let page = match conn.loaded_page_mut_for_protocol_access(command_session_id) {+ let page = match conn.loaded_page_mut_for_protocol_access_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {Ok(page) => page,Err(message) if message == "NoDocumentLoaded" => {return FetchCommandTaskStep::Complete(CommandOutputPlan::error(@@ -630,10 +634,9 @@ fn start_devtools_fail_intercepted_request_command());}};- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::FailRequest {state: Box::new(PendingFailRequestState::SubresourceResponse {pending: Box::new(pending),@@ -643,16 +646,14 @@ fn start_devtools_fail_intercepted_request_command());}- if let Some(transfer) = conn- .take_pending_fetch_response_transfer_for_terminal_action_for_session_owner(- command_session_id,- &request_id,- )- {- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ if let Some(transfer) = conn.take_pending_fetch_response_transfer_for_terminal_action_for_route(+ command_session_id,+ owner.session_owner_route(),+ &request_id,+ ) {+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::FailRequest {state: Box::new(PendingFailRequestState::ResponseTransfer {transfer: Box::new(transfer),@@ -663,7 +664,7 @@ fn start_devtools_fail_intercepted_request_command());}- pending_request_action_output_plan(conn, command_session_id, &request_id, validate_request_id)+ pending_request_action_output_plan(conn, owner, &request_id, validate_request_id).map_or_else(FetchCommandTaskStep::Complete, |()| {FetchCommandTaskStep::Complete(CommandOutputPlan::success())})@@ -671,7 +672,7 @@ fn start_devtools_fail_intercepted_request_command(pub(super) async fn complete_fail_request_command_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,state: PendingFailRequestState,out: &mut FetchCommandOutput,@@ -711,7 +712,10 @@ pub(super) async fn complete_fail_request_command_async(return;}};- match conn.loaded_page_mut_for_protocol_access(session_id) {+ match conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) {Ok(page) => {if let Err(error) = page.finish_fail_pending_subresource_fetch(completion) {out.push_error(-32000, format!("subresource fetch fail failed: {error}"));@@ -732,7 +736,7 @@ pub(super) async fn complete_fail_request_command_async(activity::flush_post_subresource_fetch_request_activity_background_events_async(conn,&mut events,- session_id,+ owner.session_id(),&pending,).await;@@ -750,7 +754,10 @@ pub(super) async fn complete_fail_request_command_async(return;}};- match conn.loaded_page_mut_for_protocol_access(session_id) {+ match conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) {Ok(page) => {if let Err(error) = page.finish_fail_pending_subresource_response(completion) {out.push_error(@@ -774,7 +781,7 @@ pub(super) async fn complete_fail_request_command_async(activity::flush_post_subresource_response_activity_background_events_async(conn,&mut events,- session_id,+ owner.session_id(),&pending,).await;@@ -910,9 +917,10 @@ fn build_cdp_fulfill_intercepted_request_command(fn start_devtools_fulfill_intercepted_request_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsFulfillInterceptedRequestCommand,) -> FetchCommandTaskStep {+ let command_session_id = owner.session_id();let validate_request_id = command.context.protocol == DevToolsProtocol::Cdp;let request_id = command.request_id.into_string();let response_code = command.response_code;@@ -927,7 +935,7 @@ fn start_devtools_fulfill_intercepted_request_command();if let Some(pending) = take_pending_subresource_fetch_request_for_action_session(conn,- command_session_id,+ owner,action_session_id,&request_id,) {@@ -948,7 +956,10 @@ fn start_devtools_fulfill_intercepted_request_command(let websocket_socket_id = pending.websocket_socket_id;let register_synthetic_websocket =pending.resource_type == SubresourceResourceType::WebSocket && response_code == 101;- let page = match conn.loaded_page_mut_for_protocol_access(command_session_id) {+ let page = match conn.loaded_page_mut_for_protocol_access_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {Ok(page) => page,Err(message) if message == "NoDocumentLoaded" => {return FetchCommandTaskStep::Complete(CommandOutputPlan::error(@@ -974,10 +985,9 @@ fn start_devtools_fulfill_intercepted_request_command());}};- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::FulfillRequest {state: Box::new(PendingFulfillRequestState::SubresourceFetch {pending: Box::new(pending),@@ -993,11 +1003,14 @@ fn start_devtools_fulfill_intercepted_request_command(if let Some(pending) = take_pending_subresource_response_request_for_action_session(conn,- command_session_id,+ owner,action_session_id,&request_id,) {- let page = match conn.loaded_page_mut_for_protocol_access(command_session_id) {+ let page = match conn.loaded_page_mut_for_protocol_access_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {Ok(page) => page,Err(message) if message == "NoDocumentLoaded" => {return FetchCommandTaskStep::Complete(CommandOutputPlan::error(@@ -1023,10 +1036,9 @@ fn start_devtools_fulfill_intercepted_request_command());}};- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::FulfillRequest {state: Box::new(PendingFulfillRequestState::SubresourceResponse {pending: Box::new(pending),@@ -1036,13 +1048,10 @@ fn start_devtools_fulfill_intercepted_request_command());}- if let Some(pending) =- take_pending_navigation(conn, command_session_id, action_session_id, &request_id)- {- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ if let Some(pending) = take_pending_navigation(conn, owner, action_session_id, &request_id) {+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::FulfillRequest {state: Box::new(PendingFulfillRequestState::Navigation {pending: Box::new(pending),@@ -1055,16 +1064,14 @@ fn start_devtools_fulfill_intercepted_request_command());}- if let Some(transfer) = conn- .take_pending_fetch_response_transfer_for_terminal_action_for_session_owner(- command_session_id,- &request_id,- )- {- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ if let Some(transfer) = conn.take_pending_fetch_response_transfer_for_terminal_action_for_route(+ command_session_id,+ owner.session_owner_route(),+ &request_id,+ ) {+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::FulfillRequest {state: Box::new(PendingFulfillRequestState::ResponseTransfer {transfer: Box::new(transfer),@@ -1077,7 +1084,7 @@ fn start_devtools_fulfill_intercepted_request_command());}- pending_request_action_output_plan(conn, command_session_id, &request_id, validate_request_id)+ pending_request_action_output_plan(conn, owner, &request_id, validate_request_id).map_or_else(FetchCommandTaskStep::Complete, |()| {FetchCommandTaskStep::Complete(CommandOutputPlan::success())})@@ -1085,7 +1092,7 @@ fn start_devtools_fulfill_intercepted_request_command(pub(super) async fn complete_fulfill_request_command_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,state: PendingFulfillRequestState,out: &mut FetchCommandOutput,@@ -1109,7 +1116,10 @@ pub(super) async fn complete_fulfill_request_command_async(return;}};- match conn.loaded_page_mut_for_protocol_access(session_id) {+ match conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) {Ok(page) => {if let Err(error) = page.finish_fulfill_pending_subresource_fetch(completion) {out.push_error(@@ -1129,8 +1139,9 @@ pub(super) async fn complete_fulfill_request_command_async(}}if register_synthetic_websocket && let Some(socket_id) = websocket_socket_id {- conn.register_synthetic_websocket_request_for_session_owner(- session_id,+ conn.register_synthetic_websocket_request_for_route(+ owner.session_id(),+ owner.session_owner_route(),request_id,network_request_id,socket_id,@@ -1141,7 +1152,7 @@ pub(super) async fn complete_fulfill_request_command_async(activity::flush_post_subresource_fetch_request_activity_background_events_async(conn,&mut events,- session_id,+ owner.session_id(),&pending,).await;@@ -1159,7 +1170,10 @@ pub(super) async fn complete_fulfill_request_command_async(return;}};- match conn.loaded_page_mut_for_protocol_access(session_id) {+ match conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) {Ok(page) => {if let Err(error) = page.finish_fulfill_pending_subresource_response(completion){@@ -1184,7 +1198,7 @@ pub(super) async fn complete_fulfill_request_command_async(activity::flush_post_subresource_response_activity_background_events_async(conn,&mut events,- session_id,+ owner.session_id(),&pending,).await;@@ -1256,16 +1270,11 @@ pub(super) async fn complete_fulfill_request_command_async(fn pending_request_action_output_plan(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: &str,validate_request_id: bool,) -> Result<(), CommandOutputPlan> {- pending_request_action_result_with_id_validation(- conn,- session_id,- request_id,- validate_request_id,- )+ pending_request_action_result_with_id_validation(conn, owner, request_id, validate_request_id)}pub(super) fn start_dispatch_websocket_message_command(@@ -1399,7 +1408,7 @@ pub(super) fn start_close_websocket_command(pub(super) fn complete_websocket_page_command(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,operation: PendingWebSocketCommandOperation,out: &mut FetchCommandOutput,@@ -1415,7 +1424,10 @@ pub(super) fn complete_websocket_page_command(return;}};- let result = match conn.loaded_page_mut_for_protocol_access(session_id) {+ let result = match conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) {Ok(page) => match operation {PendingWebSocketCommandOperation::DispatchText => {page.finish_receive_synthetic_websocket_text(completion)@@ -1536,9 +1548,10 @@ pub(super) fn devtools_fetch_owner_identity_for_session(fn start_devtools_continue_intercepted_response_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: &DevToolsContinueInterceptedResponseCommand,) -> FetchCommandTaskStep {+ let command_session_id = owner.session_id();let request_id = command.request_id.as_str().to_owned();let response_code = command.response_code;let response_headers = command.response_headers.clone();@@ -1547,17 +1560,17 @@ fn start_devtools_continue_intercepted_response_command(command.context.protocol,command.context.session_id.as_ref(),);- if let Some(transfer) = conn- .take_pending_fetch_response_transfer_for_terminal_action_for_session_owner(- command_session_id,- &request_id,- )- {+ if let Some(transfer) = conn.take_pending_fetch_response_transfer_for_terminal_action_for_route(+ command_session_id,+ owner.session_owner_route(),+ &request_id,+ ) {let _ = &command.response_phrase;let transfer_response_headers = response_headers.clone().unwrap_or_default();- if let Some(sender) =- conn.background_navigation_completion_sender_for_session_owner(command_session_id)- {+ if let Some(sender) = conn.background_navigation_completion_sender_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {match transfer.into_pending_streaming_document_response_navigation() {Ok(pending) => {// Chromium ACKs Fetch.continueResponse when the response-stage@@ -1575,27 +1588,27 @@ fn start_devtools_continue_intercepted_response_command(return FetchCommandTaskStep::Complete(CommandOutputPlan::success());}Err(transfer) => {- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,- command_id,- command_session_id,- PendingFetchCommandKind::ContinueResponse {- state: Box::new(PendingContinueResponseState::ResponseTransfer {- request_id,- transfer,- response_code,- response_headers: transfer_response_headers,- }),- },- PendingFetchCommandOperation::Ready,- ));+ return FetchCommandTaskStep::Pending(+ PendingFetchCommandDispatch::new_for_owner(+ command_id,+ owner.clone(),+ PendingFetchCommandKind::ContinueResponse {+ state: Box::new(PendingContinueResponseState::ResponseTransfer {+ request_id,+ transfer,+ response_code,+ response_headers: transfer_response_headers,+ }),+ },+ PendingFetchCommandOperation::Ready,+ ),+ );}}}- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueResponse {state: Box::new(PendingContinueResponseState::ResponseTransfer {request_id,@@ -1609,13 +1622,14 @@ fn start_devtools_continue_intercepted_response_command(}if let Some(pending) = take_pending_subresource_response_request_for_action_session(conn,- command_session_id,+ owner,action_session_id,&request_id,) {if pending.response_body_taken_as_stream {- conn.register_pending_subresource_fetch_response_request_for_session_owner(+ conn.register_pending_subresource_fetch_response_request_for_route(command_session_id,+ owner.session_owner_route(),request_id,pending,);@@ -1667,8 +1681,9 @@ fn start_devtools_continue_intercepted_response_command(|| response_headers.is_some()|| command.response_phrase.is_some(){- conn.register_pending_subresource_fetch_response_request_for_session_owner(+ conn.register_pending_subresource_fetch_response_request_for_route(command_session_id,+ owner.session_owner_route(),request_id,pending,);@@ -1690,7 +1705,10 @@ fn start_devtools_continue_intercepted_response_command(response_headers};let pending_internal_id = pending.internal_id;- let page = match conn.loaded_page_mut_for_protocol_access(command_session_id) {+ let page = match conn.loaded_page_mut_for_protocol_access_for_route(+ command_session_id,+ owner.session_owner_route(),+ ) {Ok(page) => page,Err(message) if message == "NoDocumentLoaded" => {return FetchCommandTaskStep::Complete(CommandOutputPlan::error(@@ -1715,10 +1733,9 @@ fn start_devtools_continue_intercepted_response_command());}};- return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new(- conn,+ return FetchCommandTaskStep::Pending(PendingFetchCommandDispatch::new_for_owner(command_id,- command_session_id,+ owner.clone(),PendingFetchCommandKind::ContinueResponse {state: Box::new(PendingContinueResponseState::SubresourceResponse {pending: Box::new(pending),@@ -1730,14 +1747,14 @@ fn start_devtools_continue_intercepted_response_command(if let Some(step) = super::auth::start_devtools_continue_with_auth_command_for_pending(conn,command_id,- command_session_id,+ owner,&continue_response_auth_command(command),) {return step;}pending_request_action_output_plan(conn,- command_session_id,+ owner,&request_id,command.context.protocol == DevToolsProtocol::Cdp,)@@ -1770,7 +1787,7 @@ fn continue_response_auth_command(async fn continue_response_transfer_inline(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,out: &mut FetchCommandOutput,request_id: String,transfer: crate::conn::PausedDocumentTransfer,@@ -1795,8 +1812,11 @@ async fn continue_response_transfer_inline(.await;}Err(transfer) => {- conn.register_pending_fetch_response_transfer_for_session_owner(- session_id, request_id, transfer,+ conn.register_pending_fetch_response_transfer_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ request_id,+ transfer,);out.push_error(-32000, "ResponseBodyStreamActive");}@@ -1805,7 +1825,7 @@ async fn continue_response_transfer_inline(pub(super) async fn complete_continue_response_command_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,completed: Option<Result<CompletedPageCommand, String>>,state: PendingContinueResponseState,out: &mut FetchCommandOutput,@@ -1819,7 +1839,7 @@ pub(super) async fn complete_continue_response_command_async(} => {continue_response_transfer_inline(conn,- session_id,+ owner,out,request_id,*transfer,@@ -1841,7 +1861,10 @@ pub(super) async fn complete_continue_response_command_async(return;}};- match conn.loaded_page_mut_for_protocol_access(session_id) {+ match conn.loaded_page_mut_for_protocol_access_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) {Ok(page) => {if let Err(error) =page.finish_continue_pending_subresource_response(completion)@@ -1867,7 +1890,7 @@ pub(super) async fn complete_continue_response_command_async(activity::flush_post_subresource_response_activity_background_events_async(conn,&mut events,- session_id,+ owner.session_id(),&pending,).await;@@ -2341,8 +2364,9 @@ mod protocol_neutral_tests {);assert!(- conn.take_pending_subresource_fetch_response_request_for_action_session_owner(+ conn.take_pending_subresource_fetch_response_request_for_route(Some("SID-primary"),+ None,Some("SID-primary"),"FETCH-response-aux",)@@ -2350,8 +2374,9 @@ mod protocol_neutral_tests {"old owner action session must not be able to resolve the chained response");let chained = conn- .take_pending_subresource_fetch_response_request_for_action_session_owner(+ .take_pending_subresource_fetch_response_request_for_route(Some("SID-aux"),+ None,Some("SID-aux"),"FETCH-response-aux",)@@ -2455,8 +2480,9 @@ mod protocol_neutral_tests {"BiDi-only session id has no CDP route and must not own the stored pending request");let chained = conn- .take_pending_subresource_fetch_request_for_action_session_owner(+ .take_pending_subresource_fetch_request_for_route(Some("SID-primary"),+ None,Some("BIDI-SID"),"FETCH-bidi",)diff --git a/moli-protocol/src/domains/fetch/navigation.rs b/moli-protocol/src/domains/fetch/navigation.rsindex 3df74e47b..f1fc6e47f 100644--- a/moli-protocol/src/domains/fetch/navigation.rs+++ b/moli-protocol/src/domains/fetch/navigation.rs@@ -1,6 +1,6 @@use crate::conn::{- CdpConnection, DocumentBodySource, DocumentNavigationToken, FetchAuthChallenge,- NavigationDispatchState, NavigationLoadOutcome, PendingFetchNavigation,+ CdpConnection, CommandOwnerScope, DocumentBodySource, DocumentNavigationToken,+ FetchAuthChallenge, NavigationDispatchState, NavigationLoadOutcome, PendingFetchNavigation,PendingSubresourceFetchAuthStage, PendingSubresourceFetchAuthStageChain,PendingSubresourceFetchOwnerKind, PendingSubresourceFetchRequest, decode_data_url_response,};@@ -37,8 +37,9 @@ fn prepare_navigation_response_stage(return true;}let Some(response_stage) = conn- .target_fetch_subresource_interception_snapshot_for_session_owner(+ .target_fetch_subresource_interception_snapshot_for_route(pending.navigation.owner.session_id(),+ pending.navigation.owner.session_owner_route(),).and_then(|snapshot| {snapshot@@ -64,10 +65,12 @@ pub(crate) async fn load_or_pause_navigation_for_auth_into_buffer_async(auth: Option<SubresourceAuthCredentials>,prior_network_observation_journal: Option<NetworkObservationJournal>,) {+ let navigate_owner = pending.navigation.owner.clone();let navigate_session_id = pending.navigation.owner.session_id().map(str::to_owned);network::record_main_document_request_body(conn, &pending.navigation);- let should_handle_auth = conn.target_fetch_matches_auth_required_for_session_owner(+ let should_handle_auth = conn.target_fetch_matches_auth_required_for_route(navigate_session_id.as_deref(),+ navigate_owner.session_owner_route(),&pending.navigation.requested_url,) && pending.navigation.requested_url.scheme() != "data";@@ -79,8 +82,9 @@ pub(crate) async fn load_or_pause_navigation_for_auth_into_buffer_async(let has_auth_credentials = auth.is_some();if pending.intercept_response && navigation_response_stage_auth_can_stream(auth.as_ref()) {match conn- .fetch_navigation_streaming_raw_response_for_session_owner_async(+ .fetch_navigation_streaming_raw_response_for_route_async(navigate_session_id.as_deref(),+ navigate_owner.session_owner_route(),pending.navigation.request_load_policy,&method,&raw_url,@@ -136,8 +140,9 @@ pub(crate) async fn load_or_pause_navigation_for_auth_into_buffer_async(// before libcurl has completed the credential retry, so keep// credential replay on the buffered path until the fetch runtime// can mark intermediate auth responses separately.- conn.fetch_navigation_auth_raw_response_for_session_owner_async(+ conn.fetch_navigation_auth_raw_response_for_route_async(navigate_session_id.as_deref(),+ navigate_owner.session_owner_route(),pending.navigation.request_load_policy,&method,&raw_url,@@ -148,8 +153,9 @@ pub(crate) async fn load_or_pause_navigation_for_auth_into_buffer_async(.await} else {match conn- .fetch_navigation_streaming_raw_response_for_session_owner_async(+ .fetch_navigation_streaming_raw_response_for_route_async(navigate_session_id.as_deref(),+ navigate_owner.session_owner_route(),pending.navigation.request_load_policy,&method,&raw_url,@@ -219,8 +225,9 @@ pub(crate) async fn load_or_pause_navigation_for_auth_into_buffer_async(if pending.intercept_response && pending.navigation.requested_url.scheme() != "data" {match conn- .fetch_navigation_streaming_raw_response_for_session_owner_async(+ .fetch_navigation_streaming_raw_response_for_route_async(navigate_session_id.as_deref(),+ navigate_owner.session_owner_route(),pending.navigation.request_load_policy,&pending.navigation.request_method,pending.navigation.requested_url.as_str(),@@ -740,7 +747,7 @@ pub(crate) async fn continue_navigation_without_request_pause_into_buffer_async(pub(crate) async fn continue_subresource_without_fetch_pause_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: Option<String>,page_owner: crate::conn::TargetPageResidenceIdentity,internal_id: u64,@@ -752,6 +759,8 @@ pub(crate) async fn continue_subresource_without_fetch_pause_async(handle_auth_requests: bool,owner_kind: PendingSubresourceFetchOwnerKind,) {+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();let pending = PendingSubresourceFetchRequest {residence: crate::conn::PendingSubresourceFetchResidence::InstalledPage(page_owner),owner_session_id: None,@@ -767,8 +776,9 @@ pub(crate) async fn continue_subresource_without_fetch_pause_async(request_stage_chain: None,};if conn- .continue_pending_subresource_fetch_for_session_owner_async(+ .continue_pending_subresource_fetch_for_route_async(session_id,+ owner_route,internal_id,None,None,@@ -780,8 +790,11 @@ pub(crate) async fn continue_subresource_without_fetch_pause_async(.await.is_ok(){- conn.register_in_flight_subresource_fetch_request_for_session_owner(- session_id, request_id, pending,+ conn.register_in_flight_subresource_fetch_request_for_route(+ session_id,+ owner_route,+ request_id,+ pending,);}}@@ -862,8 +875,9 @@ fn register_navigation_auth_required_event(let auth_sessions = conn.target_fetch_subresource_interception_snapshot_for_target(&pending.navigation.frame_id).or_else(|| {- conn.target_fetch_subresource_interception_snapshot_for_session_owner(+ conn.target_fetch_subresource_interception_snapshot_for_route(pending.navigation.owner.session_id(),+ pending.navigation.owner.session_owner_route(),)}).map(|snapshot| {@@ -888,8 +902,9 @@ fn register_navigation_auth_required_event();let mut remaining_sessions = Vec::new();for session in auth_sessions.into_iter().skip(1) {- let Ok(next_request_id) = conn.allocate_fetch_navigation_request_id_for_session_owner(+ let Ok(next_request_id) = conn.allocate_fetch_navigation_request_id_for_route(pending.navigation.owner.session_id(),+ pending.navigation.owner.session_owner_route(),) else {break;};@@ -915,8 +930,13 @@ fn register_navigation_auth_required_event(.owner_session_id.as_deref().or(pending.navigation.owner.session_id());- conn.register_pending_fetch_auth_navigation_for_session_owner(+ let pending_owner_route = pending_owner_session_id+ .is_none()+ .then(|| pending.navigation.owner.session_owner_route())+ .flatten();+ conn.register_pending_fetch_auth_navigation_for_route(pending_owner_session_id,+ pending_owner_route,pending.fetch_request_id.clone(),pending_auth.clone(),);@@ -929,15 +949,21 @@ fn register_navigation_auth_required_event(pub(crate) async fn continue_subresource_for_response_stage_async(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,session_id: Option<&str>,request_id: String,pending: PendingSubresourceFetchRequest,handle_auth_requests: bool,response_stage_blocked_intercepts: Vec<DevToolsNetworkInterceptId>,) {+ let owner_route = session_id+ .is_none()+ .then(|| owner.session_owner_route())+ .flatten();if conn- .continue_pending_subresource_fetch_for_session_owner_async(+ .continue_pending_subresource_fetch_for_route_async(session_id,+ owner_route,pending.internal_id,None,None,@@ -949,8 +975,9 @@ pub(crate) async fn continue_subresource_for_response_stage_async(.await.is_ok(){- conn.register_in_flight_response_stage_subresource_fetch_request_for_session_owner(+ conn.register_in_flight_response_stage_subresource_fetch_request_for_route(session_id,+ owner_route,Some(request_id),pending,response_stage_blocked_intercepts,@@ -960,14 +987,20 @@ pub(crate) async fn continue_subresource_for_response_stage_async(pub(crate) async fn continue_subresource_for_deferred_response_stage_async(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,session_id: Option<&str>,request_id: String,pending: PendingSubresourceFetchRequest,handle_auth_requests: bool,) {+ let owner_route = session_id+ .is_none()+ .then(|| owner.session_owner_route())+ .flatten();if conn- .continue_pending_subresource_fetch_for_session_owner_async(+ .continue_pending_subresource_fetch_for_route_async(session_id,+ owner_route,pending.internal_id,None,None,@@ -979,8 +1012,9 @@ pub(crate) async fn continue_subresource_for_deferred_response_stage_async(.await.is_ok(){- conn.register_in_flight_deferred_response_stage_subresource_fetch_request_for_session_owner(+ conn.register_in_flight_deferred_response_stage_subresource_fetch_request_for_route(session_id,+ owner_route,Some(request_id),pending,);diff --git a/moli-protocol/src/domains/fetch/state.rs b/moli-protocol/src/domains/fetch/state.rsindex d30e99b29..14ed512c9 100644--- a/moli-protocol/src/domains/fetch/state.rs+++ b/moli-protocol/src/domains/fetch/state.rs@@ -1,5 +1,5 @@use crate::conn::{- CdpConnection, PendingFetchAuthNavigation, PendingFetchNavigation,+ CdpConnection, CommandOwnerScope, PendingFetchAuthNavigation, PendingFetchNavigation,PendingSubresourceFetchAuthRequest, PendingSubresourceFetchRequest,PendingSubresourceFetchResponseRequest,};@@ -11,23 +11,25 @@ use super::patterns::validate_request_id;/// Correlation state installed before renderer work can produce an observable/// subresource completion. The command keeps this token only so a failed/// renderer dispatch can remove the prepared entry again.-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone)]pub(super) struct PreparedSubresourceCorrelation {internal_id: u64,registered: bool,+ owner_scope: CommandOwnerScope,}impl PreparedSubresourceCorrelation {pub(super) fn prepare(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: &str,pending: &PendingSubresourceFetchRequest,should_register: bool,) -> Option<Self> {if should_register- && !conn.register_in_flight_subresource_fetch_request_for_session_owner(- session_id,+ && !conn.register_in_flight_subresource_fetch_request_for_route(+ owner.session_id(),+ owner.session_owner_route(),Some(request_id.to_owned()),pending.clone(),)@@ -37,13 +39,15 @@ impl PreparedSubresourceCorrelation {Some(Self {internal_id: pending.internal_id,registered: should_register,+ owner_scope: owner.clone(),})}- pub(super) fn rollback(self, conn: &mut CdpConnection, session_id: Option<&str>) {+ pub(super) fn rollback(self, conn: &mut CdpConnection) {if self.registered {- conn.take_in_flight_subresource_fetch_request_for_session_owner(- session_id,+ conn.take_in_flight_subresource_fetch_request_for_route(+ self.owner_scope.session_id(),+ self.owner_scope.session_owner_route(),self.internal_id,);}@@ -51,22 +55,22 @@ impl PreparedSubresourceCorrelation {pub(super) fn prepare_deferred_response_stage(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: &str,pending: &PendingSubresourceFetchRequest,) -> Option<Self> {- if !conn- .register_in_flight_deferred_response_stage_subresource_fetch_request_for_session_owner(- session_id,- Some(request_id.to_owned()),- pending.clone(),- )- {+ if !conn.register_in_flight_deferred_response_stage_subresource_fetch_request_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ Some(request_id.to_owned()),+ pending.clone(),+ ) {return None;}Some(Self {internal_id: pending.internal_id,registered: true,+ owner_scope: owner.clone(),})}}@@ -85,43 +89,45 @@ pub(crate) fn action_session_id_for_devtools_context<'a>(pub(crate) fn pending_request_action_output_plan(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: &str,) -> CommandOutputPlan {- pending_request_action_result(conn, session_id, request_id)+ pending_request_action_result(conn, owner, request_id).map_or_else(|plan| plan, |()| CommandOutputPlan::success())}pub(crate) fn pending_request_action_result(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: &str,) -> Result<(), CommandOutputPlan> {- pending_request_action_result_with_id_validation(conn, session_id, request_id, true)+ pending_request_action_result_with_id_validation(conn, owner, request_id, true)}pub(crate) fn pending_request_action_output_plan_with_id_validation(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: &str,validate_id: bool,) -> CommandOutputPlan {- pending_request_action_result_with_id_validation(conn, session_id, request_id, validate_id)+ pending_request_action_result_with_id_validation(conn, owner, request_id, validate_id).map_or_else(|plan| plan, |()| CommandOutputPlan::success())}pub(crate) fn pending_request_action_result_with_id_validation(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,request_id: &str,validate_id: bool,) -> Result<(), CommandOutputPlan> {if validate_id && validate_request_id(request_id).is_err() {return Err(CommandOutputPlan::error(-32602, "InvalidParams"));}- let Some(result) =- conn.consume_pending_request_action_for_session_owner(session_id, request_id)- else {+ let Some(result) = conn.consume_pending_request_action_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ request_id,+ ) else {return Err(CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"));};if result.is_err() {@@ -132,12 +138,13 @@ pub(crate) fn pending_request_action_result_with_id_validation(pub(crate) fn take_pending_navigation(conn: &mut CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingFetchNavigation> {- conn.take_pending_fetch_navigation_for_session_owner(- owner_session_id,+ conn.take_pending_fetch_navigation_for_route(+ owner.session_id(),+ owner.session_owner_route(),action_session_id,request_id,)@@ -145,12 +152,13 @@ pub(crate) fn take_pending_navigation(pub(crate) fn take_pending_auth_navigation_for_action_session(conn: &mut CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingFetchAuthNavigation> {- conn.take_pending_fetch_auth_navigation_for_action_session_owner(- owner_session_id,+ conn.take_pending_fetch_auth_navigation_for_route(+ owner.session_id(),+ owner.session_owner_route(),action_session_id,request_id,)@@ -158,12 +166,13 @@ pub(crate) fn take_pending_auth_navigation_for_action_session(pub(crate) fn take_pending_subresource_fetch_request_for_action_session(conn: &mut CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingSubresourceFetchRequest> {- conn.take_pending_subresource_fetch_request_for_action_session_owner(- owner_session_id,+ conn.take_pending_subresource_fetch_request_for_route(+ owner.session_id(),+ owner.session_owner_route(),action_session_id,request_id,)@@ -171,12 +180,13 @@ pub(crate) fn take_pending_subresource_fetch_request_for_action_session(pub(crate) fn take_pending_subresource_auth_request_for_action_session(conn: &mut CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingSubresourceFetchAuthRequest> {- conn.take_pending_subresource_fetch_auth_request_for_action_session_owner(- owner_session_id,+ conn.take_pending_subresource_fetch_auth_request_for_route(+ owner.session_id(),+ owner.session_owner_route(),action_session_id,request_id,)@@ -184,12 +194,13 @@ pub(crate) fn take_pending_subresource_auth_request_for_action_session(pub(crate) fn take_pending_subresource_response_request_for_action_session(conn: &mut CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingSubresourceFetchResponseRequest> {- conn.take_pending_subresource_fetch_response_request_for_action_session_owner(- owner_session_id,+ conn.take_pending_subresource_fetch_response_request_for_route(+ owner.session_id(),+ owner.session_owner_route(),action_session_id,request_id,)@@ -197,12 +208,13 @@ pub(crate) fn take_pending_subresource_response_request_for_action_session(pub(crate) fn pending_subresource_response_request_for_action_session(conn: &mut CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,action_session_id: Option<&str>,request_id: &str,) -> Option<PendingSubresourceFetchResponseRequest> {- conn.pending_subresource_fetch_response_request_for_action_session_owner(- owner_session_id,+ conn.pending_subresource_fetch_response_request_for_route(+ owner.session_id(),+ owner.session_owner_route(),action_session_id,request_id,)@@ -210,12 +222,13 @@ pub(crate) fn pending_subresource_response_request_for_action_session(pub(crate) fn mark_pending_subresource_response_body_taken_as_stream_for_action_session(conn: &mut CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,action_session_id: Option<&str>,request_id: &str,) -> bool {- conn.mark_pending_subresource_fetch_response_body_taken_as_stream_for_action_session_owner(- owner_session_id,+ conn.mark_pending_subresource_fetch_response_body_taken_as_stream_for_route(+ owner.session_id(),+ owner.session_owner_route(),action_session_id,request_id,)diff --git a/moli-protocol/src/domains/fetch/subresource.rs b/moli-protocol/src/domains/fetch/subresource.rsindex 1405e08e9..29195fc89 100644--- a/moli-protocol/src/domains/fetch/subresource.rs+++ b/moli-protocol/src/domains/fetch/subresource.rs@@ -3,8 +3,8 @@ use url::Url;use super::helpers::pending_subresource_response_stage_request_paused_event;use crate::conn::{- BackgroundProtocolEvent, CdpConnection, DEFAULT_LOADER_ID, FetchRequestStage,- PendingSubresourceFetchOwnerKind, PendingSubresourceFetchRequest,+ BackgroundProtocolEvent, CdpConnection, CommandOwnerScope, DEFAULT_LOADER_ID,+ FetchRequestStage, PendingSubresourceFetchOwnerKind, PendingSubresourceFetchRequest,PendingSubresourceFetchRequestStage, PendingSubresourceFetchRequestStageChain,PendingSubresourceFetchResponseRequest, build_event, monotonic_timestamp_seconds,};@@ -57,18 +57,21 @@ struct PendingSubresourceFetchPauseSource {pub(crate) async fn subresource_fetch_pause_prepared_outputs_for_renderer_record_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_document: moli_core::RendererDocumentLifecycleIdentity,info: moli_core::page::PendingSubresourceFetchInfo,) -> network::NetworkPreparedOutputs {- if conn.target_root_document_lifecycle_identity_for_session(session_id) != Some(source_document)+ if conn.target_root_document_lifecycle_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) != Some(source_document){return network::NetworkPreparedOutputs::default();}network::NetworkPreparedOutputs::from_subresource_fetch_pauses(prepare_subresource_fetch_pause_sources_async(conn,- session_id,+ owner,None,None,vec![PendingSubresourceFetchPauseSource {@@ -82,19 +85,22 @@ pub(crate) async fn subresource_fetch_pause_prepared_outputs_for_renderer_recordpub(crate) async fn detached_parser_script_fetch_pause_prepared_outputs_for_renderer_record_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_document: moli_core::RendererDocumentLifecycleIdentity,info: moli_core::page::PendingSubresourceFetchInfo,continuation: DetachedParserScriptFetchContinuation,) -> network::NetworkPreparedOutputs {- if conn.target_root_document_lifecycle_identity_for_session(session_id) != Some(source_document)+ if conn.target_root_document_lifecycle_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) != Some(source_document){return network::NetworkPreparedOutputs::default();}network::NetworkPreparedOutputs::from_subresource_fetch_pauses(prepare_subresource_fetch_pause_sources_async(conn,- session_id,+ owner,None,None,vec![PendingSubresourceFetchPauseSource {@@ -108,27 +114,29 @@ pub(crate) async fn detached_parser_script_fetch_pause_prepared_outputs_for_rendasync fn prepare_subresource_fetch_pause_sources_async(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,frame_id: Option<&str>,document_url: Option<&Url>,sources: Vec<PendingSubresourceFetchPauseSource>,) -> Vec<network::TargetSubresourceFetchPauseOutput> {let mut outputs = Vec::new();- let page_owner = conn.target_page_residence_identity_for_session(session_id);+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();+ let page_owner = conn.target_page_residence_identity_for_route(session_id, owner_route);let Some((fetch_snapshot, frame_id)) = (|| {let target_frame_id = conn- .target_session_owner_frame_tree_identity(session_id)+ .target_session_owner_frame_tree_identity_for_route(session_id, owner_route).map(|(target_id, _, _, _)| target_id)?;let frame_id = frame_id.unwrap_or(&target_frame_id);Some((- conn.target_fetch_subresource_interception_snapshot_for_session_owner(session_id)?,+ conn.target_fetch_subresource_interception_snapshot_for_route(session_id, owner_route)?,frame_id.to_owned(),))})() else {return outputs;};let loader_id = conn- .current_document_loader_id_for_session_owner(session_id)+ .current_document_loader_id_for_route(session_id, owner_route).unwrap_or_else(|| DEFAULT_LOADER_ID.to_owned());for source in sources {let PendingSubresourceFetchPauseSource {@@ -136,7 +144,7 @@ async fn prepare_subresource_fetch_pause_sources_async(detached_parser_script_fetch_continuation,} = source;let Ok((request_id, network_request_id)) =- conn.allocate_pending_subresource_fetch_request_ids_for_session_owner(session_id)+ conn.allocate_pending_subresource_fetch_request_ids_for_route(session_id, owner_route)else {return outputs;};@@ -202,6 +210,7 @@ async fn prepare_subresource_fetch_pause_sources_async(pending.action_session_id = fetch_owner_session_id.clone();continue_subresource_for_response_stage_async(conn,+ owner,response_stage_owner_session_id,request_id,pending,@@ -232,6 +241,7 @@ async fn prepare_subresource_fetch_pause_sources_async(pending.action_session_id = fetch_owner_session_id.clone();continue_subresource_for_deferred_response_stage_async(conn,+ owner,response_stage_owner_session_id,request_id,pending,@@ -246,7 +256,7 @@ async fn prepare_subresource_fetch_pause_sources_async(.unwrap_or(PendingSubresourceFetchOwnerKind::NetworkOrBidi);continue_subresource_without_fetch_pause_async(conn,- session_id,+ owner,handle_auth_requests.then_some(request_id),page_owner.clone(),info.internal_id,@@ -297,8 +307,8 @@ async fn prepare_subresource_fetch_pause_sources_async();let mut remaining_sessions = Vec::new();for session in request_stage_pause_sessions.into_iter().skip(1) {- let Ok((next_request_id, _)) =- conn.allocate_pending_subresource_fetch_request_ids_for_session_owner(session_id)+ let Ok((next_request_id, _)) = conn+ .allocate_pending_subresource_fetch_request_ids_for_route(session_id, owner_route)else {return outputs;};@@ -355,7 +365,7 @@ async fn prepare_subresource_fetch_pause_sources_async(pub(crate) fn emit_subresource_fetch_pause_outputs(conn: &mut CdpConnection,out: &mut Vec<BackgroundProtocolEvent>,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,network_session_ids: &[Option<String>],outputs: Vec<network::TargetSubresourceFetchPauseOutput>,) {@@ -374,7 +384,11 @@ pub(crate) fn emit_subresource_fetch_pause_outputs(let pending_owner_session_id = event_session_id.as_deref().filter(|session_id| conn.session_route(Some(session_id)).is_some())- .or(owner_session_id);+ .or(owner.session_id());+ let pending_owner_route = pending_owner_session_id+ .is_none()+ .then(|| owner.session_owner_route())+ .flatten();pending.action_session_id = event_session_id.clone();let blocked_intercepts = blocked_intercepts_from_fetch_payload(&payload);let fetch_event = subresource_request_paused_event(@@ -384,14 +398,17 @@ pub(crate) fn emit_subresource_fetch_pause_outputs(payload,blocked_intercepts,);- if !conn.register_pending_subresource_fetch_request_for_session_owner(+ if !conn.register_pending_subresource_fetch_request_for_route(pending_owner_session_id,+ pending_owner_route,request_id,pending,) {return;}- if let Ok(runtime_slot) = conn.runtime_session_owner_slot_mut(pending_owner_session_id) {+ if let Ok(runtime_slot) = conn+ .runtime_session_owner_slot_mut_for_route(pending_owner_session_id, pending_owner_route)+ {// Chromium publishes Network.requestWillBeSent before the Fetch pause.// The renderer's later transport start belongs to the same lifecycle// and must not publish a second initial Network event.@@ -587,7 +604,7 @@ mod tests {use url::Url;use crate::conn::{- BackgroundProtocolEvent, BrowserContext, CdpConnection, PageTargetHost,+ BackgroundProtocolEvent, BrowserContext, CdpConnection, CommandOwnerScope, PageTargetHost,PendingSubresourceFetchOwnerKind, PendingSubresourceFetchRequest,};use crate::devtools_runtime::{AutomationEvent, DevToolsNetworkResourceType};@@ -700,12 +717,13 @@ mod tests {let page_owner = conn.target_page_residence_identity_for_session(None).expect("active test target should expose a Page residence identity");+ let owner = CommandOwnerScope::capture(&conn, None);let mut events = Vec::new();super::emit_subresource_fetch_pause_outputs(&mut conn,&mut events,- None,+ &owner,&[Some("NETWORK-SID".to_owned())],vec![fetch_pause_output(@@ -720,7 +738,7 @@ mod tests {super::emit_subresource_fetch_pause_outputs(&mut conn,&mut events,- None,+ &owner,&[Some("NETWORK-SID".to_owned())],Vec::new(),);@@ -778,12 +796,13 @@ mod tests {let page_owner = conn.target_page_residence_identity_for_session(None).expect("active test target should expose a Page residence identity");+ let owner = CommandOwnerScope::capture(&conn, None);let mut events = Vec::new();super::emit_subresource_fetch_pause_outputs(&mut conn,&mut events,- None,+ &owner,&[Some("NETWORK-SID".to_owned())],vec![fetch_pause_output_with_cookie_report(page_owner,@@ -828,12 +847,13 @@ mod tests {.active_page_state_mut().runtime_slot.replace_page_attachment_id_for_test();+ let owner = CommandOwnerScope::capture(&conn, None);let mut events = Vec::new();super::emit_subresource_fetch_pause_outputs(&mut conn,&mut events,- None,+ &owner,&[Some("NETWORK-SID".to_owned())],vec![fetch_pause_output(page_owner,@@ -880,7 +900,7 @@ mod tests {super::emit_subresource_fetch_pause_outputs(&mut conn,&mut events,- Some("SID-background"),+ &CommandOwnerScope::for_session("SID-background"),&[Some("NETWORK-SID".to_owned())],vec![fetch_pause_output(page_owner,diff --git a/moli-protocol/src/domains/fetch/tests/basics.rs b/moli-protocol/src/domains/fetch/tests/basics.rsindex 07034dd6a..d67991c64 100644--- a/moli-protocol/src/domains/fetch/tests/basics.rs+++ b/moli-protocol/src/domains/fetch/tests/basics.rs@@ -452,7 +452,7 @@ async fn pending_fetch_enable_keeps_background_owner_route_across_completion() {let mut ctx = TestContext::new();let background = PageTargetHost::with_url("TID-fetch-background".to_owned(),- None,+ Some("SID-fetch-background".to_owned()),"about:blank".to_owned(),);@@ -467,20 +467,11 @@ async fn pending_fetch_enable_keeps_background_owner_route_across_completion() {).await;- let background_route = ctx- .conn- .target_session_route_for_target_id("TID-fetch-background")- .expect("background target route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route.clone()));ctx.install_navigation_fixture_for_session_owner("data:text/html,<title>background fetch</title>",- None,+ Some("SID-fetch-background"),).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);ctx.sent.clear();let raw = serde_json::to_string(&json!({"id": 1204,@@ -489,42 +480,33 @@ async fn pending_fetch_enable_keeps_background_owner_route_across_completion() {"patterns": [{ "urlPattern": "*", "resourceType": "XHR", "requestStage": "Request" }]- }+ },+ "sessionId": "SID-fetch-background"})).expect("Fetch.enable command should serialize");- let pending = {- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route));- let step = ctx.conn.start_command_dispatch(&raw);- ctx.conn- .replace_none_session_owner_route_override(previous_route);- match step {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(outcome) => {- panic!(- "background Fetch.enable should update the live background page: {:?}",- outcome.into_parts().0- )- }+ let pending = match ctx.conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(pending) => pending,+ CdpCommandTaskStep::Complete(outcome) => {+ panic!(+ "background Fetch.enable should update the live background page: {:?}",+ outcome.into_parts().0+ )}};- let active_route = ctx- .conn- .target_session_route_for_target_id("TID-fetch-active")- .expect("active target route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(active_route));let (messages, scheduler_events) = ctx.complete_command_task_step_for_test(CdpCommandTaskStep::Pending(pending)).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);assert!(scheduler_events.is_empty());- assert_eq!(messages, vec![json!({ "id": 1204, "result": {} })]);+ assert_eq!(+ messages,+ vec![json!({+ "id": 1204,+ "result": {},+ "sessionId": "SID-fetch-background"+ })]+ );let bc = ctx.conn.browser_context.as_ref().expect("browser context");assert_eq!(bc.active_target_id(), Some("TID-fetch-active"));@@ -1073,7 +1055,9 @@ async fn disable_clears_fetch_state() {document_navigation_token: None,navigation: crate::conn::NavigationDispatchState {navigate_id: Some(1),- owner: crate::conn::CommandOwnerScope::for_implicit_route(None),+ owner: crate::conn::CommandOwnerScope::for_route(+ crate::conn::CdpSessionRoute::Browser,+ ),result_projection: crate::conn::NavigationResultProjection::Cdp(json!({"frameId": "TID-1", "loaderId": "LID-0000000001"}),),@@ -1111,7 +1095,9 @@ async fn disable_clears_fetch_state() {document_navigation_token: None,navigation: crate::conn::NavigationDispatchState {navigate_id: Some(1),- owner: crate::conn::CommandOwnerScope::for_implicit_route(None),+ owner: crate::conn::CommandOwnerScope::for_route(+ crate::conn::CdpSessionRoute::Browser,+ ),result_projection: crate::conn::NavigationResultProjection::Cdp(json!({"frameId": "TID-1", "loaderId": "LID-0000000001"}),),diff --git a/moli-protocol/src/domains/fetch/tests/command_correlation.rs b/moli-protocol/src/domains/fetch/tests/command_correlation.rsindex 460579940..b9af71fce 100644--- a/moli-protocol/src/domains/fetch/tests/command_correlation.rs+++ b/moli-protocol/src/domains/fetch/tests/command_correlation.rs@@ -130,7 +130,7 @@ async fn assert_correlation_lifetime(assert!(matches!(&step, CdpCommandTaskStep::Pending(_)));assert_eq!(ctx.conn- .in_flight_subresource_fetch_request_id_for_session_owner(Some("SID-1"), internal_id,)+ .in_flight_subresource_fetch_request_id_for_route(Some("SID-1"), None, internal_id,).as_deref(),Some(request_id),"renderer-visible network work must have protocol correlation state"@@ -145,7 +145,7 @@ async fn assert_correlation_lifetime();assert_eq!(ctx.conn- .in_flight_subresource_fetch_request_id_for_session_owner(Some("SID-1"), internal_id,),+ .in_flight_subresource_fetch_request_id_for_route(Some("SID-1"), None, internal_id,),None,"failed renderer completion must roll back prepared correlation state");@@ -173,10 +173,11 @@ async fn deferred_fetch_command_keeps_its_exact_page_for_implicit_work() {).wait().await;- let mut scope = completed.owner_scope.enter(&mut ctx.conn);-assert_eq!(- scope.conn_mut().target_owner_identity_for_session(None),+ ctx.conn.target_owner_identity_for_route(+ completed.owner_scope.session_id(),+ completed.owner_scope.session_owner_route(),+ ),Some(("BID-1".to_owned(), Some("TID-background".to_owned()))),"protocol-neutral completion work must stay on the Page that issued the Fetch command");@@ -208,10 +209,11 @@ async fn deferred_sessionless_fetch_command_freezes_the_active_page_at_admission.as_mut().expect("browser context").set_active_target_id("TID-next");- let mut scope = completed.owner_scope.enter(&mut ctx.conn);-assert_eq!(- scope.conn_mut().target_owner_identity_for_session(None),+ ctx.conn.target_owner_identity_for_route(+ completed.owner_scope.session_id(),+ completed.owner_scope.session_owner_route(),+ ),Some(("BID-sessionless".to_owned(),Some("TID-original".to_owned())@@ -273,8 +275,9 @@ async fn pending_fetch_command_state_is_bound_to_page_attachment() {.replace_page_attachment_id_for_test();assert!(ctx.conn- .take_pending_subresource_fetch_request_for_action_session_owner(+ .take_pending_subresource_fetch_request_for_route(Some("SID-1"),+ None,Some("SID-1"),"INT-collision",)@@ -298,8 +301,9 @@ async fn pending_fetch_command_state_is_bound_to_page_attachment() {);assert_eq!(ctx.conn- .take_pending_subresource_fetch_request_for_action_session_owner(+ .take_pending_subresource_fetch_request_for_route(Some("SID-1"),+ None,Some("SID-1"),"INT-collision",)@@ -327,8 +331,9 @@ async fn completed_continue_atomically_claims_a_pause_still_pending_publication(assert!(ctx.conn- .claim_subresource_continue_request_for_session_owner(+ .claim_subresource_continue_request_for_route(Some("SID-1"),+ None,&page_owner,74,false,@@ -338,7 +343,7 @@ async fn completed_continue_atomically_claims_a_pause_still_pending_publication();let claimed = ctx.conn- .claim_subresource_continue_request_for_session_owner(Some("SID-1"), &page_owner, 74, true)+ .claim_subresource_continue_request_for_route(Some("SID-1"), None, &page_owner, 74, true).expect("terminal completion should claim the still-pending pause");let ClaimedSubresourceContinueRequest::PendingCompletion(pending) = claimed else {panic!("terminal completion must preserve the pending-publication race state");@@ -346,8 +351,9 @@ async fn completed_continue_atomically_claims_a_pause_still_pending_publication(assert_eq!(pending.network_request_id, "NETWORK-74");assert!(ctx.conn- .claim_subresource_continue_request_for_session_owner(+ .claim_subresource_continue_request_for_route(Some("SID-1"),+ None,&page_owner,74,true,@@ -367,16 +373,18 @@ async fn completed_continue_atomically_claims_a_pause_still_pending_publication(let replacement = pending_request(&replacement_owner, 75);assert!(ctx.conn- .register_in_flight_subresource_fetch_request_for_session_owner(+ .register_in_flight_subresource_fetch_request_for_route(Some("SID-1"),+ None,Some("INT-replacement".to_owned()),replacement,));assert!(ctx.conn- .claim_subresource_continue_request_for_session_owner(+ .claim_subresource_continue_request_for_route(Some("SID-1"),+ None,&page_owner,75,true,@@ -386,7 +394,7 @@ async fn completed_continue_atomically_claims_a_pause_still_pending_publication();assert_eq!(ctx.conn- .in_flight_subresource_fetch_request_id_for_session_owner(Some("SID-1"), 75)+ .in_flight_subresource_fetch_request_id_for_route(Some("SID-1"), None, 75).as_deref(),Some("INT-replacement"),"a rejected stale capture must leave the replacement request resident"@@ -402,8 +410,9 @@ async fn continuation_claim_preserves_state_owned_by_a_different_page_residence(.expect("initial Page residence should exist");assert!(ctx.conn- .register_in_flight_subresource_fetch_request_for_session_owner(+ .register_in_flight_subresource_fetch_request_for_route(Some("SID-1"),+ None,Some("INT-retired-in-flight".to_owned()),pending_request(&retired_owner, 76),)@@ -428,8 +437,9 @@ async fn continuation_claim_preserves_state_owned_by_a_different_page_residence(assert!(ctx.conn- .claim_subresource_continue_request_for_session_owner(+ .claim_subresource_continue_request_for_route(Some("SID-1"),+ None,&replacement_owner,76,false,@@ -439,8 +449,9 @@ async fn continuation_claim_preserves_state_owned_by_a_different_page_residence();assert!(ctx.conn- .claim_subresource_continue_request_for_session_owner(+ .claim_subresource_continue_request_for_route(Some("SID-1"),+ None,&replacement_owner,77,true,@@ -455,8 +466,9 @@ async fn continuation_claim_preserves_state_owned_by_a_different_page_residence(.install_page_attachment_id_for_test(retired_owner.page_attachment_id());let ClaimedSubresourceContinueRequest::InFlight(in_flight) = ctx.conn- .claim_subresource_continue_request_for_session_owner(+ .claim_subresource_continue_request_for_route(Some("SID-1"),+ None,&retired_owner,76,false,@@ -472,12 +484,7 @@ async fn continuation_claim_preserves_state_owned_by_a_different_page_residence(let ClaimedSubresourceContinueRequest::PendingCompletion(pending) = ctx.conn- .claim_subresource_continue_request_for_session_owner(- Some("SID-1"),- &retired_owner,- 77,- true,- )+ .claim_subresource_continue_request_for_route(Some("SID-1"), None, &retired_owner, 77, true).expect("owner mismatch must leave the pending request resident")else {panic!("the preserved request should remain pending");@@ -507,8 +514,9 @@ async fn pending_fetch_auth_state_is_bound_to_page_attachment() {.replace_page_attachment_id_for_test();assert!(ctx.conn- .take_pending_subresource_fetch_auth_request_for_action_session_owner(+ .take_pending_subresource_fetch_auth_request_for_route(Some("SID-1"),+ None,Some("SID-1"),"AUTH-collision",)@@ -532,8 +540,9 @@ async fn pending_fetch_auth_state_is_bound_to_page_attachment() {);assert_eq!(ctx.conn- .take_pending_subresource_fetch_auth_request_for_action_session_owner(+ .take_pending_subresource_fetch_auth_request_for_route(Some("SID-1"),+ None,Some("SID-1"),"AUTH-collision",)@@ -565,8 +574,9 @@ async fn pending_fetch_response_state_is_bound_to_page_attachment() {.replace_page_attachment_id_for_test();assert!(ctx.conn- .take_pending_subresource_fetch_response_request_for_action_session_owner(+ .take_pending_subresource_fetch_response_request_for_route(Some("SID-1"),+ None,Some("SID-1"),"RESPONSE-collision",)@@ -590,8 +600,9 @@ async fn pending_fetch_response_state_is_bound_to_page_attachment() {);assert_eq!(ctx.conn- .take_pending_subresource_fetch_response_request_for_action_session_owner(+ .take_pending_subresource_fetch_response_request_for_route(Some("SID-1"),+ None,Some("SID-1"),"RESPONSE-collision",)diff --git a/moli-protocol/src/domains/fetch/tests/navigation_auth.rs b/moli-protocol/src/domains/fetch/tests/navigation_auth.rsindex 4040c3a71..5519a7908 100644--- a/moli-protocol/src/domains/fetch/tests/navigation_auth.rs+++ b/moli-protocol/src/domains/fetch/tests/navigation_auth.rs@@ -927,7 +927,7 @@ async fn run_navigation_cdp_fetch_then_bidi_network_auth_required_terminal(let parsed_url = Url::parse(&url).unwrap();let auth_pause_sessions = ctx.conn- .target_fetch_subresource_interception_snapshot_for_session_owner(Some("SID-1"))+ .target_fetch_subresource_interception_snapshot_for_route(Some("SID-1"), None).expect("active target fetch snapshot").matching_auth_required_pause_sessions(Some("SID-1"), &parsed_url);assert_eq!(diff --git a/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs b/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rsindex 6dc21c01c..7c8f6f7de 100644--- a/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs+++ b/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs@@ -1825,7 +1825,7 @@ async fn run_cdp_fetch_then_bidi_network_auth_required_terminal_credentials_complet protected_parsed_url = Url::parse(&protected_url).unwrap();let auth_pause_sessions = ctx.conn- .target_fetch_subresource_interception_snapshot_for_session_owner(Some("SID-1"))+ .target_fetch_subresource_interception_snapshot_for_route(Some("SID-1"), None).expect("active target fetch snapshot").matching_auth_required_pause_sessions(Some("SID-1"), &protected_parsed_url);assert_eq!(diff --git a/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs b/moli-protocol/src/domains/fetch/tests/runtime_fetch.rsindex 7b3ef578b..94a45024f 100644--- a/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs+++ b/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs@@ -1139,7 +1139,7 @@ async fn response_body_stream_taken_blocks_chained_bidi_response_stage_pause() {let api_url = Url::parse(&hit_url).unwrap();let response_pause_sessions = ctx.conn- .target_fetch_subresource_interception_snapshot_for_session_owner(Some("SID-1"))+ .target_fetch_subresource_interception_snapshot_for_route(Some("SID-1"), None).expect("active target fetch snapshot").matching_response_stage_pause_sessions(Some("SID-1"),@@ -6992,7 +6992,7 @@ async fn cdp_fetch_then_bidi_network_intercept_response_stage_chain_completes()let api_url = Url::parse(&hit_url).unwrap();let response_pause_sessions = ctx.conn- .target_fetch_subresource_interception_snapshot_for_session_owner(Some("SID-1"))+ .target_fetch_subresource_interception_snapshot_for_route(Some("SID-1"), None).expect("active target fetch snapshot").matching_response_stage_pause_sessions(Some("SID-1"),@@ -7072,10 +7072,11 @@ async fn cdp_fetch_then_bidi_network_intercept_response_stage_chain_completes().as_str().expect("CDP response-stage request id").to_owned();+ let cdp_owner = crate::conn::CommandOwnerScope::for_session("SID-1");let pending_cdp_pause =crate::domains::fetch::state::pending_subresource_response_request_for_action_session(&mut ctx.conn,- Some("SID-1"),+ &cdp_owner,Some("SID-1"),&cdp_request_id,)diff --git a/moli-protocol/src/domains/input.rs b/moli-protocol/src/domains/input.rsindex 652c45fe4..5623ae471 100644--- a/moli-protocol/src/domains/input.rs+++ b/moli-protocol/src/domains/input.rs@@ -1,5 +1,5 @@use crate::conn::{- BackgroundProtocolEvent, CdpConnection, Cmd, CommandDispatchContext,+ BackgroundProtocolEvent, CdpConnection, Cmd, CommandDispatchContext, CommandOwnerScope,TargetPageResidenceIdentity, TargetPageResidenceObservation, TargetPageResidenceToken,};use crate::devtools_runtime::{@@ -165,10 +165,6 @@ async fn wait_for_renderer_input_or_page_replacement<T>(}impl PendingInputCommandDispatch {- pub(crate) fn session_id(&self) -> Option<&str> {- self.session_id.as_deref()- }-pub(crate) async fn wait(self) -> CompletedInputCommandDispatch {let completed = match self.pending {PendingInputOperation::Page(pending) => {@@ -346,8 +342,8 @@ fn set_ignore_input_events_command_output_plan(CommandOutputPlan::success()}-fn input_events_ignored_for_session_owner(conn: &CdpConnection, session_id: Option<&str>) -> bool {- conn.page_event_session_ids_for_session_owner(session_id)+fn input_events_ignored_for_owner(conn: &CdpConnection, owner: &CommandOwnerScope) -> bool {+ conn.page_event_session_ids_for_route(owner.session_id(), owner.session_owner_route()).into_iter().any(|event_session_id| {conn.target_page_session_state_for_session(event_session_id.as_deref())@@ -574,8 +570,10 @@ fn start_pending_input_command(cmd: &Cmd<'_>,action: InputAction,) -> Result<Option<PendingInputCommandDispatch>, PendingInputCommandStartError> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);if action.requires_document_access()- && let Err(message) = conn.ensure_document_accessible_for_session_owner(cmd.session_id)+ && let Err(message) = conn+ .ensure_document_accessible_for_route(owner.session_id(), owner.session_owner_route()){return Err(PendingInputCommandStartError {code: -32000,@@ -587,14 +585,14 @@ fn start_pending_input_command(InputAction::DispatchKeyEvent => {let parsed = key::parse_dispatch_key_event(cmd).map_err(|_| PendingInputCommandStartError::invalid_params())?;- if input_events_ignored_for_session_owner(conn, cmd.session_id) {+ if input_events_ignored_for_owner(conn, &owner) {return Ok(None);}let command = build_cdp_dispatch_key_event_command(conn, cmd, parsed);- start_devtools_input_command(+ start_devtools_input_command_for_owner(conn,cmd.id,- cmd.session_id,+ &owner,DevToolsCommand::DispatchKeyEvent(command),)}@@ -608,11 +606,11 @@ fn start_pending_input_command(coordinate_input_unsupported_message(action),));}- if input_events_ignored_for_session_owner(conn, cmd.session_id) {+ if input_events_ignored_for_owner(conn, &owner) {return Ok(None);}let command = build_cdp_coordinate_input_command(conn, cmd, action)?;- start_devtools_input_command(conn, cmd.id, cmd.session_id, command)+ start_devtools_input_command_for_owner(conn, cmd.id, &owner, command)}InputAction::InsertText => {let text = key::parse_insert_text(cmd)@@ -620,7 +618,7 @@ fn start_pending_input_command(start_page_input_command(conn,cmd.id,- cmd.session_id,+ &owner,PendingInputCommandKind::InsertText,|page| page.start_insert_text_into_active_control(&text),)@@ -903,21 +901,15 @@ pub(crate) async fn execute_devtools_input_command_async_with_protocol_events(Ok(route) => route,Err(error) => return (Err(error), Vec::new()),};- let mut route_scope = conn.scoped_none_session_owner_route_override(route);- return execute_devtools_input_command_on_current_route_with_protocol_events(- route_scope.conn_mut(),- None,- command,+ let owner = CommandOwnerScope::for_route(route);+ return execute_devtools_input_command_for_owner_with_protocol_events(+ conn, &owner, command,).await;}- execute_devtools_input_command_on_current_route_with_protocol_events(- conn,- command_session_id.as_deref(),- command,- )- .await+ let owner = CommandOwnerScope::capture(conn, command_session_id.as_deref());+ execute_devtools_input_command_for_owner_with_protocol_events(conn, &owner, command).await}fn devtools_input_command_route(@@ -948,15 +940,15 @@ fn devtools_input_command_route())}-async fn execute_devtools_input_command_on_current_route_with_protocol_events(+async fn execute_devtools_input_command_for_owner_with_protocol_events(conn: &mut CdpConnection,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsCommand,) -> (Result<DevToolsCommandResult, DevToolsError>,Vec<crate::conn::BackgroundProtocolEvent>,) {- let pending = match start_devtools_input_command(conn, None, command_session_id, command) {+ let pending = match start_devtools_input_command_for_owner(conn, None, owner, command) {Ok(Some(pending)) => pending,Ok(None) => return (Ok(DevToolsCommandResult::Empty), Vec::new()),Err(error) => {@@ -983,13 +975,13 @@ fn devtools_error_from_input_start_error(error: PendingInputCommandStartError) -fn start_devtools_dispatch_key_event_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsDispatchKeyEventCommand,) -> Result<Option<PendingInputCommandDispatch>, PendingInputCommandStartError> {start_page_input_command(conn,command_id,- command_session_id,+ owner,PendingInputCommandKind::DispatchKeyEvent,|page| {page.start_dispatch_key_event_with_outcome(@@ -1008,28 +1000,39 @@ fn start_devtools_dispatch_key_event_command(fn start_page_input_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ command_owner: &CommandOwnerScope,kind: PendingInputCommandKind,start: impl FnOnce(&Page) -> anyhow::Result<PendingPageCommand>,) -> Result<Option<PendingInputCommandDispatch>, PendingInputCommandStartError> {- let owner = conn- .target_page_residence_identity_for_session(command_session_id)+ let page_owner = conn+ .target_page_residence_identity_for_route(+ command_owner.session_id(),+ command_owner.session_owner_route(),+ ).ok_or_else(PendingInputCommandStartError::no_document_loaded)?;let page_residence_token = if kind.uses_renderer_host_ack_cleanup() {Some(- conn.capture_target_page_residence_token_for_session(command_session_id)- .ok_or_else(PendingInputCommandStartError::no_document_loaded)?,+ conn.capture_target_page_residence_token_for_route(+ command_owner.session_id(),+ command_owner.session_owner_route(),+ )+ .ok_or_else(PendingInputCommandStartError::no_document_loaded)?,)} else {None};- let page = loaded_page_mut(conn, command_session_id)+ let page = conn+ .loaded_page_mut_for_protocol_access_for_route(+ command_owner.session_id(),+ command_owner.session_owner_route(),+ )+ .ok().ok_or_else(PendingInputCommandStartError::no_document_loaded)?;let pending = start(page).map_err(PendingInputCommandStartError::renderer_error)?;Ok(Some(PendingInputCommandDispatch {command_id,- session_id: command_session_id.map(str::to_owned),- owner,+ session_id: command_owner.session_id().map(str::to_owned),+ owner: page_owner,page_residence_token,kind,pending: PendingInputOperation::Page(pending),@@ -1066,7 +1069,7 @@ fn drag_event_name(event_type: DevToolsDragEventType) -> &'static str {fn start_devtools_dispatch_mouse_event_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsDispatchMouseEventCommand,) -> Result<Option<PendingInputCommandDispatch>, PendingInputCommandStartError> {let event_name = mouse_event_name(command.event_type);@@ -1086,7 +1089,7 @@ fn start_devtools_dispatch_mouse_event_command(start_page_input_command(conn,command_id,- command_session_id,+ owner,PendingInputCommandKind::DispatchMouseEvent,|page| {page.start_dispatch_mouse_event_at_point_with_pointer_outcome(@@ -1108,7 +1111,7 @@ fn start_devtools_dispatch_mouse_event_command(fn start_devtools_dispatch_touch_event_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsDispatchTouchEventCommand,) -> Result<Option<PendingInputCommandDispatch>, PendingInputCommandStartError> {let event_name = touch_event_name(command.event_type);@@ -1124,7 +1127,7 @@ fn start_devtools_dispatch_touch_event_command(start_page_input_command(conn,command_id,- command_session_id,+ owner,PendingInputCommandKind::DispatchTouchEvent,|page| page.start_dispatch_touch_event_at_points_with_outcome(points, event_name, false),)@@ -1196,7 +1199,7 @@ fn renderer_drag_data(fn start_devtools_dispatch_drag_event_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsDispatchDragEventCommand,) -> Result<Option<PendingInputCommandDispatch>, PendingInputCommandStartError> {let event_name = drag_event_name(command.event_type);@@ -1204,7 +1207,7 @@ fn start_devtools_dispatch_drag_event_command(start_page_input_command(conn,command_id,- command_session_id,+ owner,PendingInputCommandKind::DispatchDragEvent,|page| {page.start_dispatch_drag_event_at_point_with_outcome(@@ -1221,13 +1224,13 @@ fn start_devtools_dispatch_drag_event_command(fn start_devtools_synthesize_tap_gesture_command(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsSynthesizeTapGestureCommand,) -> Result<Option<PendingInputCommandDispatch>, PendingInputCommandStartError> {start_page_input_command(conn,command_id,- command_session_id,+ owner,PendingInputCommandKind::SynthesizeTapGesture,|page| {page.start_dispatch_touch_event_at_point_with_outcome(@@ -1237,10 +1240,10 @@ fn start_devtools_synthesize_tap_gesture_command()}-fn start_devtools_input_command(+fn start_devtools_input_command_for_owner(conn: &mut CdpConnection,command_id: Option<u64>,- command_session_id: Option<&str>,+ owner: &CommandOwnerScope,command: DevToolsCommand,) -> Result<Option<PendingInputCommandDispatch>, PendingInputCommandStartError> {let coordinate_unsupported = match &command {@@ -1256,43 +1259,25 @@ fn start_devtools_input_command(if conn.layout_policy() == moli_core::LayoutPolicy::Mock {return Err(PendingInputCommandStartError::unsupported(message));}- if input_events_ignored_for_session_owner(conn, command_session_id) {+ if input_events_ignored_for_owner(conn, owner) {return Ok(None);}}match command {DevToolsCommand::DispatchMouseEvent(command) => {- start_devtools_dispatch_mouse_event_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_dispatch_mouse_event_command(conn, command_id, owner, command)}DevToolsCommand::DispatchTouchEvent(command) => {- start_devtools_dispatch_touch_event_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_dispatch_touch_event_command(conn, command_id, owner, command)+ }+ DevToolsCommand::DispatchDragEvent(command) => {+ start_devtools_dispatch_drag_event_command(conn, command_id, owner, command)}- DevToolsCommand::DispatchDragEvent(command) => start_devtools_dispatch_drag_event_command(- conn,- command_id,- command_session_id,- command,- ),DevToolsCommand::SynthesizeTapGesture(command) => {- start_devtools_synthesize_tap_gesture_command(- conn,- command_id,- command_session_id,- command,- )+ start_devtools_synthesize_tap_gesture_command(conn, command_id, owner, command)}DevToolsCommand::DispatchKeyEvent(command) => {- start_devtools_dispatch_key_event_command(conn, command_id, command_session_id, command)+ start_devtools_dispatch_key_event_command(conn, command_id, owner, command)}_ => Err(PendingInputCommandStartError {code: -32000,@@ -1508,13 +1493,6 @@ fn completed_page_command_result(}}-pub(super) fn loaded_page_mut<'a>(- conn: &'a mut CdpConnection,- session_id: Option<&str>,-) -> Option<&'a mut Page> {- conn.loaded_page_mut_for_protocol_access(session_id).ok()-}-#[derive(Debug, Default, Eq, PartialEq)]pub(crate) struct InputPreparedOutputs {download_activations: Vec<RendererPendingDownloadActivation>,@@ -1538,14 +1516,17 @@ impl InputPreparedOutputs {pub(crate) fn from_renderer_file_chooser_activation(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,activation: RendererPendingFileChooserActivation,) -> Self {- let Some(page_owner) = conn.target_page_residence_identity_for_session(session_id) else {+ let Some(page_owner) = conn.target_page_residence_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {return Self::default();};let Some(activation) = file_chooser::PreparedFileChooserActivation::capture(- conn, session_id, page_owner, activation,+ conn, owner, page_owner, activation,) else {return Self::default();};@@ -1642,6 +1623,9 @@ async fn handle_input_dispatch_outcome_async(outcome: RendererInputDispatchOutcome,command_context: &mut CommandDispatchContext,) -> Result<(), String> {+ let action_owner = session_id+ .map(CommandOwnerScope::for_session)+ .unwrap_or_else(|| CommandOwnerScope::for_page_residence(owner));if let Some(download) = outcome.pending_download {let mut events = Vec::new();conn.handle_pending_download_activation_background_events_async(@@ -1656,7 +1640,7 @@ async fn handle_input_dispatch_outcome_async(if let Some(file_chooser) = outcome.pending_file_chooser&& let Some(file_chooser) = file_chooser::PreparedFileChooserActivation::capture(conn,- session_id,+ &action_owner,owner.clone(),file_chooser,)@@ -1741,7 +1725,7 @@ mod protocol_neutral_tests {};use serde_json::Value;- use crate::conn::{CdpConnection, Cmd};+ use crate::conn::{CdpConnection, Cmd, CommandOwnerScope};use crate::testing::real_layout_test_connection;fn assert_coordinate_routes_to_document_owner(@@ -1758,6 +1742,17 @@ mod protocol_neutral_tests {assert_eq!(error.message, "NoDocumentLoaded");}+ fn start_input_command(+ conn: &mut CdpConnection,+ command_id: Option<u64>,+ session_id: Option<&str>,+ command: DevToolsCommand,+ ) -> Result<Option<super::PendingInputCommandDispatch>, super::PendingInputCommandStartError>+ {+ let owner = CommandOwnerScope::capture(conn, session_id);+ super::start_devtools_input_command_for_owner(conn, command_id, &owner, command)+ }+fn cdp_context(session_id: &str) -> DevToolsCommandContext {DevToolsCommandContext {protocol: DevToolsProtocol::Cdp,@@ -1821,7 +1816,7 @@ mod protocol_neutral_tests {#[test]fn devtools_input_entry_routes_coordinate_mouse_command_to_document_owner() {let mut conn = real_layout_test_connection();- let result = super::start_devtools_input_command(+ let result = start_input_command(&mut conn,Some(42),Some("SID-mouse"),@@ -1892,7 +1887,7 @@ mod protocol_neutral_tests {};let command = super::build_cdp_dispatch_key_event_command(&conn, &cmd, parsed);- let result = super::start_devtools_input_command(+ let result = start_input_command(&mut conn,cmd.id,cmd.session_id,@@ -1909,7 +1904,7 @@ mod protocol_neutral_tests {#[test]fn devtools_input_entry_routes_coordinate_touch_command_to_document_owner() {let mut conn = real_layout_test_connection();- let result = super::start_devtools_input_command(+ let result = start_input_command(&mut conn,Some(46),Some("SID-touch"),@@ -1922,7 +1917,7 @@ mod protocol_neutral_tests {#[test]fn devtools_input_entry_routes_coordinate_drag_command_to_document_owner() {let mut conn = real_layout_test_connection();- let result = super::start_devtools_input_command(+ let result = start_input_command(&mut conn,Some(48),Some("SID-drag"),@@ -1935,7 +1930,7 @@ mod protocol_neutral_tests {#[test]fn devtools_input_entry_routes_zero_mask_coordinate_drag_drop_to_document_owner() {let mut conn = real_layout_test_connection();- let result = super::start_devtools_input_command(+ let result = start_input_command(&mut conn,Some(49),Some("SID-drag"),@@ -1948,7 +1943,7 @@ mod protocol_neutral_tests {#[test]fn devtools_input_entry_routes_coordinate_tap_command_to_document_owner() {let mut conn = real_layout_test_connection();- let result = super::start_devtools_input_command(+ let result = start_input_command(&mut conn,Some(51),Some("SID-tap"),@@ -1975,7 +1970,7 @@ mod producer_tests {use crate::conn::{BackgroundProtocolEvent, BrowserContext, CdpConnection, CommandDispatchContext,- TargetPageResidenceIdentity, build_event,+ CommandOwnerScope, TargetPageResidenceIdentity, build_event,};use crate::devtools_runtime::{AutomationEvent, BrowserDownloadProgressEvent, BrowserDownloadWillBeginEvent,@@ -2019,8 +2014,8 @@ mod producer_tests {load: None,terminated: None,};- let (binding, initial_events) = conn.bind_renderer_document_lifecycle_for_session_owner(- Some(session_id),+ let (binding, initial_events) = conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session(session_id),RendererPageCreationArtifacts {active_document: identity.document,active_epoch: identity.epoch,@@ -2197,7 +2192,7 @@ mod producer_tests {let prepared = super::file_chooser::PreparedFileChooserActivation::capture(&conn,- Some("SID-typed"),+ &CommandOwnerScope::for_session("SID-typed"),owner,renderer_file_chooser_for_test(source_document, Some("FRAME-typed"), 77, false),)@@ -2253,7 +2248,7 @@ mod producer_tests {let prepared = super::file_chooser::PreparedFileChooserActivation::capture(&conn,- Some("SID-root-capture"),+ &CommandOwnerScope::for_session("SID-root-capture"),owner,renderer_file_chooser_for_test(source_document, None, 41, false),)@@ -2284,7 +2279,7 @@ mod producer_tests {let owner = page_residence_identity_for_test(&conn, "SID-document-collision");let prepared = super::file_chooser::PreparedFileChooserActivation::capture(&conn,- Some("SID-document-collision"),+ &CommandOwnerScope::for_session("SID-document-collision"),owner,renderer_file_chooser_for_test(source_document, None, 42, false),)@@ -2355,7 +2350,7 @@ mod producer_tests {let owner = page_residence_identity_for_test(&conn, "SID-page-replacement");let stale = super::file_chooser::PreparedFileChooserActivation::capture(&conn,- Some("SID-page-replacement"),+ &CommandOwnerScope::for_session("SID-page-replacement"),owner.clone(),renderer_file_chooser_for_test(source_document, None, 43, false),)@@ -2373,7 +2368,7 @@ mod producer_tests {let replacement_owner = page_residence_identity_for_test(&conn, "SID-page-replacement");let current = super::file_chooser::PreparedFileChooserActivation::capture(&conn,- Some("SID-page-replacement"),+ &CommandOwnerScope::for_session("SID-page-replacement"),replacement_owner,renderer_file_chooser_for_test(replacement_document, None, 43, true),)diff --git a/moli-protocol/src/domains/input/file_chooser.rs b/moli-protocol/src/domains/input/file_chooser.rsindex f772d7443..863dfbb19 100644--- a/moli-protocol/src/domains/input/file_chooser.rs+++ b/moli-protocol/src/domains/input/file_chooser.rs@@ -3,7 +3,9 @@ use moli_core::page::{RendererPendingFileChooserActivation,};-use crate::conn::{BackgroundProtocolEvent, CdpConnection, TargetPageResidenceIdentity};+use crate::conn::{+ BackgroundProtocolEvent, CdpConnection, CommandOwnerScope, TargetPageResidenceIdentity,+};use crate::devtools_runtime::{DevToolsRemoteHandleId, webdriver_bidi_node_shared_id_for_backend_node_id,};@@ -29,11 +31,13 @@ pub(super) struct PreparedFileChooserActivation {impl PreparedFileChooserActivation {pub(super) fn capture(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,page_owner: TargetPageResidenceIdentity,activation: RendererPendingFileChooserActivation,) -> Option<Self> {- if !conn.target_page_residence_identity_is_current_for_session(session_id, &page_owner) {+ if !conn+ .target_page_residence_identity_is_current_for_session(owner.session_id(), &page_owner)+ {return None;}let source_document = activation.source_document();@@ -41,8 +45,11 @@ impl PreparedFileChooserActivation {.source_frame_id().map(str::to_owned).or_else(|| {- conn.target_session_owner_frame_tree_identity(session_id)- .map(|(frame_id, _, _, _)| frame_id)+ conn.target_session_owner_frame_tree_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )+ .map(|(frame_id, _, _, _)| frame_id)})?;Some(Self {page_owner,diff --git a/moli-protocol/src/domains/input/tests.rs b/moli-protocol/src/domains/input/tests.rsindex 3af10b9ed..d03facec7 100644--- a/moli-protocol/src/domains/input/tests.rs+++ b/moli-protocol/src/domains/input/tests.rs@@ -272,7 +272,9 @@ async fn completed_mouse_event_does_not_restore_replaced_page_state() {.conn.target_page_residence_identity_for_session(None).expect("the original Page should have a residence identity");- let pending = loaded_page_mut(&mut ctx.conn, None)+ let pending = ctx+ .conn+ .loaded_page_mut_for_protocol_access(None).expect("the original Page should be loaded").start_dispatch_mouse_event_at_point_with_outcome(INPUT_HIT_X.into(),@@ -333,7 +335,7 @@ async fn pending_mouse_event_acknowledges_when_page_is_replaced_before_renderer_.expect("the original Page should have a residence identity");let page_residence_token = ctx.conn- .capture_target_page_residence_token_for_session(None)+ .capture_target_page_residence_token_for_route(None, None).expect("the original Page should expose its attachment lifetime");let replacement_url = "data:text/html,<body>replacement-before-completion</body>";@@ -375,7 +377,7 @@ async fn completed_renderer_ack_wins_when_page_replacement_is_already_observablelet page_residence_token = ctx.conn- .capture_target_page_residence_token_for_session(None)+ .capture_target_page_residence_token_for_route(None, None).expect("the original Page should expose its attachment lifetime");ctx.install_navigation_fixture_for_session_owner("data:text/html,<body>replacement-after-ack</body>",diff --git a/moli-protocol/src/domains/io.rs b/moli-protocol/src/domains/io.rsindex 7f328e205..3bdf63c5b 100644--- a/moli-protocol/src/domains/io.rs+++ b/moli-protocol/src/domains/io.rs@@ -572,28 +572,20 @@ mod tests {.await;ctx.expect_error(9, -32000, "StreamHandleNotFound");- let background_route = ctx- .conn- .target_session_route_for_target_id("TID-background")- .expect("background target route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route));process_via_command_dispatch(&mut ctx,json!({"id": 10,+ "sessionId": "SID-background","method": "IO.read","params": { "handle": handle, "size": 10 }}),).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);ctx.expect_result(10,json!({ "base64Encoded": false, "data": "background", "eof": false }),- None,+ Some("SID-background"),);process_via_command_dispatch(diff --git a/moli-protocol/src/domains/log.rs b/moli-protocol/src/domains/log.rsindex 2acfd268a..aa3d46161 100644--- a/moli-protocol/src/domains/log.rs+++ b/moli-protocol/src/domains/log.rs@@ -516,8 +516,8 @@ mod tests {.is_some());- let prepared =- live_log_prepared_outputs_for_renderer_network_fact(&ctx.conn, Some("SID-1"));+ let owner = crate::conn::CommandOwnerScope::for_session("SID-1");+ let prepared = live_log_prepared_outputs_for_renderer_network_fact(&ctx.conn, &owner);let mut slot = ObservablePreparedOutputSlot::from_outputs(prepared);let mut events = Vec::new();slot.emit_activity_background_events_async(diff --git a/moli-protocol/src/domains/network.rs b/moli-protocol/src/domains/network.rsindex b850365f2..c13c2656c 100644--- a/moli-protocol/src/domains/network.rs+++ b/moli-protocol/src/domains/network.rs@@ -178,10 +178,6 @@ enum PendingNetworkCommandKind {}impl PendingNetworkCommandDispatch {- pub(crate) fn session_id(&self) -> Option<&str> {- self.owner_scope.session_id()- }-pub(crate) async fn wait(self) -> CompletedNetworkCommandDispatch {let completed = match self.pending {PendingNetworkCommandWork::Page {diff --git a/moli-protocol/src/domains/network/activity.rs b/moli-protocol/src/domains/network/activity.rsindex cf6c96609..ccd29b820 100644--- a/moli-protocol/src/domains/network/activity.rs+++ b/moli-protocol/src/domains/network/activity.rs@@ -81,7 +81,7 @@ impl NetworkPreparedOutputs {pub(crate) fn from_renderer_subresource_continue(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_document: moli_core::RendererDocumentLifecycleIdentity,event: moli_core::page::PendingSubresourceContinueEvent,) -> Self {@@ -89,7 +89,7 @@ impl NetworkPreparedOutputs {pending_subresource_continue_actions:prepare_subresource_continue_action_for_renderer_record(conn,- session_id,+ owner,source_document,event,)@@ -306,11 +306,11 @@ impl NetworkPreparedOutputSlot {&mut self,conn: &mut CdpConnection,out: &mut Vec<crate::conn::BackgroundProtocolEvent>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) {if let Some(actions) = self.take_pending_subresource_continue_actions() {flush_prepared_subresource_continue_actions_background_events_async(- conn, out, session_id, actions,+ conn, out, owner, actions,).await;}@@ -341,12 +341,12 @@ impl NetworkPreparedOutputSlot {&mut self,conn: &mut CdpConnection,out: &mut Vec<crate::conn::BackgroundProtocolEvent>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) {super::emit_prepared_renderer_network_live_background_events(conn,out,- session_id,+ owner,self.outputs.renderer_live_mut(),);}@@ -368,13 +368,14 @@ impl NetworkOutputProjectionStep {context: &mut ProtocolOutputProjectionContext<'_>,prepared_outputs: Option<&mut ProtocolOutputPayloads>,) {+ let owner = context.owner().clone();match self {NetworkOutputProjectionStep::PendingSubresourceContinueEvents => {if let Some(slot) = prepared_outputs.and_then(ProtocolOutputPayloads::network_mut) {slot.emit_pending_subresource_continue_background_events(conn,context.command.protocol_events_mut(),- context.session_id,+ &owner,).await;}@@ -384,13 +385,12 @@ impl NetworkOutputProjectionStep {slot.emit_renderer_live_background_events(conn,context.command.protocol_events_mut(),- context.session_id,+ &owner,);}}NetworkOutputProjectionStep::NetworkBacklog => {if let Some(slot) = prepared_outputs.and_then(ProtocolOutputPayloads::network_mut) {- let owner = CommandOwnerScope::capture(conn, context.session_id);slot.emit_backlog_activity_background_events(conn,context.command.protocol_events_mut(),@@ -407,12 +407,14 @@ impl NetworkOutputProjectionStep {.and_then(NetworkPreparedOutputSlot::take_subresource_fetch_pauses){let mut events = Vec::new();- let network_session_ids =- conn.network_event_session_ids_for_session_owner(context.session_id);+ let network_session_ids = conn.network_event_session_ids_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ );fetch::emit_subresource_fetch_pause_outputs(conn,&mut events,- context.session_id,+ &owner,&network_session_ids,pauses,);@@ -463,29 +465,6 @@ pub(in crate::domains) async fn project_subresource_fetch_interception_async(.await;}-pub(in crate::domains) fn network_backlog_prepared_outputs(- conn: &mut CdpConnection,- session_id: Option<&str>,- preferred_request_id: Option<super::NetworkBacklogPreferredRequestId<'_>>,-) -> NetworkPreparedOutputs {- let mut outputs = NetworkPreparedOutputs::default();- let primary_session_id = conn.runtime_session_owner_primary_session_id(session_id);- if let Some(backlog) = conn.network_backlog_prepared_delivery_for_session_owner(- session_id,- session_id,- primary_session_id.as_deref(),- preferred_request_id,- ) {- outputs.extend(NetworkPreparedOutputs {- pending_subresource_continue_actions: Vec::new(),- renderer_live: TargetNetworkBacklogPreparedDelivery::default(),- backlog,- subresource_fetch_pauses: Vec::new(),- });- }- outputs-}-pub(in crate::domains) fn network_backlog_prepared_outputs_for_owner(conn: &mut CdpConnection,owner: &crate::conn::CommandOwnerScope,@@ -634,8 +613,9 @@ mod tests {request_stage_chain: None,};assert!(- conn.register_in_flight_subresource_fetch_request_for_session_owner(+ conn.register_in_flight_subresource_fetch_request_for_route(Some("SID-1"),+ None,Some("fetch-req-1".to_owned()),pending,),@@ -669,15 +649,9 @@ mod tests {action,]),));+ let owner = CommandOwnerScope::for_session("SID-1");let mut command_context = CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: Some("SID-1"),- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::NetworkOutputProjectionStep::PendingSubresourceContinueEvents.project_async(&mut conn, &mut context, Some(&mut prepared))@@ -720,13 +694,12 @@ mod tests {.target_page_residence_identity_for_session(Some("SID-collision")).expect("old Page residence should exist");let reused_handle = SubresourceNetworkRequestHandle::new(9);- assert!(- conn.register_in_flight_subresource_fetch_request_for_session_owner(- Some("SID-collision"),- Some("FETCH-old".to_owned()),- pending_request_for_page(old_owner, 7, "NETWORK-old", reused_handle),- )- );+ assert!(conn.register_in_flight_subresource_fetch_request_for_route(+ Some("SID-collision"),+ None,+ Some("FETCH-old".to_owned()),+ pending_request_for_page(old_owner, 7, "NETWORK-old", reused_handle),+ ));let event =PendingSubresourceContinueEvent::ResponsePaused(PendingSubresourceResponseInfo {internal_id: 7,@@ -757,19 +730,19 @@ mod tests {let replacement_owner = conn.target_page_residence_identity_for_session(Some("SID-collision")).expect("replacement Page residence should exist");- assert!(- conn.register_in_flight_subresource_fetch_request_for_session_owner(- Some("SID-collision"),- Some("FETCH-new".to_owned()),- pending_request_for_page(replacement_owner, 7, "NETWORK-new", reused_handle),- )- );+ assert!(conn.register_in_flight_subresource_fetch_request_for_route(+ Some("SID-collision"),+ None,+ Some("FETCH-new".to_owned()),+ pending_request_for_page(replacement_owner, 7, "NETWORK-new", reused_handle),+ ));let mut out = Vec::new();+ let command_owner = CommandOwnerScope::for_session("SID-collision");crate::domains::activity::flush_prepared_subresource_continue_actions_background_events_async(&mut conn,&mut out,- Some("SID-collision"),+ &command_owner,vec![old_action],).await;@@ -779,11 +752,8 @@ mod tests {"stale continuation must not project an event for the replacement request");assert_eq!(- conn.in_flight_subresource_fetch_request_id_for_session_owner(- Some("SID-collision"),- 7,- )- .as_deref(),+ conn.in_flight_subresource_fetch_request_id_for_route(Some("SID-collision"), None, 7,)+ .as_deref(),Some("FETCH-new"),"stale apply must not claim the replacement request even when both renderer IDs collide");@@ -808,15 +778,9 @@ mod tests {ProtocolOutputPayloads::from_slot(super::NetworkPreparedOutputSlot::from_outputs(NetworkPreparedOutputs::from_subresource_fetch_interception_for_test(page_owner),));+ let owner = CommandOwnerScope::for_session("SID-1");let mut command_context = CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: Some("SID-1"),- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::NetworkOutputProjectionStep::SubresourceFetchInterception.project_async(&mut conn, &mut context, Some(&mut prepared))@@ -872,15 +836,9 @@ mod tests {ProtocolOutputPayloads::from_slot(super::NetworkPreparedOutputSlot::from_outputs(NetworkPreparedOutputs::from_subresource_fetch_interception_for_test(page_owner),));+ let owner = CommandOwnerScope::for_session("SID-1");let mut command_context = CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: Some("SID-1"),- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::NetworkOutputProjectionStep::SubresourceFetchInterception.project_async(&mut conn, &mut context, Some(&mut prepared))@@ -900,8 +858,9 @@ mod tests {#[test]fn network_backlog_prepared_outputs_are_absent_without_loaded_observed_page() {let mut conn = crate::conn::CdpConnection::default();+ let owner = CommandOwnerScope::capture(&conn, None);assert_eq!(- super::network_backlog_prepared_outputs(&mut conn, None, None).outputs(),+ super::network_backlog_prepared_outputs_for_owner(&mut conn, &owner, None,).outputs(),&[]);}diff --git a/moli-protocol/src/domains/network/backlog.rs b/moli-protocol/src/domains/network/backlog.rsindex e842a0b0d..ac7069cf5 100644--- a/moli-protocol/src/domains/network/backlog.rs+++ b/moli-protocol/src/domains/network/backlog.rs@@ -754,12 +754,9 @@ pub(crate) fn emit_pending_network_backlog_activity_background_events(pub(crate) fn emit_prepared_renderer_network_live_background_events(conn: &mut CdpConnection,out: &mut Vec<BackgroundProtocolEvent>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,prepared: &mut TargetNetworkBacklogPreparedDelivery,) {- let owner = session_id- .map(CommandOwnerScope::for_session)- .unwrap_or_else(|| CommandOwnerScope::for_implicit_route(None));let session_id = owner.session_id();let Some((frame_id, snapshot)) = (|| {let frame_id = conn@@ -776,7 +773,7 @@ pub(crate) fn emit_prepared_renderer_network_live_background_events(emit_network_delivery_snapshot(conn,out,- &owner,+ owner,&frame_id,monotonic_timestamp_seconds(),snapshot,@@ -1135,7 +1132,7 @@ mod tests {let mut events = Vec::new();let mut conn = CdpConnection::new();conn.install_default_browser_target();- let owner = crate::conn::CommandOwnerScope::for_implicit_route(None);+ let owner = crate::conn::CommandOwnerScope::capture(&conn, None);emit_network_delivery_snapshot(&mut conn, &mut events, &owner, "FRAME-1", 1.0, snapshot);events.into_iter()diff --git a/moli-protocol/src/domains/network/tests/session.rs b/moli-protocol/src/domains/network/tests/session.rsindex a54892013..8ceeceed7 100644--- a/moli-protocol/src/domains/network/tests/session.rs+++ b/moli-protocol/src/domains/network/tests/session.rs@@ -51,10 +51,7 @@ async fn network_configuration_commands_succeed_while_the_target_is_changing_doclet mut ctx = TestContext::new();install_network_session_page(&mut ctx, "data:text/html,committed").await;ctx.conn- .start_document_navigation_for_session_owner(- Some("SID-navigation"),- "LID-pending".to_owned(),- )+ .start_document_navigation_for_route(Some("SID-navigation"), None, "LID-pending".to_owned()).expect("the replacement navigation should start");ctx.process_async(json!({@@ -124,8 +121,8 @@ async fn network_configuration_commands_succeed_while_the_target_is_changing_doc);let configuration = ctx.conn- .prepared_document_commit_configuration_for_session_owner(- Some("SID-navigation"),+ .prepared_document_commit_configuration_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-navigation"),&url::Url::parse("data:text/html,committed").unwrap(),).expect("commit configuration should resolve the target resource runtime");@@ -241,8 +238,8 @@ async fn commit_configuration_resolves_the_exact_target_network_runtime() {] {let configuration = ctx.conn- .prepared_document_commit_configuration_for_session_owner(- Some(session_id),+ .prepared_document_commit_configuration_for_owner(+ &crate::conn::CommandOwnerScope::for_session(session_id),&url::Url::parse("about:blank").unwrap(),).expect("the target-specific resource runtime should resolve");diff --git a/moli-protocol/src/domains/observable_output/emission.rs b/moli-protocol/src/domains/observable_output/emission.rsindex 81c239a3d..88a573eba 100644--- a/moli-protocol/src/domains/observable_output/emission.rs+++ b/moli-protocol/src/domains/observable_output/emission.rs@@ -37,12 +37,13 @@ async fn project_observable_output_async(context: &mut ProtocolOutputProjectionContext<'_>,prepared_outputs: Option<&mut ProtocolOutputPayloads>,) {+ let owner = context.owner().clone();if let Some(slot) = prepared_outputs.and_then(ProtocolOutputPayloads::observable_mut) {slot.emit_activity_background_events_async(step,conn,context.command.protocol_events_mut(),- context.session_id,+ owner.session_id(),).await;}diff --git a/moli-protocol/src/domains/observable_output/mod.rs b/moli-protocol/src/domains/observable_output/mod.rsindex adf41f356..f998ec6cf 100644--- a/moli-protocol/src/domains/observable_output/mod.rs+++ b/moli-protocol/src/domains/observable_output/mod.rs@@ -29,7 +29,10 @@ pub(in crate::domains) use presence::{runtime_console_message_prepared_outputs, runtime_lifecycle_error_prepared_outputs,};pub(crate) use runtime_cursor::TargetRuntimeObservableState;-pub(in crate::domains) use runtime_emission::advance_runtime_observable_cursors_to_current_for_session_owner;+pub(in crate::domains) use runtime_emission::{+ advance_runtime_observable_cursors_to_current_for_owner,+ advance_runtime_observable_cursors_to_current_for_session_owner,+};#[cfg(test)]pub(in crate::domains) use runtime_queue::RuntimeObservableEmissionSnapshot;#[cfg(test)]diff --git a/moli-protocol/src/domains/observable_output/presence.rs b/moli-protocol/src/domains/observable_output/presence.rsindex 006d77a0b..7ebaef600 100644--- a/moli-protocol/src/domains/observable_output/presence.rs+++ b/moli-protocol/src/domains/observable_output/presence.rs@@ -7,7 +7,7 @@ use super::ObservableOutputProjectionStep;use super::output_queue::{ObservablePreparedOutputs, ObservableSessionAuditsPreparedRange, TargetObservableOutputQueue,};-use crate::conn::CdpConnection;+use crate::conn::{CdpConnection, CommandOwnerScope};#[derive(Clone, Copy)]enum RuntimeObservableAudience {@@ -83,18 +83,17 @@ pub(in crate::domains) fn observable_source_activity_outputs(pub(in crate::domains) fn runtime_console_message_prepared_outputs(conn: &mut CdpConnection,message: RuntimeConsoleMessageSnapshot,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> ObservablePreparedOutputs {let mut prepared = ObservablePreparedOutputs::default();- let Some(source) = runtime_console_source_tail_for_session_owner(conn, message, session_id)- else {+ let Some(source) = runtime_console_source_tail_for_owner(conn, message, owner) else {return prepared;};push_runtime_observable_tail_prepared_outputs(&mut prepared,conn,&source,- session_id,+ owner,true,RuntimeObservableAudience::SourceSession,);@@ -105,22 +104,19 @@ pub(in crate::domains) fn runtime_lifecycle_error_prepared_outputs(conn: &mut CdpConnection,text: String,execution_context_id: Option<i64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> ObservablePreparedOutputs {let mut prepared = ObservablePreparedOutputs::default();- let Some(source) = runtime_lifecycle_error_source_tail_for_session_owner(- conn,- text,- execution_context_id,- session_id,- ) else {+ let Some(source) =+ runtime_lifecycle_error_source_tail_for_owner(conn, text, execution_context_id, owner)+ else {return prepared;};push_runtime_observable_tail_prepared_outputs(&mut prepared,conn,&source,- session_id,+ owner,true,RuntimeObservableAudience::EnabledTargetAttachments,);@@ -131,15 +127,17 @@ pub(in crate::domains) fn inspector_issue_prepared_outputs(conn: &mut CdpConnection,source_document: moli_core::RendererDocumentLifecycleIdentity,issue: InspectorIssueSnapshot,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> ObservablePreparedOutputs {let mut prepared = ObservablePreparedOutputs::default();+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();// Inspector issues are Document facts. Resolve them only against the// exact committed Document captured by the renderer; otherwise a late// issue from a retired generation could be stored and replayed as if it// belonged to its replacement.let Some(document_binding) = conn- .runtime_session_owner_slot(session_id)+ .runtime_session_owner_slot_for_route(session_id, owner_route).ok().and_then(|slot| slot.committed_renderer_document_binding())else {@@ -151,12 +149,14 @@ pub(in crate::domains) fn inspector_issue_prepared_outputs(let page_attachment_id = document_binding.page_attachment_id;let frame_id = document_binding.frame_id.clone();let loader_id = document_binding.loader_id.clone();- let Some(storage) = conn.with_target_owner_state_for_session_mut(session_id, |owner_state| {- owner_state- .audits_storage_state- .append_concrete_issue(issue);- owner_state.audits_storage_state.clone()- }) else {+ let Some(storage) =+ conn.with_target_owner_state_for_route_mut(session_id, owner_route, |owner_state| {+ owner_state+ .audits_storage_state+ .append_concrete_issue(issue);+ owner_state.audits_storage_state.clone()+ })+ else {return prepared;};@@ -164,10 +164,11 @@ pub(in crate::domains) fn inspector_issue_prepared_outputs(// then fans out to every enabled frontend session. Each session keeps its// own cursor, matching Blink's per-session Audits agent state without// rediscovering the issue from a later Page snapshot.- for event_session_id in conn.page_event_session_ids_for_session_owner(session_id) {+ for event_session_id in conn.page_event_session_ids_for_route(session_id, owner_route) {let event_session_id = event_session_id.as_deref();+ let event_owner_route = event_session_id.is_none().then_some(owner_route).flatten();let Some(cursor) = conn- .target_page_session_state_for_session(event_session_id)+ .target_page_session_state_for_route(event_session_id, event_owner_route).and_then(|state| state.audits.pending_cursor(&storage))else {continue;@@ -208,6 +209,7 @@ fn push_runtime_observable_source_prepared_outputs(source: &RendererRuntimeObservableSourceSummary,session_id: Option<&str>,) {+ let owner = CommandOwnerScope::capture(conn, session_id);let Some(source) = runtime_observable_source_tail_for_session_owner(conn, source, session_id)else {return;@@ -216,7 +218,7 @@ fn push_runtime_observable_source_prepared_outputs(prepared,conn,&source,- session_id,+ &owner,false,RuntimeObservableAudience::SourceSession,);@@ -226,16 +228,18 @@ fn push_runtime_observable_tail_prepared_outputs(prepared: &mut ObservablePreparedOutputs,conn: &mut CdpConnection,source: &super::TargetRuntimeObservableSourceOutput,- session_id: Option<&str>,+ owner: &CommandOwnerScope,deliver_log_to_enabled_sessions: bool,runtime_audience: RuntimeObservableAudience,) {+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();let owner_state = conn- .target_owner_state_for_session(session_id)+ .target_owner_state_for_route(session_id, owner_route).cloned().unwrap_or_default();let include_console_api_messages =- !renderer_agent_owns_page_console_api_events(conn, session_id);+ !renderer_agent_owns_page_console_api_events(conn, session_id, owner_route);push_console_log_source_prepared_outputs(prepared,@@ -245,27 +249,33 @@ fn push_runtime_observable_tail_prepared_outputs(&owner_state,include_console_api_messages,deliver_log_to_enabled_sessions,+ owner_route,);let attachments = match runtime_audience {RuntimeObservableAudience::SourceSession => conn- .target_page_protocol_attachment_identity_for_session(session_id)+ .target_page_protocol_attachment_identity_for_route(session_id, owner_route).into_iter().collect(),RuntimeObservableAudience::EnabledTargetAttachments => conn- .runtime_event_protocol_attachments_for_session_owner(session_id)+ .runtime_event_protocol_attachments_for_route(session_id, owner_route).unwrap_or_default(),};for attachment in attachments {let event_session_id = attachment.session_id();+ let event_owner_route = event_session_id.is_none().then_some(owner_route).flatten();if !conn- .target_runtime_session_state_for_session(event_session_id)+ .target_runtime_session_state_for_route(event_session_id, event_owner_route).is_some_and(|state| state.runtime_frontend_enabled){continue;}let include_runtime_console_api_messages =- !renderer_runtime_agent_owns_page_console_api_events(conn, event_session_id);+ !renderer_runtime_agent_owns_page_console_api_events(+ conn,+ event_session_id,+ event_owner_route,+ );if let Some(items) = source.source_items_prepared_for_state(&owner_state.runtime_observable_state,include_runtime_console_api_messages,@@ -283,9 +293,11 @@ fn push_console_log_source_prepared_outputs(owner_state: &crate::conn::TargetOwnerState,include_console_api_messages: bool,deliver_log_to_enabled_sessions: bool,+ owner_route: Option<&crate::conn::CdpSessionRoute>,) {let queue = TargetObservableOutputQueue::from_runtime_source_output_ref(Some(source));- if let Some(devtools_session_state) = conn.target_devtools_session_state_for_session(session_id)+ if let Some(devtools_session_state) =+ conn.target_devtools_session_state_for_route(session_id, owner_route){prepared.extend(queue.console_log_backlog_ranges(@@ -318,12 +330,14 @@ fn push_console_log_source_prepared_outputs(source.page_attachment_id(),owner_state,session_id,+ owner_route,);}fn renderer_agent_owns_page_console_api_events(conn: &CdpConnection,session_id: Option<&str>,+ owner_route: Option<&crate::conn::CdpSessionRoute>,) -> bool {if session_id.is_some_and(|session_id| {conn.shared_worker_target_for_session(Some(session_id))@@ -331,13 +345,14 @@ fn renderer_agent_owns_page_console_api_events(}) {return false;}- let Ok(runtime_slot) = conn.runtime_session_owner_slot(session_id) else {+ let Ok(runtime_slot) = conn.runtime_session_owner_slot_for_route(session_id, owner_route)+ else {return false;};if !runtime_slot.has_loaded_page() {return false;}- conn.target_devtools_session_state_for_session(session_id)+ conn.target_devtools_session_state_for_route(session_id, owner_route).is_some_and(|state| {state.console_output_session_state@@ -348,6 +363,7 @@ fn renderer_agent_owns_page_console_api_events(fn renderer_runtime_agent_owns_page_console_api_events(conn: &CdpConnection,session_id: Option<&str>,+ owner_route: Option<&crate::conn::CdpSessionRoute>,) -> bool {if session_id.is_some_and(|session_id| {conn.shared_worker_target_for_session(Some(session_id))@@ -355,13 +371,14 @@ fn renderer_runtime_agent_owns_page_console_api_events(}) {return false;}- let Ok(runtime_slot) = conn.runtime_session_owner_slot(session_id) else {+ let Ok(runtime_slot) = conn.runtime_session_owner_slot_for_route(session_id, owner_route)+ else {return false;};if !runtime_slot.has_loaded_page() {return false;}- conn.target_devtools_session_state_for_session(session_id)+ conn.target_devtools_session_state_for_route(session_id, owner_route).is_some_and(|state| {state.console_output_session_state@@ -380,24 +397,34 @@ fn runtime_observable_source_tail_for_session_owner(runtime_slot.sync_observable_output_source_from_renderer_runtime_source(url, source)}-fn runtime_console_source_tail_for_session_owner(+fn runtime_console_source_tail_for_owner(conn: &mut CdpConnection,message: RuntimeConsoleMessageSnapshot,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Option<super::TargetRuntimeObservableSourceOutput> {- let url = conn.runtime_session_owner_target_url(session_id)?;- let runtime_slot = conn.runtime_session_owner_slot_mut(session_id).ok()?;+ let url = conn.runtime_session_owner_target_url_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?;+ let runtime_slot = conn+ .runtime_session_owner_slot_mut_for_route(owner.session_id(), owner.session_owner_route())+ .ok()?;runtime_slot.append_renderer_runtime_console_message(url, message)}-fn runtime_lifecycle_error_source_tail_for_session_owner(+fn runtime_lifecycle_error_source_tail_for_owner(conn: &mut CdpConnection,text: String,execution_context_id: Option<i64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Option<super::TargetRuntimeObservableSourceOutput> {- let url = conn.runtime_session_owner_target_url(session_id)?;- let runtime_slot = conn.runtime_session_owner_slot_mut(session_id).ok()?;+ let url = conn.runtime_session_owner_target_url_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?;+ let runtime_slot = conn+ .runtime_session_owner_slot_mut_for_route(owner.session_id(), owner.session_owner_route())+ .ok()?;runtime_slot.append_renderer_runtime_lifecycle_error(url, text, execution_context_id)}@@ -425,16 +452,21 @@ pub(in crate::domains) fn observable_backlog_prepared_outputs_for_session_owner(/// instead and never calls this live projection entry point.pub(in crate::domains) fn live_log_prepared_outputs_for_renderer_network_fact(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> ObservablePreparedOutputs {+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();let owner_state = conn- .target_owner_state_for_session(session_id)+ .target_owner_state_for_route(session_id, owner_route).cloned().unwrap_or_default();- let Some(runtime_slot) = conn.runtime_session_owner_slot(session_id).ok() else {+ let Some(runtime_slot) = conn+ .runtime_session_owner_slot_for_route(session_id, owner_route)+ .ok()+ else {return ObservablePreparedOutputs::default();};- let Some(url) = conn.runtime_session_owner_target_url(session_id) else {+ let Some(url) = conn.runtime_session_owner_target_url_for_route(session_id, owner_route) else {return ObservablePreparedOutputs::default();};let Some(queue) = TargetObservableOutputQueue::from_log_storage(runtime_slot) else {@@ -452,6 +484,7 @@ pub(in crate::domains) fn live_log_prepared_outputs_for_renderer_network_fact(page_attachment_id,&owner_state,session_id,+ owner_route,);prepared}@@ -472,7 +505,7 @@ fn observable_console_log_prepared_outputs_for_session_owner(let queue = super::output_queue::TargetObservableOutputQueue::from_runtime_slot(runtime_slot)?;let page_attachment_id = runtime_slot.page_attachment_id()?;let include_console_api_messages =- !renderer_agent_owns_page_console_api_events(conn, session_id);+ !renderer_agent_owns_page_console_api_events(conn, session_id, None);let mut prepared = ObservablePreparedOutputs::default();if console_allowed@@ -504,6 +537,7 @@ fn observable_console_log_prepared_outputs_for_session_owner(page_attachment_id,&owner_state,session_id,+ None,);}@@ -518,15 +552,17 @@ fn push_log_prepared_outputs_for_enabled_sessions(page_attachment_id: crate::conn::TargetPageAttachmentId,owner_state: &crate::conn::TargetOwnerState,session_id: Option<&str>,+ owner_route: Option<&crate::conn::CdpSessionRoute>,) {// A concrete Page error is stored once but observed by every Log agent// attached to that target. The publication route names one canonical// session only; it must not accidentally turn a target-owned fact into a// single-session event.- for event_session_id in conn.page_event_session_ids_for_session_owner(session_id) {+ for event_session_id in conn.page_event_session_ids_for_route(session_id, owner_route) {let event_session_id = event_session_id.as_deref();+ let event_owner_route = event_session_id.is_none().then_some(owner_route).flatten();let Some(devtools_session_state) =- conn.target_devtools_session_state_for_session(event_session_id)+ conn.target_devtools_session_state_for_route(event_session_id, event_owner_route)else {continue;};@@ -553,7 +589,7 @@ mod tests {RendererRuntimeObservableSourceSummary, RuntimeConsoleMessageSnapshot,};- use crate::conn::BrowserContext;+ use crate::conn::{BrowserContext, CommandOwnerScope};use crate::domains::observable_output::output_queue::TargetObservableOutputQueue;use crate::testing::TestContext;@@ -592,7 +628,7 @@ mod tests {&mut conn,"uncaught timer error".to_owned(),Some(7),- Some("SID-runtime-a"),+ &CommandOwnerScope::for_session("SID-runtime-a"),).take_runtime_observable_items().into_iter()diff --git a/moli-protocol/src/domains/observable_output/runtime_emission.rs b/moli-protocol/src/domains/observable_output/runtime_emission.rsindex 80d7d0c6d..6e90576d6 100644--- a/moli-protocol/src/domains/observable_output/runtime_emission.rs+++ b/moli-protocol/src/domains/observable_output/runtime_emission.rs@@ -1,7 +1,8 @@use std::collections::HashMap;-use crate::conn::CdpConnection;+use crate::conn::{CdpConnection, CommandOwnerScope};+#[cfg(test)]use super::TargetRuntimeObservableSourceOutput;use super::items::ObservableRuntimeEmissionCursor;#[cfg(test)]@@ -11,57 +12,70 @@ pub(in crate::domains) fn advance_runtime_observable_cursors_to_current_for_sessconn: &mut CdpConnection,session_id: Option<&str>,) {- let owner_session_id = runtime_observable_owner_session_id(conn, session_id);+ let owner = CommandOwnerScope::capture(conn, session_id);+ advance_runtime_observable_cursors_to_current_for_owner(conn, &owner);+}++pub(in crate::domains) fn advance_runtime_observable_cursors_to_current_for_owner(+ conn: &mut CdpConnection,+ owner: &CommandOwnerScope,+) {if let Some((context_console_counts, exception_entries)) =- runtime_observable_cursor_end_from_owner_queue(conn, owner_session_id)+ runtime_observable_cursor_end_from_owner_queue_for_owner(conn, owner){- let _ = conn.with_target_owner_state_for_session_mut(owner_session_id, |owner_state| {- owner_state.runtime_observable_state.advance_to_current(- context_console_counts,- 0,- exception_entries,- );- });+ let _ = conn.with_target_owner_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |owner_state| {+ owner_state.runtime_observable_state.advance_to_current(+ context_console_counts,+ 0,+ exception_entries,+ );+ },+ );return;}let Some((owner_queue_console_entries, exception_entries)) =- runtime_observable_cursor_end_from_owner_observable_queue(conn, owner_session_id)+ runtime_observable_cursor_end_from_owner_observable_queue_for_owner(conn, owner)else {return;};- let _ = conn.with_target_owner_state_for_session_mut(owner_session_id, |owner_state| {- owner_state.runtime_observable_state.advance_to_current(- HashMap::new(),- owner_queue_console_entries,- exception_entries,- );- });+ let _ = conn.with_target_owner_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |owner_state| {+ owner_state.runtime_observable_state.advance_to_current(+ HashMap::new(),+ owner_queue_console_entries,+ exception_entries,+ );+ },+ );}-fn runtime_observable_cursor_end_from_owner_queue(+fn runtime_observable_cursor_end_from_owner_queue_for_owner(conn: &CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Option<(HashMap<i64, usize>, usize)> {- let source = runtime_observable_source_tail_for_session_owner(conn, owner_session_id)?;- source.cursor_end()-}--fn runtime_observable_source_tail_for_session_owner(- conn: &CdpConnection,- owner_session_id: Option<&str>,-) -> Option<TargetRuntimeObservableSourceOutput> {- let runtime_slot = conn.runtime_session_owner_slot(owner_session_id).ok()?;+ let runtime_slot = conn+ .runtime_session_owner_slot_for_route(owner.session_id(), owner.session_owner_route())+ .ok()?;let source = runtime_slot.observable_output_latest_source_tail()?;- let url = conn.runtime_session_owner_target_url(owner_session_id)?;+ let url = conn.runtime_session_owner_target_url_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )?;(source.url() == url && runtime_slot.page_attachment_id() == Some(source.page_attachment_id()))- .then_some(source)+ .then_some(source)?+ .cursor_end()}-fn runtime_observable_cursor_end_from_owner_observable_queue(+fn runtime_observable_cursor_end_from_owner_observable_queue_for_owner(conn: &CdpConnection,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Option<(usize, usize)> {- conn.runtime_session_owner_slot(owner_session_id)+ conn.runtime_session_owner_slot_for_route(owner.session_id(), owner.session_owner_route()).ok()?.observable_output_cursor_end()}diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rsindex b92966ee6..664569647 100644--- a/moli-protocol/src/domains/page.rs+++ b/moli-protocol/src/domains/page.rs@@ -515,22 +515,25 @@ pub(crate) struct PagePreparedOutputSlot {impl PagePreparedOutputs {pub(crate) fn from_renderer_javascript_dialog(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,dialog: moli_core::page::RendererPendingJavaScriptDialog,) -> Self {+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();let Some(source_attachment) =- conn.target_page_protocol_attachment_identity_for_session(session_id)+ conn.target_page_protocol_attachment_identity_for_route(session_id, owner_route)else {let _ = dialog.finish(false, String::new());return Self::default();};let Some((root_frame_id, _, _, _)) =- conn.target_session_owner_frame_tree_identity(session_id)+ conn.target_session_owner_frame_tree_identity_for_route(session_id, owner_route)else {let _ = dialog.finish(false, String::new());return Self::default();};- let Ok(runtime_slot) = conn.runtime_session_owner_slot(session_id) else {+ let Ok(runtime_slot) = conn.runtime_session_owner_slot_for_route(session_id, owner_route)+ else {let _ = dialog.finish(false, String::new());return Self::default();};@@ -547,10 +550,13 @@ impl PagePreparedOutputs {pub(crate) fn from_renderer_popup_activation(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,activation: moli_core::page::RendererPendingPopupActivation,) -> Self {- let Some(page_owner) = conn.target_page_residence_identity_for_session(session_id) else {+ let Some(page_owner) = conn.target_page_residence_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {return Self::default();};Self {@@ -563,12 +569,15 @@ impl PagePreparedOutputs {pub(crate) fn from_renderer_window_open_event(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,event: RendererPendingWindowOpenEvent,) -> Self {Self {window_open_events: vec![popup::PagePreparedWindowOpenEvent::new(- conn.subscribed_page_event_session_ids_for_session_owner(session_id),+ conn.subscribed_page_event_session_ids_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ),event,)],..Self::default()@@ -577,15 +586,18 @@ impl PagePreparedOutputs {pub(crate) fn from_renderer_same_document_navigation(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,navigation: RendererDocumentSourcedSameDocumentNavigation,) -> Self {- let Some(owner) = conn.target_page_residence_identity_for_session(session_id) else {+ let Some(page_owner) = conn.target_page_residence_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {return Self::default();};Self {same_document_navigations: vec![PagePreparedSameDocumentNavigation::new(- owner, navigation,+ page_owner, navigation,)],..Self::default()}@@ -593,15 +605,18 @@ impl PagePreparedOutputs {pub(crate) fn from_renderer_top_level_location_navigation(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,navigation: RendererDocumentSourcedTopLevelLocationNavigation,) -> Self {- let Some(owner) = conn.target_page_residence_identity_for_session(session_id) else {+ let Some(page_owner) = conn.target_page_residence_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {return Self::default();};Self {top_level_location_navigation: Some(PagePreparedTopLevelLocationNavigation::new(- owner, navigation,+ page_owner, navigation,)),..Self::default()}@@ -618,18 +633,21 @@ impl PagePreparedOutputs {pub(crate) fn from_renderer_child_frame_tree_event(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_document: RendererDocumentLifecycleIdentity,event: ChildFrameTreeEventSnapshot,) -> Self {- let Some(binding) = conn.target_root_document_protocol_attachment_identity_for_session(+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();+ let Some(binding) = conn.target_root_document_protocol_attachment_identity_for_route(session_id,+ owner_route,source_document,) else {return Self::default();};let Some((root_frame_id, _, security_origin, secure_context_type)) =- conn.target_session_owner_frame_tree_identity(session_id)+ conn.target_session_owner_frame_tree_identity_for_route(session_id, owner_route)else {return Self::default();};@@ -665,18 +683,21 @@ impl PagePreparedOutputs {pub(crate) fn from_renderer_child_frame_document_opened(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_document: RendererDocumentLifecycleIdentity,mut event: ChildFrameDocumentOpenedSnapshot,) -> Self {- let Some(binding) = conn.target_root_document_protocol_attachment_identity_for_session(+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();+ let Some(binding) = conn.target_root_document_protocol_attachment_identity_for_route(session_id,+ owner_route,source_document,) else {return Self::default();};let Some((root_frame_id, _, security_origin, secure_context_type)) =- conn.target_session_owner_frame_tree_identity(session_id)+ conn.target_session_owner_frame_tree_identity_for_route(session_id, owner_route)else {return Self::default();};@@ -702,18 +723,21 @@ impl PagePreparedOutputs {pub(crate) fn from_renderer_child_frame_document_network(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_document: RendererDocumentLifecycleIdentity,event: ChildFrameDocumentNetworkActivitySnapshot,) -> Self {- let Some(binding) = conn.target_root_document_protocol_attachment_identity_for_session(+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();+ let Some(binding) = conn.target_root_document_protocol_attachment_identity_for_route(session_id,+ owner_route,source_document,) else {return Self::default();};let Some((_, _, security_origin, secure_context_type)) =- conn.target_session_owner_frame_tree_identity(session_id)+ conn.target_session_owner_frame_tree_identity_for_route(session_id, owner_route)else {return Self::default();};@@ -736,18 +760,21 @@ impl PagePreparedOutputs {pub(crate) fn from_renderer_child_frame_load(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,source_document: RendererDocumentLifecycleIdentity,mut event: ChildFrameNavigationSnapshot,) -> Self {- let Some(binding) = conn.target_root_document_protocol_attachment_identity_for_session(+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();+ let Some(binding) = conn.target_root_document_protocol_attachment_identity_for_route(session_id,+ owner_route,source_document,) else {return Self::default();};let Some((root_frame_id, _, security_origin, secure_context_type)) =- conn.target_session_owner_frame_tree_identity(session_id)+ conn.target_session_owner_frame_tree_identity_for_route(session_id, owner_route)else {return Self::default();};@@ -1189,13 +1216,14 @@ impl PageOutputProjectionStep {context: &mut ProtocolOutputProjectionContext<'_>,prepared_outputs: Option<&mut ProtocolOutputPayloads>,) {+ let owner = context.owner().clone();match self {PageOutputProjectionStep::Download => {let mut events = Vec::new();input::emit_download_activity_background_events_async(conn,&mut events,- context.session_id,+ owner.session_id(),prepared_outputs,context.command,)@@ -1208,8 +1236,8 @@ impl PageOutputProjectionStep {.and_then(PagePreparedOutputSlot::take_document_lifecycle_events){let (binding, accepted) = conn- .ingest_renderer_document_lifecycle_events_for_session_owner(- context.session_id,+ .ingest_renderer_document_lifecycle_events_for_owner(+ &owner,renderer_events,);if let Some(binding) = binding {@@ -1217,7 +1245,7 @@ impl PageOutputProjectionStep {emit_bound_renderer_document_lifecycle_background_events(conn,&mut events,- context.session_id,+ &owner,&binding,&accepted,);@@ -1234,7 +1262,7 @@ impl PageOutputProjectionStep {for change in changes {if conn.apply_renderer_document_title_for_session_owner(- context.session_id,+ owner.session_id(),&change,).unwrap_or(false)@@ -1242,7 +1270,7 @@ impl PageOutputProjectionStep {crate::domains::target::emit_target_info_changed_for_session_owner_background_event(conn,&mut events,- context.session_id,+ owner.session_id(),);}}@@ -1254,7 +1282,7 @@ impl PageOutputProjectionStep {input::emit_file_chooser_activity_background_events_async(conn,&mut events,- context.session_id,+ owner.session_id(),prepared_outputs,).await;@@ -1265,7 +1293,7 @@ impl PageOutputProjectionStep {emit_javascript_dialog_activity_background_events_async(conn,&mut events,- context.session_id,+ owner.session_id(),prepared_outputs,).await;@@ -1289,7 +1317,7 @@ impl PageOutputProjectionStep {emit_popup_activity_background_events_async(conn,&mut events,- context.session_id,+ owner.session_id(),prepared_outputs,).await;@@ -1312,7 +1340,7 @@ impl PageOutputProjectionStep {emit_same_document_navigation_activity_background_events_async(conn,&mut events,- context.session_id,+ owner.session_id(),prepared_outputs,).await;@@ -1321,7 +1349,7 @@ impl PageOutputProjectionStep {PageOutputProjectionStep::TopLevelLocationNavigation => {publish_prepared_top_level_location_navigation_owner_action(conn,- context.session_id,+ owner.session_id(),prepared_outputs,);}@@ -1330,7 +1358,7 @@ impl PageOutputProjectionStep {emit_top_level_history_traversal_activity_background_events_async(conn,&mut events,- context.session_id,+ owner.session_id(),prepared_outputs,).await;@@ -2360,16 +2388,6 @@ pub(crate) async fn navigate_page_owned_top_level_location_background_events_asy.await;}-pub(crate) async fn navigate_session_owner_from_renderer_background_events_async(- conn: &mut CdpConnection,- out: &mut Vec<BackgroundProtocolEvent>,- session_id: Option<&str>,- url: &str,-) {- let owner = CommandOwnerScope::capture(conn, session_id);- navigate_command_owner_from_renderer_background_events_async(conn, out, &owner, url).await;-}-pub(crate) async fn navigate_command_owner_from_renderer_background_events_async(conn: &mut CdpConnection,out: &mut Vec<BackgroundProtocolEvent>,@@ -2446,24 +2464,29 @@ async fn complete_renderer_navigation_step_background_events_async(}}-pub(crate) fn emit_page_window_open_background_events(+pub(crate) fn emit_page_window_open_background_events_for_route(conn: &CdpConnection,out: &mut Vec<BackgroundProtocolEvent>,owner_session_id: Option<&str>,+ owner_route: Option<&crate::conn::CdpSessionRoute>,url: &str,window_name: &str,window_features: &[String],user_gesture: bool,) {- if !crate::domains::target::popup_activation_creates_new_target(+ if !crate::domains::target::popup_activation_creates_new_target_for_route(conn,owner_session_id,+ owner_route,window_name,) {return;}- for event_session_id in conn.page_event_session_ids_for_session_owner(owner_session_id) {- if conn.page_domain_enabled_for_session_owner(event_session_id.as_deref()) == Some(true) {+ for event_session_id in conn.page_event_session_ids_for_route(owner_session_id, owner_route) {+ let event_owner_route = event_session_id.is_none().then_some(owner_route).flatten();+ if conn.page_domain_enabled_for_route(event_session_id.as_deref(), event_owner_route)+ == Some(true)+ {out.push(BackgroundProtocolEvent::page_window_open(event_session_id.as_deref(),url,@@ -2555,8 +2578,8 @@ mod producer_tests {load: None,terminated: None,};- let (binding, initial_events) = conn.bind_renderer_document_lifecycle_for_session_owner(- Some(session_id),+ let (binding, initial_events) = conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session(session_id),RendererPageCreationArtifacts {active_document: identity.document,active_epoch: identity.epoch,@@ -3568,9 +3591,9 @@ mod producer_tests {.into(),);+ let owner = crate::conn::CommandOwnerScope::for_session("SID-activity-order");let mut command_context = crate::conn::CommandDispatchContext::default();- let mut context =- ProtocolOutputProjectionContext::new(Some("SID-activity-order"), &mut command_context);+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);for step in [super::PageOutputProjectionStep::FileChooser,@@ -3703,11 +3726,9 @@ mod producer_tests {.into(),);+ let owner = crate::conn::CommandOwnerScope::for_session("SID-later-activity-order");let mut command_context = crate::conn::CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext::new(- Some("SID-later-activity-order"),- &mut command_context,- );+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);for step in [super::PageOutputProjectionStep::ChildFrameActivity,@@ -4463,15 +4484,9 @@ mod producer_tests {};let mut prepared =ProtocolOutputPayloads::from_slot(super::PagePreparedOutputSlot::from_outputs(outputs));+ let owner = crate::conn::CommandOwnerScope::for_session("SID-1");let mut command_context = crate::conn::CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: Some("SID-1"),- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::PageOutputProjectionStep::ChildFrameActivity.project_async(&mut conn, &mut context, Some(&mut prepared))@@ -4752,15 +4767,9 @@ mod producer_tests {bc.set_target_url("https://example.test/page".to_owned());bc.attach_active_session("SID-1");conn.browser_context = Some(bc);+ let owner = crate::conn::CommandOwnerScope::for_session("SID-1");let mut command_context = crate::conn::CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: Some("SID-1"),- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::PageOutputProjectionStep::ChildFrameActivity.project_async(&mut conn, &mut context, None)diff --git a/moli-protocol/src/domains/page/lifecycle.rs b/moli-protocol/src/domains/page/lifecycle.rsindex 26ef94073..a025da2ab 100644--- a/moli-protocol/src/domains/page/lifecycle.rs+++ b/moli-protocol/src/domains/page/lifecycle.rs@@ -3,7 +3,9 @@ use crate::devtools_runtime::{NavigationFrameEventKind, NavigationLifecycleEvent, PageLifecycleEvent,};-use crate::conn::{BackgroundProtocolEvent, CdpConnection, CommittedRendererDocumentBinding};+use crate::conn::{+ BackgroundProtocolEvent, CdpConnection, CommandOwnerScope, CommittedRendererDocumentBinding,+};use moli_core::page::{RendererDocumentLifecycleEvent, RendererDocumentLifecycleEventKind,RendererDocumentLifecycleMilestone, RendererLifecycleStartReason,@@ -179,11 +181,12 @@ fn emit_renderer_navigation_domcontentloaded_background_events(pub(crate) fn emit_bound_renderer_document_lifecycle_background_events(conn: &mut CdpConnection,out: &mut Vec<BackgroundProtocolEvent>,- owner_session_id: Option<&str>,+ owner: &CommandOwnerScope,binding: &CommittedRendererDocumentBinding,events: &[RendererDocumentLifecycleEvent],) {- let session_ids = conn.page_event_session_ids_for_session_owner(owner_session_id);+ let session_ids =+ conn.page_event_session_ids_for_route(owner.session_id(), owner.session_owner_route());for event in events {if event.frame != binding.renderer_frame || event.document != binding.renderer_document {continue;@@ -194,9 +197,14 @@ pub(crate) fn emit_bound_renderer_document_lifecycle_background_events(RendererDocumentLifecycleMilestone::DomContentLoaded,) => {for session_id in &session_ids {- if crate::domains::dom::dom_agent_enabled_for_session(+ let owner_route = session_id+ .is_none()+ .then_some(owner.session_owner_route())+ .flatten();+ if crate::domains::dom::dom_agent_enabled_for_route(conn,session_id.as_deref(),+ owner_route,) {emit_cdp_page_background_automation_event(out,@@ -209,8 +217,11 @@ pub(crate) fn emit_bound_renderer_document_lifecycle_background_events(session_id.as_deref(),);}- let lifecycle_enabled =- page_lifecycle_events_enabled_for_session(conn, session_id.as_deref());+ let lifecycle_enabled = page_lifecycle_events_enabled_for_route(+ conn,+ session_id.as_deref(),+ owner_route,+ );emit_renderer_navigation_domcontentloaded_background_events(out,session_id.as_deref(),@@ -225,8 +236,15 @@ pub(crate) fn emit_bound_renderer_document_lifecycle_background_events(RendererDocumentLifecycleMilestone::Load,) => {for session_id in &session_ids {- let lifecycle_enabled =- page_lifecycle_events_enabled_for_session(conn, session_id.as_deref());+ let owner_route = session_id+ .is_none()+ .then_some(owner.session_owner_route())+ .flatten();+ let lifecycle_enabled = page_lifecycle_events_enabled_for_route(+ conn,+ session_id.as_deref(),+ owner_route,+ );emit_renderer_navigation_load_background_events(out,session_id.as_deref(),@@ -245,11 +263,18 @@ pub(crate) fn emit_bound_renderer_document_lifecycle_background_events(| RendererLifecycleStartReason::JavascriptDocumentReplacement,} => {let frame_identity = conn- .target_session_owner_frame_tree_identity(owner_session_id)+ .target_session_owner_frame_tree_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ).map(|(_, url, security_origin, secure_context_type)| {(url, security_origin, secure_context_type)});for session_id in &session_ids {+ let owner_route = session_id+ .is_none()+ .then_some(owner.session_owner_route())+ .flatten();if let Some((url, security_origin, secure_context_type)) =frame_identity.as_ref(){@@ -264,8 +289,11 @@ pub(crate) fn emit_bound_renderer_document_lifecycle_background_events(secure_context_type.clone(),));}- let lifecycle_enabled =- page_lifecycle_events_enabled_for_session(conn, session_id.as_deref());+ let lifecycle_enabled = page_lifecycle_events_enabled_for_route(+ conn,+ session_id.as_deref(),+ owner_route,+ );emit_navigation_lifecycle_init_background_events(out,session_id.as_deref(),@@ -282,11 +310,12 @@ pub(crate) fn emit_bound_renderer_document_lifecycle_background_events(}}-fn page_lifecycle_events_enabled_for_session(+fn page_lifecycle_events_enabled_for_route(conn: &CdpConnection,session_id: Option<&str>,+ owner_route: Option<&crate::conn::CdpSessionRoute>,) -> bool {- conn.target_page_session_state_for_session(session_id)+ conn.target_page_session_state_for_route(session_id, owner_route).is_some_and(|state| state.page_lifecycle_events)}diff --git a/moli-protocol/src/domains/page/main_document_commit.rs b/moli-protocol/src/domains/page/main_document_commit.rsindex 40b38b482..b44a8a78d 100644--- a/moli-protocol/src/domains/page/main_document_commit.rs+++ b/moli-protocol/src/domains/page/main_document_commit.rs@@ -45,14 +45,19 @@ pub(in crate::domains) async fn project_main_document_commit_async(};for commit in commits {- let Some((current_frame_id, _, _, _)) =- conn.target_session_owner_frame_tree_identity(context.session_id)+ let owner = context.owner();+ let Some((current_frame_id, _, _, _)) = conn+ .target_session_owner_frame_tree_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ )else {continue;};- let Some(current_loader_id) =- conn.target_session_owner_frame_tree_loader_id(context.session_id)- else {+ let Some(current_loader_id) = conn.target_session_owner_frame_tree_loader_id_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {continue;};if current_frame_id != commit.frame_id || current_loader_id != commit.loader_id {@@ -62,11 +67,16 @@ pub(in crate::domains) async fn project_main_document_commit_async(continue;}- let session_ids = conn.page_event_session_ids_for_session_owner(context.session_id);+ let session_ids =+ conn.page_event_session_ids_for_route(owner.session_id(), owner.session_owner_route());let mut events = Vec::new();for session_id in session_ids {+ let event_owner_route = session_id+ .is_none()+ .then_some(owner.session_owner_route())+ .flatten();let lifecycle_enabled = conn- .target_page_session_state_for_session(session_id.as_deref())+ .target_page_session_state_for_route(session_id.as_deref(), event_owner_route).is_some_and(|state| state.page_lifecycle_events);super::emit_navigation_lifecycle_init_background_events(&mut events,@@ -77,8 +87,11 @@ pub(in crate::domains) async fn project_main_document_commit_async(commit.timestamp,);- let dom_enabled =- crate::domains::dom::dom_agent_enabled_for_session(conn, session_id.as_deref());+ let dom_enabled = crate::domains::dom::dom_agent_enabled_for_route(+ conn,+ session_id.as_deref(),+ event_owner_route,+ );super::emit_navigation_frame_commit_background_events(&mut events,session_id.as_deref(),diff --git a/moli-protocol/src/domains/page/navigation.rs b/moli-protocol/src/domains/page/navigation.rsindex a48f62f61..b2af61e1f 100644--- a/moli-protocol/src/domains/page/navigation.rs+++ b/moli-protocol/src/domains/page/navigation.rs@@ -1092,7 +1092,7 @@ fn start_protocol_neutral_navigation_command(is_download: None,},};- let command_owner = CommandOwnerScope::for_implicit_route(Some(route.clone()));+ let command_owner = CommandOwnerScope::for_route(route.clone());let reloaded_after_crash_session_ids = reloaded_after_crash_session_ids(conn, &command_owner);let step = match command {DevToolsCommand::Navigate(command) => {@@ -3365,10 +3365,8 @@ pub(crate) async fn complete_materialized_navigation_into_buffer_async(navigation: network::MaterializedNavigationLoadOutcome,command_context: &mut crate::conn::CommandDispatchContext,) {- let owner = state.owner.clone();- let mut route_scope = owner.enter(conn);complete_materialized_navigation_into_buffer_inner_async(- route_scope.conn_mut(),+ conn,out,token,state,@@ -3386,13 +3384,14 @@ async fn complete_materialized_navigation_into_buffer_inner_async(navigation: network::MaterializedNavigationLoadOutcome,command_context: &mut crate::conn::CommandDispatchContext,) {- let navigation_session_id = state.owner.session_id().map(str::to_owned);+ let navigation_owner = state.owner.clone();+ let navigation_session_id = navigation_owner.session_id().map(str::to_owned);let navigation_loader_id = state.loader_id.clone();match navigation {network::MaterializedNavigationLoadOutcome::ResponseCommitReady(navigation) => {let navigation = *navigation;- let update_result = match conn.prepared_document_commit_configuration_for_session_owner(- state.owner.session_id(),+ let update_result = match conn.prepared_document_commit_configuration_for_owner(+ &state.owner,navigation.final_url(),) {Ok(configuration) => navigation.update_commit_configuration(configuration).await,@@ -3402,14 +3401,14 @@ async fn complete_materialized_navigation_into_buffer_inner_async(push_navigation_commit_error(out, &state, error);} else {let renderer_page = navigation.renderer_page_residence_identity();- let candidate = conn.prepare_renderer_agent_candidate_token_for_session_owner(- state.owner.session_id(),+ let candidate = conn.prepare_renderer_agent_candidate_token_for_owner(+ &state.owner,&token,navigation.renderer_devtools_agent_token(),);match candidate.and_then(|candidate| {- conn.commit_renderer_agent_candidate_for_session_owner(- state.owner.session_id(),+ conn.commit_renderer_agent_candidate_for_owner(+ &state.owner,candidate,renderer_page,)@@ -3434,8 +3433,8 @@ async fn complete_materialized_navigation_into_buffer_inner_async(}Err(error) => {if let Err(rollback_error) = conn- .rollback_committed_renderer_agent_candidate_for_session_owner(- state.owner.session_id(),+ .rollback_committed_renderer_agent_candidate_for_owner(+ &state.owner,transaction,){@@ -3474,15 +3473,11 @@ async fn complete_materialized_navigation_into_buffer_inner_async(.await;}network::MaterializedNavigationLoadOutcome::Download(navigation) => {- let _ = conn.clear_pending_navigation_history_update_for_session_owner(- state.owner.session_id(),- );+ let _ = conn.clear_pending_navigation_history_update_for_owner(&state.owner);commit_download_navigation_async(conn, out, state, navigation, command_context).await;}network::MaterializedNavigationLoadOutcome::Failed(navigation) => {- let _ = conn.clear_pending_navigation_history_update_for_session_owner(- state.owner.session_id(),- );+ let _ = conn.clear_pending_navigation_history_update_for_owner(&state.owner);let network::MaterializedFailedDocumentProgress {error_text,document_policy,@@ -3491,8 +3486,8 @@ async fn complete_materialized_navigation_into_buffer_inner_async(} = navigation;if document_policy.invalidates_committed_document() {let _ = conn- .discard_loaded_page_after_failed_navigation_for_session_owner_async(- state.owner.session_id(),+ .discard_loaded_page_after_failed_navigation_for_owner_async(+ &state.owner,&state.requested_url,).await;@@ -3506,13 +3501,13 @@ async fn complete_materialized_navigation_into_buffer_inner_async(}}let primary_protocol_session_id = conn- .runtime_session_owner_primary_session_id(navigation_session_id.as_deref())+ .runtime_session_owner_primary_session_id_for_route(+ navigation_owner.session_id(),+ navigation_owner.session_owner_route(),+ ).or_else(|| navigation_session_id.clone());let (routed_renderer_output, renderer_call_replacements) = conn- .finish_renderer_document_navigation_for_session_owner(- navigation_session_id.as_deref(),- &token,- )+ .finish_renderer_document_navigation_for_owner(&navigation_owner, &token).map(|finish| (finish.released_output, finish.renderer_call_replacements)).unwrap_or_default();if !routed_renderer_output.is_empty() {@@ -3544,8 +3539,8 @@ async fn complete_materialized_navigation_into_buffer_inner_async(),}}- conn.clear_pending_document_navigation_for_session_owner_if_loader_matches(- navigation_session_id.as_deref(),+ conn.clear_pending_document_navigation_for_owner_if_loader_matches(+ &navigation_owner,&navigation_loader_id,);}diff --git a/moli-protocol/src/domains/page/navigation_commit.rs b/moli-protocol/src/domains/page/navigation_commit.rsindex bd2973138..d9d605769 100644--- a/moli-protocol/src/domains/page/navigation_commit.rs+++ b/moli-protocol/src/domains/page/navigation_commit.rs@@ -63,7 +63,6 @@ pub(super) async fn commit_loaded_navigation_async(return;};let is_network_error_page = network_error_page.is_some();- let navigation_session_id = state.owner.session_id().map(str::to_owned);let (page_creation_artifacts, mut deferred_initial_renderer_document_lifecycle_events) =split_renderer_page_creation_lifecycle_at_load_boundary(page_creation_artifacts);let mut navigation_activity = MainDocumentNavigationActivity::new(@@ -94,8 +93,8 @@ pub(super) async fn commit_loaded_navigation_async(return;};if !is_network_error_page {- let _ = conn.commit_main_document_resource_for_session_owner(- navigation_session_id.as_deref(),+ let _ = conn.commit_main_document_resource_for_owner(+ &navigation_activity.state().owner,navigation_activity.state().frame_id.clone(),navigation_activity.state().loader_id.clone(),final_url.clone(),@@ -109,16 +108,16 @@ pub(super) async fn commit_loaded_navigation_async(preload_channel_execution_context_ids: _,} = commit;let (renderer_document_binding, mut initial_renderer_document_lifecycle_events) = conn- .bind_renderer_document_lifecycle_for_session_owner(- navigation_activity.state().owner.session_id(),+ .bind_renderer_document_lifecycle_for_owner(+ &navigation_activity.state().owner,page_creation_artifacts,token.cloned(),navigation_activity.state().frame_id.clone(),navigation_activity.state().loader_id.clone(),);let load_visibility_barrier_armed = renderer_document_binding.is_some()- && conn.begin_renderer_document_load_visibility_barrier_for_session_owner(- navigation_activity.state().owner.session_id(),+ && conn.begin_renderer_document_load_visibility_barrier_for_owner(+ &navigation_activity.state().owner,&navigation_activity.state().loader_id,);if load_visibility_barrier_armed {@@ -127,8 +126,8 @@ pub(super) async fn commit_loaded_navigation_async(// into the Page output FIFO, even if it is produced before protocol// finishes installing this binding. Never read the Page back here:// ordered ingress and the commit cursor preserve that handoff.- let (_, visible_events) = conn.ingest_renderer_document_lifecycle_events_for_session_owner(- navigation_activity.state().owner.session_id(),+ let (_, visible_events) = conn.ingest_renderer_document_lifecycle_events_for_owner(+ &navigation_activity.state().owner,std::mem::take(&mut deferred_initial_renderer_document_lifecycle_events),);initial_renderer_document_lifecycle_events.extend(visible_events);@@ -137,10 +136,7 @@ pub(super) async fn commit_loaded_navigation_async(deferred_initial_renderer_document_lifecycle_events,);if let Some(engine) = navigation_engine {- conn.adopt_loaded_navigation_engine_for_session_owner(- navigation_session_id.as_deref(),- engine,- );+ conn.adopt_loaded_navigation_engine_for_owner(&navigation_activity.state().owner, engine);}// Keep the loaded commit tail boxed: the target/Patchright CDP test thread@@ -266,7 +262,7 @@ async fn restore_and_commit_loaded_navigation_page_async(if let Some(transaction) = committed_renderer_attachment.as_ref() {if token != Some(transaction.navigation())|| transaction.current().agent_token() != page_agent_token- || conn.current_renderer_agent_attachment_id_for_session_owner(state.owner.session_id())+ || conn.current_renderer_agent_attachment_id_for_owner(&state.owner)!= Some(transaction.current().id()){tracing::warn!(@@ -279,11 +275,7 @@ async fn restore_and_commit_loaded_navigation_page_async(}let renderer_agent_candidate = match (token, committed_renderer_attachment.as_ref()) {(Some(token), None) => {- match conn.prepare_renderer_agent_candidate_for_session_owner(- state.owner.session_id(),- token,- &mut page,- ) {+ match conn.prepare_renderer_agent_candidate_for_owner(&state.owner, token, &mut page) {Ok(candidate) => Some(candidate),Err(error) => {tracing::debug!(@@ -298,9 +290,7 @@ async fn restore_and_commit_loaded_navigation_page_async(}_ => None,};- let Some(commit_state) =- conn.prepare_loaded_navigation_commit_for_session_owner(state.owner.session_id())- else {+ let Some(commit_state) = conn.prepare_loaded_navigation_commit_for_owner(&state.owner) else {return Some(outcome);};let permission_overrides = conn@@ -447,8 +437,8 @@ async fn restore_and_commit_loaded_navigation_page_async(}let page_commit_started = timing_enabled.then(std::time::Instant::now);let page_commit = match conn- .commit_loaded_navigation_page_for_session_owner_async(- state.owner.session_id(),+ .commit_loaded_navigation_page_for_owner_async(+ &state.owner,page,match committed_renderer_attachment {Some(transaction) => {@@ -492,22 +482,17 @@ async fn restore_and_commit_loaded_navigation_page_async(.response_flush().defer_until_response_flush(move || continuation.release());}- let _ = conn.commit_loaded_navigation_target_identity_for_session_owner(- state.owner.session_id(),+ let _ = conn.commit_loaded_navigation_target_identity_for_owner(+ &state.owner,main_document_commit,target_url,);if commit_state.runtime_frontend_enabled {- let _ = conn.set_renderer_runtime_agent_owns_page_console_api_events_for_session_owner(- state.owner.session_id(),- true,- );+ let _ = conn+ .set_renderer_runtime_agent_owns_page_console_api_events_for_owner(&state.owner, true);}if let Some(token) = token {- conn.commit_document_navigation_for_session_owner_if_matches(- state.owner.session_id(),- token,- );+ conn.commit_document_navigation_for_owner_if_matches(&state.owner, token);}if let Some(started) = page_commit_started {tracing::info!(@@ -523,8 +508,10 @@ async fn restore_and_commit_loaded_navigation_page_async();}let preload_channel_execution_context_ids = if conn- .target_owner_has_bidi_channel_preload_script_for_session(state.owner.session_id())- {+ .target_owner_has_bidi_channel_preload_script_for_route(+ state.owner.session_id(),+ state.owner.session_owner_route(),+ ) {dedupe_preload_channel_execution_context_ids(std::mem::take(&mut outcome.preload_channel_execution_context_ids,))diff --git a/moli-protocol/src/domains/page/preload.rs b/moli-protocol/src/domains/page/preload.rsindex 8e0686083..f5e11c87e 100644--- a/moli-protocol/src/domains/page/preload.rs+++ b/moli-protocol/src/domains/page/preload.rs@@ -399,7 +399,7 @@ async fn execute_devtools_single_route_preload_command_async(Ok(resolved) => resolved,Err(error) => return (Err(error), Vec::new(), None),};- let owner = CommandOwnerScope::for_implicit_route(Some(route));+ let owner = CommandOwnerScope::for_route(route);let mut events = Vec::new();let mut command_context = CommandDispatchContext::default();let result = match command {@@ -480,7 +480,7 @@ async fn execute_devtools_browser_context_add_preload_script_command(target_id: active_target_id,is_attached_session: false,};- let owner = CommandOwnerScope::for_implicit_route(Some(route));+ let owner = CommandOwnerScope::for_route(route);append_loaded_page_document_start_script_for_owner_async(conn, &owner, &renderer_script).await.map_err(|message| devtools_preload_owner_error(&message))?;@@ -710,7 +710,7 @@ async fn execute_devtools_bidi_browser_context_remove_preload_script_command(target_id: active_target_id,is_attached_session: false,};- let owner = CommandOwnerScope::for_implicit_route(Some(route));+ let owner = CommandOwnerScope::for_route(route);remove_loaded_page_document_start_script_for_owner_async(conn, &owner, registry_key).await.map_err(|message| devtools_preload_owner_error(&message))?;diff --git a/moli-protocol/src/domains/page/termination.rs b/moli-protocol/src/domains/page/termination.rsindex 8f2cb24ca..684a35789 100644--- a/moli-protocol/src/domains/page/termination.rs+++ b/moli-protocol/src/domains/page/termination.rs@@ -537,15 +537,12 @@ pub(super) async fn complete_crash_command_dispatch(.as_deref().map(CommandOwnerScope::for_session).unwrap_or_else(|| owner.clone());- let mut route_scope = inspector_owner.enter(conn);- route_scope- .conn_mut()- .fail_pending_inspector_awaits_for_session_owner_background_events_into(- &mut pending_await_events,- command_context.protocol_events_mut(),- inspector_session_id.as_deref(),- "Page crashed",- );+ conn.fail_pending_inspector_awaits_for_owner_background_events_into(+ &mut pending_await_events,+ command_context.protocol_events_mut(),+ &inspector_owner,+ "Page crashed",+ );}out.extend(pending_await_events);@@ -660,17 +657,12 @@ pub(super) async fn complete_close_command_dispatch() = take_pending_fetch_state_for_owner(conn, owner);let mut pending_await_events = Vec::new();- {- let mut route_scope = owner.enter(conn);- route_scope- .conn_mut()- .fail_pending_inspector_awaits_for_session_owner_background_events_into(- &mut pending_await_events,- command_context.protocol_events_mut(),- session_id,- "Page closed",- );- }+ conn.fail_pending_inspector_awaits_for_owner_background_events_into(+ &mut pending_await_events,+ command_context.protocol_events_mut(),+ owner,+ "Page closed",+ );out.extend(pending_await_events);let renderer_output_predecessor = fail_pending_fetch_state_for_owner_background_events_async(diff --git a/moli-protocol/src/domains/page/tests/document_content.rs b/moli-protocol/src/domains/page/tests/document_content.rsindex c5a4a17e3..6fde96bd2 100644--- a/moli-protocol/src/domains/page/tests/document_content.rs+++ b/moli-protocol/src/domains/page/tests/document_content.rs@@ -47,8 +47,8 @@ async fn install_document_content_test_page(ctx: &mut TestContext, url: &str) {"the fixture should not leave buffered Inspector output behind");}- let (binding, _) = ctx.conn.bind_renderer_document_lifecycle_for_session_owner(- Some("SID-1"),+ let (binding, _) = ctx.conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),artifacts,Some(committed_document),"TID-1".to_owned(),@@ -56,8 +56,10 @@ async fn install_document_content_test_page(ctx: &mut TestContext, url: &str) {);assert!(binding.is_some(), "renderer lifecycle should bind");if let Some(navigation_engine) = navigation_engine {- ctx.conn- .adopt_loaded_navigation_engine_for_session_owner(Some("SID-1"), navigation_engine);+ ctx.conn.adopt_loaded_navigation_engine_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),+ navigation_engine,+ );}// The fixture commits an already-running renderer Page directly instead// of going through the production navigation command. Route that exact@@ -1705,12 +1707,10 @@ async fn root_set_document_content_unloads_descendant_frame_before_clearing_pare"data:text/html,<body><iframe srcdoc='<body>child</body>'></iframe></body>",).await;+ let owner = crate::conn::CommandOwnerScope::for_session("SID-1");let pending = ctx.conn- .start_child_frame_lifecycle_work_for_session_owner(- Some("SID-1"),- std::time::Duration::from_secs(2),- )+ .start_child_frame_lifecycle_work_for_owner(owner, std::time::Duration::from_secs(2)).expect("loaded page should expose child-frame lifecycle work");let completed = pending.wait()diff --git a/moli-protocol/src/domains/page/tests/frame_tree.rs b/moli-protocol/src/domains/page/tests/frame_tree.rsindex 49d1cc19a..9f9f8138e 100644--- a/moli-protocol/src/domains/page/tests/frame_tree.rs+++ b/moli-protocol/src/domains/page/tests/frame_tree.rs@@ -1,9 +1,10 @@use super::*;async fn complete_child_frame_lifecycle(ctx: &mut TestContext) {+ let owner = crate::conn::CommandOwnerScope::capture(&ctx.conn, None);let pending = ctx.conn- .start_child_frame_lifecycle_work_for_session_owner(None, std::time::Duration::from_secs(2))+ .start_child_frame_lifecycle_work_for_owner(owner, std::time::Duration::from_secs(2)).expect("loaded page should expose child-frame lifecycle work");let completed = pending.wait()diff --git a/moli-protocol/src/domains/page/tests/lifecycle.rs b/moli-protocol/src/domains/page/tests/lifecycle.rsindex c21ef7a54..8f76f40ec 100644--- a/moli-protocol/src/domains/page/tests/lifecycle.rs+++ b/moli-protocol/src/domains/page/tests/lifecycle.rs@@ -285,8 +285,8 @@ async fn install_runtime_document_replacement_test_page(ctx: &mut TestContext) -.active_page_state_mut().runtime_slot.set_loaded_page_for_test(navigation.page);- let (binding, initial_events) = ctx.conn.bind_renderer_document_lifecycle_for_session_owner(- Some("SID-1"),+ let (binding, initial_events) = ctx.conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),artifacts,None,"TID-1".to_owned(),@@ -299,8 +299,10 @@ async fn install_runtime_document_replacement_test_page(ctx: &mut TestContext) -"prepared data navigation commits at DOMContentLoaded; load remains renderer-owned tail work");if let Some(navigation_engine) = navigation_engine {- ctx.conn- .adopt_loaded_navigation_engine_for_session_owner(Some("SID-1"), navigation_engine);+ ctx.conn.adopt_loaded_navigation_engine_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),+ navigation_engine,+ );}ctx.enable_dom_events_for_test(Some("SID-1"));@@ -373,8 +375,8 @@ fn take_released_renderer_load_event() -> moli_core::page::RendererDocumentLifecycleEvent {let released = ctx.conn- .release_renderer_document_load_visibility_barrier_for_session_owner(- Some(session_id),+ .release_renderer_document_load_visibility_barrier_for_owner(+ &crate::conn::CommandOwnerScope::for_session(session_id),LOADER_ID,).expect("load visibility barrier should remain active");@@ -842,8 +844,8 @@ async fn set_lifecycle_events_enabled_replays_loaded_page_events() {.active_page_state_mut().runtime_slot.set_loaded_page_for_test(navigation.page);- let (binding, initial_events) = ctx.conn.bind_renderer_document_lifecycle_for_session_owner(- Some("SID-1"),+ let (binding, initial_events) = ctx.conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),navigation.page_creation_artifacts,None,"TID-1".to_owned(),@@ -852,8 +854,10 @@ async fn set_lifecycle_events_enabled_replays_loaded_page_events() {assert!(binding.is_some());assert_eq!(initial_events.len(), 2);if let Some(navigation_engine) = navigation_engine {- ctx.conn- .adopt_loaded_navigation_engine_for_session_owner(Some("SID-1"), navigation_engine);+ ctx.conn.adopt_loaded_navigation_engine_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),+ navigation_engine,+ );}let load_timestamp = wait_for_visible_renderer_load(&mut ctx, "SID-1").await@@ -916,8 +920,8 @@ async fn set_lifecycle_events_enabled_replays_only_protocol_visible_load_state().active_page_state_mut().runtime_slot.set_loaded_page_for_test(navigation.page);- let (binding, initial_events) = ctx.conn.bind_renderer_document_lifecycle_for_session_owner(- Some("SID-visible"),+ let (binding, initial_events) = ctx.conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-visible"),artifacts,None,"TID-visible".to_owned(),@@ -926,15 +930,15 @@ async fn set_lifecycle_events_enabled_replays_only_protocol_visible_load_state()assert!(binding.is_some());assert_eq!(initial_events.len(), 2);if let Some(navigation_engine) = navigation_engine {- ctx.conn.adopt_loaded_navigation_engine_for_session_owner(- Some("SID-visible"),+ ctx.conn.adopt_loaded_navigation_engine_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-visible"),navigation_engine,);}assert!(ctx.conn- .begin_renderer_document_load_visibility_barrier_for_session_owner(- Some("SID-visible"),+ .begin_renderer_document_load_visibility_barrier_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-visible"),LOADER_ID,));@@ -1018,8 +1022,8 @@ async fn set_lifecycle_events_enabled_is_session_local_for_active_auxiliary_sess.runtime_slot.set_loaded_page_for_test(navigation.page);assert!(browser_context.assign_auxiliary_session_to_target("TID-active", "SID-aux".to_owned()));- let (binding, initial_events) = ctx.conn.bind_renderer_document_lifecycle_for_session_owner(- Some("SID-aux"),+ let (binding, initial_events) = ctx.conn.bind_renderer_document_lifecycle_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-aux"),artifacts,None,"TID-active".to_owned(),@@ -1028,8 +1032,10 @@ async fn set_lifecycle_events_enabled_is_session_local_for_active_auxiliary_sessassert!(binding.is_some());assert_eq!(initial_events.len(), 2);if let Some(navigation_engine) = navigation_engine {- ctx.conn- .adopt_loaded_navigation_engine_for_session_owner(Some("SID-aux"), navigation_engine);+ ctx.conn.adopt_loaded_navigation_engine_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-aux"),+ navigation_engine,+ );}let _ = wait_for_visible_renderer_load(&mut ctx, "SID-aux").await;ctx.sent.clear();@@ -1564,7 +1570,7 @@ async fn runtime_document_close_emits_lifecycle_for_repeated_playwright_set_contfor iteration in 0..32 {let previous_document = ctx.conn- .target_root_document_lifecycle_identity_for_session(Some("SID-1"))+ .target_root_document_lifecycle_identity_for_route(Some("SID-1"), None).expect("the previous replacement must retain an exact Document identity");let id = 100 + iteration;ctx.process_async(json!({diff --git a/moli-protocol/src/domains/page/tests/navigation.rs b/moli-protocol/src/domains/page/tests/navigation.rsindex 6bcba1a36..6ea4ca36e 100644--- a/moli-protocol/src/domains/page/tests/navigation.rs+++ b/moli-protocol/src/domains/page/tests/navigation.rs@@ -238,10 +238,11 @@ async fn renderer_navigation_background_events_keep_typed_sidecars() {);let mut events = Vec::new();- crate::domains::page::navigate_session_owner_from_renderer_background_events_async(+ let owner = crate::conn::CommandOwnerScope::for_session("SID-typed");+ crate::domains::page::navigate_command_owner_from_renderer_background_events_async(&mut ctx.conn,&mut events,- Some("SID-typed"),+ &owner,"data:text/html,<body>typed</body>",).await;@@ -320,10 +321,11 @@ async fn renderer_fragment_navigation_preserves_initial_document_residence() {.expect("initial renderer Page residence");let mut events = Vec::new();- crate::domains::page::navigate_session_owner_from_renderer_background_events_async(+ let owner = crate::conn::CommandOwnerScope::for_session("SID-renderer-fragment");+ crate::domains::page::navigate_command_owner_from_renderer_background_events_async(&mut ctx.conn,&mut events,- Some("SID-renderer-fragment"),+ &owner,"about:blank#popup",).await;diff --git a/moli-protocol/src/domains/performance.rs b/moli-protocol/src/domains/performance.rsindex 62c3f8e86..534f1d096 100644--- a/moli-protocol/src/domains/performance.rs+++ b/moli-protocol/src/domains/performance.rs@@ -976,41 +976,18 @@ mod tests {).await;- let background_route = ctx- .conn- .target_session_route_for_target_id("TID-performance-background")- .expect("background Performance route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route.clone()));- let enable = ctx- .conn- .start_command_dispatch(r#"{"id":4200,"method":"Performance.enable"}"#);+ let enable = ctx.conn.start_command_dispatch(+ r#"{"id":4200,"method":"Performance.enable","sessionId":"SID-performance-background"}"#,+ );let enable_messages = complete_immediate_command_task_step_for_test(enable);- ctx.conn- .replace_none_session_owner_route_override(previous_route);assert_eq!(enable_messages[0]["result"], json!({}));- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route));- let pending = ctx- .conn- .start_command_dispatch(r#"{"id":4201,"method":"Performance.getMetrics"}"#);- ctx.conn- .replace_none_session_owner_route_override(previous_route);+ let pending = ctx.conn.start_command_dispatch(+ r#"{"id":4201,"method":"Performance.getMetrics","sessionId":"SID-performance-background"}"#,+ );assert!(matches!(pending, CdpCommandTaskStep::Pending(_)));- let active_route = ctx- .conn- .target_session_route_for_target_id("TID-performance-active")- .expect("active Performance route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(active_route));let messages = complete_command_task_step_for_test(&mut ctx, pending, 4201).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);let response = messages.iter().find(|message| message["id"] == json!(4201))@@ -1019,7 +996,6 @@ mod tests {metric_map(response)["Nodes"] >= 8.0,"completion must finish the snapshot on the captured background Page");- assert_eq!(ctx.conn.none_session_owner_route_override(), None);}#[tokio::test(flavor = "multi_thread")]diff --git a/moli-protocol/src/domains/runtime.rs b/moli-protocol/src/domains/runtime.rsindex 3f572419e..dfcbf8f93 100644--- a/moli-protocol/src/domains/runtime.rs+++ b/moli-protocol/src/domains/runtime.rs@@ -20,6 +20,7 @@ pub(crate) use dispatcher::{complete_pending_runtime_command_at_response_boundary,devtools_deep_serialization_options_json,execute_devtools_runtime_command_async_with_protocol_events,+ execute_runtime_listener_command_for_owner,start_bidi_preload_channel_listeners_for_execution_context_background_events_async,start_console_inspector_command_dispatch, start_debugger_inspector_command_dispatch,start_heap_profiler_inspector_command_dispatch, start_moli_diagnostics_command_dispatch,diff --git a/moli-protocol/src/domains/runtime/activity.rs b/moli-protocol/src/domains/runtime/activity.rsindex 93d90b652..d4da9fbd7 100644--- a/moli-protocol/src/domains/runtime/activity.rs+++ b/moli-protocol/src/domains/runtime/activity.rs@@ -2,7 +2,7 @@ use crate::domains::activity::{ProtocolOutputPayloads, ProtocolOutputProjectionContext, ProtocolOutputSink, ProtocolOutputSlot,};use crate::{- conn::{BackgroundProtocolEvent, CdpConnection},+ conn::{BackgroundProtocolEvent, CdpConnection, CommandOwnerScope},domains::command_output::protocol_message_background_event_for_target,domains::runtime_context_events::{RuntimeContextProtocolEvent, apply_runtime_context_protocol_event_side_effects_typed,@@ -265,12 +265,13 @@ pub(in crate::domains) async fn project_runtime_inspector_post_response_messagesimpl RuntimePreparedOutputs {pub(crate) fn from_renderer_runtime_binding_call(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,call: moli_core::page::PendingRuntimeBindingCall,) -> Self {- let Some(attachment) =- conn.target_page_protocol_attachment_identity_for_session(session_id)- else {+ let Some(attachment) = conn.target_page_protocol_attachment_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ) else {return Self::default();};Self {@@ -287,14 +288,14 @@ impl RuntimePreparedOutputs {pub(crate) fn from_renderer_runtime_inspector_message_batches(conn: &mut CdpConnection,- source_session_id: Option<&str>,+ source_owner: &CommandOwnerScope,batches: &[RendererRuntimeInspectorMessageBatch],) -> Self {let mut outputs = Self::default();for batch in batches.iter().filter(|batch| !batch.messages.is_empty()) {let Some(attachment) = conn- .target_page_protocol_attachment_identity_for_renderer_inspector_route(- source_session_id,+ .target_page_protocol_attachment_identity_for_renderer_inspector_owner(+ source_owner,batch.session.wire_session_id(),)else {@@ -356,7 +357,7 @@ impl RuntimePreparedOutputs {/// from the retired document are discarded.pub(crate) fn from_retired_renderer_runtime_inspector_session_responses(conn: &mut CdpConnection,- source_session_id: Option<&str>,+ source_owner: &CommandOwnerScope,batches: &[RendererRuntimeInspectorMessageBatch],) -> Self {let mut outputs = Self::default();@@ -365,8 +366,8 @@ impl RuntimePreparedOutputs {continue;};let Some(protocol_attachment) = conn- .target_page_protocol_attachment_identity_for_renderer_inspector_route(- source_session_id,+ .target_page_protocol_attachment_identity_for_renderer_inspector_owner(+ source_owner,batch.session.wire_session_id(),)else {@@ -536,8 +537,12 @@ pub(in crate::domains) fn push_routed_renderer_runtime_inspector_message_batch_bbatches: Vec<RendererRuntimeInspectorMessageBatch>,session_id: Option<&str>,) {+ let owner = match session_id {+ Some(session_id) => CommandOwnerScope::for_session(session_id),+ None => CommandOwnerScope::capture(conn, None),+ };let prepared = RuntimePreparedOutputs::from_renderer_runtime_inspector_message_batches(- conn, session_id, &batches,+ conn, &owner, &batches,);for batch in prepared.inspector_message_batches@@ -567,7 +572,7 @@ mod tests {use serde_json::Value;use serde_json::json;- use crate::conn::{BrowserContext, CdpConnection, CommandDispatchContext};+ use crate::conn::{BrowserContext, CdpConnection, CommandDispatchContext, CommandOwnerScope};use crate::devtools_runtime::AutomationEvent;use crate::domains::activity::{ProtocolOutputPayloads, ProtocolOutputProjectionContext};use crate::testing::TestContext;@@ -666,6 +671,10 @@ mod tests {renderer_inspector_session_id: Option<&str>,messages: Vec<Value>,) -> RuntimePreparedOutputs {+ let owner = match source_session_id {+ Some(session_id) => CommandOwnerScope::for_session(session_id),+ None => CommandOwnerScope::capture(conn, None),+ };let session = renderer_inspector_session_id.map_or(DevToolsSessionKey::Primary, |session_id| {DevToolsSessionKey::Attached(session_id.to_owned())@@ -676,9 +685,7 @@ mod tests {renderer_messages(messages),)];RuntimePreparedOutputs::from_renderer_runtime_inspector_message_batches(- conn,- source_session_id,- &batches,+ conn, &owner, &batches,)}@@ -708,7 +715,7 @@ mod tests {let outputs = RuntimePreparedOutputs::from_renderer_runtime_inspector_message_batches(&mut conn,- Some("SID-1"),+ &CommandOwnerScope::for_session("SID-1"),&batches,);@@ -729,16 +736,13 @@ mod tests {) -> Vec<crate::conn::BackgroundProtocolEvent> {let mut prepared =ProtocolOutputPayloads::from_slot(RuntimePreparedOutputSlot::from_outputs(outputs));+ let owner = match drain_session_id {+ Some(session_id) => crate::conn::CommandOwnerScope::for_session(session_id),+ None => crate::conn::CommandOwnerScope::capture(conn, None),+ };let mut command_context = CommandDispatchContext::default();{- let mut context = ProtocolOutputProjectionContext {- session_id: drain_session_id,- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::project_runtime_inspector_messages_async(conn,&mut context,@@ -803,7 +807,7 @@ mod tests {let outputs =RuntimePreparedOutputs::from_retired_renderer_runtime_inspector_session_responses(&mut ctx.conn,- Some("SID-1"),+ &CommandOwnerScope::for_session("SID-1"),&[batch],);let outputs_after_detach = outputs.clone();@@ -885,15 +889,9 @@ mod tests {#[tokio::test(flavor = "multi_thread")]async fn runtime_binding_drain_consumes_prepared_events_without_page_readback() {let (mut conn, attachment) = runtime_binding_attachment_fixture();+ let owner = crate::conn::CommandOwnerScope::for_session("SID-drain-current");let mut command_context = CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: Some("SID-drain-current"),- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);let mut prepared = prepared_runtime_binding_calls(attachment);super::project_runtime_binding_calls_async(&mut conn, &mut context, Some(&mut prepared))@@ -922,15 +920,9 @@ mod tests {conn.runtime_session_owner_slot_mut(Some("SID-1")).expect("Runtime binding target").replace_page_attachment_id_for_test();+ let owner = crate::conn::CommandOwnerScope::for_session("SID-1");let mut command_context = CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: Some("SID-1"),- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::project_runtime_binding_calls_async(&mut conn, &mut context, Some(&mut prepared)).await;@@ -957,15 +949,9 @@ mod tests {));let mut prepared =ProtocolOutputPayloads::from_slot(RuntimePreparedOutputSlot::from_outputs(outputs));+ let owner = crate::conn::CommandOwnerScope::for_session("SID-unrelated-drain");let mut command_context = CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: Some("SID-unrelated-drain"),- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::project_runtime_binding_calls_async(&mut conn, &mut context, Some(&mut prepared)).await;@@ -993,15 +979,9 @@ mod tests {.as_deref(),Some("SID-1"),);+ let owner = crate::conn::CommandOwnerScope::capture(&conn, None);let mut command_context = CommandDispatchContext::default();- let mut context = ProtocolOutputProjectionContext {- session_id: None,- command: &mut command_context,- subresource_frame_id: None,- subresource_document_url: None,- subresource_timestamp: None,- subresource_network_request_id: None,- };+ let mut context = ProtocolOutputProjectionContext::new(&owner, &mut command_context);super::project_runtime_binding_calls_async(&mut conn, &mut context, Some(&mut prepared)).await;diff --git a/moli-protocol/src/domains/runtime/bidi_nodes.rs b/moli-protocol/src/domains/runtime/bidi_nodes.rsindex c7953e12b..9686337b1 100644--- a/moli-protocol/src/domains/runtime/bidi_nodes.rs+++ b/moli-protocol/src/domains/runtime/bidi_nodes.rs@@ -4,7 +4,7 @@ use moli_core::page::{};use serde_json::{Map, Value, json};-use crate::conn::CdpConnection;+use crate::conn::{CdpConnection, CommandOwnerScope};use crate::devtools_runtime::{DevToolsError, DevToolsErrorKind, DevToolsRemoteHandleId, DevToolsRemoteValue,DevToolsSerializationOptions, webdriver_bidi_node_shared_id_for_backend_node_id,@@ -26,19 +26,20 @@ pub(super) struct BidiNodeSerializationOptions {pub(super) async fn bidi_node_snapshot_for_shared_id_async(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,shared_id: &str,depth: i32,pierce: bool,) -> Result<Option<DocumentNodeObjectSnapshot>, DevToolsError> {match conn- .document_bidi_node_binding_for_session_owner_async(None, shared_id)+ .document_bidi_node_binding_for_owner_async(owner, shared_id).await.map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))?{RendererDomBidiNodeBindingResolution::BackendNodeId(backend_node_id) => {return conn- .document_node_snapshot_for_backend_node_id_async(- None,+ .document_node_snapshot_for_backend_node_id_for_owner_async(+ owner,backend_node_id,depth,pierce,@@ -48,9 +49,11 @@ pub(super) async fn bidi_node_snapshot_for_shared_id_async(}RendererDomBidiNodeBindingResolution::NotFound => {}}- conn.document_node_snapshot_for_runtime_remote_object_id_async(None, shared_id, depth, pierce)- .await- .map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))+ conn.document_node_snapshot_for_runtime_remote_object_id_for_owner_async(+ owner, shared_id, depth, pierce,+ )+ .await+ .map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))}pub(super) fn bidi_node_shared_id_for_snapshot(diff --git a/moli-protocol/src/domains/runtime/bindings.rs b/moli-protocol/src/domains/runtime/bindings.rsindex dcaac3acf..ffe2d1258 100644--- a/moli-protocol/src/domains/runtime/bindings.rs+++ b/moli-protocol/src/domains/runtime/bindings.rs@@ -1,6 +1,6 @@use serde::Deserialize;-use crate::conn::CdpConnection;+use crate::conn::{CdpConnection, CommandOwnerScope};#[derive(Deserialize)]#[serde(rename_all = "camelCase")]@@ -12,35 +12,41 @@ pub(super) struct AddBindingParams {pub(super) execution_context_id: Option<i64>,}-pub(super) fn persist_runtime_binding_definition_for_session_owner(+pub(super) fn persist_runtime_binding_definition_for_owner(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,name: String,execution_context_name: Option<String>,) -> Result<(), String> {- conn.with_target_devtools_session_state_for_session_mut(session_id, |state| {- state.upsert_runtime_binding_definition(name, execution_context_name);- })+ conn.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.upsert_runtime_binding_definition(name, execution_context_name),+ ).ok_or_else(|| "BrowserContextNotLoaded".to_owned())}-pub(super) fn remove_runtime_binding_definitions_for_session_owner(+pub(super) fn remove_runtime_binding_definitions_for_owner(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,name: &str,) -> Result<(), String> {- conn.with_target_devtools_session_state_for_session_mut(session_id, |state| {- state.remove_runtime_binding_definitions(name);- })+ conn.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.remove_runtime_binding_definitions(name),+ ).ok_or_else(|| "BrowserContextNotLoaded".to_owned())}-pub(super) fn clear_runtime_binding_definitions_for_session_owner(+pub(super) fn clear_runtime_binding_definitions_for_owner(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Result<(), String> {- conn.with_target_devtools_session_state_for_session_mut(session_id, |state| {- state.clear_runtime_binding_definitions();- })+ conn.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.clear_runtime_binding_definitions(),+ ).ok_or_else(|| "BrowserContextNotLoaded".to_owned())}diff --git a/moli-protocol/src/domains/runtime/dispatcher.rs b/moli-protocol/src/domains/runtime/dispatcher.rsindex 821810fba..07285e156 100644--- a/moli-protocol/src/domains/runtime/dispatcher.rs+++ b/moli-protocol/src/domains/runtime/dispatcher.rs@@ -15,9 +15,8 @@ use crate::devtools_runtime::{webdriver_bidi_node_shared_id_for_backend_node_id,};use moli_core::page::{- BidiPreloadChannelHandoff, DocumentNodeObjectSnapshot, DocumentNodeSnapshot,- MAX_INSPECTOR_PROTOCOL_VALUE_DEPTH, RendererCommandTurnOutput,- RendererDomBidiNodeBindingResolution, RendererRuntimeCommandOutput,+ BidiPreloadChannelHandoff, DocumentNodeSnapshot, MAX_INSPECTOR_PROTOCOL_VALUE_DEPTH,+ RendererCommandTurnOutput, RendererDomBidiNodeBindingResolution, RendererRuntimeCommandOutput,RendererRuntimeInspectorMessage,};use moli_page_types::RendererInspectorResponseDelivery;@@ -32,10 +31,10 @@ use crate::conn::{CompletedServiceWorkerRuntimeProtocolMessageDispatch,CompletedSharedWorkerRuntimeProtocolMessageDispatch, DevToolsCommandDispatchOutcome,DevToolsCommandExecutionOutput, DuplicatePendingRendererCommand, InspectorCommandDispatch,- NoneSessionOwnerRouteOverrideScope, ParsedCdpCommand, PendingBidiChannelListener,- PendingMoliDiagnosticsDispatch, PendingRuntimeBindingPageCommandDispatch,- PendingRuntimeChildDefaultContextLookupDispatch, PendingRuntimeEnableEventsDispatch,- PendingRuntimeProtocolMessageDispatch, PendingServiceWorkerRuntimeProtocolMessageDispatch,+ ParsedCdpCommand, PendingBidiChannelListener, PendingMoliDiagnosticsDispatch,+ PendingRuntimeBindingPageCommandDispatch, PendingRuntimeChildDefaultContextLookupDispatch,+ PendingRuntimeEnableEventsDispatch, PendingRuntimeProtocolMessageDispatch,+ PendingServiceWorkerRuntimeProtocolMessageDispatch,PendingSharedWorkerRuntimeProtocolMessageDispatch, ProfilerInspectorCommand,RendererCommandDescriptor, RuntimeBindingDefinition, RuntimeEnableReplayEvent,RuntimeInspectorAsyncCompletionReceiver, RuntimeInspectorResponseReady,@@ -47,16 +46,19 @@ use crate::domains::actions::{ConsoleAction, HeapProfilerAction, RuntimeAction};use crate::domains::command_output::{CommandOutputPlan, devtools_error_from_cdp_error_parts, devtools_error_from_cdp_error_value,};-use crate::domains::console::apply_console_output_state_for_session;+use crate::domains::console::{+ apply_console_output_state_for_owner, apply_console_output_state_for_session,+};use crate::domains::observable_output::{+ advance_runtime_observable_cursors_to_current_for_owner,advance_runtime_observable_cursors_to_current_for_session_owner,runtime_console_api_called_background_event, runtime_console_message_type_and_text,runtime_exception_thrown_background_event,};use crate::domains::runtime_context_events::{- RuntimeContextProtocolEvent, apply_runtime_context_protocol_event_side_effects_typed,+ RuntimeContextProtocolEvent, apply_runtime_context_protocol_event_side_effects_for_owner_typed,emit_runtime_context_protocol_background_event_typed,- should_emit_child_default_context_inventory_replay_once,+ should_emit_child_default_context_inventory_replay_once_for_owner,};const SHARED_WORKER_RUNTIME_BINDING_REPLAY_COMMAND_ID_BASE: u64 = 900_000_000;@@ -76,9 +78,8 @@ use super::{devtools_serialization_options_for_node_probe,},bindings::{- AddBindingParams, clear_runtime_binding_definitions_for_session_owner,- persist_runtime_binding_definition_for_session_owner,- remove_runtime_binding_definitions_for_session_owner,+ AddBindingParams, clear_runtime_binding_definitions_for_owner,+ persist_runtime_binding_definition_for_owner, remove_runtime_binding_definitions_for_owner,},command_classification::{MainRuntimeCommand, MainRuntimeInspectorCommand, RuntimeBindingCommand,@@ -248,15 +249,6 @@ pub(crate) enum RuntimeCommandTaskStep {Complete(CommandOutputPlan),}-impl RuntimeCommandTaskStep {- fn with_owner_scope(mut self, owner_scope: CommandOwnerScope) -> Self {- if let RuntimeCommandTaskStep::Pending(pending) = &mut self {- pending.owner_scope = owner_scope;- }- self- }-}-enum PendingRuntimeCommandKind {Inspector {pending: PendingRuntimeProtocolMessageDispatch,@@ -381,7 +373,7 @@ impl RuntimeInspectorRoutedOutput {fn register_object_group_for_success(&self,conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_group: Option<&str>,) {let Some(object_group) = object_group else {@@ -391,14 +383,14 @@ impl RuntimeInspectorRoutedOutput {if let Some((_, _, BackgroundCommandResponsePayloadRef::Success { result })) =event.command_response_payload_ref(){- conn.register_runtime_remote_object_ids_from_value_for_session_owner_with_group(- session_id,+ conn.register_runtime_remote_object_ids_from_value_for_owner_with_group(+ owner,result,object_group,);} else if let Some(message) = event.protocol_message() {- conn.register_runtime_remote_object_ids_from_value_for_session_owner_with_group(- session_id,+ conn.register_runtime_remote_object_ids_from_value_for_owner_with_group(+ owner,message,object_group,);@@ -531,6 +523,11 @@ impl PendingRuntimeCommandDispatch {self.owner_scope.session_id()}+ #[cfg(test)]+ pub(crate) fn owner_scope(&self) -> &CommandOwnerScope {+ &self.owner_scope+ }+pub(crate) fn executes_page_javascript(&self) -> bool {matches!(self.action,@@ -602,20 +599,16 @@ impl PendingRuntimeCommandDispatch {return false;}let owner_scope = self.owner_scope.clone();- let session_id = self.session_id().map(str::to_owned);let mut response_events = Vec::new();let mut background_events = Vec::new();- let mut route_scope = owner_scope.enter(conn);- let (routed, renderer_output_predecessor) = route_scope- .conn_mut()+ let (routed, renderer_output_predecessor) = conn.route_scheduler_deferred_runtime_inspector_response_into(response,- session_id.as_deref(),+ &owner_scope,&mut response_events,&mut background_events,).await;- drop(route_scope);if let Some(predecessor) = renderer_output_predecessor {let PendingRuntimeCommandKind::InspectorDeferredReply { routed_output, .. } =&mut self.pending@@ -641,13 +634,12 @@ impl PendingRuntimeCommandDispatch {let response = response_rx.await.map_err(|_| "RuntimeDeferredInspectorResponseCanceled".to_owned());- let session_id = self.session_id().map(str::to_owned);let routed = self.route_scheduler_deferred_inspector_response(conn,- crate::conn::RuntimeInspectorResponseReady::new(+ crate::conn::RuntimeInspectorResponseReady::for_owner(command_id,- session_id.as_deref(),+ &self.owner_scope,response,),)@@ -667,13 +659,10 @@ impl PendingRuntimeCommandDispatch {renderer_response_rx: _,claimed_await,} => {- let mut route_scope = owner_scope.enter(conn);- route_scope- .conn_mut()- .complete_claimed_pending_inspector_await_for_scheduler_deferred_reply(- claimed_await,- routed_output.events(),- );+ conn.complete_claimed_pending_inspector_await_for_scheduler_deferred_reply(+ claimed_await,+ routed_output.events(),+ );CompletedRuntimeCommandKind::InspectorDeferredReplyReady { routed_output }}_ => {@@ -696,23 +685,17 @@ impl PendingRuntimeCommandDispatch {}pub(crate) fn forget_scheduler_deferred_inspector_reply(self, conn: &mut CdpConnection) {- let session_id = self.owner_scope.session_id().map(str::to_owned);let owner_scope = self.owner_scope.clone();- let mut route_scope = owner_scope.enter(conn);match self.pending {PendingRuntimeCommandKind::InspectorDeferredReply { claimed_await, .. } => {- route_scope- .conn_mut()- .cancel_claimed_pending_inspector_await_for_scheduler_deferred_reply(- claimed_await,- "forgotten",- );+ conn.cancel_claimed_pending_inspector_await_for_scheduler_deferred_reply(+ claimed_await,+ "forgotten",+ );}_ => {if let Some(command_id) = self.command_id {- route_scope- .conn_mut()- .forget_pending_inspector_await(command_id, session_id.as_deref());+ conn.forget_pending_inspector_await_for_owner(command_id, &owner_scope);}}}@@ -878,6 +861,43 @@ fn runtime_object_group_for_command_result(}}+fn runtime_object_group_for_command_result_for_owner(+ conn: &CdpConnection,+ cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,+ action: RuntimeAction,+) -> Option<String> {+ match action {+ RuntimeAction::Evaluate => runtime_object_group_from_params(cmd.params).map(str::to_owned),+ RuntimeAction::CallFunctionOn => runtime_object_group_from_params(cmd.params)+ .map(str::to_owned)+ .or_else(|| {+ conn.runtime_remote_object_group_for_owner(+ owner,+ runtime_object_id_from_params(cmd.params)?,+ )+ }),+ RuntimeAction::GetProperties => conn.runtime_remote_object_group_for_owner(+ owner,+ runtime_object_id_from_params(cmd.params)?,+ ),+ RuntimeAction::AwaitPromise => conn.runtime_remote_object_group_for_owner(+ owner,+ runtime_promise_object_id_from_params(cmd.params)?,+ ),+ RuntimeAction::RunScript => runtime_object_group_from_params(cmd.params).map(str::to_owned),+ RuntimeAction::QueryObjects => runtime_object_group_from_params(cmd.params)+ .map(str::to_owned)+ .or_else(|| {+ conn.runtime_remote_object_group_for_owner(+ owner,+ runtime_prototype_object_id_from_params(cmd.params)?,+ )+ }),+ _ => None,+ }+}+fn runtime_command_awaits_promise(cmd: &Cmd<'_>, action: RuntimeAction) -> bool {action == RuntimeAction::AwaitPromise|| cmd@@ -943,20 +963,33 @@ fn start_main_runtime_inspector_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,command: MainRuntimeInspectorCommand,+) -> RuntimeCommandTaskStep {+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);+ start_main_runtime_inspector_command_for_owner(conn, cmd, command, owner_scope)+}++fn start_main_runtime_inspector_command_for_owner(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+ command: MainRuntimeInspectorCommand,+ owner_scope: CommandOwnerScope,) -> RuntimeCommandTaskStep {let action = command.action();let action_label = action.label();let await_promise = runtime_command_awaits_promise(cmd, action);- let inspector_json =- match prepare_runtime_inspector_payload(conn, cmd, command.payload_preparation()) {- Ok(json) => json,- Err(message) => {- return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(- cmd.id, message,- ));- }- };- let object_group = runtime_object_group_for_command_result(conn, cmd, action);+ let inspector_json = match prepare_runtime_inspector_payload_for_owner(+ conn,+ cmd,+ &owner_scope,+ command.payload_preparation(),+ ) {+ Ok(json) => json,+ Err(message) => {+ return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(cmd.id, message));+ }+ };+ let object_group =+ runtime_object_group_for_command_result_for_owner(conn, cmd, &owner_scope, action);let release_object_ids = if action == RuntimeAction::ReleaseObject {cmd.params.map(runtime_remote_object_ids_in_map)@@ -969,12 +1002,11 @@ fn start_main_runtime_inspector_command(} else {None};- let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pre_registered_await = match pre_register_runtime_await_if_needed(conn,await_promise,cmd.id,- cmd.session_id,+ &owner_scope,object_group.as_deref(),action_label,) {@@ -989,6 +1021,7 @@ fn start_main_runtime_inspector_command(let pending = match start_pending_runtime_routable_inspector_dispatch(conn,cmd,+ &owner_scope,inspector_json,if await_promise {RendererInspectorResponseDelivery::CommandReply@@ -998,7 +1031,7 @@ fn start_main_runtime_inspector_command() {Ok(pending) => pending,Err(message) => {- forget_pre_registered_runtime_await(conn, pre_registered_await, cmd.session_id);+ forget_pre_registered_runtime_await(conn, pre_registered_await, &owner_scope);return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(cmd.id, message));}};@@ -1048,9 +1081,11 @@ pub(crate) fn start_profiler_inspector_command_dispatch(}let action = dispatch.protocol_method();+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pending = match start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,dispatch.into_inspector_json(),cmd.terminal_response_delivery(RendererInspectorResponseDelivery::DevToolsSession),) {@@ -1063,7 +1098,7 @@ pub(crate) fn start_profiler_inspector_command_dispatch(RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {command_id: cmd.id,action,- owner_scope: CommandOwnerScope::capture(conn, cmd.session_id),+ owner_scope,object_group: None,release_object_ids: Vec::new(),release_object_group: None,@@ -1135,9 +1170,11 @@ pub(crate) fn start_heap_profiler_inspector_command_dispatch(let method = heap_profiler_action_protocol_method(action);let object_group = heap_profiler_object_group_for_command_result(cmd, action);+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pending = match start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,cmd.json.to_owned(),RendererInspectorResponseDelivery::CommandReply,) {@@ -1150,7 +1187,7 @@ pub(crate) fn start_heap_profiler_inspector_command_dispatch(RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {command_id: cmd.id,action: method,- owner_scope: CommandOwnerScope::capture(conn, cmd.session_id),+ owner_scope,object_group,release_object_ids: Vec::new(),release_object_group: None,@@ -1185,11 +1222,13 @@ pub(crate) fn start_debugger_inspector_command_dispatch());}+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pending = match cmd.renderer_policy().access() {CdpRendererCommandAccess::MainThread => {start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,inspector_json,cmd.terminal_response_delivery(RendererInspectorResponseDelivery::DevToolsSession),)@@ -1197,6 +1236,7 @@ pub(crate) fn start_debugger_inspector_command_dispatch(CdpRendererCommandAccess::Io => start_pending_runtime_io_inspector_dispatch(conn,cmd,+ &owner_scope,inspector_json,cmd.terminal_response_delivery(RendererInspectorResponseDelivery::DevToolsSession),),@@ -1215,7 +1255,7 @@ pub(crate) fn start_debugger_inspector_command_dispatch(RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {command_id: cmd.id,action: "Debugger.inspectorCommand",- owner_scope: CommandOwnerScope::capture(conn, cmd.session_id),+ owner_scope,object_group: None,release_object_ids: Vec::new(),release_object_group: None,@@ -1402,9 +1442,11 @@ pub(crate) fn start_console_inspector_command_dispatch());}+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pending = match start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,cmd.json.to_owned(),cmd.terminal_response_delivery(RendererInspectorResponseDelivery::DevToolsSession),) {@@ -1417,7 +1459,7 @@ pub(crate) fn start_console_inspector_command_dispatch(RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {command_id: cmd.id,action: console_action_protocol_method(action),- owner_scope: CommandOwnerScope::capture(conn, cmd.session_id),+ owner_scope,object_group: None,release_object_ids: Vec::new(),release_object_group: None,@@ -1589,64 +1631,69 @@ fn try_start_pending_runtime_enable_command(cmd: &Cmd<'_>,) -> Option<RuntimeCommandTaskStep> {let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);- let has_loaded_page = match conn.runtime_session_owner_slot(cmd.session_id) {+ Some(start_runtime_enable_command_for_owner(+ conn,+ cmd.id,+ owner_scope,+ ))+}++fn start_runtime_enable_command_for_owner(+ conn: &mut CdpConnection,+ command_id: Option<u64>,+ owner_scope: CommandOwnerScope,+) -> RuntimeCommandTaskStep {+ let has_loaded_page = match conn.runtime_session_owner_slot_for_route(+ owner_scope.session_id(),+ owner_scope.session_owner_route(),+ ) {Ok(slot) => slot.has_loaded_page(),- Err(_) if cmd.session_id.is_some() => {- return Some(RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(+ Err(_) if owner_scope.session_id().is_some() => {+ return RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(-32001,"Unknown sessionId",- )));+ ));}Err(_) => {- match conn.set_runtime_frontend_enabled_for_session_owner(cmd.session_id, true) {+ match conn.set_runtime_frontend_enabled_for_owner(&owner_scope, true) {SessionOwnerRuntimeFrontendEnableResult::Handled => {}SessionOwnerRuntimeFrontendEnableResult::UnknownSession => {- return Some(RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(+ return RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(-32001,"Unknown sessionId",- )));+ ));}}- return Some(RuntimeCommandTaskStep::Complete(- CommandOutputPlan::success(),- ));+ return RuntimeCommandTaskStep::Complete(CommandOutputPlan::success());}};if !has_loaded_page {if conn.can_defer_initial_document_page_build() {- match conn.set_runtime_frontend_enabled_for_session_owner(cmd.session_id, true) {+ match conn.set_runtime_frontend_enabled_for_owner(&owner_scope, true) {SessionOwnerRuntimeFrontendEnableResult::Handled => {}SessionOwnerRuntimeFrontendEnableResult::UnknownSession => {- return Some(RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(+ return RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(-32001,"Unknown sessionId",- )));+ ));}}- return Some(RuntimeCommandTaskStep::Complete(- CommandOutputPlan::success(),- ));+ return RuntimeCommandTaskStep::Complete(CommandOutputPlan::success());}- return Some(RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(+ return RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(-32000,"NoDocumentLoaded",- )));+ ));}- Some(start_pending_runtime_enable_events_phase(- conn,- cmd.id,- cmd.session_id,- owner_scope,- ))+ start_pending_runtime_enable_events_phase(conn, command_id, owner_scope)}fn start_pending_runtime_enable_events_phase(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,owner_scope: CommandOwnerScope,) -> RuntimeCommandTaskStep {- match conn.start_runtime_enable_events_for_session_owner(session_id) {+ match conn.start_runtime_enable_events_for_owner(&owner_scope) {Ok(pending) => RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {command_id,action: "enable",@@ -1667,9 +1714,9 @@ fn start_pending_runtime_enable_events_phase(fn runtime_remove_binding_should_skip_live_page_update(conn: &CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> bool {- conn.target_runtime_session_state_for_session(session_id)+ conn.target_runtime_session_state_for_route(owner.session_id(), owner.session_owner_route()).is_some_and(|state| state.runtime_frontend_enabled)}@@ -1741,10 +1788,18 @@ fn try_start_pending_runtime_binding_command(skip_live_page_update_after_inspector_success: false,};let live_page_update_unavailable = conn- .runtime_session_owner_slot(cmd.session_id)+ .runtime_session_owner_slot_for_route(+ owner_scope.session_id(),+ owner_scope.session_owner_route(),+ ).is_ok_and(|slot| !slot.has_loaded_page())|| should_persist- && conn.renderer_document_navigation_is_suspended_for_session_owner(cmd.session_id);+ && conn+ .runtime_session_owner_slot_for_route(+ owner_scope.session_id(),+ owner_scope.session_owner_route(),+ )+ .is_ok_and(|slot| slot.renderer_document_navigation_is_suspended());if live_page_update_unavailable {task.command_response = Some(RuntimeBindingCommandResponse::empty_success());let meta = RuntimeCommandCompletionMeta {@@ -1763,7 +1818,6 @@ fn try_start_pending_runtime_binding_command(return start_pending_runtime_binding_context_lookup_phase(conn,cmd.id,- cmd.session_id,task,execution_context_id,owner_scope,@@ -1771,7 +1825,7 @@ fn try_start_pending_runtime_binding_command(}if matches!(task.action, RuntimeBindingCommand::Add)|| matches!(task.action, RuntimeBindingCommand::Remove)- && runtime_remove_binding_should_skip_live_page_update(conn, cmd.session_id)+ && runtime_remove_binding_should_skip_live_page_update(conn, &owner_scope){task.skip_live_page_update_after_inspector_success = true;}@@ -1780,12 +1834,14 @@ fn try_start_pending_runtime_binding_command(RuntimeBindingCommand::Add => start_pending_runtime_context_resolved_inspector_dispatch(conn,cmd,+ &owner_scope,action_label,cmd.json.to_owned(),),RuntimeBindingCommand::Remove => start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,cmd.json.to_owned(),RendererInspectorResponseDelivery::CommandReply,),@@ -1816,6 +1872,7 @@ fn try_start_pending_runtime_binding_command(fn start_pending_runtime_routable_inspector_dispatch(conn: &mut CdpConnection,cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,inspector_json: String,response_delivery: RendererInspectorResponseDelivery,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {@@ -1824,6 +1881,7 @@ fn start_pending_runtime_routable_inspector_dispatch(start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ owner,inspector_json,response_delivery,)@@ -1831,6 +1889,7 @@ fn start_pending_runtime_routable_inspector_dispatch(CdpRendererCommandAccess::Io => start_pending_runtime_io_inspector_dispatch(conn,cmd,+ owner,inspector_json,response_delivery,),@@ -1843,6 +1902,7 @@ fn start_pending_runtime_routable_inspector_dispatch(fn start_pending_runtime_io_inspector_dispatch(conn: &mut CdpConnection,cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,inspector_json: String,response_delivery: RendererInspectorResponseDelivery,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {@@ -1852,25 +1912,25 @@ fn start_pending_runtime_io_inspector_dispatch(cmd.renderer_policy(),response_delivery,);- conn.start_runtime_io_protocol_message_for_session_owner_with_deferred_response(- cmd.session_id,- descriptor,- command_id,+ conn.start_runtime_io_protocol_message_for_owner_with_deferred_response(+ owner, descriptor, command_id,)} else {- conn.start_runtime_io_protocol_message_for_session_owner(cmd.session_id, inspector_json)+ conn.start_runtime_io_protocol_message_for_owner(owner, inspector_json)}}fn start_pending_runtime_context_resolved_inspector_dispatch(conn: &mut CdpConnection,cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,action: &'static str,inspector_json: String,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {start_pending_runtime_context_resolved_inspector_dispatch_with_delivery(conn,cmd,+ owner,action,inspector_json,RendererInspectorResponseDelivery::CommandReply,@@ -1880,6 +1940,7 @@ fn start_pending_runtime_context_resolved_inspector_dispatch(fn start_pending_runtime_context_resolved_inspector_dispatch_with_delivery(conn: &mut CdpConnection,cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,action: &'static str,inspector_json: String,response_delivery: RendererInspectorResponseDelivery,@@ -1890,15 +1951,15 @@ fn start_pending_runtime_context_resolved_inspector_dispatch_with_delivery(cmd.renderer_policy(),response_delivery,);- conn.start_runtime_protocol_message_with_context_resolution_for_session_owner_with_deferred_response(- cmd.session_id,+ conn.start_runtime_protocol_message_with_context_resolution_for_owner_with_deferred_response(+ owner,action,descriptor,command_id,)} else {- conn.start_runtime_protocol_message_with_context_resolution_for_session_owner(- cmd.session_id,+ conn.start_runtime_protocol_message_with_context_resolution_for_owner(+ owner,action,inspector_json,)@@ -1908,6 +1969,7 @@ fn start_pending_runtime_context_resolved_inspector_dispatch_with_delivery(fn start_pending_runtime_inspector_dispatch_with_delivery(conn: &mut CdpConnection,cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,inspector_json: String,response_delivery: RendererInspectorResponseDelivery,) -> Result<PendingRuntimeProtocolMessageDispatch, String> {@@ -1917,13 +1979,11 @@ fn start_pending_runtime_inspector_dispatch_with_delivery(cmd.renderer_policy(),response_delivery,);- conn.start_runtime_protocol_message_for_session_owner_with_deferred_response(- cmd.session_id,- descriptor,- command_id,+ conn.start_runtime_protocol_message_for_owner_with_deferred_response(+ owner, descriptor, command_id,)} else {- conn.start_runtime_protocol_message_for_session_owner(cmd.session_id, inspector_json)+ conn.start_runtime_protocol_message_for_owner(owner, inspector_json)}}@@ -2026,11 +2086,21 @@ fn prepare_pending_devtools_runtime_inspector_json(conn: &CdpConnection,cmd: &Cmd<'_>,command: &DevToolsCommand,+) -> Result<String, String> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ prepare_pending_devtools_runtime_inspector_json_for_owner(conn, cmd, &owner, command)+}++fn prepare_pending_devtools_runtime_inspector_json_for_owner(+ conn: &CdpConnection,+ cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,+ command: &DevToolsCommand,) -> Result<String, String> {match command {DevToolsCommand::EvaluateScript(_) => Ok(cmd.json.to_owned()),DevToolsCommand::CallFunction(command) => {- prepare_pending_devtools_call_function_json(conn, cmd, command)+ prepare_pending_devtools_call_function_json_for_owner(conn, cmd, owner, command)}_ => Err("UnsupportedDevToolsCommand".to_owned()),}@@ -2043,6 +2113,27 @@ fn start_devtools_runtime_command(inspector_json: String,wait_for_deferred_reply: bool,response_delivery: RendererInspectorResponseDelivery,+) -> RuntimeCommandTaskStep {+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);+ start_devtools_runtime_command_for_owner(+ conn,+ cmd,+ command,+ inspector_json,+ wait_for_deferred_reply,+ response_delivery,+ owner_scope,+ )+}++fn start_devtools_runtime_command_for_owner(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+ command: DevToolsCommand,+ inspector_json: String,+ wait_for_deferred_reply: bool,+ response_delivery: RendererInspectorResponseDelivery,+ owner_scope: CommandOwnerScope,) -> RuntimeCommandTaskStep {let (action, action_label, await_promise) = match &command {DevToolsCommand::EvaluateScript(command) => {@@ -2060,13 +2151,13 @@ fn start_devtools_runtime_command());}};- let object_group = runtime_object_group_for_command_result(conn, cmd, action);- let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);+ let object_group =+ runtime_object_group_for_command_result_for_owner(conn, cmd, &owner_scope, action);let pre_registered_await = match pre_register_runtime_await_if_needed(conn,await_promise,cmd.id,- cmd.session_id,+ &owner_scope,object_group.as_deref(),action_label,) {@@ -2081,13 +2172,14 @@ fn start_devtools_runtime_command(let pending = match start_pending_runtime_context_resolved_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,action_label,inspector_json,response_delivery,) {Ok(pending) => pending,Err(message) => {- forget_pre_registered_runtime_await(conn, pre_registered_await, cmd.session_id);+ forget_pre_registered_runtime_await(conn, pre_registered_await, &owner_scope);return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(cmd.id, message));}};@@ -2108,7 +2200,7 @@ fn pre_register_runtime_await_if_needed(conn: &mut CdpConnection,await_promise: bool,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,object_group: Option<&str>,action: &'static str,) -> Result<Option<u64>, DuplicatePendingRendererCommand> {@@ -2118,23 +2210,23 @@ fn pre_register_runtime_await_if_needed(let Some(command_id) = command_id else {return Ok(None);};- conn.try_register_pending_inspector_await_with_object_group(+ conn.try_register_pending_inspector_await_with_object_group_for_owner(command_id,- session_id,+ owner,object_group,)?;- conn.register_runtime_await_job(command_id, session_id, object_group, action);- conn.trace_runtime_await_pending_registered(command_id, session_id);+ conn.register_runtime_await_job_for_owner(command_id, owner, object_group, action);+ conn.trace_runtime_await_pending_registered(command_id, owner.session_id());Ok(Some(command_id))}fn forget_pre_registered_runtime_await(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) {if let Some(command_id) = command_id {- conn.forget_pending_inspector_await(command_id, session_id);+ conn.forget_pending_inspector_await_for_owner(command_id, owner);}}@@ -2171,14 +2263,14 @@ pub(crate) async fn execute_devtools_runtime_command_async_with_protocol_events(}DevToolsRuntimeCommandResultKind::Empty => None,};- let mut route_scope = conn.scoped_none_session_owner_route_override(target.route.clone());+ let target_owner = CommandOwnerScope::for_route(target.route.clone());if let DevToolsCommand::CallFunction(call_function) = &mut command&& matches!(call_function.context.protocol,DevToolsProtocol::WebDriverBidi)&& let Err(error) = remap_bidi_node_shared_references_for_target_async(- route_scope.conn_mut(),+ conn,&target,call_function,target_realm.as_ref(),@@ -2188,11 +2280,11 @@ pub(crate) async fn execute_devtools_runtime_command_async_with_protocol_events(return DevToolsCommandExecutionOutput::new(Err(error));}let validation_result = validate_protocol_neutral_runtime_handle_realms(- route_scope.conn_mut(),+ conn,+ &target_owner,&command,target_realm.as_ref(),);- drop(route_scope);if let Err(error) = validation_result {return DevToolsCommandExecutionOutput::new(Err(error));}@@ -2240,11 +2332,9 @@ pub(crate) async fn execute_devtools_runtime_command_async_with_protocol_events();}};- let mut route_scope =- conn.scoped_none_session_owner_route_override(target.route.clone());- register_devtools_script_result_remote_object(route_scope.conn_mut(), &result);+ register_devtools_script_result_remote_object(conn, &target_owner, &result);materialize_devtools_script_dom_collection_remote_value_async(- route_scope.conn_mut(),+ conn,&mut result,serialization_options.as_ref(),&target,@@ -2252,14 +2342,14 @@ pub(crate) async fn execute_devtools_runtime_command_async_with_protocol_events().await;materialize_devtools_script_deep_serialized_root_value_async(- route_scope.conn_mut(),+ conn,&mut result,serialization_options.as_ref(),&target,).await;materialize_devtools_script_node_remote_value_async(- route_scope.conn_mut(),+ conn,&mut result,serialization_options.as_ref(),&target,@@ -2267,7 +2357,7 @@ pub(crate) async fn execute_devtools_runtime_command_async_with_protocol_events().await;materialize_devtools_script_deep_serialized_node_remote_values_async(- route_scope.conn_mut(),+ conn,&mut result,serialization_options.as_ref(),&target,@@ -2276,11 +2366,11 @@ pub(crate) async fn execute_devtools_runtime_command_async_with_protocol_events(.await;materialize_devtools_script_window_remote_value(&mut result, &target);register_devtools_script_result_remote_object_realm(- route_scope.conn_mut(),+ conn,+ &target_owner,&result,target_realm.as_ref(),);- drop(route_scope);return DevToolsCommandExecutionOutput::from_parts(Ok(result),protocol_events,@@ -2305,9 +2395,7 @@ pub(crate) async fn execute_devtools_runtime_command_async_with_protocol_events(} else {pending.wait().await};- let mut route_scope =- conn.scoped_none_session_owner_route_override(target.route.clone());- step = complete_pending_runtime_command(route_scope.conn_mut(), completed).await;+ step = complete_pending_runtime_command(conn, completed).await;}}}@@ -2369,21 +2457,20 @@ impl CdpConnection {}DevToolsRuntimeCommandResultKind::Empty => None,};- let mut route_scope = self.scoped_none_session_owner_route_override(target.route.clone());+ let target_owner = CommandOwnerScope::for_route(target.route.clone());if let DevToolsCommand::CallFunction(call_function) = &mut command&& matches!(call_function.context.protocol,DevToolsProtocol::WebDriverBidi)&& let Err(error) = remap_bidi_node_shared_references_for_target_async(- route_scope.conn_mut(),+ self,&target,call_function,target_realm.as_ref(),).await{- drop(route_scope);return self.complete_devtools_runtime_direct_result(command_context,@@ -2394,11 +2481,11 @@ impl CdpConnection {.await;}let validation_result = validate_protocol_neutral_runtime_handle_realms(- route_scope.conn_mut(),+ self,+ &target_owner,&command,target_realm.as_ref(),);- drop(route_scope);if let Err(error) = validation_result {return self.complete_devtools_runtime_direct_result(@@ -2431,11 +2518,7 @@ impl CdpConnection {&mut self,completed: CompletedDevToolsRuntimeCommandDispatch,) -> DevToolsRuntimeCommandTaskStep {- let route = completed.state.target.route.clone();- let mut route_scope = self.scoped_none_session_owner_route_override(route);- let step =- complete_pending_runtime_command(route_scope.conn_mut(), completed.completed).await;- drop(route_scope);+ let step = complete_pending_runtime_command(self, completed.completed).await;self.complete_devtools_runtime_command_step(completed.state,step,@@ -2521,11 +2604,10 @@ impl CdpConnection {.await;}};- let mut route_scope =- self.scoped_none_session_owner_route_override(state.target.route.clone());- register_devtools_script_result_remote_object(route_scope.conn_mut(), &result);+ let target_owner = CommandOwnerScope::for_route(state.target.route.clone());+ register_devtools_script_result_remote_object(self, &target_owner, &result);materialize_devtools_script_dom_collection_remote_value_async(- route_scope.conn_mut(),+ self,&mut result,state.serialization_options.as_ref(),&state.target,@@ -2533,14 +2615,14 @@ impl CdpConnection {).await;materialize_devtools_script_deep_serialized_root_value_async(- route_scope.conn_mut(),+ self,&mut result,state.serialization_options.as_ref(),&state.target,).await;materialize_devtools_script_node_remote_value_async(- route_scope.conn_mut(),+ self,&mut result,state.serialization_options.as_ref(),&state.target,@@ -2548,7 +2630,7 @@ impl CdpConnection {).await;materialize_devtools_script_deep_serialized_node_remote_values_async(- route_scope.conn_mut(),+ self,&mut result,state.serialization_options.as_ref(),&state.target,@@ -2557,11 +2639,11 @@ impl CdpConnection {.await;materialize_devtools_script_window_remote_value(&mut result, &state.target);register_devtools_script_result_remote_object_realm(- route_scope.conn_mut(),+ self,+ &target_owner,&result,state.target_realm.as_ref(),);- drop(route_scope);self.complete_devtools_runtime_direct_result(state.command_context,Ok(result),@@ -2854,12 +2936,10 @@ async fn renderer_locate_nodes_start_node_reference_for_shared_id_async(target: &DevToolsRuntimeTarget,shared_id: &str,) -> Result<Option<DevToolsDomNodeReference>, DevToolsError> {- let mut route_scope = conn.scoped_none_session_owner_route_override(target.route.clone());- let result = route_scope- .conn_mut()- .document_bidi_node_binding_for_session_owner_async(None, shared_id)+ let owner = CommandOwnerScope::for_route(target.route.clone());+ let result = conn+ .document_bidi_node_binding_for_owner_async(&owner, shared_id).await;- drop(route_scope);match result {Ok(RendererDomBidiNodeBindingResolution::BackendNodeId(backend_node_id)) => Ok(Some(DevToolsDomNodeReference::BackendNodeId(backend_node_id),@@ -3265,7 +3345,7 @@ async fn materialize_locate_nodes_result_node_ids_async(target: &DevToolsRuntimeTarget,result: &mut DevToolsLocateNodesResult,) {- let mut route_scope = conn.scoped_none_session_owner_route_override(target.route.clone());+ let owner = CommandOwnerScope::for_route(target.route.clone());for index in 0..result.nodes.len() {let shared_id = result.nodes[index].shared_id@@ -3273,10 +3353,9 @@ async fn materialize_locate_nodes_result_node_ids_async(.map(|shared_id| shared_id.as_str().to_owned());let mut materialized = false;if let Some(shared_id) = shared_id {- let snapshot = route_scope- .conn_mut()- .document_node_snapshot_for_runtime_remote_object_id_async(- None, &shared_id, 0, false,+ let snapshot = conn+ .document_node_snapshot_for_runtime_remote_object_id_for_owner_async(+ &owner, &shared_id, 0, false,).await;if let Ok(Some(snapshot)) = snapshot {@@ -3292,11 +3371,14 @@ async fn materialize_locate_nodes_result_node_ids_async(if !materialized&& let Some(backend_node_id) = result.nodes[index].backend_node_id- && let Some(snapshot) = locate_nodes_snapshot_for_backend_node_id_async(- route_scope.conn_mut(),- backend_node_id,- )- .await+ && let Ok(Some(snapshot)) = conn+ .document_node_snapshot_for_backend_node_id_for_owner_async(+ &owner,+ backend_node_id,+ 0,+ false,+ )+ .await{result.nodes[index].node_id =frontend_node_id_for_locate_node_snapshot(&snapshot.snapshot);@@ -3304,7 +3386,6 @@ async fn materialize_locate_nodes_result_node_ids_async(snapshot.snapshot.backend_node_id.or(Some(backend_node_id));}}- drop(route_scope);result.node_ids = result.nodes.iter()@@ -3312,22 +3393,6 @@ async fn materialize_locate_nodes_result_node_ids_async(.collect();}-async fn locate_nodes_snapshot_for_backend_node_id_async(- conn: &mut CdpConnection,- backend_node_id: u32,-) -> Option<DocumentNodeObjectSnapshot> {- let pending = conn- .loaded_page_mut_for_protocol_access(None)- .ok()?- .start_document_node_snapshot_for_backend_node_id(backend_node_id, 0, false)- .ok()?;- let completion = pending.wait().await.ok()?;- conn.loaded_page_mut_for_protocol_access(None)- .ok()?- .finish_document_node_snapshot_for_backend_node_id(completion)- .ok()?-}-fn frontend_node_id_for_locate_node_snapshot(snapshot: &DocumentNodeSnapshot) -> Option<u32> {snapshot.frontend_node_id}@@ -3687,15 +3752,13 @@ async fn devtools_runtime_context_target_async(.await?,)} else {- let mut route_scope = conn.scoped_none_session_owner_route_override(route.clone());- let result = route_scope- .conn_mut()- .child_default_execution_context_id_for_frame_id_for_session_owner_async(- None,+ let owner = CommandOwnerScope::for_route(route.clone());+ let result = conn+ .child_default_execution_context_id_for_frame_id_for_owner_async(+ &owner,target_id.as_str(),).await;- drop(route_scope);Some(result.map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))?@@ -3758,16 +3821,10 @@ async fn devtools_ensure_runtime_world_async(frame_id: &DevToolsTargetId,world_name: &str,) -> Result<i64, DevToolsError> {- let mut route_scope = conn.scoped_none_session_owner_route_override(route);- let result = route_scope- .conn_mut()- .runtime_ensure_isolated_world_for_session_owner_async(- None,- Some(frame_id.as_str()),- world_name,- )+ let owner = CommandOwnerScope::for_route(route);+ let result = conn+ .runtime_ensure_isolated_world_for_owner_async(&owner, Some(frame_id.as_str()), world_name).await;- drop(route_scope);result.map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))}@@ -3842,6 +3899,7 @@ async fn remap_bidi_node_shared_references_for_target_async(command: &mut DevToolsCallFunctionCommand,realm_id: Option<&DevToolsRealmId>,) -> Result<(), DevToolsError> {+ let owner = CommandOwnerScope::for_route(target.route.clone());let mut references = Vec::new();if let Some(this_parameter) = command.this_parameter.as_ref() {collect_bidi_node_shared_reference_paths(@@ -3869,12 +3927,9 @@ async fn remap_bidi_node_shared_references_for_target_async(let execution_context_id = if let Some(execution_context_id) = target.execution_context_id {Some(execution_context_id)} else {- let mut route_scope = conn.scoped_none_session_owner_route_override(target.route.clone());- let result = route_scope- .conn_mut()- .runtime_default_or_initial_execution_context_id_for_session_owner_async(None)+ let result = conn+ .runtime_default_or_initial_execution_context_id_for_owner_async(&owner).await;- drop(route_scope);Some(result.map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))?@@ -3887,6 +3942,7 @@ async fn remap_bidi_node_shared_references_for_target_async(for reference in references {let Some(target_shared_id) = remap_bidi_node_shared_id_for_target_async(conn,+ &owner,execution_context_id,&reference.shared_id,realm_id,@@ -3956,12 +4012,13 @@ fn collect_bidi_node_shared_reference_paths(async fn remap_bidi_node_shared_id_for_target_async(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,execution_context_id: Option<i64>,shared_id: &str,realm_id: Option<&DevToolsRealmId>,) -> Result<Option<DevToolsRemoteHandleId>, DevToolsError> {let is_internal_bidi_node_id = is_webdriver_bidi_node_shared_id(shared_id);- let snapshot = bidi_node_snapshot_for_shared_id_async(conn, shared_id, 0, false).await?;+ let snapshot = bidi_node_snapshot_for_shared_id_async(conn, owner, shared_id, 0, false).await?;let Some(snapshot) = snapshot else {return if is_internal_bidi_node_id {Err(DevToolsError::new(@@ -3980,8 +4037,8 @@ async fn remap_bidi_node_shared_id_for_target_async());};let Some(remote_object) = conn- .runtime_remote_object_for_backend_node_id_async(- None,+ .runtime_remote_object_for_backend_node_id_for_owner_async(+ owner,backend_node_id,execution_context_id,None,@@ -4005,24 +4062,25 @@ async fn remap_bidi_node_shared_id_for_target_async());};- register_remapped_bidi_node_remote_object(conn, &remote_object, &object_id, realm_id);+ register_remapped_bidi_node_remote_object(conn, owner, &remote_object, &object_id, realm_id);Ok(Some(DevToolsRemoteHandleId::from(object_id)))}fn register_remapped_bidi_node_remote_object(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,remote_object: &Value,object_id: &str,realm_id: Option<&DevToolsRealmId>,) {if let Some(realm_id) = realm_id {- conn.register_runtime_remote_object_ids_for_session_owner_with_realm(- None,+ conn.register_runtime_remote_object_ids_for_owner_with_realm(+ owner,vec![object_id.to_owned()],realm_id.as_str(),);} else {- conn.register_runtime_remote_object_ids_from_value_for_session_owner(None, remote_object);+ conn.register_runtime_remote_object_ids_from_value_for_owner(owner, remote_object);}}@@ -4345,13 +4403,10 @@ async fn release_bidi_channel_object_group_for_target_best_effort_async(session_id: Option<&str>,object_group: &str,) {- let mut route_scope = conn.scoped_none_session_owner_route_override(target.route.clone());- route_scope- .conn_mut()- .release_bidi_channel_object_group_for_session_owner_best_effort_async(- session_id,- object_group,- )+ let owner = session_id+ .map(CommandOwnerScope::for_session)+ .unwrap_or_else(|| CommandOwnerScope::for_route(target.route.clone()));+ conn.release_bidi_channel_object_group_for_owner_best_effort_async(&owner, object_group).await;}@@ -4363,7 +4418,7 @@ fn bidi_channel_page_owner_for_runtime_target(let exact_owner = owner.session_id().map(CommandOwnerScope::for_session)- .unwrap_or_else(|| CommandOwnerScope::for_implicit_route(Some(target.route.clone())));+ .unwrap_or_else(|| CommandOwnerScope::for_route(target.route.clone()));BidiChannelPageOwner::capture_for_owner(conn, exact_owner)}@@ -4383,7 +4438,7 @@ async fn create_bidi_channel_proxy_and_start_listener_async(let listener_owner = bidi_channel_page_owner_for_runtime_target(conn,target,- &CommandOwnerScope::for_implicit_route(Some(target.route.clone())),+ &CommandOwnerScope::for_route(target.route.clone()),).ok_or_else(|| "NoSuchBidiChannelTarget".to_owned())?;let channel_object_group = conn.next_bidi_channel_object_group();@@ -4571,9 +4626,8 @@ async fn start_protocol_neutral_runtime_command(command: DevToolsCommand,internal_command_id: u64,) -> RuntimeCommandTaskStep {- let session_owner_route = target.route.clone();- let mut route_scope = conn.scoped_none_session_owner_route_override(target.route.clone());- let step = match command {+ let owner = CommandOwnerScope::for_route(target.route.clone());+ match command {DevToolsCommand::EvaluateScript(command) => {let params = devtools_evaluate_script_params(&command, target.execution_context_id);let json =@@ -4590,18 +4644,17 @@ async fn start_protocol_neutral_runtime_command(let cmd = Cmd::from_parsed(&parsed).expect("synthesized Runtime command must contain a domain separator");let command = DevToolsCommand::EvaluateScript(command);- match prepare_pending_devtools_runtime_inspector_json(- route_scope.conn_mut(),- &cmd,- &command,+ match prepare_pending_devtools_runtime_inspector_json_for_owner(+ conn, &cmd, &owner, &command,) {- Ok(inspector_json) => start_devtools_runtime_command(- route_scope.conn_mut(),+ Ok(inspector_json) => start_devtools_runtime_command_for_owner(+ conn,&cmd,command,inspector_json,runtime_command_awaits_promise(&cmd, RuntimeAction::Evaluate),RendererInspectorResponseDelivery::CommandReply,+ owner.clone(),),Err(message) => {RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(cmd.id, message))@@ -4611,7 +4664,7 @@ async fn start_protocol_neutral_runtime_command(DevToolsCommand::CallFunction(mut command) => {if matches!(command.context.protocol, DevToolsProtocol::WebDriverBidi)&& let Err(message) = Box::pin(materialize_bidi_channel_argument_proxies_async(- route_scope.conn_mut(),+ conn,&target,&mut command,))@@ -4623,7 +4676,8 @@ async fn start_protocol_neutral_runtime_command());}match devtools_call_function_params_async(- route_scope.conn_mut(),+ conn,+ &owner,&command,target.execution_context_id,)@@ -4647,18 +4701,17 @@ async fn start_protocol_neutral_runtime_command(let cmd = Cmd::from_parsed(&parsed).expect("synthesized Runtime command must contain a domain separator");let command = DevToolsCommand::CallFunction(command);- match prepare_pending_devtools_runtime_inspector_json(- route_scope.conn_mut(),- &cmd,- &command,+ match prepare_pending_devtools_runtime_inspector_json_for_owner(+ conn, &cmd, &owner, &command,) {- Ok(inspector_json) => start_devtools_runtime_command(- route_scope.conn_mut(),+ Ok(inspector_json) => start_devtools_runtime_command_for_owner(+ conn,&cmd,command,inspector_json,runtime_command_awaits_promise(&cmd, RuntimeAction::CallFunctionOn),RendererInspectorResponseDelivery::CommandReply,+ owner.clone(),),Err(message) => RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(cmd.id, message),@@ -4693,16 +4746,12 @@ async fn start_protocol_neutral_runtime_command(else {unreachable!("Runtime.terminateExecution must use an Inspector command route")};- start_main_runtime_inspector_command(route_scope.conn_mut(), &cmd, command)+ start_main_runtime_inspector_command_for_owner(conn, &cmd, command, owner.clone())}_ => RuntimeCommandTaskStep::Complete(CommandOutputPlan::from_devtools_error(DevToolsError::new(DevToolsErrorKind::Unsupported, "UnsupportedDevToolsCommand"),)),- };- drop(route_scope);- step.with_owner_scope(CommandOwnerScope::for_implicit_route(Some(- session_owner_route,- )))+ }}fn runtime_inspector_command_json(command_id: u64, method: &str, params: &Value) -> String {@@ -4760,6 +4809,7 @@ fn devtools_evaluate_script_params(async fn devtools_call_function_params_async(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,command: &DevToolsCallFunctionCommand,execution_context_id: Option<i64>,) -> Result<Value, String> {@@ -4802,7 +4852,7 @@ async fn devtools_call_function_params_async(map.insert("executionContextId".to_owned(), json!(execution_context_id));} else if command.realm_id.is_none() {let Some(execution_context_id) = conn- .runtime_default_or_initial_execution_context_id_for_session_owner_async(None)+ .runtime_default_or_initial_execution_context_id_for_owner_async(owner).await?else {return Err("NoDefaultExecutionContext".to_owned());@@ -5647,6 +5697,7 @@ fn devtools_empty_result_from_response(fn validate_protocol_neutral_runtime_handle_realms(conn: &CdpConnection,+ owner: &CommandOwnerScope,command: &DevToolsCommand,target_realm: Option<&DevToolsRealmId>,) -> Result<(), DevToolsError> {@@ -5660,7 +5711,7 @@ fn validate_protocol_neutral_runtime_handle_realms(let references = devtools_call_function_remote_references(command);for reference in references {- if !conn.runtime_remote_object_id_known_for_session_owner(None, &reference.object_id) {+ if !conn.runtime_remote_object_id_known_for_owner(owner, &reference.object_id) {return Err(match reference.kind {RuntimeRemoteReferenceKind::Node => DevToolsError::new(DevToolsErrorKind::NoSuchNode,@@ -5675,7 +5726,7 @@ fn validate_protocol_neutral_runtime_handle_realms(if reference.kind == RuntimeRemoteReferenceKind::Object&& let Some(target_realm) = target_realm&& let Some(owner_realm) =- conn.runtime_remote_object_realm_for_session_owner(None, &reference.object_id)+ conn.runtime_remote_object_realm_for_owner(owner, &reference.object_id)&& owner_realm != target_realm.as_str(){return Err(DevToolsError::new(@@ -5689,6 +5740,7 @@ fn validate_protocol_neutral_runtime_handle_realms(fn register_devtools_script_result_remote_object_realm(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,result: &DevToolsCommandResult,realm_id: Option<&DevToolsRealmId>,) {@@ -5702,18 +5754,18 @@ fn register_devtools_script_result_remote_object_realm(return;};if let Some(object_id) =- conn.runtime_remote_object_alias_for_session_owner(None, remote_object_id.as_str())+ conn.runtime_remote_object_alias_for_owner(owner, remote_object_id.as_str()){- conn.register_runtime_remote_object_alias_for_session_owner_with_realm(- None,+ conn.register_runtime_remote_object_alias_for_owner_with_realm(+ owner,remote_object_id.as_str().to_owned(),object_id,realm_id.as_str(),);return;}- conn.register_runtime_remote_object_ids_for_session_owner_with_realm(- None,+ conn.register_runtime_remote_object_ids_for_owner_with_realm(+ owner,vec![remote_object_id.as_str().to_owned()],realm_id.as_str(),);@@ -5721,6 +5773,7 @@ fn register_devtools_script_result_remote_object_realm(fn register_devtools_script_result_remote_object(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,result: &DevToolsCommandResult,) {let Some(value) = devtools_script_result_remote_value(result) else {@@ -5729,8 +5782,8 @@ fn register_devtools_script_result_remote_object(let Some(remote_object_id) = value.handle.as_ref().or(value.shared_id.as_ref()) else {return;};- conn.register_runtime_remote_object_ids_from_value_for_session_owner(- None,+ conn.register_runtime_remote_object_ids_from_value_for_owner(+ owner,&json!({ "objectId": remote_object_id.as_str() }),);}@@ -5826,7 +5879,6 @@ async fn devtools_probe_remote_value_async(target: DevToolsRuntimeTarget,command: DevToolsCommand,) -> Result<Option<DevToolsRemoteValue>, DevToolsError> {- let target_route = target.route.clone();let result_ownership = devtools_runtime_result_ownership(&command);let internal_command_id = conn.next_internal_runtime_command_id();let mut step =@@ -5857,39 +5909,12 @@ async fn devtools_probe_remote_value_async(}RuntimeCommandTaskStep::Pending(pending) => {let completed = pending.wait().await;- let mut scope = RuntimeProbeCompletionScope::enter(conn, target_route.clone());- step = complete_pending_runtime_command(scope.conn_mut(), completed).await;+ step = complete_pending_runtime_command(conn, completed).await;}}}}-struct RuntimeProbeCompletionScope<'a> {- route_scope: NoneSessionOwnerRouteOverrideScope<'a>,-}--impl<'a> RuntimeProbeCompletionScope<'a> {- fn enter(conn: &'a mut CdpConnection, target_route: CdpSessionRoute) -> Self {- Self {- route_scope: conn.scoped_none_session_owner_route_override(target_route),- }- }-- fn conn_mut(&mut self) -> &mut CdpConnection {- self.route_scope.conn_mut()- }-- fn restore(&mut self) {- self.route_scope.restore();- }-}--impl Drop for RuntimeProbeCompletionScope<'_> {- fn drop(&mut self) {- self.restore();- }-}-async fn materialize_devtools_script_deep_serialized_root_value_async(conn: &mut CdpConnection,result: &mut DevToolsCommandResult,@@ -6254,6 +6279,7 @@ async fn materialize_devtools_script_node_remote_value_async(target: &DevToolsRuntimeTarget,realm_id: Option<&DevToolsRealmId>,) {+ let owner = CommandOwnerScope::for_route(target.route.clone());let Some(value) = devtools_script_result_remote_value_mut(result) else {return;};@@ -6266,7 +6292,9 @@ async fn materialize_devtools_script_node_remote_value_async(if value.remote_subtype.as_deref() != Some("node") && !is_attribute_node {return;}- if materialize_devtools_script_node_remote_value_from_deep_serialized(conn, value, realm_id) {+ if materialize_devtools_script_node_remote_value_from_deep_serialized(+ conn, &owner, value, realm_id,+ ) {return;}let Some(shared_id) = value@@ -6278,8 +6306,8 @@ async fn materialize_devtools_script_node_remote_value_async(};let node_options = bidi_node_serialization_options(serialization_options);let object_snapshot = match conn- .document_node_snapshot_for_runtime_remote_object_id_async(- None,+ .document_node_snapshot_for_runtime_remote_object_id_for_owner_async(+ &owner,&shared_id,node_options.snapshot_depth,true,@@ -6334,8 +6362,8 @@ async fn materialize_devtools_script_node_remote_value_async(else {return;};- register_bidi_node_bindings_for_snapshot_tree(conn, &object_snapshot.snapshot).await;- register_bidi_node_shared_id_alias(conn, &canonical_shared_id, &shared_id, realm_id);+ register_bidi_node_bindings_for_snapshot_tree(conn, &owner, &object_snapshot.snapshot).await;+ register_bidi_node_shared_id_alias(conn, &owner, &canonical_shared_id, &shared_id, realm_id);value.node_id = object_snapshot.snapshot.frontend_node_id;value.backend_node_id = object_snapshot.snapshot.backend_node_id;value.shared_id = Some(canonical_shared_id);@@ -6597,6 +6625,7 @@ async fn materialize_bidi_dom_collection_entries_async(node_options: &BidiNodeSerializationOptions,realm_id: Option<&DevToolsRealmId>,) -> Vec<Value> {+ let owner = CommandOwnerScope::for_route(target.route.clone());let mut entries = Vec::new();for index in 0..length {let js_path = [json!({@@ -6636,14 +6665,16 @@ async fn materialize_bidi_dom_collection_entries_async(if let Some(remote) =bidi_node_remote_value_from_deep_serialized_remote_value(&remote_value){- register_devtools_script_remote_object_realm(conn, &object_id, realm_id);- register_bidi_node_remote_value_shared_id_alias(conn, &remote, &object_id, realm_id);+ register_devtools_script_remote_object_realm(conn, &owner, &object_id, realm_id);+ register_bidi_node_remote_value_shared_id_alias(+ conn, &owner, &remote, &object_id, realm_id,+ );entries.push(remote);continue;}let object_snapshot = match conn- .document_node_snapshot_for_runtime_remote_object_id_async(- None,+ .document_node_snapshot_for_runtime_remote_object_id_for_owner_async(+ &owner,&object_id,node_options.snapshot_depth,true,@@ -6664,12 +6695,13 @@ async fn materialize_bidi_dom_collection_entries_async(let Some(object_snapshot) = object_snapshot else {continue;};- register_devtools_script_remote_object_realm(conn, &object_id, realm_id);+ register_devtools_script_remote_object_realm(conn, &owner, &object_id, realm_id);let Some(shared_id) = bidi_node_shared_id_for_snapshot(&object_snapshot.snapshot) else {continue;};- register_bidi_node_bindings_for_snapshot_tree(conn, &object_snapshot.snapshot).await;- register_bidi_node_shared_id_alias(conn, &shared_id, &object_id, realm_id);+ register_bidi_node_bindings_for_snapshot_tree(conn, &owner, &object_snapshot.snapshot)+ .await;+ register_bidi_node_shared_id_alias(conn, &owner, &shared_id, &object_id, realm_id);entries.push(bidi_node_remote_value_from_snapshot(&object_snapshot.snapshot,shared_id,@@ -6688,6 +6720,7 @@ async fn materialize_devtools_script_deep_serialized_node_remote_value_async(serialization_options: Option<&DevToolsSerializationOptions>,realm_id: Option<&DevToolsRealmId>,) -> Option<Value> {+ let owner = CommandOwnerScope::for_route(target.route.clone());let remote_value = match devtools_deep_serialized_path_remote_value_async(conn,target,@@ -6713,14 +6746,16 @@ async fn materialize_devtools_script_deep_serialized_node_remote_value_async(.as_ref().map(|shared_id| shared_id.as_str().to_owned())?;if let Some(remote) = bidi_node_remote_value_from_deep_serialized_remote_value(&remote_value) {- register_devtools_script_remote_object_realm(conn, &object_id, realm_id);- register_bidi_node_remote_value_shared_id_alias(conn, &remote, &object_id, realm_id);+ register_devtools_script_remote_object_realm(conn, &owner, &object_id, realm_id);+ register_bidi_node_remote_value_shared_id_alias(+ conn, &owner, &remote, &object_id, realm_id,+ );return Some(remote);}let object_snapshot = match conn- .document_node_snapshot_for_runtime_remote_object_id_async(- None,+ .document_node_snapshot_for_runtime_remote_object_id_for_owner_async(+ &owner,&object_id,node_options.snapshot_depth,true,@@ -6740,10 +6775,11 @@ async fn materialize_devtools_script_deep_serialized_node_remote_value_async(};if let Some(object_snapshot) = object_snapshot {- register_devtools_script_remote_object_realm(conn, &object_id, realm_id);+ register_devtools_script_remote_object_realm(conn, &owner, &object_id, realm_id);let shared_id = bidi_node_shared_id_for_snapshot(&object_snapshot.snapshot)?;- register_bidi_node_bindings_for_snapshot_tree(conn, &object_snapshot.snapshot).await;- register_bidi_node_shared_id_alias(conn, &shared_id, &object_id, realm_id);+ register_bidi_node_bindings_for_snapshot_tree(conn, &owner, &object_snapshot.snapshot)+ .await;+ register_bidi_node_shared_id_alias(conn, &owner, &shared_id, &object_id, realm_id);return Some(bidi_node_remote_value_from_snapshot(&object_snapshot.snapshot,shared_id,@@ -6774,7 +6810,7 @@ async fn materialize_devtools_script_deep_serialized_node_remote_value_async(return None;}};- register_devtools_script_remote_object_realm(conn, &object_id, realm_id);+ register_devtools_script_remote_object_realm(conn, &owner, &object_id, realm_id);return Some(json!({"type": "node","sharedId": object_id,@@ -6796,7 +6832,7 @@ async fn materialize_devtools_script_deep_serialized_node_remote_value_async(return None;}};- register_devtools_script_remote_object_realm(conn, &object_id, realm_id);+ register_devtools_script_remote_object_realm(conn, &owner, &object_id, realm_id);Some(json!({"type": "node","sharedId": object_id,@@ -6868,6 +6904,7 @@ async fn devtools_deep_serialized_path_remote_value_async(fn materialize_devtools_script_node_remote_value_from_deep_serialized(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,value: &mut DevToolsRemoteValue,realm_id: Option<&DevToolsRealmId>,) -> bool {@@ -6887,6 +6924,7 @@ fn materialize_devtools_script_node_remote_value_from_deep_serialized(if let Some(original_object_id) = original_object_id.as_deref() {register_bidi_node_remote_value_shared_id_alias(conn,+ owner,&remote,original_object_id,realm_id,@@ -6901,6 +6939,7 @@ fn materialize_devtools_script_node_remote_value_from_deep_serialized(fn register_bidi_node_remote_value_shared_id_alias(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,remote: &Value,remote_object_id: &str,realm_id: Option<&DevToolsRealmId>,@@ -6910,6 +6949,7 @@ fn register_bidi_node_remote_value_shared_id_alias(};register_bidi_node_shared_id_alias(conn,+ owner,&DevToolsRemoteHandleId::from(shared_id.to_owned()),remote_object_id,realm_id,@@ -6918,6 +6958,7 @@ fn register_bidi_node_remote_value_shared_id_alias(async fn register_bidi_node_bindings_for_snapshot_tree(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,snapshot: &DocumentNodeSnapshot,) {let mut entries = Vec::new();@@ -6935,8 +6976,8 @@ async fn register_bidi_node_bindings_for_snapshot_tree(for (shared_id, backend_node_id) in entries {if let Err(error) = conn- .register_document_bidi_node_binding_for_session_owner_async(- None,+ .register_document_bidi_node_binding_for_owner_async(+ owner,shared_id.as_str(),backend_node_id,)@@ -7033,14 +7074,15 @@ async fn devtools_detached_node_value_async(fn register_devtools_script_remote_object_realm(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,remote_object_id: &str,realm_id: Option<&DevToolsRealmId>,) {let Some(realm_id) = realm_id else {return;};- conn.register_runtime_remote_object_ids_for_session_owner_with_realm(- None,+ conn.register_runtime_remote_object_ids_for_owner_with_realm(+ owner,vec![remote_object_id.to_owned()],realm_id.as_str(),);@@ -7048,6 +7090,7 @@ fn register_devtools_script_remote_object_realm(fn register_bidi_node_shared_id_alias(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,shared_id: &DevToolsRemoteHandleId,remote_object_id: &str,realm_id: Option<&DevToolsRealmId>,@@ -7059,8 +7102,8 @@ fn register_bidi_node_shared_id_alias({return;}- conn.register_runtime_remote_object_alias_for_session_owner_with_realm(- None,+ conn.register_runtime_remote_object_alias_for_owner_with_realm(+ owner,shared_id.as_str().to_owned(),remote_object_id.to_owned(),realm_id.as_str(),@@ -7126,31 +7169,25 @@ async fn execute_devtools_release_objects_command_async(devtools_runtime_target_async(conn, &DevToolsCommand::ReleaseObjects(command.clone())).await?;let target_realm = devtools_realm_id_for_runtime_target_async(conn, &target).await;- let mut route_scope = conn.scoped_none_session_owner_route_override(target.route);- let result = release_devtools_objects_on_current_route_async(- route_scope.conn_mut(),- &command.handles,- target_realm.as_ref(),- )- .await;- drop(route_scope);- result?;+ let owner = CommandOwnerScope::for_route(target.route);+ release_devtools_objects_for_owner_async(conn, &owner, &command.handles, target_realm.as_ref())+ .await?;Ok(DevToolsCommandResult::Empty)}-async fn release_devtools_objects_on_current_route_async(+async fn release_devtools_objects_for_owner_async(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,handles: &[DevToolsRemoteHandleId],target_realm: Option<&DevToolsRealmId>,) -> Result<(), DevToolsError> {for handle in handles {let object_id = handle.as_str().to_owned();- if !conn.runtime_remote_object_id_known_for_session_owner(None, &object_id) {+ if !conn.runtime_remote_object_id_known_for_owner(owner, &object_id) {continue;}if let Some(target_realm) = target_realm- && let Some(owner_realm) =- conn.runtime_remote_object_realm_for_session_owner(None, &object_id)+ && let Some(owner_realm) = conn.runtime_remote_object_realm_for_owner(owner, &object_id)&& owner_realm != target_realm.as_str(){continue;@@ -7158,33 +7195,34 @@ async fn release_devtools_objects_on_current_route_async(let params = json!({ "objectId": object_id });let command_id = conn.next_internal_runtime_command_id();let raw_json = runtime_inspector_command_json(command_id, "Runtime.releaseObject", ¶ms);- let response = dispatch_runtime_inspector_command_response_for_current_route_async(- conn, raw_json, command_id,+ let response = dispatch_runtime_inspector_command_response_for_owner_async(+ conn, owner, raw_json, command_id,).await?;if let BackgroundCommandResponsePayload::Error { code, message, .. } = response {let error = devtools_error_from_cdp_error_parts(Some(i64::from(code)), &message);if matches!(error.kind, DevToolsErrorKind::NoSuchHandle) {- conn.unregister_runtime_remote_object_ids_for_session_owner(None, &[object_id]);+ conn.unregister_runtime_remote_object_ids_for_owner(owner, &[object_id]);continue;}return Err(error);}- conn.unregister_runtime_remote_object_ids_for_session_owner(None, &[object_id]);+ conn.unregister_runtime_remote_object_ids_for_owner(owner, &[object_id]);}Ok(())}-async fn dispatch_runtime_inspector_command_response_for_current_route_async(+async fn dispatch_runtime_inspector_command_response_for_owner_async(conn: &mut CdpConnection,+ owner: &CommandOwnerScope,raw_json: String,command_id: u64,) -> Result<BackgroundCommandResponsePayload, DevToolsError> {let descriptor = RendererCommandDescriptor::from_synthesized_payload(raw_json).map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))?;let pending = conn- .start_runtime_protocol_message_for_session_owner_with_deferred_response(- None, descriptor, command_id,+ .start_runtime_protocol_message_for_owner_with_deferred_response(+ owner, descriptor, command_id,).map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))?;let mut completed = pending@@ -7198,7 +7236,7 @@ async fn dispatch_runtime_inspector_command_response_for_current_route_async()})?;let output = conn- .complete_runtime_protocol_message_for_session_owner_async(completed)+ .complete_runtime_protocol_message_async(completed).await.map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))?;if let Some(message) = output@@ -7207,9 +7245,9 @@ async fn dispatch_runtime_inspector_command_response_for_current_route_async({return Ok(BackgroundCommandResponsePayload::from_runtime_inspector_message(message));}- let response = RuntimeInspectorResponseReady::new(+ let response = RuntimeInspectorResponseReady::for_owner(command_id,- None,+ owner,response_rx.await.map_err(|_| "RuntimeInspectorResponseCanceled".to_owned()),@@ -7223,7 +7261,7 @@ async fn dispatch_runtime_inspector_command_response_for_current_route_async(if response.renderer_agent_attachment_id().is_some_and(|attachment_id| {- !conn.renderer_agent_attachment_is_current_for_session_owner(None, attachment_id)+ conn.current_renderer_agent_attachment_id_for_owner(owner) != Some(attachment_id)}){response.replace_with_error("Execution context was destroyed by navigation");@@ -7401,14 +7439,10 @@ async fn devtools_realms_for_route_async(.into_iter().collect());}- let mut route_scope = conn.scoped_none_session_owner_route_override(route);- let result = route_scope- .conn_mut()- .runtime_realm_inventory_for_session_owner_async(None)+ let owner = CommandOwnerScope::for_route(route);+ conn.runtime_realm_inventory_for_owner_async(&owner).await- .map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message));- drop(route_scope);- result+ .map_err(|message| DevToolsError::new(DevToolsErrorKind::Internal, message))}fn shared_worker_target_runtime_realm(@@ -7593,16 +7627,12 @@ fn cdp_remote_object_value(remote: &Value) -> Value {fn start_pending_runtime_binding_context_lookup_phase(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,task: RuntimeBindingCommandTask,execution_context_id: i64,owner_scope: CommandOwnerScope,) -> Option<RuntimeCommandTaskStep> {let pending = conn- .start_child_default_execution_context_lookup_for_session_owner(- session_id,- execution_context_id,- )+ .start_child_default_execution_context_lookup_for_owner(&owner_scope, execution_context_id).ok()?;Some(RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {@@ -7638,15 +7668,15 @@ fn start_pending_runtime_binding_inspector_phase(task.renderer_policy,RendererInspectorResponseDelivery::CommandReply,);- conn.start_runtime_protocol_message_with_context_resolution_for_session_owner_with_deferred_response(- completed.session_id(),+ conn.start_runtime_protocol_message_with_context_resolution_for_owner_with_deferred_response(+ &completed.owner_scope,"addBinding",descriptor,command_id,)} else {- conn.start_runtime_protocol_message_with_context_resolution_for_session_owner(- completed.session_id(),+ conn.start_runtime_protocol_message_with_context_resolution_for_owner(+ &completed.owner_scope,"addBinding",inspector_json,)@@ -7659,14 +7689,14 @@ fn start_pending_runtime_binding_inspector_phase(task.renderer_policy,RendererInspectorResponseDelivery::CommandReply,);- conn.start_runtime_protocol_message_for_session_owner_with_deferred_response(- completed.session_id(),+ conn.start_runtime_protocol_message_for_owner_with_deferred_response(+ &completed.owner_scope,descriptor,command_id,)} else {- conn.start_runtime_protocol_message_for_session_owner(- completed.session_id(),+ conn.start_runtime_protocol_message_for_owner(+ &completed.owner_scope,inspector_json,)}@@ -7690,7 +7720,6 @@ fn start_pending_runtime_binding_inspector_phase(match start_pending_runtime_binding_page_phase(conn,completed.command_id,- completed.session_id(),task.clone(),completed.owner_scope.clone(),) {@@ -7708,24 +7737,23 @@ fn start_pending_runtime_binding_inspector_phase(fn start_pending_runtime_binding_page_phase(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,task: RuntimeBindingCommandTask,owner_scope: CommandOwnerScope,) -> Option<PendingRuntimeCommandDispatch> {let pending = match task.phase {RuntimeBindingPhase::LivePageUpdate => match task.action {- RuntimeBindingCommand::Add => conn.start_install_runtime_binding_for_session_owner(- session_id,+ RuntimeBindingCommand::Add => conn.start_install_runtime_binding_for_owner(+ &owner_scope,&task.name,task.execution_context_name.as_deref(),task.execution_context_id,),RuntimeBindingCommand::Remove => {- conn.start_remove_runtime_binding_for_session_owner(session_id, &task.name)+ conn.start_remove_runtime_binding_for_owner(&owner_scope, &task.name)}},RuntimeBindingPhase::StoredBindingsApply => {- conn.start_apply_stored_runtime_bindings_for_session_owner(session_id)+ conn.start_apply_stored_runtime_bindings_for_owner(&owner_scope)}}.ok()?;@@ -7746,19 +7774,45 @@ fn prepare_runtime_inspector_payload(conn: &CdpConnection,cmd: &Cmd<'_>,preparation: RuntimeInspectorPayloadPreparation,+) -> Result<String, String> {+ let owner = CommandOwnerScope::capture(conn, cmd.session_id);+ prepare_runtime_inspector_payload_for_owner(conn, cmd, &owner, preparation)+}++fn prepare_runtime_inspector_payload_for_owner(+ conn: &CdpConnection,+ cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,+ preparation: RuntimeInspectorPayloadPreparation,) -> Result<String, String> {match preparation {RuntimeInspectorPayloadPreparation::Passthrough => Ok(cmd.json.to_owned()),RuntimeInspectorPayloadPreparation::ValidateObjectOwner => {- validate_pending_runtime_object_ownership(conn, cmd)?;+ let object_ids = cmd+ .params+ .map(runtime_remote_object_ids_in_map)+ .unwrap_or_default();+ conn.validate_runtime_remote_object_ids_for_owner(owner, &object_ids)?;Ok(cmd.json.to_owned())}RuntimeInspectorPayloadPreparation::ValidatePrototypeOwner => {- validate_pending_runtime_prototype_object_ownership(conn, cmd)?;+ let object_ids = runtime_prototype_object_id_from_params(cmd.params)+ .map(|object_id| vec![object_id.to_owned()])+ .unwrap_or_default();+ conn.validate_runtime_remote_object_ids_for_owner(owner, &object_ids)?;Ok(cmd.json.to_owned())}RuntimeInspectorPayloadPreparation::PrepareCallFunctionOn => {- prepare_pending_runtime_call_function_on_json(conn, cmd)+ let (browser_context_id, target_id) = conn+ .target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())+ .map(|(browser_context_id, target_id)| (Some(browser_context_id), target_id))+ .unwrap_or((None, None));+ let command = build_cdp_call_function_command(+ cmd,+ target_id.as_deref(),+ browser_context_id.as_deref(),+ );+ prepare_pending_devtools_call_function_json_for_owner(conn, cmd, owner, &command)}}}@@ -7838,17 +7892,6 @@ fn devtools_runtime_owner_identity_for_session(.unwrap_or((None, None))}-fn prepare_pending_runtime_call_function_on_json(- conn: &CdpConnection,- cmd: &Cmd<'_>,-) -> Result<String, String> {- let (browser_context_id, target_id) =- devtools_runtime_owner_identity_for_session(conn, cmd.session_id);- let command =- build_cdp_call_function_command(cmd, target_id.as_deref(), browser_context_id.as_deref());- prepare_pending_devtools_call_function_json(conn, cmd, &command)-}-fn build_cdp_call_function_command(cmd: &Cmd<'_>,target_id: Option<&str>,@@ -7904,37 +7947,17 @@ fn cdp_call_function_arguments_from_params(params: Option<&Map<String, Value>>).unwrap_or_default()}-fn prepare_pending_devtools_call_function_json(+fn prepare_pending_devtools_call_function_json_for_owner(conn: &CdpConnection,cmd: &Cmd<'_>,+ owner: &CommandOwnerScope,command: &DevToolsCallFunctionCommand,) -> Result<String, String> {let object_ids = devtools_call_function_remote_object_ids(command);- conn.validate_runtime_remote_object_ids_for_session_owner(cmd.session_id, &object_ids)?;+ conn.validate_runtime_remote_object_ids_for_owner(owner, &object_ids)?;Ok(cmd.json.to_owned())}-fn validate_pending_runtime_object_ownership(- conn: &CdpConnection,- cmd: &Cmd<'_>,-) -> Result<(), String> {- let object_ids = cmd- .params- .map(runtime_remote_object_ids_in_map)- .unwrap_or_default();- conn.validate_runtime_remote_object_ids_for_session_owner(cmd.session_id, &object_ids)-}--fn validate_pending_runtime_prototype_object_ownership(- conn: &CdpConnection,- cmd: &Cmd<'_>,-) -> Result<(), String> {- let object_ids = runtime_prototype_object_id_from_params(cmd.params)- .map(|object_id| vec![object_id.to_owned()])- .unwrap_or_default();- conn.validate_runtime_remote_object_ids_for_session_owner(cmd.session_id, &object_ids)-}-pub(crate) async fn complete_pending_runtime_command(conn: &mut CdpConnection,completed: CompletedRuntimeCommandDispatch,@@ -7947,21 +7970,6 @@ pub(crate) async fn complete_pending_runtime_command_at_response_boundary(conn: &mut CdpConnection,completed: CompletedRuntimeCommandDispatch,response_flush: &crate::conn::CommandResponseFlushContext,-) -> RuntimeCommandTaskStep {- let owner_scope = completed.owner_scope.clone();- let mut route_scope = owner_scope.enter(conn);- Box::pin(complete_pending_runtime_command_inner(- route_scope.conn_mut(),- completed,- response_flush,- ))- .await-}--async fn complete_pending_runtime_command_inner(- conn: &mut CdpConnection,- completed: CompletedRuntimeCommandDispatch,- response_flush: &crate::conn::CommandResponseFlushContext,) -> RuntimeCommandTaskStep {let timing_started = moli_trace::cdp_nav_timing_enabled().then(std::time::Instant::now);let meta = RuntimeCommandCompletionMeta::from(&completed);@@ -8050,16 +8058,16 @@ async fn complete_pending_runtime_command_inner(async fn route_registered_runtime_response_receiver_into(conn: &mut CdpConnection,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,response_rx: RuntimeInspectorAsyncCompletionReceiver,routed_output: &mut RuntimeInspectorRoutedOutput,) -> bool {let Some(command_id) = command_id else {return false;};- let response = RuntimeInspectorResponseReady::new(+ let response = RuntimeInspectorResponseReady::for_owner(command_id,- session_id,+ owner,response_rx.await.map_err(|_| "RuntimeInspectorResponseCanceled".to_owned()),@@ -8075,7 +8083,7 @@ async fn route_registered_runtime_response_receiver_into(conn,output,Some(command_id),- session_id,+ owner,routed_output,).await@@ -8085,14 +8093,14 @@ async fn route_runtime_command_output_into_routed_output(conn: &mut CdpConnection,output: RendererRuntimeCommandOutput,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,routed_output: &mut RuntimeInspectorRoutedOutput,) -> bool {let mut ordered_events = Vec::new();- let saw_current_response = conn.route_renderer_runtime_command_output_into(+ let saw_current_response = conn.route_renderer_runtime_command_output_for_owner_into(output,command_id,- session_id,+ owner,&mut ordered_events,);routed_output.append_ordered_events(ordered_events);@@ -8103,17 +8111,17 @@ async fn route_renderer_command_turn_output_into_routed_output(conn: &mut CdpConnection,output: RendererCommandTurnOutput,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,response_flush: &crate::conn::CommandResponseFlushContext,routed_output: &mut RuntimeInspectorRoutedOutput,) -> bool {let mut ordered_events = Vec::new();let mut post_response_events = Vec::new();let (saw_current_response, renderer_output_predecessor) = conn- .route_renderer_command_turn_output_into(+ .route_renderer_command_turn_output_for_owner_into(output,command_id,- session_id,+ owner,response_flush,&mut ordered_events,&mut post_response_events,@@ -8130,7 +8138,7 @@ fn route_inspector_messages_into_routed_output(conn: &mut CdpConnection,messages: Vec<RendererRuntimeInspectorMessage>,command_id: Option<u64>,- session_id: Option<&str>,+ owner: &CommandOwnerScope,routed_output: &mut RuntimeInspectorRoutedOutput,) -> bool {let mut saw_current_response = false;@@ -8138,10 +8146,10 @@ fn route_inspector_messages_into_routed_output(let mut response_events = Vec::new();let mut background_events = Vec::new();saw_current_response |= conn- .route_renderer_runtime_inspector_messages_with_background_events_into(+ .route_renderer_runtime_inspector_messages_for_owner_with_background_events_into(vec![message],command_id,- session_id,+ owner,&mut response_events,&mut background_events,);@@ -8171,7 +8179,7 @@ async fn complete_pending_runtime_inspector_command(let response_delivery = completed_protocol.response_delivery();let renderer_response_rx = completed_protocol.take_deferred_response_receiver();match conn- .complete_runtime_protocol_message_for_session_owner_async(completed_protocol)+ .complete_runtime_protocol_message_async(completed_protocol).await{Ok(messages) => (@@ -8183,7 +8191,10 @@ async fn complete_pending_runtime_inspector_command(),Err(message) => {if let Some(command_id) = completed.command_id {- conn.forget_pending_inspector_await(command_id, completed.session_id());+ conn.forget_pending_inspector_await_for_owner(+ command_id,+ &completed.owner_scope,+ );}if session_response_succeeded.is_some() {tracing::debug!(@@ -8201,11 +8212,10 @@ async fn complete_pending_runtime_inspector_command()} else {if let Some(command_id) = completed.command_id {- let correlation = conn- .take_renderer_call_for_frontend_for_session_owner(- completed.session_id(),- command_id,- );+ let correlation = conn.take_renderer_call_for_frontend_for_owner(+ &completed.owner_scope,+ command_id,+ );if correlation.is_none() {tracing::debug!(command_id,@@ -8228,11 +8238,9 @@ async fn complete_pending_runtime_inspector_command(}Err(message) => {if let Some(command_id) = completed.command_id {- conn.forget_pending_inspector_await(command_id, completed.session_id());- let correlation = conn.take_renderer_call_for_frontend_for_session_owner(- completed.session_id(),- command_id,- );+ conn.forget_pending_inspector_await_for_owner(command_id, &completed.owner_scope);+ let correlation = conn+ .take_renderer_call_for_frontend_for_owner(&completed.owner_scope, command_id);if correlation.is_none() {tracing::debug!(command_id,@@ -8274,7 +8282,7 @@ async fn complete_pending_runtime_inspector_command(conn,messages,completed.command_id,- completed.session_id(),+ &completed.owner_scope,response_flush,&mut routed_output,)@@ -8297,8 +8305,12 @@ async fn complete_pending_runtime_inspector_command(if !saw_current_response&& renderer_response_rx.is_some()&& completed.command_id.is_some_and(|command_id| {- conn.renderer_runtime_command_cause_for_frontend(completed.session_id(), command_id)- .is_none()+ conn.renderer_runtime_command_cause_for_route(+ completed.session_id(),+ completed.owner_scope.session_owner_route(),+ command_id,+ )+ .is_none()}){renderer_response_rx.take();@@ -8317,7 +8329,7 @@ async fn complete_pending_runtime_inspector_command(let saw_deferred_response = route_registered_runtime_response_receiver_into(conn,completed.command_id,- completed.session_id(),+ &completed.owner_scope,renderer_response_rx,&mut routed_output,)@@ -8348,13 +8360,13 @@ async fn complete_pending_runtime_inspector_command(if succeeded {routed_output.register_object_group_for_success(conn,- completed.session_id(),+ &completed.owner_scope,completed.object_group.as_deref(),);}if succeeded {if let Some(console_action) = console_action_from_protocol_method(completed.action)- && !apply_console_output_state_for_session(conn, completed.session_id(), console_action)+ && !apply_console_output_state_for_owner(conn, &completed.owner_scope, console_action){let message = format!("ConsoleCommandCompletionFailed: {}", completed.action);if session_response_succeeded.is_some() {@@ -8372,15 +8384,13 @@ async fn complete_pending_runtime_inspector_command(}}if completed.action == "discardConsoleEntries" {- advance_runtime_observable_cursors_to_current_for_session_owner(- conn,- completed.session_id(),- );+ advance_runtime_observable_cursors_to_current_for_owner(conn, &completed.owner_scope);}if completed.action == "disable" {- if let Err(message) =- apply_runtime_disable_projection_after_success(conn, completed.session_id())- {+ if let Err(message) = apply_runtime_disable_projection_after_success_for_owner(+ conn,+ &completed.owner_scope,+ ) {if session_response_succeeded.is_some() {tracing::warn!(command_id = completed.command_id,@@ -8396,7 +8406,7 @@ async fn complete_pending_runtime_inspector_command(}}if let Err(message) = conn- .apply_runtime_binding_state_for_session_owner_async(completed.session_id())+ .apply_runtime_binding_state_for_owner_async(&completed.owner_scope).await{if session_response_succeeded.is_some() {@@ -8415,14 +8425,14 @@ async fn complete_pending_runtime_inspector_command(}}if !completed.release_object_ids.is_empty() {- conn.unregister_runtime_remote_object_ids_for_session_owner(- completed.session_id(),+ conn.unregister_runtime_remote_object_ids_for_owner(+ &completed.owner_scope,&completed.release_object_ids,);}if let Some(object_group) = completed.release_object_group.as_deref() {- conn.unregister_runtime_remote_object_group_for_session_owner(- completed.session_id(),+ conn.unregister_runtime_remote_object_group_for_owner(+ &completed.owner_scope,object_group,);}@@ -8456,7 +8466,7 @@ fn pending_runtime_deferred_inspector_reply_command(let claimed_await = completed.command_id.and_then(|command_id| {conn.claim_pending_inspector_await_for_scheduler_deferred_reply(command_id,- completed.session_id(),+ &completed.owner_scope,)});RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {@@ -8535,28 +8545,29 @@ fn complete_pending_runtime_enable_command(completed_enable: Result<CompletedRuntimeEnableEventsDispatch, String>,) -> CommandOutputPlan {let replay = match completed_enable {- Ok(completed_enable) => {- match conn.complete_runtime_enable_events_for_session_owner(completed_enable) {- Ok(replay) => replay,- Err(message) => return CommandOutputPlan::error(-32000, message),- }- }+ Ok(completed_enable) => match conn.complete_runtime_enable_events(completed_enable) {+ Ok(replay) => replay,+ Err(message) => return CommandOutputPlan::error(-32000, message),+ },Err(message) => return CommandOutputPlan::error(-32000, message),};if let Err(message) =- apply_runtime_enable_projection_after_success(conn, completed.session_id())+ apply_runtime_enable_projection_after_success(conn, &completed.owner_scope){return CommandOutputPlan::error(-32000, message);}- let frame_id = conn.runtime_session_owner_frame_id(completed.session_id());+ let frame_id = conn.runtime_session_owner_frame_id_for_route(+ completed.owner_scope.session_id(),+ completed.owner_scope.session_owner_route(),+ );let mut plan = CommandOutputPlan::success();for event in replay.into_events() {match event {RuntimeEnableReplayEvent::Context(event) => {- if !should_emit_child_default_context_inventory_replay_once(+ if !should_emit_child_default_context_inventory_replay_once_for_owner(conn,- completed.session_id(),+ &completed.owner_scope,frame_id.as_deref(),&event,) {@@ -8566,10 +8577,10 @@ fn complete_pending_runtime_enable_command(// context producer. Record delivery only after the replay// cursor accepts this exact event; marking it while merely// preparing the replay would suppress the first delivery.- apply_runtime_context_protocol_event_side_effects_typed(+ apply_runtime_context_protocol_event_side_effects_for_owner_typed(conn,&event,- completed.session_id(),+ &completed.owner_scope,);let mut background_events = Vec::new();emit_runtime_context_protocol_background_event_typed(@@ -8591,9 +8602,9 @@ fn complete_pending_runtime_enable_command(fn apply_runtime_enable_projection_after_success(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Result<(), String> {- match conn.set_runtime_frontend_enabled_for_session_owner(session_id, true) {+ match conn.set_runtime_frontend_enabled_for_owner(owner, true) {SessionOwnerRuntimeFrontendEnableResult::Handled => Ok(()),SessionOwnerRuntimeFrontendEnableResult::UnknownSession => {Err("Runtime.enable succeeded after session owner disappeared".to_owned())@@ -8608,17 +8619,17 @@ fn complete_pending_runtime_binding_context_lookup_command(completed_lookup: Result<CompletedRuntimeChildDefaultContextLookupDispatch, String>,) -> RuntimeCommandTaskStep {let is_child_default_context = match completed_lookup {- Ok(completed_lookup) => match conn- .complete_child_default_execution_context_lookup_for_session_owner(completed_lookup)- {- Ok(is_child_default_context) => is_child_default_context,- Err(message) => {- return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(- completed.command_id,- message,- ));+ Ok(completed_lookup) => {+ match conn.complete_child_default_execution_context_lookup(completed_lookup) {+ Ok(is_child_default_context) => is_child_default_context,+ Err(message) => {+ return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(+ completed.command_id,+ message,+ ));+ }}- },+ }Err(message) => {return RuntimeCommandTaskStep::Complete(runtime_inspector_error_plan(completed.command_id,@@ -8630,7 +8641,7 @@ fn complete_pending_runtime_binding_context_lookup_command(if !is_child_default_context {if matches!(task.action, RuntimeBindingCommand::Add)|| matches!(task.action, RuntimeBindingCommand::Remove)- && runtime_remove_binding_should_skip_live_page_update(conn, completed.session_id())+ && runtime_remove_binding_should_skip_live_page_update(conn, &completed.owner_scope){task.skip_live_page_update_after_inspector_success = true;}@@ -8641,7 +8652,6 @@ fn complete_pending_runtime_binding_context_lookup_command(match start_pending_runtime_binding_page_phase(conn,completed.command_id,- completed.session_id(),task.clone(),completed.owner_scope.clone(),) {@@ -8661,7 +8671,7 @@ async fn complete_pending_runtime_binding_inspector_command(Ok(mut completed_protocol) => {let renderer_response_rx = completed_protocol.take_deferred_response_receiver();match conn- .complete_runtime_protocol_message_for_session_owner_async(completed_protocol)+ .complete_runtime_protocol_message_async(completed_protocol).await{Ok(messages) => (messages, renderer_response_rx),@@ -8686,7 +8696,7 @@ async fn complete_pending_runtime_binding_inspector_command(conn,messages,completed.command_id,- completed.session_id(),+ &completed.owner_scope,response_flush,&mut routed_output,)@@ -8701,7 +8711,7 @@ async fn complete_pending_runtime_binding_inspector_command(route_registered_runtime_response_receiver_into(conn,completed.command_id,- completed.session_id(),+ &completed.owner_scope,renderer_response_rx,&mut routed_output,)@@ -8727,7 +8737,6 @@ async fn complete_pending_runtime_binding_inspector_command(match start_pending_runtime_binding_page_phase(conn,completed.command_id,- completed.session_id(),task.clone(),completed.owner_scope.clone(),) {@@ -8744,8 +8753,7 @@ fn complete_pending_runtime_binding_page_command() -> RuntimeCommandTaskStep {match completed_page {Ok(completed_page) => {- if let Err(message) =- conn.complete_runtime_binding_page_command_for_session_owner(completed_page)+ if let Err(message) = conn.complete_runtime_binding_page_command(completed_page)&& message != "NoDocumentLoaded"{tracing::warn!(@@ -8780,15 +8788,15 @@ fn complete_runtime_binding_after_live_update() -> RuntimeCommandTaskStep {if task.should_persist {let persistence = match task.action {- RuntimeBindingCommand::Add => persist_runtime_binding_definition_for_session_owner(+ RuntimeBindingCommand::Add => persist_runtime_binding_definition_for_owner(conn,- completed.session_id(),+ &completed.owner_scope,task.name.clone(),task.execution_context_name.clone(),),- RuntimeBindingCommand::Remove => remove_runtime_binding_definitions_for_session_owner(+ RuntimeBindingCommand::Remove => remove_runtime_binding_definitions_for_owner(conn,- completed.session_id(),+ &completed.owner_scope,&task.name,),};@@ -8804,7 +8812,6 @@ fn complete_runtime_binding_after_live_update(if let Some(pending) = start_pending_runtime_binding_page_phase(conn,completed.command_id,- completed.session_id(),task.clone(),completed.owner_scope.clone(),) {@@ -9189,12 +9196,12 @@ fn start_pending_shared_worker_runtime_inspector_command(} else {None};- let session_owner_route = conn.session_route(cmd.session_id);+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pre_registered_await = pre_register_runtime_await_if_needed(conn,await_promise,cmd.id,- cmd.session_id,+ &owner_scope,object_group.as_deref(),action.label(),)@@ -9202,7 +9209,7 @@ fn start_pending_shared_worker_runtime_inspector_command(let pending = match start_shared_worker_frontend_inspector_dispatch(conn, cmd, inspector_json) {Ok(pending) => pending,Err(message) => {- forget_pre_registered_runtime_await(conn, pre_registered_await, cmd.session_id);+ forget_pre_registered_runtime_await(conn, pre_registered_await, &owner_scope);return Err(message);}};@@ -9211,10 +9218,7 @@ fn start_pending_shared_worker_runtime_inspector_command(PendingRuntimeCommandDispatch {command_id: cmd.id,action: action.label(),- owner_scope: cmd- .session_id- .map(CommandOwnerScope::for_session)- .unwrap_or_else(|| CommandOwnerScope::for_implicit_route(session_owner_route)),+ owner_scope,object_group,release_object_ids,release_object_group,@@ -9254,12 +9258,12 @@ fn start_pending_service_worker_runtime_inspector_command(} else {None};- let session_owner_route = conn.session_route(cmd.session_id);+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pre_registered_await = pre_register_runtime_await_if_needed(conn,await_promise,cmd.id,- cmd.session_id,+ &owner_scope,object_group.as_deref(),action.label(),)@@ -9268,7 +9272,7 @@ fn start_pending_service_worker_runtime_inspector_command({Ok(pending) => pending,Err(message) => {- forget_pre_registered_runtime_await(conn, pre_registered_await, cmd.session_id);+ forget_pre_registered_runtime_await(conn, pre_registered_await, &owner_scope);return Err(message);}};@@ -9276,10 +9280,7 @@ fn start_pending_service_worker_runtime_inspector_command(PendingRuntimeCommandDispatch {command_id: cmd.id,action: action.label(),- owner_scope: cmd- .session_id- .map(CommandOwnerScope::for_session)- .unwrap_or_else(|| CommandOwnerScope::for_implicit_route(session_owner_route)),+ owner_scope,object_group,release_object_ids,release_object_group,@@ -9456,7 +9457,7 @@ async fn complete_pending_shared_worker_runtime_inspector_command(conn,messages,completed.command_id,- completed.session_id(),+ &completed.owner_scope,&mut routed_output,);if !completed.wait_for_deferred_reply@@ -9465,7 +9466,7 @@ async fn complete_pending_shared_worker_runtime_inspector_command(saw_current_response |= route_registered_runtime_response_receiver_into(conn,completed.command_id,- completed.session_id(),+ &completed.owner_scope,renderer_response_rx,&mut routed_output,)@@ -9519,7 +9520,7 @@ async fn complete_pending_shared_worker_runtime_inspector_command(if succeeded {routed_output.register_object_group_for_success(conn,- completed.session_id(),+ &completed.owner_scope,completed.object_group.as_deref(),);}@@ -9593,7 +9594,7 @@ async fn complete_pending_service_worker_runtime_inspector_command(conn,messages,completed.command_id,- completed.session_id(),+ &completed.owner_scope,&mut routed_output,);if !completed.wait_for_deferred_reply@@ -9602,7 +9603,7 @@ async fn complete_pending_service_worker_runtime_inspector_command(saw_current_response |= route_registered_runtime_response_receiver_into(conn,completed.command_id,- completed.session_id(),+ &completed.owner_scope,renderer_response_rx,&mut routed_output,)@@ -9638,7 +9639,7 @@ async fn complete_pending_service_worker_runtime_inspector_command(if succeeded {routed_output.register_object_group_for_success(conn,- completed.session_id(),+ &completed.owner_scope,completed.object_group.as_deref(),);}@@ -10194,8 +10195,11 @@ fn build_service_worker_execution_context_created_event())}-fn disable_command_output_plan_sync(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> CommandOutputPlan {- match apply_runtime_disable_projection_after_success(conn, cmd.session_id) {+fn disable_command_output_plan_sync_for_owner(+ conn: &mut CdpConnection,+ owner: &CommandOwnerScope,+) -> CommandOutputPlan {+ match apply_runtime_disable_projection_after_success_for_owner(conn, owner) {Ok(()) => CommandOutputPlan::success(),Err(_) => CommandOutputPlan::error(-32001, "Unknown sessionId"),}@@ -10204,19 +10208,38 @@ fn disable_command_output_plan_sync(conn: &mut CdpConnection, cmd: &Cmd<'_>) ->fn start_pending_runtime_disable_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,+) -> RuntimeCommandTaskStep {+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);+ let response_delivery =+ cmd.terminal_response_delivery(RendererInspectorResponseDelivery::DevToolsSession);+ start_runtime_disable_command_for_owner(conn, cmd, owner_scope, response_delivery)+}++fn start_runtime_disable_command_for_owner(+ conn: &mut CdpConnection,+ cmd: &Cmd<'_>,+ owner_scope: CommandOwnerScope,+ response_delivery: RendererInspectorResponseDelivery,) -> RuntimeCommandTaskStep {if !conn- .runtime_session_owner_slot(cmd.session_id)+ .runtime_session_owner_slot_for_route(+ owner_scope.session_id(),+ owner_scope.session_owner_route(),+ ).is_ok_and(|slot| slot.has_loaded_page()){- return RuntimeCommandTaskStep::Complete(disable_command_output_plan_sync(conn, cmd));+ return RuntimeCommandTaskStep::Complete(disable_command_output_plan_sync_for_owner(+ conn,+ &owner_scope,+ ));}let pending = match start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,cmd.json.to_owned(),- cmd.terminal_response_delivery(RendererInspectorResponseDelivery::DevToolsSession),+ response_delivery,) {Ok(pending) => pending,Err(message) => {@@ -10227,7 +10250,7 @@ fn start_pending_runtime_disable_command(RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {command_id: cmd.id,action: "disable",- owner_scope: CommandOwnerScope::capture(conn, cmd.session_id),+ owner_scope,object_group: None,release_object_ids: Vec::new(),release_object_group: None,@@ -10237,6 +10260,36 @@ fn start_pending_runtime_disable_command(}))}+pub(crate) async fn execute_runtime_listener_command_for_owner(+ conn: &mut CdpConnection,+ owner: CommandOwnerScope,+ enabled: bool,+) -> CommandOutputPlan {+ let mut step = if enabled {+ start_runtime_enable_command_for_owner(conn, Some(0), owner)+ } else {+ let raw = r#"{"id":0,"method":"Runtime.disable","params":{}}"#;+ let parsed = ParsedCdpCommand::parse_str(raw.to_owned())+ .expect("internal Runtime.disable command must be valid CDP");+ let cmd = Cmd::from_parsed(&parsed)+ .expect("internal Runtime.disable command must produce a command view");+ start_runtime_disable_command_for_owner(+ conn,+ &cmd,+ owner,+ RendererInspectorResponseDelivery::CommandReply,+ )+ };+ loop {+ match step {+ RuntimeCommandTaskStep::Complete(plan) => return plan,+ RuntimeCommandTaskStep::Pending(pending) => {+ step = complete_pending_runtime_command(conn, pending.wait().await).await;+ }+ }+ }+}+fn start_runtime_run_if_waiting_for_debugger_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,@@ -10248,9 +10301,11 @@ fn start_runtime_run_if_waiting_for_debugger_command(return RuntimeCommandTaskStep::Complete(CommandOutputPlan::success());}+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pending = match start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,cmd.json.to_owned(),cmd.terminal_response_delivery(RendererInspectorResponseDelivery::DevToolsSession),) {@@ -10266,7 +10321,7 @@ fn start_runtime_run_if_waiting_for_debugger_command(RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {command_id: cmd.id,action: "runIfWaitingForDebugger",- owner_scope: CommandOwnerScope::capture(conn, cmd.session_id),+ owner_scope,object_group: None,release_object_ids: Vec::new(),release_object_group: None,@@ -10276,18 +10331,18 @@ fn start_runtime_run_if_waiting_for_debugger_command(}))}-fn apply_runtime_disable_projection_after_success(+fn apply_runtime_disable_projection_after_success_for_owner(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,) -> Result<(), String> {let was_enabled = conn- .target_runtime_session_state_for_session(session_id)+ .target_runtime_session_state_for_route(owner.session_id(), owner.session_owner_route()).is_some_and(|state| state.runtime_frontend_enabled);- match conn.set_runtime_frontend_enabled_for_session_owner(session_id, false) {+ match conn.set_runtime_frontend_enabled_for_owner(owner, false) {SessionOwnerRuntimeFrontendEnableResult::Handled => {- advance_runtime_observable_cursors_to_current_for_session_owner(conn, session_id);+ advance_runtime_observable_cursors_to_current_for_owner(conn, owner);if was_enabled {- clear_runtime_binding_definitions_for_session_owner(conn, session_id)?;+ clear_runtime_binding_definitions_for_owner(conn, owner)?;}Ok(())}@@ -10308,9 +10363,11 @@ fn start_runtime_discard_console_entries_command(advance_runtime_observable_cursors_to_current_for_session_owner(conn, cmd.session_id);return RuntimeCommandTaskStep::Complete(CommandOutputPlan::success());}+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let pending = match start_pending_runtime_inspector_dispatch_with_delivery(conn,cmd,+ &owner_scope,cmd.json.to_owned(),cmd.terminal_response_delivery(RendererInspectorResponseDelivery::DevToolsSession),) {@@ -10322,7 +10379,7 @@ fn start_runtime_discard_console_entries_command(RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {command_id: cmd.id,action: "discardConsoleEntries",- owner_scope: CommandOwnerScope::capture(conn, cmd.session_id),+ owner_scope,object_group: None,release_object_ids: Vec::new(),release_object_group: None,@@ -10345,7 +10402,8 @@ mod protocol_neutral_tests {use serde_json::{Value, json};use crate::conn::{- BrowserContext, CdpConnection, CdpSessionRoute, Cmd, SharedWorkerTargetState,+ BrowserContext, CdpConnection, CdpSessionRoute, Cmd, CommandOwnerScope,+ SharedWorkerTargetState,};use crate::domains::actions::ConsoleAction;use crate::testing::TestContext;@@ -10355,7 +10413,7 @@ mod protocol_neutral_tests {devtools_serialization_options_for_node_probe,};use super::{- DevToolsRuntimeTarget, RuntimeCommandTaskStep, RuntimeProbeCompletionScope,+ DevToolsRuntimeTarget, RuntimeCommandTaskStep,apply_shared_worker_runtime_completion_projection, build_cdp_call_function_command,build_cdp_evaluate_script_command, cdp_call_argument_from_devtools_argument,devtools_call_function_cdp_arguments, devtools_call_function_declaration,@@ -11287,50 +11345,6 @@ mod protocol_neutral_tests {);}- #[test]- fn runtime_probe_completion_scope_restores_on_drop() {- let mut conn = CdpConnection::new();- let previous_route = Some(CdpSessionRoute::Browser);- conn.replace_none_session_owner_route_override(previous_route.clone());-- let target_route = CdpSessionRoute::PageTarget {- browser_context_id: "BID-active".to_owned(),- target_id: "TID-active".to_owned(),- is_attached_session: false,- };- {- let mut scope = RuntimeProbeCompletionScope::enter(&mut conn, target_route.clone());- assert_eq!(- scope.conn_mut().none_session_owner_route_override(),- Some(target_route)- );- }-- assert_eq!(conn.none_session_owner_route_override(), previous_route);- }-- #[test]- fn none_session_owner_route_override_scope_restores_on_drop() {- let mut conn = CdpConnection::new();- let previous_route = Some(CdpSessionRoute::Browser);- conn.replace_none_session_owner_route_override(previous_route.clone());-- let target_route = CdpSessionRoute::PageTarget {- browser_context_id: "BID-active".to_owned(),- target_id: "TID-active".to_owned(),- is_attached_session: false,- };- {- let mut scope = conn.scoped_none_session_owner_route_override(target_route.clone());- assert_eq!(- scope.conn_mut().none_session_owner_route_override(),- Some(target_route)- );- }-- assert_eq!(conn.none_session_owner_route_override(), previous_route);- }-#[test]fn devtools_runtime_entry_routes_evaluate_command_to_inspector_error_plan() {let mut conn = CdpConnection::new();@@ -11368,9 +11382,9 @@ mod protocol_neutral_tests {browser_context.set_active_target_id("TID-duplicate".to_owned());browser_context.attach_active_session("SID-duplicate".to_owned());conn.browser_context = Some(browser_context);- conn.try_register_pending_inspector_await_with_object_group(+ conn.try_register_pending_inspector_await_with_object_group_for_owner(77,- Some("SID-duplicate"),+ &CommandOwnerScope::for_session("SID-duplicate"),Some("original-group"),).unwrap();diff --git a/moli-protocol/src/domains/runtime/tests/evaluate.rs b/moli-protocol/src/domains/runtime/tests/evaluate.rsindex 5b6ad2523..33219be83 100644--- a/moli-protocol/src/domains/runtime/tests/evaluate.rs+++ b/moli-protocol/src/domains/runtime/tests/evaluate.rs@@ -2328,7 +2328,9 @@ async fn page_navigate_network_failure_commits_error_document() {.expect("loaded renderer Page residence");let before_renderer_attachment = ctx.conn- .current_renderer_agent_attachment_id_for_session_owner(Some("SID-1"))+ .current_renderer_agent_attachment_id_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),+ ).expect("loaded renderer attachment");ctx.sent.clear();@@ -2445,7 +2447,7 @@ async fn page_navigate_network_failure_commits_error_document() {);let error_document_loader_id = ctx.conn- .target_session_owner_frame_tree_loader_id(Some("SID-1"))+ .target_session_owner_frame_tree_loader_id_for_route(Some("SID-1"), None).expect("error Document loader id");let stale_request_id = "REQ-before-network-error";let stale_body_completion = BackgroundNavigationCompletion::main_document_body(@@ -2489,7 +2491,7 @@ async fn page_navigate_network_failure_commits_error_document() {assert!(stale_completion_scheduler_events.is_empty());assert_eq!(ctx.conn- .target_session_owner_frame_tree_loader_id(Some("SID-1"))+ .target_session_owner_frame_tree_loader_id_for_route(Some("SID-1"), None).as_deref(),Some(error_document_loader_id.as_str()),"stale body completion must not replace the error Document loader"@@ -2525,8 +2527,9 @@ async fn page_navigate_network_failure_commits_error_document() {"the error Document must not reuse the retired renderer Page");assert_ne!(- ctx.conn- .current_renderer_agent_attachment_id_for_session_owner(Some("SID-1")),+ ctx.conn.current_renderer_agent_attachment_id_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),+ ),Some(before_renderer_attachment),"the error Document must own a replacement realm/Inspector attachment");@@ -8089,7 +8092,9 @@ fn replay_policy_command_rotates_lease_and_completes_on_replacement_attachment().await;let old_attachment = ctx.conn- .current_renderer_agent_attachment_id_for_session_owner(Some("SID-1"))+ .current_renderer_agent_attachment_id_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),+ ).expect("old Page attachment");let frontend_id = 9_021;let payload = json!({@@ -8126,7 +8131,9 @@ fn replay_policy_command_rotates_lease_and_completes_on_replacement_attachment()let new_attachment = ctx.conn- .current_renderer_agent_attachment_id_for_session_owner(Some("SID-1"))+ .current_renderer_agent_attachment_id_for_owner(+ &crate::conn::CommandOwnerScope::for_session("SID-1"),+ ).expect("replacement Page attachment");assert_ne!(new_attachment, old_attachment);assert!(diff --git a/moli-protocol/src/domains/runtime_context_events.rs b/moli-protocol/src/domains/runtime_context_events.rsindex 59f49d82d..7765112b4 100644--- a/moli-protocol/src/domains/runtime_context_events.rs+++ b/moli-protocol/src/domains/runtime_context_events.rs@@ -10,7 +10,7 @@ use serde_json::Value;#[cfg(test)]use serde_json::json;-use crate::conn::{BackgroundProtocolEvent, CdpConnection, CdpSessionRoute};+use crate::conn::{BackgroundProtocolEvent, CdpConnection, CdpSessionRoute, CommandOwnerScope};#[derive(Clone, Debug, PartialEq)]pub(crate) enum RuntimeContextProtocolEvent {@@ -210,6 +210,33 @@ pub(crate) fn apply_runtime_context_protocol_event_side_effects_typed(}}+pub(crate) fn apply_runtime_context_protocol_event_side_effects_for_owner_typed(+ conn: &mut CdpConnection,+ event: &RuntimeContextProtocolEvent,+ owner: &CommandOwnerScope,+) {+ if owner.session_id().is_some() {+ apply_runtime_context_protocol_event_side_effects_typed(conn, event, owner.session_id());+ return;+ }+ conn.record_runtime_context_protocol_event_for_owner(owner, event);+ match event {+ RuntimeContextProtocolEvent::Cleared(_) => {+ conn.clear_runtime_remote_object_tracking_for_owner(owner);+ conn.record_runtime_contexts_cleared_for_owner(owner);+ }+ RuntimeContextProtocolEvent::Created(event) => {+ conn.record_runtime_contexts_reported_for_owner(owner);+ record_child_default_context_delivery_for_owner(conn, owner, event);+ }+ RuntimeContextProtocolEvent::Destroyed(event) => {+ if let Some(realm_id) = event.realm_id.as_ref() {+ conn.clear_runtime_remote_objects_for_realm_for_owner(owner, realm_id.as_str());+ }+ }+ }+}+#[cfg(test)]pub(crate) fn qualify_runtime_context_protocol_event_for_session_owner(conn: &CdpConnection,@@ -255,6 +282,35 @@ pub(crate) fn qualify_runtime_context_protocol_event_for_session_owner_typed(}}+pub(crate) fn qualify_runtime_context_protocol_event_for_owner_typed(+ conn: &CdpConnection,+ event: &mut RuntimeContextProtocolEvent,+ owner: &CommandOwnerScope,+) {+ if owner.session_id().is_some() {+ qualify_runtime_context_protocol_event_for_session_owner_typed(+ conn,+ event,+ owner.session_id(),+ );+ return;+ }+ let Some((_, Some(target_id))) =+ conn.target_owner_identity_for_route(owner.session_id(), owner.session_owner_route())+ else {+ return;+ };+ match event {+ RuntimeContextProtocolEvent::Created(event) => {+ qualify_runtime_realm_id(&target_id, &mut event.realm_id);+ }+ RuntimeContextProtocolEvent::Destroyed(event) => {+ qualify_runtime_realm_id(&target_id, &mut event.realm_id);+ }+ RuntimeContextProtocolEvent::Cleared(_) => {}+ }+}+fn qualify_worker_runtime_context_event_for_session_owner(conn: &CdpConnection,event: &mut RuntimeContextProtocolEvent,@@ -345,9 +401,9 @@ pub(crate) fn emit_runtime_context_protocol_background_event_typed(/// must never be suppressed here. Keeping the replay cursor at this boundary/// makes repeated `Runtime.enable` calls idempotent without turning the cursor/// into a second real-time event arbiter.-pub(crate) fn should_emit_child_default_context_inventory_replay_once(+pub(crate) fn should_emit_child_default_context_inventory_replay_once_for_owner(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,root_frame_id: Option<&str>,event: &RuntimeContextProtocolEvent,) -> bool {@@ -366,14 +422,18 @@ pub(crate) fn should_emit_child_default_context_inventory_replay_once(return true;}if conn- .target_devtools_session_state_for_session(session_id)+ .target_devtools_session_state_for_route(owner.session_id(), owner.session_owner_route()).is_some_and(|state| {state.has_emitted_child_default_execution_context_id(execution_context_id)}){return false;}- mark_child_default_context_event_emitted(conn, session_id, execution_context_id);+ let _ = conn.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.mark_child_default_execution_context_id_emitted(execution_context_id),+ );true}@@ -405,6 +465,33 @@ fn record_child_default_context_delivery(mark_child_default_context_event_emitted(conn, session_id, execution_context_id);}+fn record_child_default_context_delivery_for_owner(+ conn: &mut CdpConnection,+ owner: &CommandOwnerScope,+ event: &RuntimeExecutionContextEvent,+) {+ let Some(execution_context_id) = child_default_execution_context_id(event) else {+ return;+ };+ let Some(root_frame_id) = conn+ .runtime_session_owner_frame_id_for_route(owner.session_id(), owner.session_owner_route())+ else {+ return;+ };+ if event+ .frame_id+ .as_ref()+ .is_none_or(|frame_id| frame_id.as_str() == root_frame_id)+ {+ return;+ }+ let _ = conn.with_target_devtools_session_state_for_route_mut(+ owner.session_id(),+ owner.session_owner_route(),+ |state| state.mark_child_default_execution_context_id_emitted(execution_context_id),+ );+}+fn mark_child_default_context_event_emitted(conn: &mut CdpConnection,session_id: Option<&str>,@@ -417,7 +504,7 @@ fn mark_child_default_context_event_emitted(#[cfg(test)]mod tests {- use crate::conn::{BrowserContext, CdpConnection};+ use crate::conn::{BrowserContext, CdpConnection, CommandOwnerScope};use crate::conn::{ServiceWorkerTargetState, SharedWorkerTargetState};use crate::devtools_runtime::AutomationEvent;use moli_core::{RendererOwnerLocalHostId, page::RendererServiceWorkerVersionStatus};@@ -650,18 +737,18 @@ mod tests {super::record_child_default_context_delivery(&mut conn, Some("SID-1"), created);assert!(- !super::should_emit_child_default_context_inventory_replay_once(+ !super::should_emit_child_default_context_inventory_replay_once_for_owner(&mut conn,- Some("SID-1"),+ &CommandOwnerScope::for_session("SID-1"),Some("TID-1"),&event,),"Runtime.enable inventory must not replay a child context already delivered by V8");assert!(- super::should_emit_child_default_context_inventory_replay_once(+ super::should_emit_child_default_context_inventory_replay_once_for_owner(&mut conn,- Some("SID-other"),+ &CommandOwnerScope::for_session("SID-other"),Some("TID-1"),&event,),diff --git a/moli-protocol/src/domains/storage/ops.rs b/moli-protocol/src/domains/storage/ops.rsindex caf808e6a..80594df17 100644--- a/moli-protocol/src/domains/storage/ops.rs+++ b/moli-protocol/src/domains/storage/ops.rs@@ -478,12 +478,19 @@ fn start_get_storage_key_for_frame_command(}};- let Some((target_id, target_url, _, _)) =- conn.target_session_owner_frame_tree_identity(cmd.session_id)+ let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);+ let Some((target_id, target_url, _, _)) = conn+ .target_session_owner_frame_tree_identity_for_route(+ owner_scope.session_id(),+ owner_scope.session_owner_route(),+ )else {let plan = if conn.browser_context.is_none()&& conn- .target_owner_identity_for_session(cmd.session_id)+ .target_owner_identity_for_route(+ owner_scope.session_id(),+ owner_scope.session_owner_route(),+ ).is_none(){CommandOutputPlan::error(-31998, "BrowserContextNotLoaded")@@ -494,7 +501,6 @@ fn start_get_storage_key_for_frame_command(};if params.frame_id == target_id {- let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);if let Some(page) =loaded_page_mut_for_session(conn, cmd.session_id, owner_scope.session_owner_route()){@@ -520,10 +526,12 @@ fn start_get_storage_key_for_frame_command());}- if let Err(message) = conn.ensure_document_accessible_for_session_owner(cmd.session_id) {+ if let Err(message) = conn.ensure_document_accessible_for_route(+ owner_scope.session_id(),+ owner_scope.session_owner_route(),+ ) {return StorageCommandTaskStep::Complete(CommandOutputPlan::error(-32000, message));}- let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);let Some(page) =loaded_page_mut_for_session(conn, cmd.session_id, owner_scope.session_owner_route())else {diff --git a/moli-protocol/src/domains/storage/tests.rs b/moli-protocol/src/domains/storage/tests.rsindex 0b6b7a19a..66821dd35 100644--- a/moli-protocol/src/domains/storage/tests.rs+++ b/moli-protocol/src/domains/storage/tests.rs@@ -860,7 +860,7 @@ async fn pending_storage_key_keeps_background_owner_route_across_completion() {let mut background = PageTargetHost::with_url("TID-storage-background".to_owned(),- None,+ Some("SID-storage-background".to_owned()),background_page.final_url().as_str().to_owned(),);background.replace_loaded_page(Some(background_page));@@ -874,52 +874,33 @@ async fn pending_storage_key_keeps_background_owner_route_across_completion() {bc.insert_page_target_host(background);ctx.conn.browser_context = Some(bc);- let background_route = ctx- .conn- .target_session_route_for_target_id("TID-storage-background")- .expect("background target route");let raw = serde_json::to_string(&json!({"id": 104,"method": "Storage.getStorageKeyForFrame",- "params": { "frameId": "TID-storage-background" }+ "params": { "frameId": "TID-storage-background" },+ "sessionId": "SID-storage-background"})).unwrap();- let pending = {- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(background_route.clone()));- let step = ctx.conn.start_command_dispatch(&raw);- ctx.conn- .replace_none_session_owner_route_override(previous_route);- match step {- CdpCommandTaskStep::Pending(pending) => pending,- CdpCommandTaskStep::Complete(outcome) => {- panic!(- "background Storage.getStorageKeyForFrame should snapshot the live background page: {:?}",- outcome.into_parts().0- )- }+ let pending = match ctx.conn.start_command_dispatch(&raw) {+ CdpCommandTaskStep::Pending(pending) => pending,+ CdpCommandTaskStep::Complete(outcome) => {+ panic!(+ "background Storage.getStorageKeyForFrame should snapshot the live background page: {:?}",+ outcome.into_parts().0+ )}};- let active_route = ctx- .conn- .target_session_route_for_target_id("TID-storage-active")- .expect("active target route");- let previous_route = ctx- .conn- .replace_none_session_owner_route_override(Some(active_route));let (messages, scheduler_events) = ctx.complete_command_task_step_for_test(CdpCommandTaskStep::Pending(pending)).await;- ctx.conn- .replace_none_session_owner_route_override(previous_route);assert!(scheduler_events.is_empty());assert_eq!(messages,vec![json!({"id": 104,+ "sessionId": "SID-storage-background","result": {"storageKey": first_party_storage_key_for_origin(&background_origin)}diff --git a/moli-protocol/src/domains/target.rs b/moli-protocol/src/domains/target.rsindex bbeafe9e8..232a2021e 100644--- a/moli-protocol/src/domains/target.rs+++ b/moli-protocol/src/domains/target.rs@@ -38,12 +38,14 @@ pub(crate) use popup::{schedule_initial_document_target_url_navigation_after_debugger_barrier_release_for_target,schedule_initial_document_target_url_navigation_after_debugger_resume,};-pub(crate) fn popup_activation_creates_new_target(+pub(crate) fn popup_activation_creates_new_target_for_route(conn: &CdpConnection,owner_session_id: Option<&str>,+ owner_route: Option<&crate::conn::CdpSessionRoute>,target_name: &str,) -> bool {- if let Some((browser_context_id, _)) = conn.target_owner_identity_for_session(owner_session_id)+ if let Some((browser_context_id, _)) =+ conn.target_owner_identity_for_route(owner_session_id, owner_route){return conn.browser_context_by_id(&browser_context_id)@@ -1269,7 +1271,7 @@ mod devtools_runtime_entry_tests {assert!(conn.claim_pending_inspector_await_for_scheduler_deferred_reply(7101,- Some("SID-runtime-ready-close"),+ &crate::conn::CommandOwnerScope::for_session("SID-runtime-ready-close"),).is_some(),"test must cover scheduler-deferred Runtime await owner cleanup"diff --git a/moli-protocol/src/domains/target/auto_attach.rs b/moli-protocol/src/domains/target/auto_attach.rsindex 287ae65cd..f90288aa2 100644--- a/moli-protocol/src/domains/target/auto_attach.rs+++ b/moli-protocol/src/domains/target/auto_attach.rs@@ -1290,7 +1290,7 @@ async fn ensure_initial_document_for_attached_page_targets_async(let Some(route) = conn.target_session_route_for_target_id(target_id) else {continue;};- let owner = crate::conn::CommandOwnerScope::for_implicit_route(Some(route));+ let owner = crate::conn::CommandOwnerScope::for_route(route);let pending = match conn.start_initial_document_page_ensure_for_owner(&owner) {Ok(pending) => pending,Err(message) => {diff --git a/moli-protocol/src/domains/target/closing.rs b/moli-protocol/src/domains/target/closing.rsindex ea49d9eaa..e0404d852 100644--- a/moli-protocol/src/domains/target/closing.rs+++ b/moli-protocol/src/domains/target/closing.rs@@ -175,9 +175,7 @@ async fn close_target_inner_async(let owner_scope = session_id.as_deref().map(crate::conn::CommandOwnerScope::for_session)- .unwrap_or_else(|| {- crate::conn::CommandOwnerScope::for_implicit_route(Some(target_route))- });+ .unwrap_or_else(|| crate::conn::CommandOwnerScope::for_route(target_route));let renderer_output_predecessor =events::fail_pending_fetch_state_for_target_background_events_async(conn,diff --git a/moli-protocol/src/domains/target/creation.rs b/moli-protocol/src/domains/target/creation.rsindex 0185c3138..cedf91989 100644--- a/moli-protocol/src/domains/target/creation.rs+++ b/moli-protocol/src/domains/target/creation.rs@@ -232,7 +232,7 @@ fn start_devtools_create_target_command_with_result_host(let initial_document_route =conn.target_session_route_for_target_id(created_target_id.as_str());let pending_initial_document = if let Some(route) = initial_document_route {- let owner = crate::conn::CommandOwnerScope::for_implicit_route(Some(route));+ let owner = crate::conn::CommandOwnerScope::for_route(route);conn.start_initial_document_page_ensure_for_owner(&owner)} else {Ok(None)diff --git a/moli-protocol/src/domains/target/popup.rs b/moli-protocol/src/domains/target/popup.rsindex 098e053a5..a1bbd2748 100644--- a/moli-protocol/src/domains/target/popup.rs+++ b/moli-protocol/src/domains/target/popup.rs@@ -313,7 +313,7 @@ async fn ensure_popup_initial_document_page_async(let Some(route) = conn.target_session_route_for_target_id(target_id) else {return false;};- let owner = CommandOwnerScope::for_implicit_route(Some(route));+ let owner = CommandOwnerScope::for_route(route);{let pending = match conn.start_initial_document_page_ensure_for_owner(&owner) {Ok(pending) => pending,@@ -417,7 +417,7 @@ pub(super) async fn start_target_url_navigation_if_allowed_background_events_asyelse {return;};- let owner_scope = CommandOwnerScope::for_implicit_route(Some(route));+ let owner_scope = CommandOwnerScope::for_route(route);crate::domains::page::navigate_command_owner_from_renderer_background_events_async(conn,out,diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_smoke_playwright.rs b/moli-protocol/src/domains/target/tests/tests_cdp_smoke_playwright.rsindex dedef663d..321cd9d92 100644--- a/moli-protocol/src/domains/target/tests/tests_cdp_smoke_playwright.rs+++ b/moli-protocol/src/domains/target/tests/tests_cdp_smoke_playwright.rs@@ -134,7 +134,7 @@ async fn arm_popup_route(ctx.expect_result(base + 2, json!({}), Some(popup_session_id));let fetch_snapshot = ctx.conn- .target_fetch_subresource_interception_snapshot_for_session_owner(Some(popup_session_id))+ .target_fetch_subresource_interception_snapshot_for_route(Some(popup_session_id), None).expect("popup target Fetch configuration");let matching_sessions = fetch_snapshot.matching_request_stage_pause_sessions(Some(popup_session_id),diff --git a/moli-protocol/src/domains/target/tests/tests_target_basics.rs b/moli-protocol/src/domains/target/tests/tests_target_basics.rsindex 928328e9c..b53bfc237 100644--- a/moli-protocol/src/domains/target/tests/tests_target_basics.rs+++ b/moli-protocol/src/domains/target/tests/tests_target_basics.rs@@ -1753,7 +1753,9 @@ async fn same_context_targets_do_not_replay_bare_isolated_worlds_after_switching"data:text/html,<title>target-a-replay</title><div id='ok'>target a replay</div>";let target_a_commit = ctx.conn- .prepare_loaded_navigation_commit_for_session_owner(Some("SID-active"))+ .prepare_loaded_navigation_commit_for_owner(&crate::conn::CommandOwnerScope::for_session(+ "SID-active",+ )).expect("target A commit state should be available before navigation");assert!(target_a_commit.runtime_frontend_enabled,diff --git a/moli-protocol/src/domains/target/worker_target.rs b/moli-protocol/src/domains/target/worker_target.rsindex a7b0c7623..33d232de5 100644--- a/moli-protocol/src/domains/target/worker_target.rs+++ b/moli-protocol/src/domains/target/worker_target.rs@@ -31,10 +31,10 @@ use crate::devtools_runtime::{};use crate::{conn::{- BackgroundProtocolEvent, CdpConnection, PreparedTargetAttach, PreparedTargetHostDelta,- RendererPageResidenceIdentity, ServiceWorkerRuntimeExceptionSnapshot,- ServiceWorkerTargetState, SharedWorkerTargetState, TargetPageResidenceIdentity,- TargetServiceWorkerProtocolAttachmentIdentity,+ BackgroundProtocolEvent, CdpConnection, CommandOwnerScope, PreparedTargetAttach,+ PreparedTargetHostDelta, RendererPageResidenceIdentity,+ ServiceWorkerRuntimeExceptionSnapshot, ServiceWorkerTargetState, SharedWorkerTargetState,+ TargetPageResidenceIdentity, TargetServiceWorkerProtocolAttachmentIdentity,TargetServiceWorkerProtocolAttachmentRetirement, TargetServiceWorkerRunIdentity,TargetServiceWorkerRunRetirement, TargetServiceWorkerRuntimeAttachmentIdentity,TargetServiceWorkerVersionIdentity, TargetServiceWorkerVersionRetirement,@@ -428,19 +428,23 @@ pub(in crate::domains) fn service_worker_target_lifecycle_prepared_outputs_for_epub(in crate::domains) fn dedicated_worker_target_lifecycle_prepared_outputs_for_event(conn: &mut CdpConnection,- session_id: Option<&str>,+ owner: &CommandOwnerScope,event: RendererDedicatedWorkerTargetEvent,) -> TargetPreparedOutputs {- let Some(owner_page) = conn.target_page_residence_identity_for_session(session_id) else {+ let session_id = owner.session_id();+ let owner_route = owner.session_owner_route();+ let Some(owner_page) = conn.target_page_residence_identity_for_route(session_id, owner_route)+ else {return TargetPreparedOutputs::default();};let Some(owner_renderer_page) =- conn.renderer_page_residence_identity_for_session_owner(session_id)+ conn.renderer_page_residence_identity_for_route(session_id, owner_route)else {return TargetPreparedOutputs::default();};let browser_context_id = owner_page.browser_context_id().to_owned();- let owner_page_network_sessions = conn.network_event_session_ids_for_session_owner(session_id);+ let owner_page_network_sessions =+ conn.network_event_session_ids_for_route(session_id, owner_route);dedicated_worker_target_lifecycle_outputs_for_events(conn,browser_context_id,@@ -2287,12 +2291,13 @@ async fn worker_target_removal_background_events_async(conn: &mut CdpConnection,outputs: TargetPreparedOutputs,) -> Vec<BackgroundProtocolEvent> {+ let owner = CommandOwnerScope::capture(conn, None);let mut command_context = crate::conn::CommandDispatchContext::default();let mut prepared_outputs =ProtocolOutputPayloads::from_slot(TargetPreparedOutputSlot::from_outputs(outputs));emit_target_lifecycle_events(conn,- &mut ProtocolOutputProjectionContext::new(None, &mut command_context),+ &mut ProtocolOutputProjectionContext::new(&owner, &mut command_context),Some(&mut prepared_outputs),).await;@@ -2321,9 +2326,10 @@ pub(super) async fn close_shared_worker_target_for_target_close_async(let outputs = remove_shared_worker_target(conn, &browser_context_id, instance_id);let mut prepared_outputs =ProtocolOutputPayloads::from_slot(TargetPreparedOutputSlot::from_outputs(outputs));+ let owner = CommandOwnerScope::capture(conn, None);emit_target_lifecycle_events(conn,- &mut ProtocolOutputProjectionContext::new(None, command_context),+ &mut ProtocolOutputProjectionContext::new(&owner, command_context),Some(&mut prepared_outputs),).await;@@ -2357,9 +2363,10 @@ pub(super) async fn close_dedicated_worker_target_for_target_close_async();let mut prepared_outputs =ProtocolOutputPayloads::from_slot(TargetPreparedOutputSlot::from_outputs(outputs));+ let owner = CommandOwnerScope::capture(conn, None);emit_target_lifecycle_events(conn,- &mut ProtocolOutputProjectionContext::new(None, command_context),+ &mut ProtocolOutputProjectionContext::new(&owner, command_context),Some(&mut prepared_outputs),).await;@@ -3204,10 +3211,11 @@ fn route_worker_runtime_inspector_messages_into(response_events: &mut Vec<BackgroundProtocolEvent>,background_events: &mut Vec<BackgroundProtocolEvent>,) -> bool {- conn.route_renderer_runtime_inspector_messages_with_background_events_into(+ let owner = crate::conn::CommandOwnerScope::for_session(session_id);+ conn.route_renderer_runtime_inspector_messages_for_owner_with_background_events_into(messages,None,- Some(session_id),+ &owner,response_events,background_events,)@@ -3871,10 +3879,11 @@ mod tests {) -> Vec<crate::conn::BackgroundProtocolEvent> {let mut prepared_outputs =ProtocolOutputPayloads::from_slot(TargetPreparedOutputSlot::from_outputs(outputs));+ let owner = CommandOwnerScope::capture(conn, None);let mut command_context = crate::conn::CommandDispatchContext::default();emit_target_lifecycle_events(conn,- &mut ProtocolOutputProjectionContext::new(None, &mut command_context),+ &mut ProtocolOutputProjectionContext::new(&owner, &mut command_context),Some(&mut prepared_outputs),).await;@@ -6906,10 +6915,11 @@ mod tests {);let mut prepared_outputs =ProtocolOutputPayloads::from_slot(TargetPreparedOutputSlot::from_outputs(outputs));+ let owner = CommandOwnerScope::capture(&conn, None);let mut command_context = crate::conn::CommandDispatchContext::default();emit_target_lifecycle_events(&mut conn,- &mut ProtocolOutputProjectionContext::new(None, &mut command_context),+ &mut ProtocolOutputProjectionContext::new(&owner, &mut command_context),Some(&mut prepared_outputs),).await;diff --git a/moli-protocol/src/domains/target/worker_target_attachment_tests.rs b/moli-protocol/src/domains/target/worker_target_attachment_tests.rsindex 85eb7f997..88d76da30 100644--- a/moli-protocol/src/domains/target/worker_target_attachment_tests.rs+++ b/moli-protocol/src/domains/target/worker_target_attachment_tests.rs@@ -12,7 +12,7 @@ use serde_json::{Value, json};use super::*;use crate::{- conn::{BrowserContext, CdpTargetFilter, CommandDispatchContext},+ conn::{BrowserContext, CdpTargetFilter, CommandDispatchContext, CommandOwnerScope},devtools_runtime::AutomationEvent,domains::activity::{ProtocolOutputPayloads, ProtocolOutputProjectionContext},};@@ -66,10 +66,11 @@ async fn drain() -> Vec<crate::conn::BackgroundProtocolEvent> {let mut prepared =ProtocolOutputPayloads::from_slot(TargetPreparedOutputSlot::from_outputs(outputs));+ let owner = CommandOwnerScope::capture(conn, None);let mut command = CommandDispatchContext::default();emit_target_lifecycle_events(conn,- &mut ProtocolOutputProjectionContext::new(None, &mut command),+ &mut ProtocolOutputProjectionContext::new(&owner, &mut command),Some(&mut prepared),).await;diff --git a/moli-protocol/src/domains/tracing/mod.rs b/moli-protocol/src/domains/tracing/mod.rsindex a72057f9e..629068ecd 100644--- a/moli-protocol/src/domains/tracing/mod.rs+++ b/moli-protocol/src/domains/tracing/mod.rs@@ -98,10 +98,6 @@ pub(crate) enum TracingCommandTaskStep {}impl PendingTracingCommandDispatch {- pub(crate) fn session_id(&self) -> Option<&str> {- self.session_id.as_deref()- }-pub(crate) async fn wait(self) -> CompletedTracingCommandDispatch {let completed = match self.pending {PendingTracingOperation::Start(pending) => {diff --git a/moli-protocol/src/testing.rs b/moli-protocol/src/testing.rsindex c592fef87..d8e7ffe7e 100644--- a/moli-protocol/src/testing.rs+++ b/moli-protocol/src/testing.rs@@ -306,9 +306,10 @@ impl TestContext {mut navigation: crate::conn::LoadedNavigation,session_id: Option<&str>,) {+ let owner = crate::conn::CommandOwnerScope::capture(&self.conn, session_id);let (_, target_id) = self.conn- .target_owner_identity_for_session(session_id)+ .target_owner_identity_for_route(owner.session_id(), owner.session_owner_route()).expect("navigation fixture requires an installed browser context");let target_id = target_id.expect("navigation fixture requires an exact target");let renderer_output_predecessor = navigation.renderer_output_predecessor;@@ -320,8 +321,8 @@ impl TestContext {.expect("navigation fixture must retain its frozen Document commit identity");let page_commit = self.conn- .commit_loaded_navigation_page_for_session_owner_async(- session_id,+ .commit_loaded_navigation_page_for_owner_async(+ &owner,navigation.page,LoadedNavigationRendererAttachmentCommit::Prepare(None),&final_url,@@ -337,29 +338,29 @@ impl TestContext {);let _ = self.conn- .commit_loaded_navigation_target_identity_for_session_owner(- session_id,+ .commit_loaded_navigation_target_identity_for_owner(+ &owner,&main_document_commit,&final_url,);- let (binding, _) = self- .conn- .bind_renderer_document_lifecycle_for_session_owner(- session_id,- page_creation_artifacts,- None,- target_id,- crate::domains::page::LOADER_ID.to_owned(),- );+ let (binding, _) = self.conn.bind_renderer_document_lifecycle_for_owner(+ &owner,+ page_creation_artifacts,+ None,+ target_id,+ crate::domains::page::LOADER_ID.to_owned(),+ );let binding =binding.expect("navigation fixture must install its exact renderer Document binding");if let Some(navigation_engine) = navigation_engine {self.conn- .adopt_loaded_navigation_engine_for_session_owner(session_id, navigation_engine);+ .adopt_loaded_navigation_engine_for_owner(&owner, navigation_engine);}assert_eq!(- self.conn- .target_root_document_lifecycle_identity_for_session(session_id),+ self.conn.target_root_document_lifecycle_identity_for_route(+ owner.session_id(),+ owner.session_owner_route(),+ ),Some(binding.renderer_document_identity()),"navigation fixture must retain its exact renderer Document binding");@@ -693,6 +694,8 @@ impl TestContext {drain_after_command: bool,) -> Vec<CdpSchedulerEvent> {let output_session_id = command.command_output_session_id().map(str::to_owned);+ let output_owner =+ crate::conn::CommandOwnerScope::capture(&self.conn, output_session_id.as_deref());let mut protocol_events = Vec::new();let mut scheduler_events = Vec::new();let mut command_context = crate::conn::CommandDispatchContext::default();@@ -712,7 +715,7 @@ impl TestContext {if drain_after_command && completed {crate::domains::activity::project_protocol_local_command_outputs(&mut self.conn,- output_session_id.as_deref(),+ &output_owner,&mut command_context,).await;@@ -844,12 +847,15 @@ impl TestContext {CdpCommandTaskStep::Pending(mut pending)if pending.waits_for_scheduler_deferred_inspector_reply() =>{- let session_id = pending.session_id().map(str::to_owned);+ let owner = pending+ .runtime_command_owner_scope()+ .expect("deferred Runtime commands have an exact owner")+ .clone();protocol_events.extend(pending.take_scheduler_deferred_inspector_reply_events());crate::domains::activity::project_protocol_local_command_outputs(&mut self.conn,- session_id.as_deref(),+ &owner,command_context,).await;