refactor(protocol): supervise remaining scheduler owner workflows

Run main-document lifecycle and download emission plus popup navigation through the existing owner-work supervisor. Retain each exact load interest in the scheduler queue until output handoff, and remove the adapter's private load tasks and completion channel.

Limit production ready-work completion to finite observations. Reuse the renderer navigation workflow and fenced output finalizer for compatibility callers. Classify explicit child frame navigation by its original owner instead of attachment observation timing, preserving Native validation and the parent document.

Validation: root cargo fmt, full workspace Clippy, full Nextest and protocol doctests; source-built CLI compatibility and controlled popup replacement and independent load/cancellation scenarios; parallel stress of owned output and child navigation.
This commit is contained in:
ldm0
2026-10-29 17:39:23 +08:00
committed by Donough Liu
parent a028ac0de8
commit 952bc98cbb
21 changed files with 821 additions and 655 deletions
+44 -117
View File
@@ -14,13 +14,11 @@ use moli_protocol::{
BackgroundNavigationCompletion, BackgroundProtocolEvent, CdpCommandTaskStep, CdpConnection,
CdpInitialStoragePartition, CdpRendererCommandAccess, CdpSchedulerEvent,
CdpTargetHostLifecycleObserver, CommandDispatchContext, CompletedCdpCommandDispatch,
CompletedDeferredMainDocumentLoadCompletion, DeferredMainDocumentLoadCompletionOutputAction,
DeferredMainDocumentLoadCompletionOutputInterest, DeferredMainDocumentLoadObservationId,
DeferredMainDocumentLoadCompletionOutputAction, DeferredMainDocumentLoadObservationId,
DeferredMainDocumentLoadPredecessorCandidate, DevToolsDocumentResidenceIdentity,
PageScreencastCaptureCompletion, PageScreencastCaptureStart, PageScreencastRegistration,
PageScreencastSubscriptionStatus, ParsedCdpCommand, PendingCdpCommandDispatch,
PendingDeferredMainDocumentLoadCompletion, PendingPageScreencastCapture,
ProtocolSchedulerWorkKind,
PendingPageScreencastCapture, ProtocolSchedulerWorkKind,
automation::{AutomationCommand, AutomationResult, DevToolsError, DevToolsNavigationWait},
conn::{RuntimeInspectorResponseReady, RuntimeInspectorResponseReadySender},
};
@@ -50,9 +48,7 @@ pub(crate) use adapter_scheduler::{
};
pub(crate) use command_dispatch::{CommandDispatchState, CommandTurnOutput};
pub(crate) use frontend_control::{CdpCookieSnapshot, CdpOwnerActorLifecycle};
use protocol_residence::{
ClientTurnPredecessor, ProtocolSchedulerResidence, ProtocolSchedulerStep, SchedulerQueues,
};
use protocol_residence::{ProtocolSchedulerResidence, ProtocolSchedulerStep, SchedulerQueues};
use runtime_command_barrier::CommandOutputReleasePermit;
pub(crate) use runtime_dispatch::{
DevToolsRuntimeCommandProgress, PendingDevToolsRuntimeDeferredReplyExecution,
@@ -1859,6 +1855,7 @@ impl CdpScheduler {
ProtocolSchedulerResidence::ProtocolWork { work, .. }
if work.kind() == ProtocolSchedulerWorkKind::MainDocumentLoadOwnerAction
&& !work.is_ready()
&& self.protocol_tasks.is_none()
);
if has_pending_target_predecessor
|| has_pending_scheduler_predecessor
@@ -2159,7 +2156,13 @@ impl CdpScheduler {
let Some(tasks) = &mut self.protocol_tasks else {
return Err(Box::new(work));
};
let load = work
.main_document_load_observation_id()
.zip(work.main_document_load_output_interest());
if let Some(pending) = self.conn.try_start_owned_protocol_scheduler_work(work)? {
if let Some((observation, interest)) = load {
self.queues.start_main_document_load(observation, interest);
}
tasks.start(pending);
}
Ok(())
@@ -2179,7 +2182,11 @@ impl CdpScheduler {
};
let source = completed.renderer_output_source();
let projection = completed.renderer_projection_cursor();
let load = completed.main_document_load_observation_id();
let outcome = self.conn.complete_owned_protocol_scheduler_work(completed);
if let Some(observation) = load {
self.queues.finish_main_document_load(observation);
}
let Some(source) = source else {
return Ok(self.apply_protocol_only_turn_outcome(outcome));
};
@@ -2259,7 +2266,11 @@ impl CdpScheduler {
&self,
context: &moli_protocol::automation::AutomationContext,
) -> bool {
self.queues.protocol_residences.iter().any(|residence| {
self.queues.pending_loads.iter().any(|pending| {
pending
.output_interest
.observes_devtools_context(&self.conn, context)
}) || self.queues.protocol_residences.iter().any(|residence| {
matches!(
residence,
ProtocolSchedulerResidence::ProtocolWork { work, .. }
@@ -2730,23 +2741,6 @@ impl CdpScheduler {
.await
}
pub(crate) async fn ingest_renderer_publication_after_loads(
&mut self,
publication: RendererOutputTransportMessage,
observation_ids: Vec<DeferredMainDocumentLoadObservationId>,
) -> ProtocolOutputSequence {
let future_load_predecessor = observation_ids
.is_empty()
.then(|| {
DeferredMainDocumentLoadPredecessorCandidate::from_renderer_publication(
&publication,
)
})
.flatten();
self.ingest_renderer_publication(publication, observation_ids, future_load_predecessor)
.await
}
pub(crate) async fn finish_command_dispatch_output_flush(
&mut self,
post_flush_scheduler_events: Vec<CdpSchedulerEvent>,
@@ -2816,30 +2810,6 @@ impl CdpScheduler {
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.get(index),
Some(ProtocolSchedulerResidence::ProtocolWork {
work,
client_turn_predecessor: ClientTurnPredecessor::Satisfied,
load_predecessors,
..
}) if load_predecessors.is_empty()
&& work.kind() == ProtocolSchedulerWorkKind::MainDocumentLoadOwnerAction
)
}
pub(crate) fn route_renderer_output_for_deferred_load_completion(
&self,
output: &RendererOutputTransportMessage,
interest: &DeferredMainDocumentLoadCompletionOutputInterest,
) -> DeferredMainDocumentLoadCompletionOutputAction {
interest.route_output_while_waiting(output)
}
pub(crate) async fn complete_next_protocol_residence(&mut self) -> ProtocolOutputSequence {
let Some(index) = self.next_ungated_protocol_residence_index() else {
return ProtocolOutputSequence::empty();
@@ -2913,10 +2883,22 @@ impl CdpScheduler {
Err(work) => *work,
};
let load_observation_id = work.main_document_load_observation_id();
let outcome = self
.conn
.complete_ready_protocol_scheduler_work_turn(work)
.await;
let outcome = match self.conn.try_complete_protocol_scheduler_work_turn(work) {
Ok(outcome) => outcome,
Err(work) => {
#[cfg(test)]
{
Box::pin(self.conn.complete_ready_protocol_scheduler_work_turn(*work))
.await
}
#[cfg(not(test))]
{
panic!(
"owner work requires the installed protocol task supervisor: {work:?}"
)
}
}
};
out.append(self.apply_protocol_only_turn_outcome(outcome));
if let Some(observation_id) = load_observation_id {
self.queues.satisfy_load_predecessor(observation_id);
@@ -2951,7 +2933,8 @@ impl CdpScheduler {
&self,
output: &RendererOutputTransportMessage,
) -> Vec<DeferredMainDocumentLoadObservationId> {
self.queues
let mut observations: Vec<_> = self
.queues
.protocol_residences
.iter()
.filter_map(|residence| match residence {
@@ -2963,69 +2946,13 @@ impl CdpScheduler {
}
_ => None,
})
.collect()
}
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.get(index),
Some(ProtocolSchedulerResidence::ProtocolWork {
work,
client_turn_predecessor: ClientTurnPredecessor::Satisfied,
load_predecessors,
..
}) if load_predecessors.is_empty()
&& work.kind() == ProtocolSchedulerWorkKind::MainDocumentLoadOwnerAction
);
if !should_start {
return None;
}
let Some(ProtocolSchedulerResidence::ProtocolWork { work, .. }) =
self.queues.take_protocol_residence_at(index)
else {
return None;
};
if moli_trace::command_probe_enabled() {
tracing::info!(
observation_sequence = work.publish_sequence().get(),
"CMD_PROBE_DEFERRED_LOAD_START"
);
}
if moli_trace::cdp_runtime_trace_enabled() {
tracing::info!(
target: "moli_cdp_runtime",
stage = "deferred_load_completion_start",
publish_sequence = work.publish_sequence().get(),
protocol_residence_len = self.queues.protocol_residence_len(),
);
}
Some(work.start_main_document_load_wait())
}
pub(crate) async fn complete_deferred_load_completion(
&mut self,
completion: CompletedDeferredMainDocumentLoadCompletion,
) -> ProtocolOutputSequence {
let trace_started = moli_trace::cdp_runtime_trace_enabled().then(Instant::now);
let observation_id = completion.observation_id();
let outcome = self
.conn
.complete_deferred_main_document_load_completion_for_scheduler(completion)
.await;
let output = self.apply_protocol_only_turn_outcome(outcome);
self.queues.satisfy_load_predecessor(observation_id);
if let Some(started) = trace_started {
tracing::info!(
target: "moli_cdp_runtime",
stage = "deferred_load_completion_done",
messages = output.len(),
elapsed_us = %started.elapsed().as_micros(),
);
}
output
.collect();
observations.extend(self.queues.pending_loads.iter().filter_map(|pending| {
(pending.output_interest.route_output_while_waiting(output)
== DeferredMainDocumentLoadCompletionOutputAction::Queue)
.then_some(pending.observation_id)
}));
observations
}
pub(crate) async fn drain_background_navigation_completion(
@@ -10,8 +10,7 @@ use moli_core::{RendererOutputFence, RendererOutputTransportMessage};
use moli_protocol::{
BackgroundNavigationCompletion, BackgroundProtocolEvent, CdpSchedulerEvent,
CommandDispatchContext, CommandWaitLifetime, CompletedCdpCommandDispatch,
CompletedPageScreencastCapture, DeferredMainDocumentLoadObservationId, ParsedCdpCommand,
PendingCdpCommandDispatch,
CompletedPageScreencastCapture, ParsedCdpCommand, PendingCdpCommandDispatch,
conn::{RuntimeInspectorAsyncCompletionReceiver, RuntimeInspectorResponseReady},
};
use serde_json::Value;
@@ -1371,12 +1370,9 @@ async fn handle_adapter_scheduler_input(
) -> bool {
let trace_started = moli_trace::cdp_runtime_trace_enabled().then(Instant::now);
let advance = adapter_scheduler.advance_input(scheduler, input).await;
let (kind, observation_id, ok) = match advance {
ProtocolAdapterSchedulerAdvance::Idle => ("idle", None, true),
ProtocolAdapterSchedulerAdvance::ClientTurnYielded => ("client_turn_yielded", None, true),
ProtocolAdapterSchedulerAdvance::DeferredLoadStarted { observation_id } => {
("deferred_load_started", Some(observation_id), true)
}
let (kind, ok) = match advance {
ProtocolAdapterSchedulerAdvance::Idle => ("idle", true),
ProtocolAdapterSchedulerAdvance::ClientTurnYielded => ("client_turn_yielded", true),
ProtocolAdapterSchedulerAdvance::ProtocolResidenceCompleted(output) => {
let ok = flush_protocol_output_with_runtime_deferred_reply_routing(
frontend_router,
@@ -1385,27 +1381,7 @@ async fn handle_adapter_scheduler_input(
output,
)
.await;
("protocol_residence_completed", None, ok)
}
ProtocolAdapterSchedulerAdvance::DeferredLoadCompleted {
observation_id,
output,
} => {
let ok = flush_protocol_output_with_runtime_deferred_reply_routing(
frontend_router,
scheduler,
pending_runtime_deferred_replies,
output,
)
.await;
("deferred_load_completed", Some(observation_id), ok)
}
ProtocolAdapterSchedulerAdvance::StaleDeferredLoadCompletion { observation_id } => {
tracing::debug!(
?observation_id,
"dropping stale shared adapter load completion"
);
("stale_deferred_load_completion", Some(observation_id), true)
("protocol_residence_completed", ok)
}
};
if let Some(started) = trace_started {
@@ -1413,7 +1389,6 @@ async fn handle_adapter_scheduler_input(
target: "moli_cdp_runtime",
stage = "protocol_adapter_input_done",
advance = kind,
?observation_id,
ok,
elapsed_us = %started.elapsed().as_micros(),
);
@@ -2446,7 +2421,6 @@ fn trace_scheduler_input(input: &SchedulerInput, stage: &'static str) {
target: "moli_cdp_runtime",
stage = stage,
input = scheduler_input_kind(input),
observation_id = ?scheduler_input_observation_id(input),
);
}
@@ -2464,20 +2438,6 @@ fn scheduler_input_kind(input: &SchedulerInput) -> &'static str {
SchedulerInput::AdapterScheduler(ProtocolAdapterSchedulerInput::Turn) => {
"protocol_adapter_turn"
}
SchedulerInput::AdapterScheduler(
ProtocolAdapterSchedulerInput::DeferredLoadCompletion(_),
) => "deferred_load_completion",
}
}
fn scheduler_input_observation_id(
input: &SchedulerInput,
) -> Option<DeferredMainDocumentLoadObservationId> {
match input {
SchedulerInput::AdapterScheduler(
ProtocolAdapterSchedulerInput::DeferredLoadCompletion(completion),
) => Some(completion.observation_id()),
_ => None,
}
}
@@ -1,9 +1,4 @@
use moli_core::RendererOutputTransportMessage;
use moli_protocol::{
CompletedDeferredMainDocumentLoadCompletion, DeferredMainDocumentLoadCompletionOutputAction,
DeferredMainDocumentLoadCompletionOutputInterest, DeferredMainDocumentLoadObservationId,
PendingDeferredMainDocumentLoadCompletion,
};
use tokio::sync::mpsc;
use super::{CdpScheduler, ProtocolOutputSequence, protocol_residence::ProtocolSchedulerStep};
@@ -14,9 +9,10 @@ use super::{CdpScheduler, ProtocolOutputSequence, protocol_residence::ProtocolSc
/// driver owns only the asynchronous adapter boundary needed to select that
/// work in a later client turn:
///
/// - one coalesced self-turn signal;
/// - every exact main-document load observation currently awaiting its
/// target-local terminal.
/// - one coalesced self-turn signal.
///
/// Exact load interests stay with the scheduler queue until their shared
/// owner workflow hands off its output.
///
/// It never stores a renderer publication, Page task capability or protocol
/// transport route. Independent Pages may therefore wait for load in parallel,
@@ -25,62 +21,32 @@ pub(crate) struct ProtocolAdapterScheduler {
turn_tx: mpsc::UnboundedSender<()>,
turn_rx: mpsc::UnboundedReceiver<()>,
turn_scheduled: bool,
load_completion_tx: mpsc::UnboundedSender<CompletedDeferredMainDocumentLoadCompletion>,
load_completion_rx: mpsc::UnboundedReceiver<CompletedDeferredMainDocumentLoadCompletion>,
pending_loads: Vec<PendingAdapterLoadObservation>,
}
struct PendingAdapterLoadObservation {
observation_id: DeferredMainDocumentLoadObservationId,
output_interest: DeferredMainDocumentLoadCompletionOutputInterest,
}
pub(crate) enum ProtocolAdapterSchedulerInput {
Turn,
DeferredLoadCompletion(Box<CompletedDeferredMainDocumentLoadCompletion>),
}
/// Result of consuming one shared adapter-scheduler input.
///
/// `DeferredLoadStarted` deliberately does not expose the pending observer or
/// its wake interest. The exact identity remains owned by
/// `ProtocolAdapterScheduler` until `DeferredLoadCompleted`.
pub(crate) enum ProtocolAdapterSchedulerAdvance {
Idle,
ClientTurnYielded,
DeferredLoadStarted {
observation_id: DeferredMainDocumentLoadObservationId,
},
ProtocolResidenceCompleted(ProtocolOutputSequence),
DeferredLoadCompleted {
observation_id: DeferredMainDocumentLoadObservationId,
output: ProtocolOutputSequence,
},
StaleDeferredLoadCompletion {
observation_id: DeferredMainDocumentLoadObservationId,
},
}
impl Default for ProtocolAdapterScheduler {
fn default() -> Self {
let (turn_tx, turn_rx) = mpsc::unbounded_channel();
let (load_completion_tx, load_completion_rx) = mpsc::unbounded_channel();
Self {
turn_tx,
turn_rx,
turn_scheduled: false,
load_completion_tx,
load_completion_rx,
pending_loads: Vec::new(),
}
}
}
impl ProtocolAdapterScheduler {
pub(crate) fn has_pending_loads(&self) -> bool {
!self.pending_loads.is_empty()
}
/// Coalesces scheduler readiness into one later adapter turn.
///
/// Sending through a local channel is intentional: satisfying a
@@ -112,55 +78,26 @@ impl ProtocolAdapterScheduler {
});
}
/// Waits for either the coalesced self turn or the exact load terminal.
///
/// The driver retains both senders, so a closed internal channel is an
/// invariant violation rather than an adapter shutdown signal.
/// Waits for the coalesced adapter turn. Owner work and load terminals
/// arrive through the shared protocol task supervisor.
pub(crate) async fn recv_input(&mut self) -> ProtocolAdapterSchedulerInput {
tokio::select! {
biased;
completion = self.load_completion_rx.recv(), if self.has_pending_loads() => {
ProtocolAdapterSchedulerInput::DeferredLoadCompletion(Box::new(
completion.expect("shared adapter load-completion channel must remain open"),
))
}
turn = self.turn_rx.recv(), if self.turn_scheduled => {
turn.expect("shared adapter self-turn channel must remain open");
ProtocolAdapterSchedulerInput::Turn
}
// Every adapter selects this future alongside its transport and
// renderer inputs. A completely idle protocol scheduler therefore
// means "this source is not ready", not an all-branches-disabled
// error.
else => std::future::pending::<ProtocolAdapterSchedulerInput>().await,
if !self.turn_scheduled {
return std::future::pending().await;
}
self.turn_rx
.recv()
.await
.expect("shared adapter self-turn channel must remain open");
ProtocolAdapterSchedulerInput::Turn
}
/// Ingests one concrete renderer publication behind every matching exact
/// load observation currently owned by this connection-local driver.
pub(crate) async fn ingest_renderer_publication(
&mut self,
scheduler: &mut CdpScheduler,
publication: RendererOutputTransportMessage,
) -> ProtocolOutputSequence {
if self.pending_loads.is_empty() {
return scheduler
.ingest_renderer_publication_for_scheduler(publication)
.await;
}
let observation_ids = self
.pending_loads
.iter()
.filter_map(|pending| {
(scheduler.route_renderer_output_for_deferred_load_completion(
&publication,
&pending.output_interest,
) == DeferredMainDocumentLoadCompletionOutputAction::Queue)
.then_some(pending.observation_id)
})
.collect();
scheduler
.ingest_renderer_publication_after_loads(publication, observation_ids)
.ingest_renderer_publication_for_scheduler(publication)
.await
}
@@ -177,9 +114,6 @@ impl ProtocolAdapterScheduler {
self.turn_scheduled = false;
self.advance_turn(scheduler).await
}
ProtocolAdapterSchedulerInput::DeferredLoadCompletion(completion) => {
self.complete_load(scheduler, *completion).await
}
}
}
@@ -192,28 +126,6 @@ impl ProtocolAdapterScheduler {
scheduler.satisfy_front_protocol_residence_client_turn_predecessor();
ProtocolAdapterSchedulerAdvance::ClientTurnYielded
}
ProtocolSchedulerStep::CompleteReadyResidence
if scheduler.next_ready_protocol_residence_is_main_document_load_action() =>
{
let pending = scheduler
.start_next_deferred_load_completion()
.expect("ready load residence must produce an exact pending observation");
let observation_id = pending.observation_id();
let output_interest = pending.output_interest();
assert!(
!self
.pending_loads
.iter()
.any(|pending| pending.observation_id == observation_id),
"one exact load observation cannot be started twice"
);
self.pending_loads.push(PendingAdapterLoadObservation {
observation_id,
output_interest,
});
self.spawn_load_wait(pending);
ProtocolAdapterSchedulerAdvance::DeferredLoadStarted { observation_id }
}
ProtocolSchedulerStep::CompleteReadyResidence => {
ProtocolAdapterSchedulerAdvance::ProtocolResidenceCompleted(
scheduler.complete_next_protocol_residence().await,
@@ -229,53 +141,6 @@ impl ProtocolAdapterScheduler {
fn next_scheduler_step(&self, scheduler: &CdpScheduler) -> ProtocolSchedulerStep {
scheduler.next_protocol_scheduler_step()
}
fn spawn_load_wait(&self, pending: PendingDeferredMainDocumentLoadCompletion) {
if moli_trace::cdp_runtime_trace_enabled() {
tracing::info!(
target: "moli_cdp_runtime",
stage = "protocol_adapter_load_wait_spawn",
observation_id = ?pending.observation_id(),
);
}
let completion_tx = self.load_completion_tx.clone();
tokio::task::spawn_local(async move {
let completion = pending.wait().await;
let _ = completion_tx.send(completion);
});
}
async fn complete_load(
&mut self,
scheduler: &mut CdpScheduler,
completion: CompletedDeferredMainDocumentLoadCompletion,
) -> ProtocolAdapterSchedulerAdvance {
let observation_id = completion.observation_id();
if self.take_pending_load(observation_id).is_err() {
return ProtocolAdapterSchedulerAdvance::StaleDeferredLoadCompletion { observation_id };
}
let output = scheduler
.complete_deferred_load_completion(completion)
.await;
ProtocolAdapterSchedulerAdvance::DeferredLoadCompleted {
observation_id,
output,
}
}
/// Claims only the exact observation that produced a terminal. A delayed
/// or duplicate terminal must not retire another Page's load wait.
fn take_pending_load(
&mut self,
observation_id: DeferredMainDocumentLoadObservationId,
) -> Result<PendingAdapterLoadObservation, ()> {
let index = self
.pending_loads
.iter()
.position(|pending| pending.observation_id == observation_id)
.ok_or(())?;
Ok(self.pending_loads.remove(index))
}
}
#[cfg(test)]
@@ -291,8 +156,7 @@ mod tests {
use tokio::task::LocalSet;
use super::{
PendingAdapterLoadObservation, ProtocolAdapterScheduler, ProtocolAdapterSchedulerAdvance,
ProtocolAdapterSchedulerInput,
ProtocolAdapterScheduler, ProtocolAdapterSchedulerAdvance, ProtocolAdapterSchedulerInput,
};
use crate::cdp_scheduler::{CdpScheduler, protocol_residence::ProtocolSchedulerStep};
@@ -319,16 +183,11 @@ mod tests {
scheduler.apply_scheduler_events(vec![CdpSchedulerEvent::ProtocolWorkPublished {
work: protocol_observation(1),
}]);
let adapter = ProtocolAdapterScheduler {
pending_loads: vec![PendingAdapterLoadObservation {
observation_id,
output_interest: deferred_main_document_load_output_interest(
page_residence(),
None,
),
}],
..Default::default()
};
let adapter = ProtocolAdapterScheduler::default();
scheduler.queues.start_main_document_load(
observation_id,
deferred_main_document_load_output_interest(page_residence(), None),
);
assert_eq!(
adapter.next_scheduler_step(&scheduler),
@@ -342,7 +201,7 @@ mod tests {
"independent protocol work must remain runnable while the exact observation waits"
);
assert!(
adapter.has_pending_loads(),
!scheduler.queues.pending_loads.is_empty(),
"running independent work must not release the exact load observation"
);
}
@@ -352,50 +211,33 @@ mod tests {
let first = deferred_main_document_load_observation_id(1);
let second = deferred_main_document_load_observation_id(2);
let stale = deferred_main_document_load_observation_id(3);
let mut adapter = ProtocolAdapterScheduler {
pending_loads: vec![
PendingAdapterLoadObservation {
observation_id: first,
output_interest: deferred_main_document_load_output_interest(
page_residence(),
None,
),
},
PendingAdapterLoadObservation {
observation_id: second,
output_interest: deferred_main_document_load_output_interest(
RendererOutputResidenceIdentity::Page {
owner_local_host_id: RendererOwnerLocalHostId::new_for_testing(1),
page_id: PageId::new_for_testing(8),
},
None,
),
},
],
..Default::default()
};
assert_eq!(adapter.pending_loads.len(), 2);
adapter
.take_pending_load(second)
.expect("the second Page terminal must claim only its observation");
let mut scheduler = CdpScheduler::new(CdpConnection::new());
for (id, page_id) in [(first, 7), (second, 8)] {
scheduler.queues.start_main_document_load(
id,
deferred_main_document_load_output_interest(
RendererOutputResidenceIdentity::Page {
owner_local_host_id: RendererOwnerLocalHostId::new_for_testing(1),
page_id: PageId::new_for_testing(page_id),
},
None,
),
);
}
assert!(scheduler.queues.finish_main_document_load(second));
assert_eq!(
adapter
scheduler
.queues
.pending_loads
.iter()
.map(|pending| pending.observation_id)
.collect::<Vec<_>>(),
[first],
"an out-of-order terminal must preserve the first Page wait"
[first]
);
assert!(
adapter.take_pending_load(stale).is_err(),
"an unknown terminal must not retire another Page wait"
);
adapter
.take_pending_load(first)
.expect("the first Page terminal should remain claimable");
assert!(!adapter.has_pending_loads());
assert!(!scheduler.queues.finish_main_document_load(stale));
assert_eq!(scheduler.queues.pending_loads.len(), 1);
assert!(scheduler.queues.finish_main_document_load(first));
assert!(scheduler.queues.pending_loads.is_empty());
}
#[tokio::test]
@@ -214,6 +214,7 @@ impl ProtocolSchedulerResidence {
#[derive(Debug)]
pub(super) struct SchedulerQueues {
pub(super) pending_loads: Vec<PendingMainDocumentLoadObservation>,
/// Concrete protocol output and owner work in scheduler admission order.
///
/// Renderer source publications are concrete before admission. A projected
@@ -233,12 +234,47 @@ impl Default for SchedulerQueues {
fn default() -> Self {
Self {
protocol_residences: VecDeque::new(),
pending_loads: Vec::new(),
next_protocol_work_publish_sequence: 1,
}
}
}
impl SchedulerQueues {
pub(super) fn start_main_document_load(
&mut self,
observation_id: DeferredMainDocumentLoadObservationId,
output_interest: moli_protocol::DeferredMainDocumentLoadCompletionOutputInterest,
) {
assert!(
!self
.pending_loads
.iter()
.any(|pending| pending.observation_id == observation_id),
"one exact load observation cannot be started twice"
);
self.pending_loads.push(PendingMainDocumentLoadObservation {
observation_id,
output_interest,
});
}
pub(super) fn finish_main_document_load(
&mut self,
observation_id: DeferredMainDocumentLoadObservationId,
) -> bool {
let Some(index) = self
.pending_loads
.iter()
.position(|pending| pending.observation_id == observation_id)
else {
return false;
};
self.pending_loads.remove(index);
self.satisfy_load_predecessor(observation_id);
true
}
pub(super) fn protocol_residence_len(&self) -> usize {
self.protocol_residences.len()
}
@@ -706,6 +742,12 @@ impl SchedulerQueues {
}
}
#[derive(Debug)]
pub(super) struct PendingMainDocumentLoadObservation {
pub(super) observation_id: DeferredMainDocumentLoadObservationId,
pub(super) output_interest: moli_protocol::DeferredMainDocumentLoadCompletionOutputInterest,
}
fn protocol_residence_is_command_followup_activity(residence: &ProtocolSchedulerResidence) -> bool {
matches!(
residence,
@@ -184,9 +184,17 @@ async fn verify_child_navigation_wait(replace_parent: bool) {
.await
.expect("the child lifecycle wait must allow same-Page Fetch continuation"),
);
let continuation_ack = observed
.iter()
.find(|message| message["id"] == 8)
.expect("Fetch continuation must reply");
assert!(
continuation_ack.get("error").is_none(),
"same-Page Fetch continuation failed: {observed:#?}"
);
timeout(Duration::from_secs(5), resumed.notified())
.await
.expect("same-Page HTTP work must resume before child script release");
.unwrap_or_else(|error| panic!("same-Page HTTP work must resume before child script release: {error:?}; observed={observed:#?}"));
}
let progress = timeout(
Duration::from_secs(5),
@@ -510,14 +510,9 @@ impl BidiSocketActor {
input: ProtocolAdapterSchedulerInput,
) -> bool {
let output = match adapter_scheduler.advance_input(scheduler, input).await {
ProtocolAdapterSchedulerAdvance::ProtocolResidenceCompleted(output)
| ProtocolAdapterSchedulerAdvance::DeferredLoadCompleted { output, .. } => output,
ProtocolAdapterSchedulerAdvance::ProtocolResidenceCompleted(output) => output,
ProtocolAdapterSchedulerAdvance::Idle
| ProtocolAdapterSchedulerAdvance::ClientTurnYielded
| ProtocolAdapterSchedulerAdvance::DeferredLoadStarted { .. }
| ProtocolAdapterSchedulerAdvance::StaleDeferredLoadCompletion { .. } => {
ProtocolOutputSequence::empty()
}
| ProtocolAdapterSchedulerAdvance::ClientTurnYielded => ProtocolOutputSequence::empty(),
};
self.send_or_route_protocol_output(scheduler, receivers, output, None)
.await
+28 -2
View File
@@ -20,7 +20,9 @@ use serde_json::json;
use crate::automation::{
AutomationContext, DevToolsTargetFilterEntry, DevToolsTargetInfo, DevToolsTargetKind,
};
use crate::domains::command_output::{BackgroundProtocolEventBuffer, CommandOutputBuffer};
#[cfg(any(test, feature = "test-support"))]
use crate::domains::command_output::BackgroundProtocolEventBuffer;
use crate::domains::command_output::CommandOutputBuffer;
use moli_core::{
LayoutPolicy, OptionalResourceFetchMask, RendererOutputPublicationOrdering,
@@ -728,6 +730,7 @@ impl DeferredMainDocumentLoadObservationId {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeferredMainDocumentLoadCompletionOutputInterest {
owner: Option<CommandOwnerScope>,
renderer_page: Option<RendererPageResidenceIdentity>,
renderer_document: Option<moli_core::RendererDocumentLifecycleIdentity>,
}
@@ -824,6 +827,7 @@ impl PendingDeferredMainDocumentLoadCompletion {
}
impl CompletedDeferredMainDocumentLoadCompletion {
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn new(
inner: crate::domains::activity::CompletedDeferredMainDocumentLoadCompletionActivity,
) -> Self {
@@ -845,11 +849,29 @@ impl DeferredMainDocumentLoadCompletionOutputInterest {
renderer_document: Option<moli_core::RendererDocumentLifecycleIdentity>,
) -> Self {
Self {
owner: None,
renderer_page,
renderer_document,
}
}
pub(crate) fn with_owner(mut self, owner: CommandOwnerScope) -> Self {
self.owner = Some(owner);
self
}
pub fn observes_devtools_context(
&self,
conn: &CdpConnection,
context: &crate::automation::AutomationContext,
) -> bool {
self.owner.as_ref().is_some_and(|owner| {
conn.command_owner_scope_for_devtools_context(context)
.as_ref()
== Some(owner)
})
}
#[cfg(feature = "test-support")]
pub(crate) fn from_test_residence(
renderer_page: RendererPageResidenceIdentity,
@@ -2368,7 +2390,10 @@ impl CdpConnection {
true
}
pub fn devtools_context_routes_to_top_level_target(&self, context: &AutomationContext) -> bool {
pub fn devtools_context_routes_to_top_level_target(
&self,
context: &crate::automation::AutomationContext,
) -> bool {
context.target_id.as_ref().is_some_and(|target_id| {
self.target_session_route_for_target_id(target_id.as_str())
.is_some()
@@ -2850,6 +2875,7 @@ impl CdpConnection {
.push_scheduler_event(CdpSchedulerEvent::ProtocolWorkPublished { work });
}
#[cfg(any(test, feature = "test-support"))]
pub async fn complete_deferred_main_document_load_completion_for_scheduler(
&mut self,
completion: CompletedDeferredMainDocumentLoadCompletion,
-35
View File
@@ -329,41 +329,6 @@ impl PreparedDownloadActivationDelivery {
}
impl CdpConnection {
pub(crate) async fn handle_pending_download_activation_inline_async(
&mut self,
out: &mut Vec<BackgroundProtocolEvent>,
owner: &CommandOwnerScope,
activation: RendererPendingDownloadActivation,
command_context: &mut CommandDispatchContext,
) -> Result<()> {
self.handle_pending_download_activation_with_event_route_async(
out,
owner,
activation,
false,
command_context,
)
.await
}
async fn handle_pending_download_activation_with_event_route_async(
&mut self,
out: &mut Vec<BackgroundProtocolEvent>,
owner: &CommandOwnerScope,
activation: RendererPendingDownloadActivation,
allow_background_events: bool,
command_context: &mut CommandDispatchContext,
) -> Result<()> {
self.prepare_pending_download_activation_delivery(
owner,
activation,
allow_background_events,
)?
.run(out, command_context)
.await;
Ok(())
}
pub(crate) fn prepare_pending_download_activation_delivery(
&mut self,
owner: &CommandOwnerScope,
+35 -1
View File
@@ -245,6 +245,36 @@ impl CdpConnection {
/// current target state. The work owns both. Completion performs only the
/// exact attachment authorization required to prevent a detached session
/// or replacement Page from receiving historical output.
pub fn try_complete_protocol_scheduler_work_turn(
&mut self,
work: crate::domains::activity::ProtocolSchedulerWork,
) -> Result<CdpTurnOutcome, Box<crate::domains::activity::ProtocolSchedulerWork>> {
if work.kind() != crate::domains::activity::ProtocolSchedulerWorkKind::ProtocolObservation {
return Err(Box::new(work));
}
let events = match work.into_ready() {
ReadyProtocolSchedulerWork::RendererFencedOutput(output) => {
assert!(
output
.predecessors
.iter()
.all(|fence| self.renderer_output_cursor_is_projected(fence.cursor())),
"materialized protocol output cannot cross its concrete renderer predecessor"
);
output.events
}
ReadyProtocolSchedulerWork::ProtocolObservation(work) => {
work.into_background_events(self)
}
_ => unreachable!("only finite protocol observations were admitted"),
};
Ok(CdpTurnOutcome::new_with_protocol_events(
events,
self.take_scheduler_events(),
))
}
#[cfg(any(test, feature = "test-support"))]
pub async fn complete_ready_protocol_scheduler_work_turn(
&mut self,
work: crate::domains::activity::ProtocolSchedulerWork,
@@ -275,7 +305,11 @@ impl CdpConnection {
}
ReadyProtocolSchedulerWork::MainDocumentLoadOwnerAction(completion) => {
self.complete_deferred_main_document_load_completion_for_scheduler(
super::CompletedDeferredMainDocumentLoadCompletion::new(*completion),
super::CompletedDeferredMainDocumentLoadCompletion::new(
completion.try_complete().unwrap_or_else(|_| {
panic!("inline load completion requires a terminal lifecycle observer")
}),
),
)
.await
}
+75 -1
View File
@@ -9,7 +9,7 @@ use futures_util::{
use super::*;
#[cfg(test)]
use crate::conn::BackgroundProtocolEvent;
use crate::conn::{ProtocolStateAccess, ProtocolWorkflowDriver};
use crate::conn::{PreparedCommandWorkflow, ProtocolStateAccess, ProtocolWorkflowDriver};
use crate::domains::activity::{ProtocolSchedulerWork, ProtocolSchedulerWorkKind};
use crate::domains::page::{CompletedTargetTermination, TargetTermination};
use crate::domains::target::activation::TargetActivationOutput;
@@ -140,6 +140,15 @@ impl std::fmt::Debug for PendingProtocolSchedulerWork {
}
impl CompletedProtocolSchedulerWork {
pub fn main_document_load_observation_id(
&self,
) -> Option<crate::conn::DeferredMainDocumentLoadObservationId> {
match &self.work {
CompletedProtocolWork::Workflow(workflow, _) => workflow.load_observation(),
_ => None,
}
}
pub fn renderer_projection_cursor(&self) -> Option<moli_core::RendererOutputCursor> {
match &self.work {
CompletedProtocolWork::RendererOutputProjection(projection, _) => {
@@ -218,6 +227,8 @@ impl PendingProtocolSchedulerWork {
matches!(
kind,
ProtocolSchedulerWorkKind::PageTargetTerminationOwnerAction
| ProtocolSchedulerWorkKind::MainDocumentLoadOwnerAction
| ProtocolSchedulerWorkKind::PopupTargetNavigationOwnerAction
| ProtocolSchedulerWorkKind::TopLevelNavigationOwnerAction
| ProtocolSchedulerWorkKind::PopupTargetActivationAction
| ProtocolSchedulerWorkKind::BidiChannelOwnerAction
@@ -280,6 +291,69 @@ impl CdpConnection {
return Err(Box::new(work));
}
let prepared = match work.into_ready() {
ReadyProtocolSchedulerWork::MainDocumentLoadOwnerAction(completion) => {
let observation_id = completion.observation_id();
let target_id = Some(completion.target_id().to_owned());
let workflow_access = access.clone();
let workflow = PreparedCommandWorkflow::new(move |mut context| async move {
let completed = (*completion).start_scheduler_step().wait().await;
let mut driver = ProtocolWorkflowDriver::owned(workflow_access);
let pending = match context
.with_state(&mut driver, move |state, context| {
state.prepare_deferred_load_emission(completed, context)
})
.await
{
Ok(pending) => pending,
Err(error) => {
return context.fail(
crate::domains::command_output::CommandOutputPlan::error(
-32000, error,
),
);
}
};
if let Some(pending) = pending {
let mut events = Vec::new();
pending.run(&mut events, context.context_mut()).await;
context.context_mut().protocol_events_mut().extend(events);
}
context.complete(crate::domains::command_output::CommandOutputPlan::default())
});
Some(PendingProtocolWork::Workflow(
super::workflow::PendingProtocolWorkflow::prepare(workflow, target_id)
.with_load_observation(observation_id),
))
}
ReadyProtocolSchedulerWork::PopupTargetNavigationOwnerAction(action) => {
let target_id = Some(action.target_id().to_owned());
let workflow_access = access.clone();
crate::domains::target::PreparedPopupNavigation::prepare(self, action).map(
|prepared| {
let workflow =
PreparedCommandWorkflow::new(move |mut context| async move {
if let Err(error) = prepared
.run(
&mut ProtocolWorkflowDriver::owned(workflow_access),
&mut context,
)
.await
{
tracing::warn!(
?error,
"popup navigation owner workflow failed"
);
}
context.complete(
crate::domains::command_output::CommandOutputPlan::default(),
)
});
PendingProtocolWork::Workflow(
super::workflow::PendingProtocolWorkflow::prepare(workflow, target_id),
)
},
)
}
ReadyProtocolSchedulerWork::TopLevelNavigationOwnerAction(action) => {
let target_id = action.target_id().map(str::to_owned);
let navigation_access = access.clone();
@@ -20,6 +20,7 @@ pub(super) struct PendingProtocolWorkflow {
context: Rc<RefCell<CommandDispatchContext>>,
target_id: Option<String>,
source_cursor: Option<moli_core::RendererOutputCursor>,
load_observation: Option<crate::conn::DeferredMainDocumentLoadObservationId>,
}
impl PendingProtocolWorkflow {
@@ -33,6 +34,7 @@ impl PendingProtocolWorkflow {
context: Rc::new(RefCell::new(context)),
target_id,
source_cursor: None,
load_observation: None,
}
}
@@ -48,6 +50,20 @@ impl PendingProtocolWorkflow {
self.source_cursor
}
pub(super) fn with_load_observation(
mut self,
observation: crate::conn::DeferredMainDocumentLoadObservationId,
) -> Self {
self.load_observation = Some(observation);
self
}
pub(super) fn load_observation(
&self,
) -> Option<crate::conn::DeferredMainDocumentLoadObservationId> {
self.load_observation
}
pub(super) async fn wait(&self) -> SharedProtocolWorkflowResult {
self.pending.clone().await
}
@@ -73,6 +89,21 @@ impl PendingProtocolWorkflow {
None,
None,
);
let events = conn.finish_protocol_output_projection(context, self.target_id);
if let Some(source) = self.source_cursor {
conn.scheduler_state
.bind_renderer_output_source_since(scheduler_start, source);
}
CdpTurnOutcome::new_with_protocol_events(events, conn.take_scheduler_events())
}
}
impl CdpConnection {
pub(crate) fn finish_protocol_output_projection(
&mut self,
mut context: CommandDispatchContext,
target_id: Option<String>,
) -> Vec<crate::conn::BackgroundProtocolEvent> {
let (mut events, boundary, mut after) = context.take_renderer_fenced_protocol_events();
after.extend(context.take_post_response_events());
let predecessor = context.take_renderer_output_predecessor();
@@ -80,42 +111,34 @@ impl PendingProtocolWorkflow {
if let Some(predecessor) = predecessor.as_ref()
&& !events.is_empty()
{
conn.publish_renderer_fenced_protocol_output(
self.publish_renderer_fenced_protocol_output(
std::mem::take(&mut events),
predecessor.clone(),
self.target_id.clone(),
target_id.clone(),
);
}
if !after.is_empty() {
let mut predecessors = Vec::new();
predecessors.extend(predecessor);
predecessors.push(boundary);
conn.publish_renderer_fenced_protocol_output_after(
after,
predecessors,
self.target_id,
);
self.publish_renderer_fenced_protocol_output_after(after, predecessors, target_id);
}
} else {
events.extend(after);
if let Some(predecessor) = predecessor
&& !events.is_empty()
{
conn.publish_renderer_fenced_protocol_output(
self.publish_renderer_fenced_protocol_output(
std::mem::take(&mut events),
predecessor,
self.target_id,
target_id,
);
}
}
conn.finish_runtime_output_projection_permits(
self.finish_runtime_output_projection_permits(
context.take_runtime_output_projection_permits(),
);
if let Some(source) = self.source_cursor {
conn.scheduler_state
.bind_renderer_output_source_since(scheduler_start, source);
}
CdpTurnOutcome::new_with_protocol_events(events, conn.take_scheduler_events())
events
}
}
@@ -2,6 +2,30 @@ use super::ProtocolWorkflowState;
use crate::conn::CommandWorkflowContext;
impl ProtocolWorkflowState<'_> {
#[cfg(test)]
pub(crate) fn ingest_renderer_lifecycle_for_test(
self,
owner: crate::conn::CommandOwnerScope,
event: moli_core::page::RendererDocumentLifecycleEvent,
) {
self.connection
.ingest_renderer_document_lifecycle_events_for_owner(&owner, vec![event]);
}
pub(crate) fn prepare_deferred_load_emission(
self,
completed: crate::domains::activity::CompletedDeferredMainDocumentLoadCompletionActivity,
context: &mut CommandWorkflowContext,
) -> Option<crate::conn::PreparedDownloadActivationDelivery> {
let mut events = crate::domains::command_output::BackgroundProtocolEventBuffer::default();
let pending = completed.prepare_emission(self.connection, &mut events);
context
.context_mut()
.protocol_events_mut()
.extend(events.into_events());
pending
}
pub(crate) fn prepare_renderer_projection_batch(
self,
projection: crate::domains::activity::RendererOutputProjection,
@@ -6,6 +6,26 @@ use crate::conn::{
use crate::domains::target::{NewPopupTarget, PreparedPopupTarget};
impl ProtocolWorkflowState<'_> {
pub(crate) fn finish_popup_navigation(
self,
owner: CommandOwnerScope,
host: crate::conn::PageTargetHostIdentity,
) -> Vec<BackgroundProtocolEvent> {
let mut events = Vec::new();
if self
.connection
.page_target_host_identity_for_owner(&owner)
.is_some_and(|current| host.matches(&current))
{
crate::domains::target::emit_target_info_changed_for_owner_background_event(
self.connection,
&mut events,
&owner,
);
}
events
}
pub(crate) fn prepare_page_output_close(
self,
browser_context_id: String,
@@ -260,13 +260,13 @@ impl MainDocumentNavigationActivity {
);
}
async fn emit_deferred_load_completion_async(
fn prepare_deferred_load_completion(
&mut self,
conn: &mut CdpConnection,
out: &mut BackgroundProtocolEventBuffer,
pending_download: Option<RendererPendingDownloadActivation>,
renderer_document: Option<RendererDocumentLifecycleIdentity>,
) {
) -> Option<crate::conn::PreparedDownloadActivationDelivery> {
let timing_enabled = moli_trace::cdp_nav_timing_enabled();
let timing_started = std::time::Instant::now();
if !self.is_still_current(conn) {
@@ -282,11 +282,10 @@ impl MainDocumentNavigationActivity {
reason = "stale_navigation",
);
}
return;
return None;
}
let post_load_observation_armed = self
.emit_renderer_load_completion_async(conn, out, renderer_document)
.await;
let post_load_observation_armed =
self.emit_renderer_load_completion(conn, out, renderer_document);
if post_load_observation_armed {
conn.settle_root_frame_stopped_loading_observation_for_owner(&self.state.owner)
.expect(
@@ -302,9 +301,21 @@ impl MainDocumentNavigationActivity {
);
}
if pending_download.is_some() {
self.activate_pending_download_async(conn, out, pending_download)
.await;
let download = pending_download?;
match conn.prepare_pending_download_activation_delivery(&self.state.owner, download, false)
{
Ok(pending) => Some(pending),
Err(error) => {
let mut output = CommandOutputBuffer::default();
self.emit_navigation_error_into_buffer(&mut output, &format!("{error:#}"));
out.extend_background_events(
output.into_plan().into_background_events(
self.state.navigate_id,
self.state.owner.session_id(),
),
);
None
}
}
}
@@ -461,7 +472,7 @@ impl MainDocumentNavigationActivity {
}
}
async fn emit_renderer_load_completion_async(
fn emit_renderer_load_completion(
&mut self,
conn: &mut CdpConnection,
out: &mut BackgroundProtocolEventBuffer,
@@ -562,43 +573,6 @@ impl MainDocumentNavigationActivity {
);
}
async fn activate_pending_download_async(
&mut self,
conn: &mut CdpConnection,
out: &mut BackgroundProtocolEventBuffer,
pending_download: Option<RendererPendingDownloadActivation>,
) {
let mut command_context = CommandDispatchContext::default();
let error = if let Some(download) = pending_download {
let mut download_events = Vec::new();
let error = conn
.handle_pending_download_activation_inline_async(
&mut download_events,
&self.state.owner,
download,
&mut command_context,
)
.await
.err();
out.extend_background_events(download_events);
error
} else {
None
};
if let Some(error) = error {
let navigate_id = self.state.navigate_id;
let navigate_session_id = self.state.owner.session_id().map(str::to_owned);
let mut command_output = CommandOutputBuffer::default();
self.emit_navigation_error_into_buffer(&mut command_output, &format!("{error:#}"));
out.extend_background_events(
command_output
.into_plan()
.into_background_events(navigate_id, navigate_session_id.as_deref()),
);
}
out.extend_background_events(command_context.take_protocol_events());
}
fn emit_pre_domcontentloaded_network_backlog_background_events(
&self,
conn: &mut CdpConnection,
@@ -723,6 +697,7 @@ impl DeferredMainDocumentLoadCompletionActivity {
self.lifecycle_observer.observation().is_terminal()
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn try_complete(
self: Box<Self>,
) -> Result<CompletedDeferredMainDocumentLoadCompletionActivity, Box<Self>> {
@@ -749,18 +724,6 @@ impl DeferredMainDocumentLoadCompletionState {
.as_ref()
.map(CommittedRendererDocumentBinding::renderer_document_identity)
}
async fn emit_load_completion_after_lifecycle_ready_async(
&mut self,
conn: &mut CdpConnection,
out: &mut BackgroundProtocolEventBuffer,
) {
let pending_download = self.pending_download.take();
let renderer_document = self.renderer_document_identity();
self.navigation_activity
.emit_deferred_load_completion_async(conn, out, pending_download, renderer_document)
.await;
}
}
impl PendingDeferredMainDocumentLoadCompletionActivity {
@@ -809,11 +772,11 @@ impl CompletedDeferredMainDocumentLoadCompletionActivity {
self.observation_id
}
pub(crate) async fn emit_async(
pub(crate) fn prepare_emission(
mut self,
conn: &mut CdpConnection,
out: &mut BackgroundProtocolEventBuffer,
) {
) -> Option<crate::conn::PreparedDownloadActivationDelivery> {
match self.observation {
RendererDocumentLifecycleObservation::Reached => {}
RendererDocumentLifecycleObservation::Pending => {
@@ -823,7 +786,7 @@ impl CompletedDeferredMainDocumentLoadCompletionActivity {
self.state
.navigation_activity
.emit_renderer_load_boundary_facts(conn, out);
return;
return None;
}
RendererDocumentLifecycleObservation::Superseded
| RendererDocumentLifecycleObservation::Unavailable => {
@@ -831,12 +794,29 @@ impl CompletedDeferredMainDocumentLoadCompletionActivity {
self.owner_scope(),
&self.state.navigation_activity.state.loader_id,
);
return;
return None;
}
}
let pending_download = self.state.pending_download.take();
let renderer_document = self.state.renderer_document_identity();
self.state
.emit_load_completion_after_lifecycle_ready_async(conn, out)
.await;
.navigation_activity
.prepare_deferred_load_completion(conn, out, pending_download, renderer_document)
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) async fn emit_async(
self,
conn: &mut CdpConnection,
out: &mut BackgroundProtocolEventBuffer,
) {
if let Some(pending) = self.prepare_emission(conn, out) {
let mut context = CommandDispatchContext::default();
let mut events = Vec::new();
pending.run(&mut events, &mut context).await;
out.extend_background_events(events);
out.extend_background_events(context.take_protocol_events());
}
}
}
@@ -1613,6 +1593,96 @@ mod tests {
);
}
#[tokio::test]
async fn owned_load_wait_rejoins_its_original_observer_and_output_after_ready_loss() {
use crate::conn::{CommandDispatchContext, ParsedCdpCommand, ProtocolStateOwner};
use futures_util::FutureExt as _;
for lose_ready in [false, true] {
let (mut conn, binding, started) = connection_with_dcl_only_renderer_lifecycle();
conn.browser_context
.as_mut()
.unwrap()
.active_page_target_mut()
.devtools_sessions[moli_page_types::DevToolsSessionKey::Primary]
.page_session_state
.page_domain_enabled = true;
assert!(
conn.begin_renderer_document_load_visibility_barrier_for_owner(
&CommandOwnerScope::for_session("SID-nav"),
"LID-1"
)
);
conn.enqueue_deferred_main_document_load_completion(deferred_load_admission_for_test(
binding,
));
let work = take_deferred_load_work_for_test(&mut conn);
let observation = work.main_document_load_observation_id().unwrap();
drop(conn.take_protocol_state_requests());
let owner = ProtocolStateOwner::new(conn);
let handle = owner.handle();
let pending = handle
.with_state(|state| state.try_start_owned_protocol_scheduler_work(work))
.unwrap()
.unwrap_or_else(|_| {
panic!("the production owner admits the complete load workflow")
})
.unwrap();
assert!(
pending.clone().wait().now_or_never().is_none(),
"DOMContentLoaded cannot finish the load workflow"
);
let peer =
ParsedCdpCommand::parse_str(r#"{"id":50,"method":"Browser.getVersion"}"#).unwrap();
assert!(matches!(
handle
.with_state(|state| state.start_parsed_command_dispatch_with_context(
&peer,
&mut CommandDispatchContext::default()
))
.unwrap(),
crate::conn::CdpCommandTaskStep::Complete(_)
));
handle
.with_state(|state| {
state.ingest_renderer_lifecycle_for_test(
CommandOwnerScope::for_session("SID-nav"),
renderer_load_event_for_test(started),
);
})
.unwrap();
let completed = pending.clone().wait().await;
assert_eq!(
completed.main_document_load_observation_id(),
Some(observation)
);
let completed = if lose_ready {
drop(completed);
pending.clone().wait().await
} else {
completed
};
let outcome = handle
.with_state(|state| state.complete_owned_protocol_scheduler_work(completed))
.unwrap();
let (events, _) = outcome.into_protocol_event_parts();
assert!(
events
.into_iter()
.any(|event| event.into_protocol_message()["method"] == "Page.loadEventFired"),
"the original load boundary reaches its output handoff"
);
let duplicate = pending.wait().await;
let (events, scheduler) = handle
.with_state(|state| state.complete_owned_protocol_scheduler_work(duplicate))
.unwrap()
.into_protocol_event_parts();
assert!(
events.is_empty() && scheduler.is_empty(),
"ready loss cannot emit load twice"
);
}
}
#[tokio::test]
async fn deferred_load_terminal_before_adapter_wait_is_not_lost() {
let (mut conn, binding, started) = connection_with_dcl_only_renderer_lifecycle();
@@ -489,10 +489,13 @@ impl ProtocolSchedulerWork {
else {
return None;
};
Some(DeferredMainDocumentLoadCompletionOutputInterest::new(
completion.renderer_page_residence_identity(),
completion.renderer_document_identity(),
))
Some(
DeferredMainDocumentLoadCompletionOutputInterest::new(
completion.renderer_page_residence_identity(),
completion.renderer_document_identity(),
)
.with_owner(completion.owner_scope().clone()),
)
}
pub fn main_document_load_observation_id(
@@ -596,7 +599,7 @@ pub(crate) enum ReadyProtocolSchedulerWork {
RendererFencedOutput(RendererFencedProtocolOutput),
ProtocolObservation(ProtocolOutputWork),
MainDocumentLoadOwnerAction(
Box<super::main_document::CompletedDeferredMainDocumentLoadCompletionActivity>,
Box<super::main_document::DeferredMainDocumentLoadCompletionActivity>,
),
BidiChannelOwnerAction(BidiChannelOwnerAction),
TopLevelNavigationOwnerAction(TopLevelNavigationOwnerAction),
@@ -619,12 +622,7 @@ impl ProtocolSchedulerWork {
ReadyProtocolSchedulerWork::ProtocolObservation(output)
}
ProtocolSchedulerWorkPayload::MainDocumentLoadOwnerAction(completion) => {
let completion = completion.try_complete().unwrap_or_else(|_| {
panic!(
"pending main-document load work cannot be completed by a nonblocking scheduler turn"
)
});
ReadyProtocolSchedulerWork::MainDocumentLoadOwnerAction(Box::new(completion))
ReadyProtocolSchedulerWork::MainDocumentLoadOwnerAction(completion)
}
ProtocolSchedulerWorkPayload::BidiChannelOwnerAction(action) => {
ReadyProtocolSchedulerWork::BidiChannelOwnerAction(action)
+60 -28
View File
@@ -1251,6 +1251,7 @@ pub(in crate::domains) fn publish_prepared_top_level_history_traversal_owner_act
}
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) async fn navigate_page_owned_top_level_location_background_events_async(
conn: &mut CdpConnection,
out: &mut Vec<BackgroundProtocolEvent>,
@@ -1342,6 +1343,44 @@ pub(crate) async fn navigate_command_owner_from_renderer_background_events_async
.await;
}
pub(in crate::domains) fn prepare_renderer_navigation_request(
conn: &mut CdpConnection,
owner: CommandOwnerScope,
url: &str,
request_method: &str,
request_body: Option<&bytes::Bytes>,
request_headers: &[(String, String)],
browser_navigation_kind: moli_fetch::BrowserNavigationRequestKind,
web_mcp_invocation: Option<moli_page_types::RendererWebMcpNavigation>,
auxiliary_navigation: Option<moli_core::page::RendererAuxiliaryNavigationKind>,
document_response: Option<moli_core::page::RendererAuxiliaryDocumentResponse>,
initial_document_environment: Option<moli_core::page::RendererCapturedDocumentEnvironment>,
navigation_initiator: Option<moli_core::page::RendererNavigationInitiator>,
) -> PreparedRendererNavigation {
let start = navigation::start_session_owner_navigation_from_renderer(
conn,
&owner,
url,
request_method,
request_body,
request_headers,
browser_navigation_kind,
web_mcp_invocation,
auxiliary_navigation,
document_response,
initial_document_environment,
navigation_initiator,
);
let step = navigation::finish_started_navigation_command_for_parts(
conn,
None,
owner.clone(),
start,
&[],
);
PreparedRendererNavigation::prepare(conn, owner, step)
}
pub(in crate::domains) async fn navigate_command_owner_from_renderer_request_background_events_async(
conn: &mut CdpConnection,
out: &mut Vec<BackgroundProtocolEvent>,
@@ -1357,9 +1396,9 @@ pub(in crate::domains) async fn navigate_command_owner_from_renderer_request_bac
initial_document_environment: Option<moli_core::page::RendererCapturedDocumentEnvironment>,
navigation_initiator: Option<moli_core::page::RendererNavigationInitiator>,
) {
let start = navigation::start_session_owner_navigation_from_renderer(
let prepared = prepare_renderer_navigation_request(
conn,
&owner,
owner,
url,
request_method,
request_body,
@@ -1371,11 +1410,10 @@ pub(in crate::domains) async fn navigate_command_owner_from_renderer_request_bac
initial_document_environment,
navigation_initiator,
);
let step =
navigation::finish_started_navigation_command_for_parts(conn, None, owner, start, &[]);
complete_renderer_navigation_step_background_events_async(conn, out, step).await;
run_renderer_navigation_inline(conn, out, prepared).await;
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) async fn traverse_session_owner_history_from_renderer_background_events_async(
conn: &mut CdpConnection,
out: &mut Vec<BackgroundProtocolEvent>,
@@ -1383,35 +1421,29 @@ pub(crate) async fn traverse_session_owner_history_from_renderer_background_even
delta: i64,
) {
let step = navigation::start_session_owner_history_traversal_from_renderer(conn, owner, delta);
complete_renderer_navigation_step_background_events_async(conn, out, step).await;
let prepared = PreparedRendererNavigation::prepare(conn, owner.clone(), step);
run_renderer_navigation_inline(conn, out, prepared).await;
}
async fn complete_renderer_navigation_step_background_events_async(
async fn run_renderer_navigation_inline(
conn: &mut CdpConnection,
out: &mut Vec<BackgroundProtocolEvent>,
mut step: PageCommandTaskStep,
prepared: PreparedRendererNavigation,
) {
let mut command_context = CommandDispatchContext::default();
loop {
match step {
PageCommandTaskStep::Complete(plan) => {
let (_, background_events) = plan.into_command_status_and_background_events();
out.extend(background_events);
return;
}
PageCommandTaskStep::Pending(pending) => {
// Navigation futures carry the response and renderer setup.
// Keep them out of each enclosing target-navigation future.
let completed = Box::pin(pending.wait()).await;
step = Box::pin(complete_pending_page_command(
conn,
completed,
&mut command_context,
))
.await;
}
}
let target_id = prepared.target_id(conn);
let mut command = CommandDispatchContext::default();
let (mut context, _scope) =
crate::conn::CommandWorkflowContext::take_from(&mut command, None, None);
if let Err(error) = Box::pin(prepared.run(
&mut crate::conn::ProtocolWorkflowDriver::inline(conn),
&mut context,
))
.await
{
tracing::warn!(?error, "renderer navigation failed");
}
context.finish_projection_inline(conn, &mut command);
out.extend(conn.finish_protocol_output_projection(command, target_id));
}
pub(crate) fn emit_page_window_open_background_events_for_owner(
+17 -7
View File
@@ -1045,7 +1045,13 @@ fn start_protocol_neutral_navigation_command(
let result_kind = DevToolsNavigationCommandResultKind::Navigate;
let mut direct_result = match &command {
AutomationCommand::Navigate(command) => {
let loader_id = if child_frame_navigation_target_id(conn, command).is_some() {
let loader_id = if child_frame_navigation_target_id(
conn,
&CommandOwnerScope::for_route(route.clone()),
command,
)
.is_some()
{
None
} else {
Some(LOADER_ID)
@@ -1446,7 +1452,7 @@ fn start_devtools_navigate_command(
result_projection: NavigationResultProjection,
allow_background_navigation: bool,
) -> NavigateCommandStart {
if let Some(frame_id) = child_frame_navigation_target_id(conn, command) {
if let Some(frame_id) = child_frame_navigation_target_id(conn, owner, command) {
return start_child_frame_navigate_command(
conn,
command_id,
@@ -1549,14 +1555,18 @@ fn start_top_level_same_document_navigate(
fn child_frame_navigation_target_id<'a>(
conn: &CdpConnection,
owner: &CommandOwnerScope,
command: &'a DevToolsNavigateCommand,
) -> Option<&'a str> {
let target_id = command.context.target_id.as_ref()?.as_str();
if conn.target_session_route_for_target_id(target_id).is_some() {
return None;
}
conn.has_attached_child_frame_id(target_id)
.then_some(target_id)
let root = conn
.target_owner_identity_for_owner(owner)
.and_then(|(_, target)| target)?;
// Attachment observations may still be queued after a Native frame-tree
// reply. Preserve the requested frame and let that Page validate it;
// missing observation history must never turn a child request into a
// navigation of the root document.
(root != target_id).then_some(target_id)
}
fn start_child_frame_navigate_command(
@@ -263,6 +263,11 @@ impl PreparedRendererNavigation {
}
}
pub(super) fn target_id(&self, conn: &CdpConnection) -> Option<String> {
conn.target_owner_identity_for_owner(&self.owner)
.and_then(|(_, target)| target)
}
pub(crate) async fn run(
self,
driver: &mut ProtocolWorkflowDriver<'_>,
@@ -1,5 +1,73 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn explicit_child_navigation_does_not_depend_on_projected_attachment_events() {
let mut ctx = TestContext::new();
load_bc_with_session(
&mut ctx,
"BID-frame-routing",
"TID-frame-routing",
"SID-frame-routing",
"about:blank",
);
ctx.enable_page_events_for_test(Some("SID-frame-routing"));
let parent =
"data:text/html,<p id=parent>retained</p><iframe srcdoc='<p>initial</p>'></iframe>";
ctx.process_and_wait_for_response_async(json!({
"id": 200, "method": "Page.navigate", "sessionId": "SID-frame-routing", "params": {"url": parent}
})).await;
wait_until_frame_stopped_loading(&mut ctx, "TID-frame-routing").await;
ctx.process_async(
json!({"id":201,"method":"Page.getFrameTree","sessionId":"SID-frame-routing"}),
)
.await;
let tree = take_response_by_id(&mut ctx, 201);
let child = tree["result"]["frameTree"]["childFrames"][0]["frame"]["id"]
.as_str()
.unwrap()
.to_owned();
// The Native tree is authoritative even while its frameAttached output
// has not reached the protocol observation index.
ctx.conn
.with_target_owner_state_for_session_mut(Some("SID-frame-routing"), |state| {
state.clear_attached_child_frame_ids()
})
.unwrap();
assert!(!ctx.conn.has_attached_child_frame_id(&child));
let child_url = "data:text/html,<p>child replacement</p>";
ctx.process_and_wait_for_response_async(json!({
"id":202,"method":"Page.navigate","sessionId":"SID-frame-routing", "params":{"frameId":child,"url":child_url}
})).await;
let response = take_response_by_id(&mut ctx, 202);
assert_eq!(response["result"]["frameId"], child, "{response}");
ctx.process_async(
json!({"id":203,"method":"Page.getFrameTree","sessionId":"SID-frame-routing"}),
)
.await;
let tree = take_response_by_id(&mut ctx, 203);
assert_eq!(tree["result"]["frameTree"]["frame"]["url"], parent);
assert_eq!(
tree["result"]["frameTree"]["childFrames"][0]["frame"]["url"],
child_url
);
ctx.process_and_wait_for_response_async(json!({
"id":204,"method":"Page.navigate","sessionId":"SID-frame-routing", "params":{"frameId":"missing-frame","url":"data:text/html,unexpected root replacement"}
})).await;
let response = take_response_by_id(&mut ctx, 204);
assert!(
response["error"].is_object(),
"unknown frame IDs must not navigate the root: {response}"
);
ctx.process_async(
json!({"id":205,"method":"Page.getFrameTree","sessionId":"SID-frame-routing"}),
)
.await;
assert_eq!(
take_response_by_id(&mut ctx, 205)["result"]["frameTree"]["frame"]["url"],
parent
);
}
#[tokio::test(flavor = "multi_thread")]
async fn navigate_emits_frame_and_load_events_in_order() {
let mut ctx = TestContext::new();
+8 -5
View File
@@ -48,14 +48,17 @@ pub(crate) enum TargetCommandFailureCleanup {
pub(in crate::domains) use browser_context::devtools_client_window_info_for_target;
pub(crate) use popup::{
NewPopupTarget, PopupTargetCreation, PopupTargetOpenerIdentity, PreparedPopupTarget,
complete_popup_target_activation_action_async,
complete_popup_target_navigation_owner_action_async,
emit_target_info_changed_for_owner_background_event, finish_popup_target, prepare_popup_target,
prepare_popup_target_activation,
NewPopupTarget, PopupTargetCreation, PopupTargetOpenerIdentity, PreparedPopupNavigation,
PreparedPopupTarget, emit_target_info_changed_for_owner_background_event, finish_popup_target,
prepare_popup_target, prepare_popup_target_activation,
schedule_initial_document_target_url_navigation_after_debugger_barrier_release_for_target,
schedule_initial_document_target_url_navigation_after_debugger_resume,
};
#[cfg(any(test, feature = "test-support"))]
pub(crate) use popup::{
complete_popup_target_activation_action_async,
complete_popup_target_navigation_owner_action_async,
};
pub(crate) fn popup_activation_creates_new_target_for_owner(
conn: &CdpConnection,
owner: &CommandOwnerScope,
+155 -115
View File
@@ -624,128 +624,167 @@ fn popup_target_has_loaded_page(
.is_some_and(|target| target.has_loaded_page())
}
pub(crate) struct PreparedPopupNavigation {
navigation: crate::domains::page::PreparedRendererNavigation,
completion: Option<(CommandOwnerScope, crate::conn::PageTargetHostIdentity)>,
}
impl PreparedPopupNavigation {
pub(crate) fn prepare(
conn: &mut CdpConnection,
action: PopupTargetNavigationOwnerAction,
) -> Option<Self> {
let (
owner_scope,
browser_context_id,
target_id,
url,
kind,
mut document_response,
initial_document_environment,
mut navigation_initiator,
) = action.into_parts();
let target_is_current = conn
.target_owner_identity_for_owner(&owner_scope)
.is_some_and(|(current_browser_context_id, current_target_id)| {
current_browser_context_id == browser_context_id
&& current_target_id.as_deref() == Some(target_id.as_str())
});
if !target_is_current
|| !popup_target_has_loaded_page(conn, &browser_context_id, &target_id)
{
tracing::debug!(
browser_context_id,
target_id,
url,
?kind,
"dropping popup navigation after its exact target owner retired"
);
return None;
}
match kind {
PopupTargetNavigationKind::InitialDocument
| PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume => {
// Revalidate the barrier when the queued owner action actually
// runs. Another inspector session can attach after this action is
// scheduled; that new session must be able to pause the initial
// document before any target-URL request starts.
if conn.target_has_waiting_for_debugger_session(&target_id)
|| !conn.browser_context_by_id(&browser_context_id).is_some_and(
|browser_context| {
browser_context.target_needs_initial_document_navigation(&target_id)
},
)
{
return None;
}
}
PopupTargetNavigationKind::NamedTargetReuse { .. }
| PopupTargetNavigationKind::WindowReference(_) => {}
}
if matches!(
kind,
PopupTargetNavigationKind::InitialDocument
| PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume
) && let Some(pending) = conn
.browser_context_by_id_mut(&browser_context_id)
.and_then(|context| context.page_target_mut(&target_id))
.and_then(|target| target.owner_state.pending_popup_navigation.take())
.filter(|pending| pending.url == url)
{
document_response = pending.response;
navigation_initiator = pending.initiator;
}
let auxiliary_navigation = match kind {
PopupTargetNavigationKind::WindowReference(kind) => Some(kind),
PopupTargetNavigationKind::NamedTargetReuse { replace_current } => {
Some(if replace_current {
moli_core::page::RendererAuxiliaryNavigationKind::Replace
} else {
moli_core::page::RendererAuxiliaryNavigationKind::Assign
})
}
_ => None,
};
let request_kind = if matches!(
kind,
PopupTargetNavigationKind::WindowReference(
moli_core::page::RendererAuxiliaryNavigationKind::Reload
)
) {
moli_fetch::BrowserNavigationRequestKind::Reload
} else {
moli_fetch::BrowserNavigationRequestKind::Navigate
};
let completion = matches!(
kind,
PopupTargetNavigationKind::InitialDocument
| PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume
)
.then(|| {
conn.page_target_host_identity_for_owner(&owner_scope)
.map(|host| (owner_scope.clone(), host))
})
.flatten();
let navigation = crate::domains::page::prepare_renderer_navigation_request(
conn,
owner_scope,
&url,
"GET",
None,
&[],
request_kind,
None,
auxiliary_navigation,
document_response,
initial_document_environment,
navigation_initiator,
);
Some(Self {
navigation,
completion,
})
}
pub(crate) async fn run(
self,
driver: &mut crate::conn::ProtocolWorkflowDriver<'_>,
context: &mut crate::conn::CommandWorkflowContext,
) -> Result<()> {
self.navigation.run(driver, context).await?;
if let Some((owner, host)) = self.completion {
let events = driver
.with_state(move |state| state.finish_popup_navigation(owner, host))
.await?;
context.context_mut().protocol_events_mut().extend(events);
}
Ok(())
}
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) async fn complete_popup_target_navigation_owner_action_async(
conn: &mut CdpConnection,
action: PopupTargetNavigationOwnerAction,
) -> crate::conn::CdpTurnOutcome {
let (
owner_scope,
browser_context_id,
target_id,
url,
kind,
mut document_response,
initial_document_environment,
mut navigation_initiator,
) = action.into_parts();
let target_is_current = conn
.target_owner_identity_for_owner(&owner_scope)
.is_some_and(|(current_browser_context_id, current_target_id)| {
current_browser_context_id == browser_context_id
&& current_target_id.as_deref() == Some(target_id.as_str())
});
if !target_is_current || !popup_target_has_loaded_page(conn, &browser_context_id, &target_id) {
tracing::debug!(
browser_context_id,
target_id,
url,
?kind,
"dropping popup navigation after its exact target owner retired"
);
return crate::conn::CdpTurnOutcome::new_with_protocol_events(
Vec::new(),
conn.take_scheduler_events(),
);
}
let mut protocol_events = Vec::new();
match kind {
PopupTargetNavigationKind::InitialDocument
| PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume => {
// Revalidate the barrier when the queued owner action actually
// runs. Another inspector session can attach after this action is
// scheduled; that new session must be able to pause the initial
// document before any target-URL request starts.
if conn.target_has_waiting_for_debugger_session(&target_id)
|| !conn
.browser_context_by_id(&browser_context_id)
.is_some_and(|browser_context| {
browser_context.target_needs_initial_document_navigation(&target_id)
})
{
return crate::conn::CdpTurnOutcome::new_with_protocol_events(
Vec::new(),
conn.take_scheduler_events(),
);
}
let target_id = Some(action.target_id().to_owned());
let mut command = crate::conn::CommandDispatchContext::default();
if let Some(prepared) = PreparedPopupNavigation::prepare(conn, action) {
let (mut context, _scope) =
crate::conn::CommandWorkflowContext::take_from(&mut command, None, None);
if let Err(error) = Box::pin(prepared.run(
&mut crate::conn::ProtocolWorkflowDriver::inline(conn),
&mut context,
))
.await
{
tracing::warn!(?error, "popup navigation failed");
}
PopupTargetNavigationKind::NamedTargetReuse { .. }
| PopupTargetNavigationKind::WindowReference(_) => {}
}
if matches!(
kind,
PopupTargetNavigationKind::InitialDocument
| PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume
) && let Some(pending) = conn
.browser_context_by_id_mut(&browser_context_id)
.and_then(|context| context.page_target_mut(&target_id))
.and_then(|target| target.owner_state.pending_popup_navigation.take())
.filter(|pending| pending.url == url)
{
document_response = pending.response;
navigation_initiator = pending.initiator;
}
let auxiliary_navigation = match kind {
PopupTargetNavigationKind::WindowReference(kind) => Some(kind),
PopupTargetNavigationKind::NamedTargetReuse { replace_current } => {
Some(if replace_current {
moli_core::page::RendererAuxiliaryNavigationKind::Replace
} else {
moli_core::page::RendererAuxiliaryNavigationKind::Assign
})
}
_ => None,
};
let request_kind = if matches!(
kind,
PopupTargetNavigationKind::WindowReference(
moli_core::page::RendererAuxiliaryNavigationKind::Reload
)
) {
moli_fetch::BrowserNavigationRequestKind::Reload
} else {
moli_fetch::BrowserNavigationRequestKind::Navigate
};
crate::domains::page::navigate_command_owner_from_renderer_request_background_events_async(
conn,
&mut protocol_events,
owner_scope,
&url,
"GET",
None,
&[],
request_kind,
None,
auxiliary_navigation,
document_response,
initial_document_environment,
navigation_initiator,
)
.await;
if matches!(
kind,
PopupTargetNavigationKind::InitialDocument
| PopupTargetNavigationKind::InitialDocumentAfterDebuggerResume
) {
emit_target_info_changed_for_target_background_event(
conn,
&mut protocol_events,
&browser_context_id,
&target_id,
);
context.finish_projection_inline(conn, &mut command);
}
crate::conn::CdpTurnOutcome::new_with_protocol_events(
protocol_events,
conn.finish_protocol_output_projection(command, target_id),
conn.take_scheduler_events(),
)
}
@@ -762,6 +801,7 @@ pub(crate) fn prepare_popup_target_activation(
super::activation::prepare_target_activation_for_target(conn, action.target_id())
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) async fn complete_popup_target_activation_action_async(
conn: &mut CdpConnection,
action: PopupTargetActivationAction,