Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(protocol): scope navigation gates to targets

ldm0c1505d084567
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rs
index ad6780e1b..7c98aa6f3 100644
--- a/moli-protocol/src/conn.rs
+++ b/moli-protocol/src/conn.rs
@@ -1468,6 +1468,56 @@ impl CdpConnection {
.any(BrowserContext::has_inflight_background_navigation)
}
+ pub fn has_inflight_background_navigation_for_target(&self, target_id: &str) -> bool {
+ let Some(browser_context_id) = self.browser_context_id_for_target(target_id) else {
+ return false;
+ };
+ self.browser_context_by_id(browser_context_id)
+ .is_some_and(|browser_context| {
+ browser_context.has_inflight_background_navigation_for_target(target_id)
+ })
+ }
+
+ fn target_id_for_session_owner(&self, session_id: Option<&str>) -> Option<String> {
+ let (browser_context_id, target_id) = self.target_owner_identity_for_session(session_id)?;
+ target_id.or_else(|| {
+ self.browser_context_by_id(&browser_context_id)
+ .and_then(BrowserContext::active_target_id)
+ .map(str::to_owned)
+ })
+ }
+
+ pub fn background_navigation_target_id_for_event(
+ &self,
+ event: &BackgroundProtocolEvent,
+ ) -> Option<String> {
+ event
+ .navigation_gate_target_id()
+ .filter(|target_id| self.browser_context_id_for_target(target_id).is_some())
+ .map(str::to_owned)
+ .or_else(|| self.target_id_for_session_owner(event.protocol_session_id()))
+ }
+
+ pub fn has_inflight_background_navigation_for_devtools_context(
+ &self,
+ context: &crate::devtools_runtime::DevToolsCommandContext,
+ ) -> bool {
+ context
+ .target_id
+ .as_ref()
+ .map(crate::devtools_runtime::DevToolsTargetId::as_str)
+ .map(str::to_owned)
+ .or_else(|| {
+ self.target_id_for_session_owner(
+ context
+ .session_id
+ .as_ref()
+ .map(crate::devtools_runtime::DevToolsSessionId::as_str),
+ )
+ })
+ .is_some_and(|target_id| self.has_inflight_background_navigation_for_target(&target_id))
+ }
+
pub fn has_pending_document_navigation_for_session_owner(
&self,
session_id: Option<&str>,
diff --git a/moli-protocol/src/conn/bidi_channel_work.rs b/moli-protocol/src/conn/bidi_channel_work.rs
index 4da2e0958..fedbc0a8b 100644
--- a/moli-protocol/src/conn/bidi_channel_work.rs
+++ b/moli-protocol/src/conn/bidi_channel_work.rs
@@ -35,6 +35,10 @@ impl BidiChannelPageOwner {
self.attachment.session_id()
}
+ pub(crate) fn target_id(&self) -> Option<&str> {
+ self.attachment.page_owner().target_id()
+ }
+
pub(crate) fn enter<'a>(
&self,
conn: &'a mut CdpConnection,
diff --git a/moli-protocol/src/conn/output.rs b/moli-protocol/src/conn/output.rs
index b622319f7..0a5263926 100644
--- a/moli-protocol/src/conn/output.rs
+++ b/moli-protocol/src/conn/output.rs
@@ -880,6 +880,61 @@ impl ProtocolDeliveryEnvelope {
self.route.wire_session_id()
}
+ pub(crate) fn navigation_gate_target_id(&self) -> Option<&str> {
+ if let Some(target_id) = self.route.navigation_gate_target_id() {
+ return Some(target_id);
+ }
+ let BackgroundProtocolEventPayload::Protocol(event) = &self.payload else {
+ return None;
+ };
+ match event.automation_event.as_deref()? {
+ AutomationEvent::NetworkBeforeRequestSent(event)
+ | AutomationEvent::NetworkResponseStarted(event)
+ | AutomationEvent::NetworkResponseCompleted(event)
+ | AutomationEvent::NetworkFetchError(event)
+ | AutomationEvent::NetworkAuthRequired(event)
+ | AutomationEvent::RequestPaused(event) => Some(event.target_id.as_str()),
+ AutomationEvent::TargetCreated(event) | AutomationEvent::TargetDestroyed(event) => {
+ Some(event.target_id.as_str())
+ }
+ AutomationEvent::TargetAttached(event) => Some(event.target_id.as_str()),
+ AutomationEvent::TargetDetached(event) => Some(event.target_id.as_str()),
+ AutomationEvent::NavigationFrame(event) => Some(event.target_id.as_str()),
+ AutomationEvent::NavigationStarted(event)
+ | AutomationEvent::DomContentLoaded(event)
+ | AutomationEvent::Load(event) => Some(event.target_id.as_str()),
+ AutomationEvent::PageLifecycle(event) => Some(event.target_id.as_str()),
+ AutomationEvent::SameDocumentNavigation(event) => Some(event.target_id.as_str()),
+ AutomationEvent::UserPromptClosed(event) => {
+ event.target_id.as_ref().map(|target_id| target_id.as_str())
+ }
+ AutomationEvent::LogEntryAdded(event) => {
+ event.target_id.as_ref().map(|target_id| target_id.as_str())
+ }
+ AutomationEvent::RuntimeConsoleApiCalled(event) => {
+ event.target_id.as_ref().map(|target_id| target_id.as_str())
+ }
+ AutomationEvent::RuntimeExecutionContextCreated(event)
+ | AutomationEvent::RuntimeExecutionContextDestroyed(event) => {
+ event.target_id.as_ref().map(|target_id| target_id.as_str())
+ }
+ AutomationEvent::RuntimeExecutionContextsCleared(event) => {
+ event.target_id.as_ref().map(|target_id| target_id.as_str())
+ }
+ AutomationEvent::ScriptMessage(event) => {
+ event.target_id.as_ref().map(|target_id| target_id.as_str())
+ }
+ AutomationEvent::ScriptException(event) => {
+ event.target_id.as_ref().map(|target_id| target_id.as_str())
+ }
+ AutomationEvent::PageJavaScriptDialogOpening(_)
+ | AutomationEvent::PageFileChooserOpened(_)
+ | AutomationEvent::BrowserDownloadWillBegin(_)
+ | AutomationEvent::BrowserDownloadProgress(_)
+ | AutomationEvent::DomSetChildNodes(_) => None,
+ }
+ }
+
pub fn route_is_current(&self, conn: &CdpConnection) -> bool {
self.route.is_current(conn)
}
diff --git a/moli-protocol/src/conn/output/delivery_route.rs b/moli-protocol/src/conn/output/delivery_route.rs
index 9ea35e8f5..87be715f8 100644
--- a/moli-protocol/src/conn/output/delivery_route.rs
+++ b/moli-protocol/src/conn/output/delivery_route.rs
@@ -64,6 +64,16 @@ impl ProtocolDeliveryRoute {
self.wire_session.as_deref()
}
+ pub(super) fn navigation_gate_target_id(&self) -> Option<&str> {
+ self.capabilities
+ .as_deref()?
+ .root_document
+ .as_ref()?
+ .attachment()
+ .page_owner()
+ .target_id()
+ }
+
pub(super) fn ensure_wire_session_id(&mut self, session_id: &str) {
match self.wire_session.as_deref() {
Some(existing) => assert_eq!(
diff --git a/moli-protocol/src/conn/state/browser_context.rs b/moli-protocol/src/conn/state/browser_context.rs
index d904db4b0..3d7a32d39 100644
--- a/moli-protocol/src/conn/state/browser_context.rs
+++ b/moli-protocol/src/conn/state/browser_context.rs
@@ -1208,6 +1208,17 @@ impl BrowserContext {
.any(|target| target.runtime_slot().has_inflight_background_navigation())
}
+ pub(crate) fn has_inflight_background_navigation_for_target(&self, target_id: &str) -> bool {
+ if self.active_target_id() == Some(target_id) {
+ return self
+ .active_target
+ .runtime_slot
+ .has_inflight_background_navigation();
+ }
+ self.background_target(target_id)
+ .is_some_and(|target| target.runtime_slot().has_inflight_background_navigation())
+ }
+
pub(crate) fn accepts_document_body_completion_event(
&self,
token: &DocumentNavigationToken,
diff --git a/moli-protocol/src/conn/tests/mod.rs b/moli-protocol/src/conn/tests/mod.rs
index 086a94ed9..b1824b5bd 100644
--- a/moli-protocol/src/conn/tests/mod.rs
+++ b/moli-protocol/src/conn/tests/mod.rs
@@ -257,6 +257,45 @@ fn background_navigation_completion_sender_routes_explicit_session_owners() {
);
}
+#[test]
+fn navigation_gate_resolves_websocket_events_to_their_session_target() {
+ let mut conn = CdpConnection::new();
+ let mut target_a = BrowserContext::new("BID-A".to_owned());
+ target_a.set_active_target_id("TID-A");
+ target_a.attach_active_session("SID-A");
+ let navigation_a = target_a
+ .start_document_navigation_for_active_target("LOADER-A".to_owned())
+ .expect("target A should accept a navigation request");
+ conn.browser_context = Some(target_a);
+ assert!(conn.arm_background_navigation_completion(&navigation_a, None));
+
+ let mut target_b = BrowserContext::new("BID-B".to_owned());
+ target_b.set_active_target_id("TID-B");
+ target_b.attach_active_session("SID-B");
+ conn.inactive_browser_contexts.push(target_b);
+
+ let target_b_websocket = BackgroundProtocolEvent::immediate(json!({
+ "method": "Network.webSocketClosed",
+ "sessionId": "SID-B",
+ "params": {
+ "requestId": "REQ-B",
+ "timestamp": 1.0
+ }
+ }));
+
+ assert!(target_b_websocket.should_wait_for_background_navigation_completion());
+ assert!(conn.has_inflight_background_navigation());
+ assert_eq!(
+ conn.background_navigation_target_id_for_event(&target_b_websocket)
+ .as_deref(),
+ Some("TID-B")
+ );
+ assert!(
+ !conn.has_inflight_background_navigation_for_target("TID-B"),
+ "target A's navigation must not gate target B's WebSocket events"
+ );
+}
+
#[test]
fn none_session_owner_route_override_scope_restores_previous_route_on_drop() {
let mut conn = CdpConnection::new();
diff --git a/moli-protocol/src/conn/top_level_navigation_work.rs b/moli-protocol/src/conn/top_level_navigation_work.rs
index bff9d7e1c..e1045ae84 100644
--- a/moli-protocol/src/conn/top_level_navigation_work.rs
+++ b/moli-protocol/src/conn/top_level_navigation_work.rs
@@ -50,6 +50,10 @@ impl TopLevelLocationNavigationOwnerAction {
self.owner_scope.session_id()
}
+ pub(crate) fn target_id(&self) -> Option<&str> {
+ self.page_owner.target_id()
+ }
+
pub(crate) fn source_document(&self) -> moli_core::RendererDocumentLifecycleIdentity {
self.navigation.source_document()
}
diff --git a/moli-protocol/src/domains/activity/main_document.rs b/moli-protocol/src/domains/activity/main_document.rs
index 6533b6bd8..20054e6df 100644
--- a/moli-protocol/src/domains/activity/main_document.rs
+++ b/moli-protocol/src/domains/activity/main_document.rs
@@ -726,6 +726,17 @@ impl DeferredMainDocumentLoadCompletionActivity {
self.state.owner_scope.session_id()
}
+ pub(crate) fn target_id(&self) -> &str {
+ self.state
+ .navigation_activity
+ .document_navigation_token
+ .as_ref()
+ .map_or(
+ self.state.navigation_activity.state.frame_id.as_str(),
+ |token| token.target_id.as_str(),
+ )
+ }
+
pub(crate) fn observation_id(&self) -> DeferredMainDocumentLoadObservationId {
self.observation_id
}
diff --git a/moli-protocol/src/domains/activity/output_work.rs b/moli-protocol/src/domains/activity/output_work.rs
index 727710709..9973c2c5d 100644
--- a/moli-protocol/src/domains/activity/output_work.rs
+++ b/moli-protocol/src/domains/activity/output_work.rs
@@ -76,11 +76,24 @@ impl ProtocolOutputWork {
frame_id: String,
loader_id: String,
) -> Self {
- let page_owner = TargetPageResidenceIdentity::new(
+ Self::root_frame_stopped_loading_for_target_test_support(
+ session_ids,
"__protocol_output_test_context__".to_owned(),
- Some("__protocol_output_test_target__".to_owned()),
- 1,
- );
+ "__protocol_output_test_target__".to_owned(),
+ frame_id,
+ loader_id,
+ )
+ }
+
+ #[cfg(feature = "test-support")]
+ pub(super) fn root_frame_stopped_loading_for_target_test_support(
+ session_ids: Vec<Option<String>>,
+ browser_context_id: String,
+ target_id: String,
+ frame_id: String,
+ loader_id: String,
+ ) -> Self {
+ let page_owner = TargetPageResidenceIdentity::new(browser_context_id, Some(target_id), 1);
let attachments = session_ids
.into_iter()
.map(|session_id| {
@@ -97,6 +110,20 @@ impl ProtocolOutputWork {
)
}
+ pub(crate) fn navigation_gate_target_id(&self) -> Option<&str> {
+ match &self.payload {
+ ProtocolOutputPayload::RootFrameStoppedLoading(output) => {
+ let target_id = output.attachments.first()?.page_owner().target_id()?;
+ debug_assert!(
+ output.attachments.iter().all(|attachment| {
+ attachment.page_owner().target_id() == Some(target_id)
+ })
+ );
+ Some(target_id)
+ }
+ }
+ }
+
pub(crate) fn into_background_events(
self,
conn: &CdpConnection,
diff --git a/moli-protocol/src/domains/activity/scheduler_work.rs b/moli-protocol/src/domains/activity/scheduler_work.rs
index 687bea6b6..83f5aaec1 100644
--- a/moli-protocol/src/domains/activity/scheduler_work.rs
+++ b/moli-protocol/src/domains/activity/scheduler_work.rs
@@ -246,6 +246,29 @@ impl ProtocolSchedulerWork {
)
}
+ pub fn navigation_gate_target_id(&self) -> Option<&str> {
+ match &self.payload {
+ ProtocolSchedulerWorkPayload::ProtocolObservation(output) => {
+ output.navigation_gate_target_id()
+ }
+ ProtocolSchedulerWorkPayload::MainDocumentLoadOwnerAction(completion) => {
+ Some(completion.target_id())
+ }
+ ProtocolSchedulerWorkPayload::BidiChannelOwnerAction(action) => {
+ action.owner().target_id()
+ }
+ ProtocolSchedulerWorkPayload::TopLevelLocationNavigationOwnerAction(action) => {
+ action.target_id()
+ }
+ ProtocolSchedulerWorkPayload::PopupTargetNavigationOwnerAction(action) => {
+ Some(action.target_id())
+ }
+ ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(action) => {
+ Some(action.target_id())
+ }
+ }
+ }
+
pub fn is_top_level_location_navigation_owner_action(&self) -> bool {
matches!(
&self.payload,
@@ -370,6 +393,27 @@ impl ProtocolSchedulerWork {
),
)
}
+
+ #[cfg(feature = "test-support")]
+ pub(crate) fn root_frame_stopped_loading_for_target_test_support(
+ publish_sequence: u64,
+ session_ids: Vec<Option<String>>,
+ browser_context_id: String,
+ target_id: String,
+ frame_id: String,
+ loader_id: String,
+ ) -> Self {
+ Self::protocol_observation(
+ ProtocolWorkPublishSequence::new(publish_sequence),
+ ProtocolOutputWork::root_frame_stopped_loading_for_target_test_support(
+ session_ids,
+ browser_context_id,
+ target_id,
+ frame_id,
+ loader_id,
+ ),
+ )
+ }
}
pub(crate) enum ReadyProtocolSchedulerWork {
diff --git a/moli-protocol/src/test_support.rs b/moli-protocol/src/test_support.rs
index de9d74be2..f147819a2 100644
--- a/moli-protocol/src/test_support.rs
+++ b/moli-protocol/src/test_support.rs
@@ -25,6 +25,10 @@ impl BackgroundNavigationRequestFixture {
pub fn is_cancelled(&self) -> bool {
self.cancellation.is_cancelled()
}
+
+ pub fn target_id(&self) -> &str {
+ &self.token.target_id
+ }
}
pub fn arm_background_navigation_request(
@@ -38,11 +42,19 @@ pub fn arm_background_navigation_request(
.and_then(|context| context.active_target_id())
.expect("the default browser target must have an active target")
.to_owned();
+ arm_background_navigation_request_for_target(conn, &target_id, loader_id)
+}
+
+pub fn arm_background_navigation_request_for_target(
+ conn: &mut CdpConnection,
+ target_id: &str,
+ loader_id: &str,
+) -> BackgroundNavigationRequestFixture {
let token = conn
.browser_context
.as_mut()
.and_then(|context| {
- context.start_document_navigation_for_target(&target_id, loader_id.to_owned())
+ context.start_document_navigation_for_target(target_id, loader_id.to_owned())
})
.expect("the active target must accept a navigation request fixture");
let cancellation = conn
@@ -98,3 +110,21 @@ pub fn root_frame_stopped_loading_work(
loader_id,
)
}
+
+pub fn root_frame_stopped_loading_work_for_target(
+ publish_sequence: u64,
+ session_ids: Vec<Option<String>>,
+ browser_context_id: String,
+ target_id: String,
+ frame_id: String,
+ loader_id: String,
+) -> ProtocolSchedulerWork {
+ ProtocolSchedulerWork::root_frame_stopped_loading_for_target_test_support(
+ publish_sequence,
+ session_ids,
+ browser_context_id,
+ target_id,
+ frame_id,
+ loader_id,
+ )
+}
diff --git a/moli/src/cdp_scheduler.rs b/moli/src/cdp_scheduler.rs
index 055fd4514..c2c8b4537 100644
--- a/moli/src/cdp_scheduler.rs
+++ b/moli/src/cdp_scheduler.rs
@@ -101,12 +101,18 @@ pub(crate) enum CommandStartAction {
pub(crate) struct CdpScheduler {
conn: CdpConnection,
- pending_navigation_background_events: VecDeque<BackgroundProtocolEvent>,
+ pending_navigation_background_events: VecDeque<PendingNavigationBackgroundEvent>,
runtime_command_output_barriers: RuntimeCommandOutputBarriers,
queues: SchedulerQueues,
page_screencasts: HashMap<Option<String>, PageScreencastSchedule>,
}
+#[derive(Debug)]
+struct PendingNavigationBackgroundEvent {
+ target_id: Option<String>,
+ event: BackgroundProtocolEvent,
+}
+
#[derive(Debug)]
struct PageScreencastSchedule {
registration: PageScreencastRegistration,
@@ -129,6 +135,14 @@ fn next_page_screencast_deadline(now: TokioInstant, interval: Duration) -> Tokio
now + interval
}
+fn append_unique_target_ids(target_ids: &mut Vec<String>, additional: Vec<String>) {
+ for target_id in additional {
+ if !target_ids.contains(&target_id) {
+ target_ids.push(target_id);
+ }
+ }
+}
+
#[derive(Debug, Default)]
struct ForegroundNavigationNetworkBarrier {
wait_for_document_response_started: bool,
@@ -310,6 +324,23 @@ impl ProtocolOutputSequence {
self.events.append(&mut other.events);
}
+ fn navigation_gate_target_ids(&self, conn: &CdpConnection) -> Vec<String> {
+ let mut target_ids = Vec::new();
+ for event in &self.events {
+ let Some(target_id) = conn.background_navigation_target_id_for_event(event) else {
+ // A publication is released atomically. If even one event has
+ // no exact owner, keep the whole batch behind the conservative
+ // connection-wide gate rather than attributing it to a known
+ // sibling event's target.
+ return Vec::new();
+ };
+ if !target_ids.contains(&target_id) {
+ target_ids.push(target_id);
+ }
+ }
+ target_ids
+ }
+
fn split_network_observations(self) -> (Self, Self) {
let mut network = Vec::new();
let mut remaining = Vec::new();
@@ -818,6 +849,7 @@ impl CdpScheduler {
background_command_id: Option<u64>,
) -> DevToolsCommandExecution {
let navigation_wait = devtools_navigation_wait(&command);
+ let navigation_context = command.context().clone();
let outcome = self
.conn
.execute_devtools_command_with_protocol_events_with_background_command_id(
@@ -867,7 +899,7 @@ impl CdpScheduler {
&& matches!(navigation_wait, Some(DevToolsNavigationWait::Load))
{
protocol_output.append(
- self.drain_deferred_main_document_load_completion_for_wait()
+ self.drain_deferred_main_document_load_completion_for_wait(&navigation_context)
.await,
);
}
@@ -1033,7 +1065,10 @@ impl CdpScheduler {
let mut foreground_navigation_network_barrier =
ForegroundNavigationNetworkBarrier::for_navigation_wait(navigation_wait);
let mut protocol_output = match self
- .drain_inflight_background_navigation_before_internal_command(receivers)
+ .drain_inflight_background_navigation_before_internal_command(
+ receivers,
+ &navigation_context,
+ )
.await
{
Ok(output) => output,
@@ -1249,9 +1284,13 @@ impl CdpScheduler {
async fn drain_inflight_background_navigation_before_internal_command(
&mut self,
receivers: &mut CdpSchedulerEventReceivers,
+ context: &moli_protocol::devtools_runtime::DevToolsCommandContext,
) -> Result<ProtocolOutputSequence, RendererOutputTransportFailure> {
let mut out = ProtocolOutputSequence::empty();
- while self.has_inflight_background_navigation() {
+ while self
+ .conn
+ .has_inflight_background_navigation_for_devtools_context(context)
+ {
let Some(input) = receivers.recv_interleaved_input().await else {
return Err(RendererOutputTransportFailure::new(
out,
@@ -1519,11 +1558,14 @@ impl CdpScheduler {
async fn drain_deferred_main_document_load_completion_for_wait(
&mut self,
+ context: &moli_protocol::devtools_runtime::DevToolsCommandContext,
) -> ProtocolOutputSequence {
let mut out = ProtocolOutputSequence::empty();
loop {
- if self.has_inflight_background_navigation()
- || !self.front_protocol_residence_is_main_document_load_action()
+ if self
+ .conn
+ .has_inflight_background_navigation_for_devtools_context(context)
+ || !self.front_protocol_residence_is_main_document_load_action_for_context(context)
{
return out;
}
@@ -1566,7 +1608,7 @@ impl CdpScheduler {
&mut receivers.background_event_rx,
));
out.append(
- self.drain_deferred_main_document_load_completion_for_wait()
+ self.drain_deferred_main_document_load_completion_for_wait(context)
.await,
);
out.append(self.drain_background_events_around_inflight_navigation(
@@ -1629,7 +1671,7 @@ impl CdpScheduler {
pub(crate) async fn complete_ready_protocol_residences_after_command(
&mut self,
) -> ProtocolOutputSequence {
- if self.has_inflight_background_navigation() || self.has_pending_javascript_dialog() {
+ if self.has_pending_javascript_dialog() {
return ProtocolOutputSequence::empty();
}
let snapshot = self.queues.take_command_followup_snapshot();
@@ -1642,9 +1684,6 @@ impl CdpScheduler {
&mut self,
predecessor: &moli_core::RendererOutputFence,
) -> ProtocolOutputSequence {
- if self.has_inflight_background_navigation() {
- return ProtocolOutputSequence::empty();
- }
let cursor = predecessor.cursor();
let snapshot = self
.queues
@@ -1694,24 +1733,112 @@ impl CdpScheduler {
mut snapshot: VecDeque<ProtocolSchedulerResidence>,
) -> ProtocolOutputSequence {
let mut out = ProtocolOutputSequence::empty();
+ let mut retained = VecDeque::new();
+ let mut blocked_target_ids = Vec::new();
while let Some(mut residence) = snapshot.pop_front() {
- if self.has_inflight_background_navigation() || self.has_pending_javascript_dialog() {
- snapshot.push_front(residence);
- self.queues.restore_snapshot_to_front(snapshot);
+ if self.has_pending_javascript_dialog() {
+ retained.push_back(residence);
+ retained.append(&mut snapshot);
+ self.queues.restore_snapshot_to_front(retained);
return out;
}
+ let target_ids = self.protocol_residence_navigation_gate_target_ids(&residence);
+ let blocked_by_prior_residence = target_ids
+ .iter()
+ .any(|target_id| blocked_target_ids.contains(target_id));
+ let blocked_by_navigation =
+ self.protocol_targets_have_inflight_background_navigation(&target_ids);
+ if blocked_by_prior_residence || blocked_by_navigation {
+ if target_ids.is_empty() {
+ retained.push_back(residence);
+ retained.append(&mut snapshot);
+ self.queues.restore_snapshot_to_front(retained);
+ return out;
+ }
+ append_unique_target_ids(&mut blocked_target_ids, target_ids);
+ retained.push_back(residence);
+ continue;
+ }
self.queues
.satisfy_checked_out_client_turn_predecessor(&mut residence);
if !residence.is_ready_to_complete() {
- snapshot.push_front(residence);
- self.queues.restore_snapshot_to_front(snapshot);
- return out;
+ if target_ids.is_empty() {
+ retained.push_back(residence);
+ retained.append(&mut snapshot);
+ self.queues.restore_snapshot_to_front(retained);
+ return out;
+ }
+ append_unique_target_ids(&mut blocked_target_ids, target_ids);
+ retained.push_back(residence);
+ continue;
}
out.append(self.complete_protocol_residence(residence).await);
}
+ if !retained.is_empty() {
+ self.queues.restore_snapshot_to_front(retained);
+ }
out
}
+ fn protocol_residence_navigation_gate_target_ids(
+ &self,
+ residence: &ProtocolSchedulerResidence,
+ ) -> Vec<String> {
+ match residence {
+ ProtocolSchedulerResidence::RendererOutputPublication(work) => {
+ work.output.navigation_gate_target_ids(&self.conn)
+ }
+ ProtocolSchedulerResidence::ProtocolWork { work, .. } => work
+ .navigation_gate_target_id()
+ .map(str::to_owned)
+ .into_iter()
+ .collect(),
+ }
+ }
+
+ fn protocol_targets_have_inflight_background_navigation(&self, target_ids: &[String]) -> bool {
+ if target_ids.is_empty() {
+ return self.has_inflight_background_navigation();
+ }
+ target_ids.iter().any(|target_id| {
+ self.conn
+ .has_inflight_background_navigation_for_target(target_id)
+ })
+ }
+
+ fn next_ungated_protocol_residence_index(&self) -> Option<usize> {
+ // A target-local navigation is an ordering barrier only for later
+ // work from the same target. Keep those lanes ordered while allowing
+ // an independent target to advance, matching Chromium's per-frame
+ // NavigationRequest ownership.
+ let mut blocked_target_ids = Vec::new();
+ for (index, residence) in self.queues.protocol_residences.iter().enumerate() {
+ let target_ids = self.protocol_residence_navigation_gate_target_ids(residence);
+ if target_ids
+ .iter()
+ .any(|target_id| blocked_target_ids.contains(target_id))
+ {
+ continue;
+ }
+ if self.protocol_targets_have_inflight_background_navigation(&target_ids) {
+ if target_ids.is_empty() {
+ return None;
+ }
+ append_unique_target_ids(&mut blocked_target_ids, target_ids);
+ continue;
+ }
+ if !residence.should_yield_to_client_turn() && !residence.is_ready_to_complete() {
+ if target_ids.is_empty() {
+ return None;
+ }
+ append_unique_target_ids(&mut blocked_target_ids, target_ids);
+ continue;
+ }
+ return Some(index);
+ }
+ None
+ }
+
pub(crate) async fn complete_interleaved_scheduler_input(
&mut self,
receivers: &mut CdpSchedulerEventReceivers,
@@ -1733,11 +1860,15 @@ impl CdpScheduler {
}
}
- fn front_protocol_residence_is_main_document_load_action(&self) -> bool {
+ fn front_protocol_residence_is_main_document_load_action_for_context(
+ &self,
+ context: &moli_protocol::devtools_runtime::DevToolsCommandContext,
+ ) -> bool {
matches!(
self.queues.protocol_residences.front(),
Some(ProtocolSchedulerResidence::ProtocolWork { work, .. })
if work.kind() == ProtocolSchedulerWorkKind::MainDocumentLoadOwnerAction
+ && work.observes_main_document_load_for_devtools_context(&self.conn, context)
)
}
@@ -1772,8 +1903,18 @@ impl CdpScheduler {
if !event.route_is_current(&self.conn) {
return ProtocolOutputSequence::empty();
}
- let has_inflight_navigation = self.has_inflight_background_navigation();
let should_wait = event.should_wait_for_background_navigation_completion();
+ let navigation_target_id = should_wait
+ .then(|| self.conn.background_navigation_target_id_for_event(&event))
+ .flatten();
+ let has_inflight_navigation = should_wait
+ && navigation_target_id.as_deref().map_or_else(
+ || self.has_inflight_background_navigation(),
+ |target_id| {
+ self.conn
+ .has_inflight_background_navigation_for_target(target_id)
+ },
+ );
if moli_trace::cdp_runtime_trace_enabled()
&& let Some((method, resource_type, request_id, url)) = event.trace_network_summary()
{
@@ -1788,7 +1929,7 @@ impl CdpScheduler {
should_wait,
);
}
- if has_inflight_navigation && should_wait {
+ if has_inflight_navigation {
if moli_trace::cdp_runtime_trace_enabled() {
tracing::info!(
target: "moli_cdp_runtime",
@@ -1796,7 +1937,11 @@ impl CdpScheduler {
pending_background_events = self.pending_navigation_background_events.len() + 1,
);
}
- self.pending_navigation_background_events.push_back(event);
+ self.pending_navigation_background_events
+ .push_back(PendingNavigationBackgroundEvent {
+ target_id: navigation_target_id,
+ event,
+ });
return ProtocolOutputSequence::empty();
}
ProtocolOutputSequence::from_background_event(event)
@@ -1825,15 +1970,30 @@ impl CdpScheduler {
}
fn drain_pending_navigation_background_events(&mut self) -> ProtocolOutputSequence {
- let events = self
- .pending_navigation_background_events
- .drain(..)
+ let mut events = Vec::new();
+ let mut retained = VecDeque::new();
+ while let Some(pending) = self.pending_navigation_background_events.pop_front() {
// The navigation gate deliberately extends an event's residence
// beyond its projection turn. Reauthorize its frozen route at
// the actual release boundary: the in-flight navigation may have
// replaced the root Document or detached its session meanwhile.
- .filter(|event| event.route_is_current(&self.conn))
- .collect::<Vec<_>>();
+ if !pending.event.route_is_current(&self.conn) {
+ continue;
+ }
+ let remains_gated = pending.target_id.as_deref().map_or_else(
+ || self.has_inflight_background_navigation(),
+ |target_id| {
+ self.conn
+ .has_inflight_background_navigation_for_target(target_id)
+ },
+ );
+ if remains_gated {
+ retained.push_back(pending);
+ } else {
+ events.push(pending.event);
+ }
+ }
+ self.pending_navigation_background_events = retained;
ProtocolOutputSequence::from_background_events(events)
}
@@ -1841,9 +2001,6 @@ impl CdpScheduler {
&mut self,
prefix: &mut ProtocolOutputSequence,
) {
- if self.has_inflight_background_navigation() {
- return;
- }
prefix.append(self.drain_pending_navigation_background_events());
}
@@ -2185,13 +2342,18 @@ impl CdpScheduler {
}
fn next_protocol_scheduler_step(&self) -> ProtocolSchedulerStep {
- if self.has_inflight_background_navigation() {
+ let Some(index) = self.next_ungated_protocol_residence_index() else {
return ProtocolSchedulerStep::Wait;
- }
- if self.queues.front_needs_client_turn_predecessor() {
+ };
+ let residence = self
+ .queues
+ .protocol_residences
+ .get(index)
+ .expect("selected protocol residence must exist");
+ if residence.should_yield_to_client_turn() {
return ProtocolSchedulerStep::SatisfyClientTurnPredecessor;
}
- if self.queues.should_complete_next_residence() {
+ if residence.is_ready_to_complete() {
return ProtocolSchedulerStep::CompleteReadyResidence;
}
ProtocolSchedulerStep::Wait
@@ -2205,12 +2367,18 @@ impl CdpScheduler {
protocol_residence_len = self.queues.protocol_residence_len(),
);
}
- self.queues.satisfy_front_client_turn_predecessor();
+ let Some(index) = self.next_ungated_protocol_residence_index() else {
+ return;
+ };
+ self.queues.satisfy_client_turn_predecessor_at(index);
}
fn next_ready_protocol_residence_is_main_document_load_action(&self) -> bool {
+ let Some(index) = self.next_ungated_protocol_residence_index() else {
+ return false;
+ };
matches!(
- self.queues.protocol_residences.front(),
+ self.queues.protocol_residences.get(index),
Some(ProtocolSchedulerResidence::ProtocolWork {
work,
client_turn_predecessor: ClientTurnPredecessor::Satisfied,
@@ -2230,7 +2398,10 @@ impl CdpScheduler {
}
pub(crate) async fn complete_next_protocol_residence(&mut self) -> ProtocolOutputSequence {
- let Some(residence) = self.queues.pop_next_protocol_residence() else {
+ let Some(index) = self.next_ungated_protocol_residence_index() else {
+ return ProtocolOutputSequence::empty();
+ };
+ let Some(residence) = self.queues.take_protocol_residence_at(index) else {
return ProtocolOutputSequence::empty();
};
self.complete_protocol_residence(residence).await
@@ -2351,8 +2522,9 @@ impl CdpScheduler {
pub(crate) fn start_next_deferred_load_completion(
&mut self,
) -> Option<PendingDeferredMainDocumentLoadCompletion> {
+ let index = self.next_ungated_protocol_residence_index()?;
let should_start = matches!(
- self.queues.protocol_residences.front(),
+ self.queues.protocol_residences.get(index),
Some(ProtocolSchedulerResidence::ProtocolWork {
work,
client_turn_predecessor: ClientTurnPredecessor::Satisfied,
@@ -2365,7 +2537,7 @@ impl CdpScheduler {
return None;
}
let Some(ProtocolSchedulerResidence::ProtocolWork { work, .. }) =
- self.queues.pop_next_protocol_residence()
+ self.queues.take_protocol_residence_at(index)
else {
return None;
};
diff --git a/moli/src/cdp_scheduler/protocol_residence.rs b/moli/src/cdp_scheduler/protocol_residence.rs
index 9605b26c0..0849ebc67 100644
--- a/moli/src/cdp_scheduler/protocol_residence.rs
+++ b/moli/src/cdp_scheduler/protocol_residence.rs
@@ -108,7 +108,7 @@ pub(super) enum ClientTurnPredecessor {
}
impl ProtocolSchedulerResidence {
- fn should_yield_to_client_turn(&self) -> bool {
+ pub(super) fn should_yield_to_client_turn(&self) -> bool {
matches!(
self,
Self::RendererOutputPublication(RendererOutputPublicationWork {
@@ -198,7 +198,7 @@ impl ProtocolSchedulerResidence {
#[derive(Debug)]
pub(super) struct SchedulerQueues {
- /// Concrete protocol output and owner work in scheduler selection order.
+ /// Concrete protocol output and owner work in scheduler admission order.
///
/// Renderer source publications are concrete before admission. A projected
/// event batch may briefly accept the load observation still being
@@ -206,7 +206,9 @@ pub(super) struct SchedulerQueues {
/// from the same ingress turn inherits that predecessor as well. Publication
/// stream cursor remains the admission invariant, while an exact
/// predecessor may deliberately insert its load owner action before work
- /// that was admitted earlier.
+ /// that was admitted earlier. Selection normally follows this order; a
+ /// target-local navigation gate may let an unrelated target advance while
+ /// preserving order within each target lane.
pub(super) protocol_residences: VecDeque<ProtocolSchedulerResidence>,
next_protocol_work_publish_sequence: u64,
}
@@ -365,6 +367,21 @@ impl SchedulerQueues {
self.protocol_residences.pop_front()
}
+ pub(super) fn satisfy_client_turn_predecessor_at(&mut self, index: usize) {
+ self.close_future_load_predecessor_window();
+ self.protocol_residences
+ .get_mut(index)
+ .expect("selected protocol residence must still exist")
+ .mark_client_turn_yielded();
+ }
+
+ pub(super) fn take_protocol_residence_at(
+ &mut self,
+ index: usize,
+ ) -> Option<ProtocolSchedulerResidence> {
+ self.protocol_residences.remove(index)
+ }
+
fn take_snapshot(
&mut self,
mut selected: impl FnMut(&ProtocolSchedulerResidence) -> bool,
diff --git a/moli/src/cdp_scheduler/tests.rs b/moli/src/cdp_scheduler/tests.rs
index aca366204..13e50eeff 100644
--- a/moli/src/cdp_scheduler/tests.rs
+++ b/moli/src/cdp_scheduler/tests.rs
@@ -17,15 +17,17 @@ use moli_protocol::{
ProtocolSchedulerWork,
conn::RuntimeInspectorResponseReady,
devtools_runtime::{
- AutomationEvent, BrowserDownloadWillBeginEvent, DevToolsFrameId, DevToolsLoaderId,
- DevToolsNavigationWait, DevToolsNetworkResourceType, DevToolsRequestId, DevToolsTargetId,
- NavigationFrameEvent, NavigationFrameEventKind, NetworkRequestEvent,
+ AutomationEvent, BrowserDownloadWillBeginEvent, DevToolsCommand, DevToolsCommandContext,
+ DevToolsCommandResult, DevToolsCreateTargetCommand, DevToolsFrameId, DevToolsLoaderId,
+ DevToolsNavigationWait, DevToolsNetworkResourceType, DevToolsProtocol, DevToolsRequestId,
+ DevToolsSessionId, DevToolsTargetId, NavigationFrameEvent, NavigationFrameEventKind,
+ NetworkRequestEvent,
},
test_support::{
- arm_background_navigation_request, deferred_main_document_load_observation_id,
- deferred_main_document_load_output_interest,
+ arm_background_navigation_request, arm_background_navigation_request_for_target,
+ deferred_main_document_load_observation_id, deferred_main_document_load_output_interest,
root_frame_stopped_loading_work as make_root_frame_stopped_loading_work,
- settle_background_navigation_request,
+ root_frame_stopped_loading_work_for_target, settle_background_navigation_request,
},
};
use serde_json::json;
@@ -266,6 +268,14 @@ fn protocol_output_loose_response_split_ignores_typed_runtime_response() {
fn network_response_event(
resource_type: DevToolsNetworkResourceType,
request_id: &str,
+) -> BackgroundProtocolEvent {
+ network_response_event_for_target(resource_type, request_id, "TID-nav")
+}
+
+fn network_response_event_for_target(
+ resource_type: DevToolsNetworkResourceType,
+ request_id: &str,
+ target_id: &str,
) -> BackgroundProtocolEvent {
let message = json!({
"method": "Network.responseReceived",
@@ -280,7 +290,7 @@ fn network_response_event(
}
});
let automation_event = AutomationEvent::NetworkResponseStarted(NetworkRequestEvent {
- target_id: DevToolsTargetId::from("TID-nav"),
+ target_id: DevToolsTargetId::from(target_id),
frame_id: Some(DevToolsFrameId::from("FRAME-nav")),
request_id: DevToolsRequestId::from(request_id),
loader_id: Some(DevToolsLoaderId::from("LOADER-nav")),
@@ -316,12 +326,13 @@ fn network_response_event(
BackgroundProtocolEvent::immediate_automation_event(message, automation_event)
}
-fn network_request_event(
+fn network_request_event_for_target(
resource_type: DevToolsNetworkResourceType,
request_id: &str,
+ target_id: &str,
) -> BackgroundProtocolEvent {
let (_, Some(AutomationEvent::NetworkResponseStarted(mut network_event))) =
- network_response_event(resource_type, request_id).into_parts()
+ network_response_event_for_target(resource_type, request_id, target_id).into_parts()
else {
unreachable!("network response fixture should retain its typed sidecar")
};
@@ -344,12 +355,13 @@ fn network_request_event(
)
}
-fn network_finished_event(
+fn network_finished_event_for_target(
resource_type: DevToolsNetworkResourceType,
request_id: &str,
+ target_id: &str,
) -> BackgroundProtocolEvent {
let (_, Some(AutomationEvent::NetworkResponseStarted(network_event))) =
- network_response_event(resource_type, request_id).into_parts()
+ network_response_event_for_target(resource_type, request_id, target_id).into_parts()
else {
unreachable!("network response fixture should retain its typed sidecar")
};
@@ -366,6 +378,34 @@ fn network_finished_event(
)
}
+#[test]
+fn mixed_owner_protocol_output_keeps_the_conservative_global_gate() {
+ let mut conn = CdpConnection::new();
+ let navigation = arm_background_navigation_request(&mut conn, "LOADER-known");
+ let target_id = navigation.target_id().to_owned();
+ let known = network_response_event_for_target(
+ DevToolsNetworkResourceType::Xhr,
+ "REQ-known",
+ &target_id,
+ );
+ assert_eq!(
+ ProtocolOutputSequence::from_background_event(known.clone())
+ .navigation_gate_target_ids(&conn),
+ [target_id]
+ );
+
+ let unresolved = BackgroundProtocolEvent::immediate(json!({
+ "method": "Runtime.consoleAPICalled",
+ "sessionId": "SID-missing",
+ "params": {}
+ }));
+ let mixed = ProtocolOutputSequence::from_background_events(vec![known, unresolved]);
+ assert!(
+ mixed.navigation_gate_target_ids(&conn).is_empty(),
+ "an atomic batch with any unresolved owner must remain connection-gated"
+ );
+}
+
fn output_request_ids(output: ProtocolOutputSequence) -> Vec<String> {
output
.into_background_events()
@@ -1069,21 +1109,118 @@ fn concrete_protocol_output_rejects_missing_earlier_publication() {
);
}
-#[test]
-fn background_navigation_blocks_concrete_protocol_residence_not_renderer_ingress() {
+#[tokio::test]
+async fn background_navigation_blocks_only_its_target_protocol_residences() {
let mut conn = CdpConnection::new();
- let _navigation = arm_background_navigation_request(&mut conn, "LOADER-nav");
+ let navigation = arm_background_navigation_request(&mut conn, "LOADER-nav");
+ let navigation_target_id = navigation.target_id().to_owned();
+ let browser_context_id = conn.default_browser_context_id().to_owned();
let mut scheduler = CdpScheduler::new(conn);
- scheduler.apply_scheduler_events(vec![CdpSchedulerEvent::ProtocolWorkPublished {
- work: root_frame_stopped_loading_work(1, "FRAME-1"),
- }]);
+ scheduler.apply_scheduler_events(vec![
+ CdpSchedulerEvent::ProtocolWorkPublished {
+ work: root_frame_stopped_loading_work_for_target(
+ 1,
+ vec![Some("SID-A".to_owned())],
+ browser_context_id.clone(),
+ navigation_target_id,
+ "FRAME-A".to_owned(),
+ "LOADER-A".to_owned(),
+ ),
+ },
+ CdpSchedulerEvent::ProtocolWorkPublished {
+ work: root_frame_stopped_loading_work_for_target(
+ 2,
+ vec![Some("SID-B".to_owned())],
+ browser_context_id,
+ "TID-independent".to_owned(),
+ "FRAME-B".to_owned(),
+ "LOADER-B".to_owned(),
+ ),
+ },
+ ]);
assert_eq!(
scheduler.next_protocol_scheduler_step(),
- ProtocolSchedulerStep::Wait
+ ProtocolSchedulerStep::SatisfyClientTurnPredecessor,
+ "the independent target must advance around target A's navigation"
+ );
+ scheduler.satisfy_front_protocol_residence_client_turn_predecessor();
+ assert_eq!(
+ scheduler.next_protocol_scheduler_step(),
+ ProtocolSchedulerStep::CompleteReadyResidence
+ );
+ assert!(
+ scheduler
+ .complete_next_protocol_residence()
+ .await
+ .is_empty()
+ );
+ let remaining_sequences = scheduler
+ .queues
+ .protocol_residences
+ .iter()
+ .map(|residence| match residence {
+ ProtocolSchedulerResidence::ProtocolWork { work, .. } => work.publish_sequence().get(),
+ _ => panic!("test enqueued protocol work only"),
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(remaining_sequences, [1]);
+ assert_eq!(
+ scheduler.next_protocol_scheduler_step(),
+ ProtocolSchedulerStep::Wait,
+ "target A's own residence must remain gated"
);
}
+#[tokio::test]
+async fn protocol_residence_snapshot_skips_another_targets_navigation_gate() {
+ let mut conn = CdpConnection::new();
+ let navigation = arm_background_navigation_request(&mut conn, "LOADER-A");
+ let target_a = navigation.target_id().to_owned();
+ let browser_context_id = conn.default_browser_context_id().to_owned();
+ let mut scheduler = CdpScheduler::new(conn);
+ scheduler.apply_scheduler_events(vec![
+ CdpSchedulerEvent::ProtocolWorkPublished {
+ work: root_frame_stopped_loading_work_for_target(
+ 1,
+ vec![Some("SID-A".to_owned())],
+ browser_context_id.clone(),
+ target_a,
+ "FRAME-A".to_owned(),
+ "LOADER-A".to_owned(),
+ ),
+ },
+ CdpSchedulerEvent::ProtocolWorkPublished {
+ work: root_frame_stopped_loading_work_for_target(
+ 2,
+ vec![Some("SID-B".to_owned())],
+ browser_context_id,
+ "TID-B".to_owned(),
+ "FRAME-B".to_owned(),
+ "LOADER-B".to_owned(),
+ ),
+ },
+ ]);
+ let snapshot = std::mem::take(&mut scheduler.queues.protocol_residences);
+
+ assert!(
+ scheduler
+ .complete_protocol_residence_snapshot(snapshot)
+ .await
+ .is_empty()
+ );
+ let remaining_sequences = scheduler
+ .queues
+ .protocol_residences
+ .iter()
+ .map(|residence| match residence {
+ ProtocolSchedulerResidence::ProtocolWork { work, .. } => work.publish_sequence().get(),
+ _ => panic!("test enqueued protocol work only"),
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(remaining_sequences, [1]);
+}
+
#[test]
fn replacement_navigation_cancels_and_exactly_settles_the_target_owned_request() {
let mut conn = CdpConnection::new();
@@ -1108,19 +1245,32 @@ fn replacement_navigation_cancels_and_exactly_settles_the_target_owned_request()
fn scheduler_defers_subresource_network_events_until_background_navigation_gate_clears() {
let mut conn = CdpConnection::new();
let navigation = arm_background_navigation_request(&mut conn, "LOADER-nav");
+ let target_id = navigation.target_id().to_owned();
let mut scheduler = CdpScheduler::new(conn);
let document_output = scheduler.route_background_event_around_inflight_navigation(
- network_response_event(DevToolsNetworkResourceType::Document, "REQ-document"),
+ network_response_event_for_target(
+ DevToolsNetworkResourceType::Document,
+ "REQ-document",
+ &target_id,
+ ),
);
assert_eq!(output_request_ids(document_output), ["REQ-document"]);
let script_output = scheduler.route_background_event_around_inflight_navigation(
- network_response_event(DevToolsNetworkResourceType::Script, "REQ-script"),
+ network_response_event_for_target(
+ DevToolsNetworkResourceType::Script,
+ "REQ-script",
+ &target_id,
+ ),
);
assert!(script_output.is_empty());
let script_terminal = scheduler.route_background_event_around_inflight_navigation(
- network_finished_event(DevToolsNetworkResourceType::Script, "REQ-script"),
+ network_finished_event_for_target(
+ DevToolsNetworkResourceType::Script,
+ "REQ-script",
+ &target_id,
+ ),
);
assert!(script_terminal.is_empty());
assert_eq!(scheduler.pending_navigation_background_events.len(), 2);
@@ -1156,18 +1306,109 @@ fn scheduler_defers_subresource_network_events_until_background_navigation_gate_
);
}
+#[tokio::test]
+async fn target_a_navigation_does_not_defer_target_b_network_events() {
+ let mut conn = CdpConnection::new();
+ conn.install_default_browser_target();
+ let context = DevToolsCommandContext {
+ protocol: DevToolsProtocol::WebDriverBidi,
+ session_id: Some(DevToolsSessionId::from("bidi-test")),
+ target_id: None,
+ browser_context_id: None,
+ };
+ let create_target = |context: DevToolsCommandContext| {
+ DevToolsCommand::CreateTarget(DevToolsCreateTargetCommand {
+ context,
+ url: "about:blank".to_owned(),
+ browser_context_id: None,
+ activate: false,
+ })
+ };
+ let first_create = conn
+ .execute_devtools_command(create_target(context.clone()))
+ .await;
+ let (first_result, _) = first_create.into_parts();
+ let DevToolsCommandResult::CreateTarget(first_result) =
+ first_result.expect("first target should be created")
+ else {
+ panic!("expected create-target result")
+ };
+ let first_target_id = first_result.target_id.into_string();
+ let second_create = conn.execute_devtools_command(create_target(context)).await;
+ let (second_result, _) = second_create.into_parts();
+ let DevToolsCommandResult::CreateTarget(second_result) =
+ second_result.expect("second target should be created")
+ else {
+ panic!("expected create-target result")
+ };
+ let second_target_id = second_result.target_id.into_string();
+ assert_ne!(first_target_id, second_target_id);
+ let navigation = arm_background_navigation_request(&mut conn, "LOADER-A");
+ let target_a = navigation.target_id().to_owned();
+ let target_b = if target_a == second_target_id {
+ first_target_id
+ } else {
+ second_target_id
+ };
+ assert!(conn.has_inflight_background_navigation_for_target(&target_a));
+ assert!(!conn.has_inflight_background_navigation_for_target(&target_b));
+
+ let mut scheduler = CdpScheduler::new(conn);
+ let target_b_output = scheduler.route_background_event_around_inflight_navigation(
+ network_response_event_for_target(DevToolsNetworkResourceType::Xhr, "REQ-B", &target_b),
+ );
+ assert_eq!(output_request_ids(target_b_output), ["REQ-B"]);
+
+ let navigation_b =
+ arm_background_navigation_request_for_target(&mut scheduler.conn, &target_b, "LOADER-B");
+ let target_b_held = scheduler.route_background_event_around_inflight_navigation(
+ network_response_event_for_target(
+ DevToolsNetworkResourceType::Xhr,
+ "REQ-B-held",
+ &target_b,
+ ),
+ );
+ assert!(target_b_held.is_empty());
+ let target_a_output = scheduler.route_background_event_around_inflight_navigation(
+ network_response_event_for_target(DevToolsNetworkResourceType::Xhr, "REQ-A", &target_a),
+ );
+ assert!(target_a_output.is_empty());
+ assert_eq!(scheduler.pending_navigation_background_events.len(), 2);
+
+ assert!(settle_background_navigation_request(
+ &mut scheduler.conn,
+ &navigation
+ ));
+ assert_eq!(
+ output_request_ids(scheduler.drain_pending_navigation_background_events()),
+ ["REQ-A"],
+ "settling target A must not release target B's held event"
+ );
+ assert_eq!(scheduler.pending_navigation_background_events.len(), 1);
+ assert!(settle_background_navigation_request(
+ &mut scheduler.conn,
+ &navigation_b
+ ));
+ assert_eq!(
+ output_request_ids(scheduler.drain_pending_navigation_background_events()),
+ ["REQ-B-held"]
+ );
+}
+
#[test]
fn navigation_gate_release_precedes_later_renderer_boundary_network_output() {
let mut conn = CdpConnection::new();
let navigation = arm_background_navigation_request(&mut conn, "LOADER-nav");
+ let target_id = navigation.target_id().to_owned();
let mut scheduler = CdpScheduler::new(conn);
let request_id = "REQ-boundary-race";
assert!(
scheduler
- .route_background_event_around_inflight_navigation(network_request_event(
+ .route_background_event_around_inflight_navigation(network_request_event_for_target(
DevToolsNetworkResourceType::Xhr,
request_id,
+ &target_id,
))
.is_empty()
);
@@ -1179,10 +1420,10 @@ fn navigation_gate_release_precedes_later_renderer_boundary_network_output() {
let mut output = ProtocolOutputSequence::empty();
scheduler.append_navigation_gate_release_before_renderer_boundary(&mut output);
output.append(ProtocolOutputSequence::from_background_event(
- network_response_event(DevToolsNetworkResourceType::Xhr, request_id),
+ network_response_event_for_target(DevToolsNetworkResourceType::Xhr, request_id, &target_id),
));
output.append(ProtocolOutputSequence::from_background_event(
- network_finished_event(DevToolsNetworkResourceType::Xhr, request_id),
+ network_finished_event_for_target(DevToolsNetworkResourceType::Xhr, request_id, &target_id),
));
let methods = output